repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
NotifyMeHQ/notifyme
src/Adapters/Twilio/TwilioGateway.php
TwilioGateway.mapResponse
protected function mapResponse($success, array $response) { return (new Response())->setRaw($response)->map([ 'success' => $success, 'message' => $success ? 'Message sent' : $response['message'], ]); }
php
protected function mapResponse($success, array $response) { return (new Response())->setRaw($response)->map([ 'success' => $success, 'message' => $success ? 'Message sent' : $response['message'], ]); }
[ "protected", "function", "mapResponse", "(", "$", "success", ",", "array", "$", "response", ")", "{", "return", "(", "new", "Response", "(", ")", ")", "->", "setRaw", "(", "$", "response", ")", "->", "map", "(", "[", "'success'", "=>", "$", "success", ...
Map the raw response to our response object. @param bool $success @param array $response @return \NotifyMeHQ\Contracts\ResponseInterface
[ "Map", "the", "raw", "response", "to", "our", "response", "object", "." ]
2af4bdcfe9df6db7ea79e2dce90b106ccb285b06
https://github.com/NotifyMeHQ/notifyme/blob/2af4bdcfe9df6db7ea79e2dce90b106ccb285b06/src/Adapters/Twilio/TwilioGateway.php#L117-L123
train
ekyna/PayumMonetico
src/Api/Api.php
Api.setConfig
public function setConfig(array $config) { try { $this->config = $this ->getConfigResolver() ->resolve($config); } catch (ExceptionInterface $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } }
php
public function setConfig(array $config) { try { $this->config = $this ->getConfigResolver() ->resolve($config); } catch (ExceptionInterface $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } }
[ "public", "function", "setConfig", "(", "array", "$", "config", ")", "{", "try", "{", "$", "this", "->", "config", "=", "$", "this", "->", "getConfigResolver", "(", ")", "->", "resolve", "(", "$", "config", ")", ";", "}", "catch", "(", "ExceptionInterf...
Configures the api. @param array $config
[ "Configures", "the", "api", "." ]
1251ab0166a79c6dc6424005e8e8eb85227db361
https://github.com/ekyna/PayumMonetico/blob/1251ab0166a79c6dc6424005e8e8eb85227db361/src/Api/Api.php#L57-L66
train
ekyna/PayumMonetico
src/Api/Api.php
Api.createPaymentForm
public function createPaymentForm(array $data) { $this->ensureApiIsConfigured(); try { $data = $this ->getRequestOptionsResolver() ->resolve($data); } catch (ExceptionInterface $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } $fields = [ 'TPE' => $this->config['tpe'], 'date' => $data['date'], 'montant' => $data['amount'] . $data['currency'], 'reference' => $data['reference'], 'texte-libre' => $data['comment'], 'version' => static::VERSION, 'lgue' => $data['locale'], 'societe' => $this->config['company'], 'mail' => $data['email'], ]; $macData = array_values($fields); $fields['texte-libre'] = $this->htmlEncode($data['comment']); if (!empty($data['schedule'])) { $macData[] = $fields['nbrech'] = count($data['schedule']); $count = 0; foreach ($data['schedule'] as $datum) { $count++; $macData[] = $fields['dateech' . $count] = $datum['date']; $macData[] = $fields['montantech' . $count] = $datum['amount'] . $data['currency']; } // Fills empty schedule for ($i = 2 * $count + 10; $i < 18; $i++) { $macData[] = null; } $options = []; foreach ($data['options'] as $key => $value) { $options = "$key=$value"; } $macData[] = $fields['options'] = implode('&', $options); } $fields['MAC'] = $this->computeMac($macData); $fields['url_retour'] = $data['return_url']; $fields['url_retour_ok'] = $data['success_url']; $fields['url_retour_err'] = $data['failure_url']; return [ 'action' => $this->getEndpointUrl(static::TYPE_PAYMENT), 'method' => 'POST', 'fields' => $fields, ]; }
php
public function createPaymentForm(array $data) { $this->ensureApiIsConfigured(); try { $data = $this ->getRequestOptionsResolver() ->resolve($data); } catch (ExceptionInterface $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } $fields = [ 'TPE' => $this->config['tpe'], 'date' => $data['date'], 'montant' => $data['amount'] . $data['currency'], 'reference' => $data['reference'], 'texte-libre' => $data['comment'], 'version' => static::VERSION, 'lgue' => $data['locale'], 'societe' => $this->config['company'], 'mail' => $data['email'], ]; $macData = array_values($fields); $fields['texte-libre'] = $this->htmlEncode($data['comment']); if (!empty($data['schedule'])) { $macData[] = $fields['nbrech'] = count($data['schedule']); $count = 0; foreach ($data['schedule'] as $datum) { $count++; $macData[] = $fields['dateech' . $count] = $datum['date']; $macData[] = $fields['montantech' . $count] = $datum['amount'] . $data['currency']; } // Fills empty schedule for ($i = 2 * $count + 10; $i < 18; $i++) { $macData[] = null; } $options = []; foreach ($data['options'] as $key => $value) { $options = "$key=$value"; } $macData[] = $fields['options'] = implode('&', $options); } $fields['MAC'] = $this->computeMac($macData); $fields['url_retour'] = $data['return_url']; $fields['url_retour_ok'] = $data['success_url']; $fields['url_retour_err'] = $data['failure_url']; return [ 'action' => $this->getEndpointUrl(static::TYPE_PAYMENT), 'method' => 'POST', 'fields' => $fields, ]; }
[ "public", "function", "createPaymentForm", "(", "array", "$", "data", ")", "{", "$", "this", "->", "ensureApiIsConfigured", "(", ")", ";", "try", "{", "$", "data", "=", "$", "this", "->", "getRequestOptionsResolver", "(", ")", "->", "resolve", "(", "$", ...
Creates the request form. @param array $data @return array
[ "Creates", "the", "request", "form", "." ]
1251ab0166a79c6dc6424005e8e8eb85227db361
https://github.com/ekyna/PayumMonetico/blob/1251ab0166a79c6dc6424005e8e8eb85227db361/src/Api/Api.php#L75-L136
train
ekyna/PayumMonetico
src/Api/Api.php
Api.checkPaymentResponse
public function checkPaymentResponse(array $data) { if (!isset($data['MAC'])) { return false; } $data = array_replace([ 'date' => null, 'montant' => null, 'reference' => null, 'texte-libre' => null, 'code-retour' => null, 'cvx' => null, 'vld' => null, 'brand' => null, 'status3ds' => null, 'numauto' => null, 'motifrefus' => null, 'originecb' => null, 'bincb' => null, 'hpancb' => null, 'ipclient' => null, 'originetr' => null, 'veres' => null, 'pares' => null, ], $data); $macData = [ $this->config['tpe'], $data["date"], $data['montant'], $data['reference'], $data['texte-libre'], static::VERSION, $data['code-retour'], $data['cvx'], $data['vld'], $data['brand'], $data['status3ds'], $data['numauto'], $data['motifrefus'], $data['originecb'], $data['bincb'], $data['hpancb'], $data['ipclient'], $data['originetr'], $data['veres'], $data['pares'], null, ]; return strtolower($data['MAC']) === $this->computeMac($macData); }
php
public function checkPaymentResponse(array $data) { if (!isset($data['MAC'])) { return false; } $data = array_replace([ 'date' => null, 'montant' => null, 'reference' => null, 'texte-libre' => null, 'code-retour' => null, 'cvx' => null, 'vld' => null, 'brand' => null, 'status3ds' => null, 'numauto' => null, 'motifrefus' => null, 'originecb' => null, 'bincb' => null, 'hpancb' => null, 'ipclient' => null, 'originetr' => null, 'veres' => null, 'pares' => null, ], $data); $macData = [ $this->config['tpe'], $data["date"], $data['montant'], $data['reference'], $data['texte-libre'], static::VERSION, $data['code-retour'], $data['cvx'], $data['vld'], $data['brand'], $data['status3ds'], $data['numauto'], $data['motifrefus'], $data['originecb'], $data['bincb'], $data['hpancb'], $data['ipclient'], $data['originetr'], $data['veres'], $data['pares'], null, ]; return strtolower($data['MAC']) === $this->computeMac($macData); }
[ "public", "function", "checkPaymentResponse", "(", "array", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'MAC'", "]", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "array_replace", "(", "[", "'date'", "=>", ...
Checks the payment response integrity. @param array $data @return bool
[ "Checks", "the", "payment", "response", "integrity", "." ]
1251ab0166a79c6dc6424005e8e8eb85227db361
https://github.com/ekyna/PayumMonetico/blob/1251ab0166a79c6dc6424005e8e8eb85227db361/src/Api/Api.php#L145-L197
train
ekyna/PayumMonetico
src/Api/Api.php
Api.getMacKey
public function getMacKey() { $key = $this->config['key']; $hexStrKey = substr($key, 0, 38); $hexFinal = "" . substr($key, 38, 2) . "00"; $cca0 = ord($hexFinal); if ($cca0 > 70 && $cca0 < 97) { $hexStrKey .= chr($cca0 - 23) . substr($hexFinal, 1, 1); } else { if (substr($hexFinal, 1, 1) == "M") { $hexStrKey .= substr($hexFinal, 0, 1) . "0"; } else { $hexStrKey .= substr($hexFinal, 0, 2); } } return pack("H*", $hexStrKey); }
php
public function getMacKey() { $key = $this->config['key']; $hexStrKey = substr($key, 0, 38); $hexFinal = "" . substr($key, 38, 2) . "00"; $cca0 = ord($hexFinal); if ($cca0 > 70 && $cca0 < 97) { $hexStrKey .= chr($cca0 - 23) . substr($hexFinal, 1, 1); } else { if (substr($hexFinal, 1, 1) == "M") { $hexStrKey .= substr($hexFinal, 0, 1) . "0"; } else { $hexStrKey .= substr($hexFinal, 0, 2); } } return pack("H*", $hexStrKey); }
[ "public", "function", "getMacKey", "(", ")", "{", "$", "key", "=", "$", "this", "->", "config", "[", "'key'", "]", ";", "$", "hexStrKey", "=", "substr", "(", "$", "key", ",", "0", ",", "38", ")", ";", "$", "hexFinal", "=", "\"\"", ".", "substr", ...
Returns the key formatted for mac generation. @return string
[ "Returns", "the", "key", "formatted", "for", "mac", "generation", "." ]
1251ab0166a79c6dc6424005e8e8eb85227db361
https://github.com/ekyna/PayumMonetico/blob/1251ab0166a79c6dc6424005e8e8eb85227db361/src/Api/Api.php#L220-L240
train
ekyna/PayumMonetico
src/Api/Api.php
Api.htmlEncode
private function htmlEncode($data) { if (empty($data)) { return null; } $safeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._-"; $result = ""; for ($i = 0; $i < strlen($data); $i++) { if (strstr($safeChars, $data[$i])) { $result .= $data[$i]; } else if ("7F" >= $var = bin2hex(substr($data, $i, 1))) { $result .= "&#x" . $var . ";"; } else { $result .= $data[$i]; } } return $result; }
php
private function htmlEncode($data) { if (empty($data)) { return null; } $safeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._-"; $result = ""; for ($i = 0; $i < strlen($data); $i++) { if (strstr($safeChars, $data[$i])) { $result .= $data[$i]; } else if ("7F" >= $var = bin2hex(substr($data, $i, 1))) { $result .= "&#x" . $var . ";"; } else { $result .= $data[$i]; } } return $result; }
[ "private", "function", "htmlEncode", "(", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "null", ";", "}", "$", "safeChars", "=", "\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._-\"", ";", "$", "result", ...
Encode html string. @param string $data @return string
[ "Encode", "html", "string", "." ]
1251ab0166a79c6dc6424005e8e8eb85227db361
https://github.com/ekyna/PayumMonetico/blob/1251ab0166a79c6dc6424005e8e8eb85227db361/src/Api/Api.php#L261-L281
train
grom358/pharborist
src/ArrayLookupNode.php
ArrayLookupNode.create
public static function create(ExpressionNode $array, ExpressionNode $key) { $node = new static(); /** @var Node $array */ $node->addChild($array, 'array'); $node->addChild(Token::openBracket()); /** @var Node $key */ $node->addChild($key, 'key'); $node->addChild(Token::closeBracket()); return $node; }
php
public static function create(ExpressionNode $array, ExpressionNode $key) { $node = new static(); /** @var Node $array */ $node->addChild($array, 'array'); $node->addChild(Token::openBracket()); /** @var Node $key */ $node->addChild($key, 'key'); $node->addChild(Token::closeBracket()); return $node; }
[ "public", "static", "function", "create", "(", "ExpressionNode", "$", "array", ",", "ExpressionNode", "$", "key", ")", "{", "$", "node", "=", "new", "static", "(", ")", ";", "/** @var Node $array */", "$", "node", "->", "addChild", "(", "$", "array", ",", ...
Creates a new array lookup. @param \Pharborist\ExpressionNode $array The expression representing the array (usually a VariableNode). @param \Pharborist\ExpressionNode $key The expression representing the key (usually a string). @return static
[ "Creates", "a", "new", "array", "lookup", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/ArrayLookupNode.php#L33-L42
train
grom358/pharborist
src/ArrayLookupNode.php
ArrayLookupNode.getKey
public function getKey($index = 0) { $keys = $this->getKeys(); if (!is_integer($index)) { throw new \InvalidArgumentException(); } if ($index < 0 || $index >= count($keys)) { throw new \OutOfBoundsException(); } return $keys[$index]; }
php
public function getKey($index = 0) { $keys = $this->getKeys(); if (!is_integer($index)) { throw new \InvalidArgumentException(); } if ($index < 0 || $index >= count($keys)) { throw new \OutOfBoundsException(); } return $keys[$index]; }
[ "public", "function", "getKey", "(", "$", "index", "=", "0", ")", "{", "$", "keys", "=", "$", "this", "->", "getKeys", "(", ")", ";", "if", "(", "!", "is_integer", "(", "$", "index", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", ...
Returns a specific key in the lookup. @param integer $index The index of the key to return. @return \Pharborist\Node @throws \InvalidArgumentException if $index is not an integer. \OutOfBoundsException if $index is less than zero or greater than the number of keys in the lookup.
[ "Returns", "a", "specific", "key", "in", "the", "lookup", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/ArrayLookupNode.php#L80-L90
train
johnhearfield/flarum-ext-oauth-google
src/Listener/AddClientAssets.php
AddClientAssets.addLocales
public function addLocales(ConfigureLocales $event) { foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) { if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) { $event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname()); } } }
php
public function addLocales(ConfigureLocales $event) { foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) { if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) { $event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname()); } } }
[ "public", "function", "addLocales", "(", "ConfigureLocales", "$", "event", ")", "{", "foreach", "(", "new", "DirectoryIterator", "(", "__DIR__", ".", "'/../../locale'", ")", "as", "$", "file", ")", "{", "if", "(", "$", "file", "->", "isFile", "(", ")", "...
Provides i18n files. @param ConfigureLocales $event
[ "Provides", "i18n", "files", "." ]
6cae0e3f6d5ab1d0e5d86e645c99608cbf493271
https://github.com/johnhearfield/flarum-ext-oauth-google/blob/6cae0e3f6d5ab1d0e5d86e645c99608cbf493271/src/Listener/AddClientAssets.php#L47-L54
train
thelia/core
lib/Thelia/Form/ModuleInstallForm.php
ModuleInstallForm.checkModuleValidity
public function checkModuleValidity(UploadedFile $file, ExecutionContextInterface $context) { $modulePath = $this->unzipModule($file); if ($modulePath !== false) { try { // get the first directory $moduleFiles = $this->getDirContents($modulePath); if (\count($moduleFiles['directories']) !== 1) { throw new Exception( Translator::getInstance()->trans( "Your zip must contain 1 root directory which is the root folder directory of your module" ) ); } $moduleDirectory = $moduleFiles['directories'][0]; $this->modulePath = sprintf('%s/%s', $modulePath, $moduleDirectory); $moduleValidator = new ModuleValidator($this->modulePath); $moduleValidator->validate(); $this->moduleDefinition = $moduleValidator->getModuleDefinition(); } catch (Exception $ex) { $context->addViolation( Translator::getInstance()->trans( "The module is not valid : %message", ['%message' => $ex->getMessage()] ) ); } } }
php
public function checkModuleValidity(UploadedFile $file, ExecutionContextInterface $context) { $modulePath = $this->unzipModule($file); if ($modulePath !== false) { try { // get the first directory $moduleFiles = $this->getDirContents($modulePath); if (\count($moduleFiles['directories']) !== 1) { throw new Exception( Translator::getInstance()->trans( "Your zip must contain 1 root directory which is the root folder directory of your module" ) ); } $moduleDirectory = $moduleFiles['directories'][0]; $this->modulePath = sprintf('%s/%s', $modulePath, $moduleDirectory); $moduleValidator = new ModuleValidator($this->modulePath); $moduleValidator->validate(); $this->moduleDefinition = $moduleValidator->getModuleDefinition(); } catch (Exception $ex) { $context->addViolation( Translator::getInstance()->trans( "The module is not valid : %message", ['%message' => $ex->getMessage()] ) ); } } }
[ "public", "function", "checkModuleValidity", "(", "UploadedFile", "$", "file", ",", "ExecutionContextInterface", "$", "context", ")", "{", "$", "modulePath", "=", "$", "this", "->", "unzipModule", "(", "$", "file", ")", ";", "if", "(", "$", "modulePath", "!=...
Check module validity @param UploadedFile $file @param ExecutionContextInterface $context
[ "Check", "module", "validity" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Form/ModuleInstallForm.php#L73-L107
train
thelia/core
lib/Thelia/Form/ModuleInstallForm.php
ModuleInstallForm.unzipModule
protected function unzipModule(UploadedFile $file) { $extractPath = false; $zip = new ZipArchiver(true); if (!$zip->open($file->getRealPath())) { throw new \Exception("unable to open zipfile"); } $extractPath = $this->tempdir(); if ($extractPath !== false) { if ($zip->extract($extractPath) === false) { $extractPath = false; } } $zip->close(); return $extractPath; }
php
protected function unzipModule(UploadedFile $file) { $extractPath = false; $zip = new ZipArchiver(true); if (!$zip->open($file->getRealPath())) { throw new \Exception("unable to open zipfile"); } $extractPath = $this->tempdir(); if ($extractPath !== false) { if ($zip->extract($extractPath) === false) { $extractPath = false; } } $zip->close(); return $extractPath; }
[ "protected", "function", "unzipModule", "(", "UploadedFile", "$", "file", ")", "{", "$", "extractPath", "=", "false", ";", "$", "zip", "=", "new", "ZipArchiver", "(", "true", ")", ";", "if", "(", "!", "$", "zip", "->", "open", "(", "$", "file", "->",...
Unzip a module file. @param UploadedFile $file @return string|bool the path where the module has been extracted or false if an error has occured
[ "Unzip", "a", "module", "file", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Form/ModuleInstallForm.php#L129-L148
train
thelia/core
lib/Thelia/Form/ModuleInstallForm.php
ModuleInstallForm.tempdir
protected function tempdir() { $tempfile = tempnam(sys_get_temp_dir(), ''); if (file_exists($tempfile)) { unlink($tempfile); } mkdir($tempfile); if (is_dir($tempfile)) { return $tempfile; } return false; }
php
protected function tempdir() { $tempfile = tempnam(sys_get_temp_dir(), ''); if (file_exists($tempfile)) { unlink($tempfile); } mkdir($tempfile); if (is_dir($tempfile)) { return $tempfile; } return false; }
[ "protected", "function", "tempdir", "(", ")", "{", "$", "tempfile", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "''", ")", ";", "if", "(", "file_exists", "(", "$", "tempfile", ")", ")", "{", "unlink", "(", "$", "tempfile", ")", ";", "}", ...
create a unique directory. @return bool|string the directory path or false if it fails
[ "create", "a", "unique", "directory", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Form/ModuleInstallForm.php#L155-L167
train
grom358/pharborist
src/Types/FalseNode.php
FalseNode.create
public static function create($boolean = FALSE) { $is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper'); $node = new FalseNode(); $node->addChild(NameNode::create($is_upper ? 'FALSE' : 'false'), 'constantName'); return $node; }
php
public static function create($boolean = FALSE) { $is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper'); $node = new FalseNode(); $node->addChild(NameNode::create($is_upper ? 'FALSE' : 'false'), 'constantName'); return $node; }
[ "public", "static", "function", "create", "(", "$", "boolean", "=", "FALSE", ")", "{", "$", "is_upper", "=", "FormatterFactory", "::", "getDefaultFormatter", "(", ")", "->", "getConfig", "(", "'boolean_null_upper'", ")", ";", "$", "node", "=", "new", "FalseN...
Creates a new FalseNode. @param boolean $boolean Parameter is ignored. @return FalseNode
[ "Creates", "a", "new", "FalseNode", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/Types/FalseNode.php#L22-L27
train
grom358/pharborist
src/Functions/CallNode.php
CallNode.appendMethodCall
public function appendMethodCall($method_name) { $method_call = ObjectMethodCallNode::create(clone $this, $method_name); $this->replaceWith($method_call); return $method_call; }
php
public function appendMethodCall($method_name) { $method_call = ObjectMethodCallNode::create(clone $this, $method_name); $this->replaceWith($method_call); return $method_call; }
[ "public", "function", "appendMethodCall", "(", "$", "method_name", ")", "{", "$", "method_call", "=", "ObjectMethodCallNode", "::", "create", "(", "clone", "$", "this", ",", "$", "method_name", ")", ";", "$", "this", "->", "replaceWith", "(", "$", "method_ca...
Allows you to append a method call to this one, building a chain of method calls. For example: ``` // \Drupal::entityManager() $classCall = ClassMethodCallNode::create('\Drupal', 'entityManager'); $methodCall = $classCall->appendMethodCall('getDefinitions'); echo $methodCall->getText(); // \Drupal::entityManager()->getDefinitions() echo $methodCall->getObject(); // \Drupal::entityManager() echo $methodCall->getMethodName(); // getDefinitions // You can chain yet another call, and keep going as long as you want. $methodCall = $methodCall->appendMethodCall('clearCache') echo $methodCall->getText(); // \Drupal::entityManager()->getDefinitions()->clearCache() // These methods are chainable themselves, so you can build an entire call chain // in one fell swoop. $chain = ClassMethodCallNode::create('Foo', 'bar')->appendMethodCall('baz')->appendMethodCall('zorg'); echo $chain->getText(); // Foo::bar()->baz()->zorg() ``` @param string $method_name The name of the method to call. @return \Pharborist\Objects\ObjectMethodCallNode The newly-created method call, in which every previous part of the chain will be the "object", and $method_name will be the "method". The call will be created without arguments, but you can add some using appendArgument().
[ "Allows", "you", "to", "append", "a", "method", "call", "to", "this", "one", "building", "a", "chain", "of", "method", "calls", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/Functions/CallNode.php#L56-L60
train
thelia/core
lib/Thelia/Model/Folder.php
Folder.countAllContents
public function countAllContents($contentVisibility = true) { $children = FolderQuery::findAllChild($this->getId()); array_push($children, $this); $query = ContentQuery::create()->filterByFolder(new ObjectCollection($children), Criteria::IN); if ($contentVisibility !== '*') { $query->filterByVisible($contentVisibility); } return $query->count(); }
php
public function countAllContents($contentVisibility = true) { $children = FolderQuery::findAllChild($this->getId()); array_push($children, $this); $query = ContentQuery::create()->filterByFolder(new ObjectCollection($children), Criteria::IN); if ($contentVisibility !== '*') { $query->filterByVisible($contentVisibility); } return $query->count(); }
[ "public", "function", "countAllContents", "(", "$", "contentVisibility", "=", "true", ")", "{", "$", "children", "=", "FolderQuery", "::", "findAllChild", "(", "$", "this", "->", "getId", "(", ")", ")", ";", "array_push", "(", "$", "children", ",", "$", ...
count all products for current category and sub categories @param bool|string $contentVisibility: true (default) to count only visible products, false to count only hidden products, or * to count all products. @return int
[ "count", "all", "products", "for", "current", "category", "and", "sub", "categories" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Folder.php#L47-L60
train
thelia/core
lib/Thelia/Model/Folder.php
Folder.getRoot
public function getRoot($folderId) { $folder = FolderQuery::create()->findPk($folderId); if (0 !== $folder->getParent()) { $parentFolder = FolderQuery::create()->findPk($folder->getParent()); if (null !== $parentFolder) { $folderId = $this->getRoot($parentFolder->getId()); } } return $folderId; }
php
public function getRoot($folderId) { $folder = FolderQuery::create()->findPk($folderId); if (0 !== $folder->getParent()) { $parentFolder = FolderQuery::create()->findPk($folder->getParent()); if (null !== $parentFolder) { $folderId = $this->getRoot($parentFolder->getId()); } } return $folderId; }
[ "public", "function", "getRoot", "(", "$", "folderId", ")", "{", "$", "folder", "=", "FolderQuery", "::", "create", "(", ")", "->", "findPk", "(", "$", "folderId", ")", ";", "if", "(", "0", "!==", "$", "folder", "->", "getParent", "(", ")", ")", "{...
Get the root folder @param int $folderId @return mixed
[ "Get", "the", "root", "folder" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Folder.php#L67-L80
train
thelia/core
lib/Thelia/Core/PropelInitService.php
PropelInitService.runCommand
public function runCommand(Command $command, array $parameters = [], OutputInterface $output = null) { $parameters['command'] = $command->getName(); $input = new ArrayInput($parameters); if ($output === null) { $output = new NullOutput(); } $command->setApplication(new SymfonyConsoleApplication()); return $command->run($input, $output); }
php
public function runCommand(Command $command, array $parameters = [], OutputInterface $output = null) { $parameters['command'] = $command->getName(); $input = new ArrayInput($parameters); if ($output === null) { $output = new NullOutput(); } $command->setApplication(new SymfonyConsoleApplication()); return $command->run($input, $output); }
[ "public", "function", "runCommand", "(", "Command", "$", "command", ",", "array", "$", "parameters", "=", "[", "]", ",", "OutputInterface", "$", "output", "=", "null", ")", "{", "$", "parameters", "[", "'command'", "]", "=", "$", "command", "->", "getNam...
Run a Propel command. @param Command $command Command to run. @param array $parameters Command parameters. @param OutputInterface|null $output Command output. @return int Command exit code. @throws \Exception
[ "Run", "a", "Propel", "command", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/PropelInitService.php#L161-L173
train
thelia/core
lib/Thelia/Core/PropelInitService.php
PropelInitService.buildPropelConfig
public function buildPropelConfig() { $propelConfigCache = new ConfigCache( $this->getPropelConfigFile(), $this->debug ); if ($propelConfigCache->isFresh()) { return; } $configService = new DatabaseConfigurationSource( Yaml::parse(file_get_contents($this->getTheliaDatabaseConfigFile())), $this->envParameters ); $propelConfig = $configService->getPropelConnectionsConfiguration(); $propelConfig['propel']['paths']['phpDir'] = THELIA_ROOT; $propelConfig['propel']['generator']['objectModel']['builders'] = [ 'object' => '\Thelia\Core\Propel\Generator\Builder\Om\ObjectBuilder', 'objectstub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionObjectBuilder', 'objectmultiextend' => '\Thelia\Core\Propel\Generator\Builder\Om\MultiExtendObjectBuilder', 'query' => '\Thelia\Core\Propel\Generator\Builder\Om\QueryBuilder', 'querystub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryBuilder', 'queryinheritance' => '\Thelia\Core\Propel\Generator\Builder\Om\QueryInheritanceBuilder', 'queryinheritancestub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryInheritanceBuilder', 'tablemap' => '\Thelia\Core\Propel\Generator\Builder\Om\TableMapBuilder', 'event' => '\Thelia\Core\Propel\Generator\Builder\Om\EventBuilder', ]; $propelConfigCache->write( Yaml::dump($propelConfig), [new FileResource($this->getTheliaDatabaseConfigFile())] ); }
php
public function buildPropelConfig() { $propelConfigCache = new ConfigCache( $this->getPropelConfigFile(), $this->debug ); if ($propelConfigCache->isFresh()) { return; } $configService = new DatabaseConfigurationSource( Yaml::parse(file_get_contents($this->getTheliaDatabaseConfigFile())), $this->envParameters ); $propelConfig = $configService->getPropelConnectionsConfiguration(); $propelConfig['propel']['paths']['phpDir'] = THELIA_ROOT; $propelConfig['propel']['generator']['objectModel']['builders'] = [ 'object' => '\Thelia\Core\Propel\Generator\Builder\Om\ObjectBuilder', 'objectstub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionObjectBuilder', 'objectmultiextend' => '\Thelia\Core\Propel\Generator\Builder\Om\MultiExtendObjectBuilder', 'query' => '\Thelia\Core\Propel\Generator\Builder\Om\QueryBuilder', 'querystub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryBuilder', 'queryinheritance' => '\Thelia\Core\Propel\Generator\Builder\Om\QueryInheritanceBuilder', 'queryinheritancestub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryInheritanceBuilder', 'tablemap' => '\Thelia\Core\Propel\Generator\Builder\Om\TableMapBuilder', 'event' => '\Thelia\Core\Propel\Generator\Builder\Om\EventBuilder', ]; $propelConfigCache->write( Yaml::dump($propelConfig), [new FileResource($this->getTheliaDatabaseConfigFile())] ); }
[ "public", "function", "buildPropelConfig", "(", ")", "{", "$", "propelConfigCache", "=", "new", "ConfigCache", "(", "$", "this", "->", "getPropelConfigFile", "(", ")", ",", "$", "this", "->", "debug", ")", ";", "if", "(", "$", "propelConfigCache", "->", "i...
Generate the Propel configuration file.
[ "Generate", "the", "Propel", "configuration", "file", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/PropelInitService.php#L178-L222
train
thelia/core
lib/Thelia/Core/PropelInitService.php
PropelInitService.buildPropelInitFile
public function buildPropelInitFile() { $propelInitCache = new ConfigCache( $this->getPropelInitFile(), $this->debug ); if ($propelInitCache->isFresh()) { return; } $this->runCommand( new ConfigConvertCommand(), [ '--config-dir' => $this->getPropelConfigDir(), '--output-dir' => $this->getPropelConfigDir(), '--output-file' => static::$PROPEL_CONFIG_CACHE_FILENAME, ] ); // rewrite the file as a cached file $propelInitContent = file_get_contents($this->getPropelInitFile()); $propelInitCache->write( $propelInitContent, [new FileResource($this->getPropelConfigFile())] ); }
php
public function buildPropelInitFile() { $propelInitCache = new ConfigCache( $this->getPropelInitFile(), $this->debug ); if ($propelInitCache->isFresh()) { return; } $this->runCommand( new ConfigConvertCommand(), [ '--config-dir' => $this->getPropelConfigDir(), '--output-dir' => $this->getPropelConfigDir(), '--output-file' => static::$PROPEL_CONFIG_CACHE_FILENAME, ] ); // rewrite the file as a cached file $propelInitContent = file_get_contents($this->getPropelInitFile()); $propelInitCache->write( $propelInitContent, [new FileResource($this->getPropelConfigFile())] ); }
[ "public", "function", "buildPropelInitFile", "(", ")", "{", "$", "propelInitCache", "=", "new", "ConfigCache", "(", "$", "this", "->", "getPropelInitFile", "(", ")", ",", "$", "this", "->", "debug", ")", ";", "if", "(", "$", "propelInitCache", "->", "isFre...
Generate the Propel initialization file. @throws \Exception
[ "Generate", "the", "Propel", "initialization", "file", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/PropelInitService.php#L228-L254
train
thelia/core
lib/Thelia/Core/PropelInitService.php
PropelInitService.buildPropelModels
public function buildPropelModels() { $fs = new Filesystem(); // cache testing if ($fs->exists($this->getPropelModelDir() . 'hash') && file_get_contents($this->getPropelCacheDir() . 'hash') === file_get_contents($this->getPropelModelDir() . 'hash')) { return; } $fs->remove($this->getPropelModelDir()); $this->runCommand( new ModelBuildCommand(), [ '--config-dir' => $this->getPropelConfigDir(), '--schema-dir' => $this->getPropelSchemaDir(), ] ); $fs->copy( $this->getPropelCacheDir() . 'hash', $this->getPropelModelDir() . 'hash' ); }
php
public function buildPropelModels() { $fs = new Filesystem(); // cache testing if ($fs->exists($this->getPropelModelDir() . 'hash') && file_get_contents($this->getPropelCacheDir() . 'hash') === file_get_contents($this->getPropelModelDir() . 'hash')) { return; } $fs->remove($this->getPropelModelDir()); $this->runCommand( new ModelBuildCommand(), [ '--config-dir' => $this->getPropelConfigDir(), '--schema-dir' => $this->getPropelSchemaDir(), ] ); $fs->copy( $this->getPropelCacheDir() . 'hash', $this->getPropelModelDir() . 'hash' ); }
[ "public", "function", "buildPropelModels", "(", ")", "{", "$", "fs", "=", "new", "Filesystem", "(", ")", ";", "// cache testing", "if", "(", "$", "fs", "->", "exists", "(", "$", "this", "->", "getPropelModelDir", "(", ")", ".", "'hash'", ")", "&&", "fi...
Generate the base Propel models. @throws \Exception
[ "Generate", "the", "base", "Propel", "models", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/PropelInitService.php#L302-L326
train
thelia/core
lib/Thelia/Core/PropelInitService.php
PropelInitService.registerPropelModelLoader
public function registerPropelModelLoader() { $loader = new ClassLoader(); $loader->addPrefix( '', // no prefix, models already define their full namespace $this->getPropelModelDir() ); $loader->register( true // prepend the autoloader to use cached models first ); }
php
public function registerPropelModelLoader() { $loader = new ClassLoader(); $loader->addPrefix( '', // no prefix, models already define their full namespace $this->getPropelModelDir() ); $loader->register( true // prepend the autoloader to use cached models first ); }
[ "public", "function", "registerPropelModelLoader", "(", ")", "{", "$", "loader", "=", "new", "ClassLoader", "(", ")", ";", "$", "loader", "->", "addPrefix", "(", "''", ",", "// no prefix, models already define their full namespace", "$", "this", "->", "getPropelMode...
Register a class loader to load the generated Propel models.
[ "Register", "a", "class", "loader", "to", "load", "the", "generated", "Propel", "models", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/PropelInitService.php#L331-L343
train
thelia/core
lib/Thelia/Core/PropelInitService.php
PropelInitService.init
public function init($force = false) { $flockFactory = new Factory(new FlockStore()); $lock = $flockFactory->createLock('propel-cache-generation'); // Acquire a blocking cache generation lock $lock->acquire(true); try { if ($force) { (new Filesystem())->remove($this->getPropelCacheDir()); } if (!file_exists($this->getTheliaDatabaseConfigFile())) { return false; } $this->buildPropelConfig(); $this->buildPropelInitFile(); require $this->getPropelInitFile(); $theliaDatabaseConnection = Propel::getConnection('thelia'); $this->schemaLocator->setTheliaDatabaseConnection($theliaDatabaseConnection); $this->buildPropelGlobalSchema(); $this->buildPropelModels(); $this->registerPropelModelLoader(); $theliaDatabaseConnection->setAttribute(ConnectionWrapper::PROPEL_ATTR_CACHE_PREPARES, true); if ($this->debug) { // In debug mode, we have to initialize Tlog at this point, as this class uses Propel Tlog::getInstance()->setLevel(Tlog::DEBUG); Propel::getServiceContainer()->setLogger('defaultLogger', Tlog::getInstance()); $theliaDatabaseConnection->useDebug(true); } } catch (\Throwable $th) { $fs = new Filesystem(); $fs->remove(THELIA_CACHE_DIR . $this->environment); $fs->remove($this->getPropelModelDir()); throw $th; } finally { // Release cache generation lock $lock->release(); } return true; }
php
public function init($force = false) { $flockFactory = new Factory(new FlockStore()); $lock = $flockFactory->createLock('propel-cache-generation'); // Acquire a blocking cache generation lock $lock->acquire(true); try { if ($force) { (new Filesystem())->remove($this->getPropelCacheDir()); } if (!file_exists($this->getTheliaDatabaseConfigFile())) { return false; } $this->buildPropelConfig(); $this->buildPropelInitFile(); require $this->getPropelInitFile(); $theliaDatabaseConnection = Propel::getConnection('thelia'); $this->schemaLocator->setTheliaDatabaseConnection($theliaDatabaseConnection); $this->buildPropelGlobalSchema(); $this->buildPropelModels(); $this->registerPropelModelLoader(); $theliaDatabaseConnection->setAttribute(ConnectionWrapper::PROPEL_ATTR_CACHE_PREPARES, true); if ($this->debug) { // In debug mode, we have to initialize Tlog at this point, as this class uses Propel Tlog::getInstance()->setLevel(Tlog::DEBUG); Propel::getServiceContainer()->setLogger('defaultLogger', Tlog::getInstance()); $theliaDatabaseConnection->useDebug(true); } } catch (\Throwable $th) { $fs = new Filesystem(); $fs->remove(THELIA_CACHE_DIR . $this->environment); $fs->remove($this->getPropelModelDir()); throw $th; } finally { // Release cache generation lock $lock->release(); } return true; }
[ "public", "function", "init", "(", "$", "force", "=", "false", ")", "{", "$", "flockFactory", "=", "new", "Factory", "(", "new", "FlockStore", "(", ")", ")", ";", "$", "lock", "=", "$", "flockFactory", "->", "createLock", "(", "'propel-cache-generation'", ...
Initialize the Propel environment and connection. @return bool Whether a Propel connection is available. @param bool $force force cache generation @throws \Throwable
[ "Initialize", "the", "Propel", "environment", "and", "connection", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/PropelInitService.php#L351-L402
train
nattreid/cms
src/DI/ModuleExtension.php
ModuleExtension.addLoaderFile
protected function addLoaderFile(string $file, string $locale = null): void { if ($this->loader === null) { $builder = $this->getContainerBuilder(); $loader = $builder->getByType(LoaderFactory::class); $this->loader = $builder->getDefinition($loader); } $this->loader->addSetup('addFile', [$file, $locale]); }
php
protected function addLoaderFile(string $file, string $locale = null): void { if ($this->loader === null) { $builder = $this->getContainerBuilder(); $loader = $builder->getByType(LoaderFactory::class); $this->loader = $builder->getDefinition($loader); } $this->loader->addSetup('addFile', [$file, $locale]); }
[ "protected", "function", "addLoaderFile", "(", "string", "$", "file", ",", "string", "$", "locale", "=", "null", ")", ":", "void", "{", "if", "(", "$", "this", "->", "loader", "===", "null", ")", "{", "$", "builder", "=", "$", "this", "->", "getConta...
Prida soubor do loaderu @param string $file @param string $locale
[ "Prida", "soubor", "do", "loaderu" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/src/DI/ModuleExtension.php#L98-L107
train
BoldGrid/library
src/Util/Load.php
Load.setLoad
public function setLoad( $libraries ) { $load = false; $product = false; foreach( $libraries as $name => $version ) { // Check for branch versions normalized (dev/master). if ( strpos( $version, 'dev' ) !== false ) { $load = $version; $product = $name; break; } // Check for highest loaded version. if ( version_compare( $load, $version ) === -1 ) { $load = $version; $product = $name; } } return $this->load = ( object ) array( 'product' => $product, 'version' => $load ); }
php
public function setLoad( $libraries ) { $load = false; $product = false; foreach( $libraries as $name => $version ) { // Check for branch versions normalized (dev/master). if ( strpos( $version, 'dev' ) !== false ) { $load = $version; $product = $name; break; } // Check for highest loaded version. if ( version_compare( $load, $version ) === -1 ) { $load = $version; $product = $name; } } return $this->load = ( object ) array( 'product' => $product, 'version' => $load ); }
[ "public", "function", "setLoad", "(", "$", "libraries", ")", "{", "$", "load", "=", "false", ";", "$", "product", "=", "false", ";", "foreach", "(", "$", "libraries", "as", "$", "name", "=>", "$", "version", ")", "{", "// Check for branch versions normaliz...
Sets the product and version of library to load. This check will loop through the available libraries and load the highest version found. If an active plugin or theme contains a git branch instead of a tagged version, then that library will be loaded instead. @since 1.0.0 @param array $libraries Registered library versions from options. @return object $load The product and version to load.
[ "Sets", "the", "product", "and", "version", "of", "library", "to", "load", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Load.php#L108-L128
train
BoldGrid/library
src/Util/Load.php
Load.setPath
public function setPath() { $found = $this->getLoad(); $path = false; if ( ! empty( $found->product ) ) { // Loading from must use plugin directory? if ( ! is_file( $path = trailingslashit( WPMU_PLUGIN_DIR ) . $found->product ) ) { // Loading from plugin directory? if ( ! is_file( $path = trailingslashit( WP_PLUGIN_DIR ) . $found->product ) ) { // Loading from a parent theme directory? $path = get_template_directory() . '/inc/boldgrid-theme-framework/includes/theme'; } } // Loading from framework path override directory? if ( defined( 'BGTFW_PATH' ) ) { $dir = ABSPATH . trim( BGTFW_PATH, '/' ) . '/includes'; if ( is_dir( $dir . '/vendor/boldgrid/library' ) ) { $path = $dir . '/theme'; } } $path = dirname( $path ); } return $this->path = $path; }
php
public function setPath() { $found = $this->getLoad(); $path = false; if ( ! empty( $found->product ) ) { // Loading from must use plugin directory? if ( ! is_file( $path = trailingslashit( WPMU_PLUGIN_DIR ) . $found->product ) ) { // Loading from plugin directory? if ( ! is_file( $path = trailingslashit( WP_PLUGIN_DIR ) . $found->product ) ) { // Loading from a parent theme directory? $path = get_template_directory() . '/inc/boldgrid-theme-framework/includes/theme'; } } // Loading from framework path override directory? if ( defined( 'BGTFW_PATH' ) ) { $dir = ABSPATH . trim( BGTFW_PATH, '/' ) . '/includes'; if ( is_dir( $dir . '/vendor/boldgrid/library' ) ) { $path = $dir . '/theme'; } } $path = dirname( $path ); } return $this->path = $path; }
[ "public", "function", "setPath", "(", ")", "{", "$", "found", "=", "$", "this", "->", "getLoad", "(", ")", ";", "$", "path", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "found", "->", "product", ")", ")", "{", "// Loading from must use plug...
Sets the path class property. This will determine the path to the found product's library to load. @since 1.0.0 @return string $path Path to the library to load.
[ "Sets", "the", "path", "class", "property", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Load.php#L139-L168
train
BoldGrid/library
src/Util/Load.php
Load.load
public function load( $loader ) { if ( ! empty( $this->configs['libraryDir'] ) ) { $library = $this->configs['libraryDir'] . 'src/Library'; // Only create a single instance of the BoldGrid Library Start. if ( did_action( 'Boldgrid\Library\Library\Start' ) === 0 ) { do_action( 'Boldgrid\Library\Library\Start', $library ); // Check dir and add PSR-4 dir of the BoldGrid Library to autoload. if ( is_dir( $library ) ) { $loader->addPsr4( 'Boldgrid\\Library\\Library\\', $library ); $load = new \Boldgrid\Library\Library\Start( $this->configs ); $load->init(); } } } }
php
public function load( $loader ) { if ( ! empty( $this->configs['libraryDir'] ) ) { $library = $this->configs['libraryDir'] . 'src/Library'; // Only create a single instance of the BoldGrid Library Start. if ( did_action( 'Boldgrid\Library\Library\Start' ) === 0 ) { do_action( 'Boldgrid\Library\Library\Start', $library ); // Check dir and add PSR-4 dir of the BoldGrid Library to autoload. if ( is_dir( $library ) ) { $loader->addPsr4( 'Boldgrid\\Library\\Library\\', $library ); $load = new \Boldgrid\Library\Library\Start( $this->configs ); $load->init(); } } } }
[ "public", "function", "load", "(", "$", "loader", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "configs", "[", "'libraryDir'", "]", ")", ")", "{", "$", "library", "=", "$", "this", "->", "configs", "[", "'libraryDir'", "]", ".", "'src...
Adds the Library paths to the autoloader. @since 1.0.0 @param object $loader Autoloader instance. @return null
[ "Adds", "the", "Library", "paths", "to", "the", "autoloader", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Load.php#L179-L195
train
nattreid/cms
src/Model/Locales/Locale.php
Locale.setDefault
public function setDefault(): void { $repo = $this->getRepository(); $locales = $repo->findAll(); foreach ($locales as $locale) { /* @var $locale self */ $locale->default = false; $repo->persist($locale); } $this->default = true; $repo->persist($this); $repo->flush(); }
php
public function setDefault(): void { $repo = $this->getRepository(); $locales = $repo->findAll(); foreach ($locales as $locale) { /* @var $locale self */ $locale->default = false; $repo->persist($locale); } $this->default = true; $repo->persist($this); $repo->flush(); }
[ "public", "function", "setDefault", "(", ")", ":", "void", "{", "$", "repo", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "locales", "=", "$", "repo", "->", "findAll", "(", ")", ";", "foreach", "(", "$", "locales", "as", "$", "local...
Nastavi na vychozi
[ "Nastavi", "na", "vychozi" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/src/Model/Locales/Locale.php#L24-L36
train
melisplatform/melis-cms
src/Controller/PageDuplicationController.php
PageDuplicationController.getOriginOfPageByPageIdAction
public function getOriginOfPageByPageIdAction() { $data = array(); $tool = $this->getServiceLocator()->get('MelisCmsPage'); $data = $tool->getOriginOfPage()->toArray(); return $data; }
php
public function getOriginOfPageByPageIdAction() { $data = array(); $tool = $this->getServiceLocator()->get('MelisCmsPage'); $data = $tool->getOriginOfPage()->toArray(); return $data; }
[ "public", "function", "getOriginOfPageByPageIdAction", "(", ")", "{", "$", "data", "=", "array", "(", ")", ";", "$", "tool", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "'MelisCmsPage'", ")", ";", "$", "data", "=", "$", "to...
Return the origin of the page by id return array
[ "Return", "the", "origin", "of", "the", "page", "by", "id" ]
ed470338f4c7653fd93e530013ab934eb7a52b6f
https://github.com/melisplatform/melis-cms/blob/ed470338f4c7653fd93e530013ab934eb7a52b6f/src/Controller/PageDuplicationController.php#L45-L53
train
thelia/core
lib/Thelia/Module/AbstractAdminResourcesCompiler.php
AbstractAdminResourcesCompiler.process
public function process(\Symfony\Component\DependencyInjection\ContainerBuilder $container) { if (!$container->hasDefinition("thelia.admin.resources")) { return; } /** @var \Symfony\Component\DependencyInjection\Definition $adminResources */ $adminResources = $container->getDefinition("thelia.admin.resources"); $adminResources->addMethodCall("addModuleResources", [$this->getResources(), $this->getModuleCode()]); }
php
public function process(\Symfony\Component\DependencyInjection\ContainerBuilder $container) { if (!$container->hasDefinition("thelia.admin.resources")) { return; } /** @var \Symfony\Component\DependencyInjection\Definition $adminResources */ $adminResources = $container->getDefinition("thelia.admin.resources"); $adminResources->addMethodCall("addModuleResources", [$this->getResources(), $this->getModuleCode()]); }
[ "public", "function", "process", "(", "\\", "Symfony", "\\", "Component", "\\", "DependencyInjection", "\\", "ContainerBuilder", "$", "container", ")", "{", "if", "(", "!", "$", "container", "->", "hasDefinition", "(", "\"thelia.admin.resources\"", ")", ")", "{"...
Allow module to add resources in AdminResources Service @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
[ "Allow", "module", "to", "add", "resources", "in", "AdminResources", "Service" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Module/AbstractAdminResourcesCompiler.php#L45-L55
train
thelia/core
lib/Thelia/ImportExport/Import/AbstractImport.php
AbstractImport.checkMandatoryColumns
public function checkMandatoryColumns(array $data) { $diff = array_diff($this->mandatoryColumns, array_keys($data)); if (\count($diff) > 0) { throw new \UnexpectedValueException( Translator::getInstance()->trans( 'The following columns are missing: %columns', [ '%columns' => implode(', ', $diff) ] ) ); } }
php
public function checkMandatoryColumns(array $data) { $diff = array_diff($this->mandatoryColumns, array_keys($data)); if (\count($diff) > 0) { throw new \UnexpectedValueException( Translator::getInstance()->trans( 'The following columns are missing: %columns', [ '%columns' => implode(', ', $diff) ] ) ); } }
[ "public", "function", "checkMandatoryColumns", "(", "array", "$", "data", ")", "{", "$", "diff", "=", "array_diff", "(", "$", "this", "->", "mandatoryColumns", ",", "array_keys", "(", "$", "data", ")", ")", ";", "if", "(", "\\", "count", "(", "$", "dif...
Check mandatory columns @param array $data Data @return boolean Data contains mandatory columns or not
[ "Check", "mandatory", "columns" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/ImportExport/Import/AbstractImport.php#L160-L174
train
thelia/core
lib/Thelia/ImportExport/Export/AbstractExport.php
AbstractExport.applyOrderAndAliases
public function applyOrderAndAliases(array $data) { if ($this->orderAndAliases === null) { return $data; } $processedData = []; foreach ($this->orderAndAliases as $key => $value) { if (\is_integer($key)) { $fieldName = $value; $fieldAlias = $value; } else { $fieldName = $key; $fieldAlias = $value; } $processedData[$fieldAlias] = null; if (array_key_exists($fieldName, $data)) { $processedData[$fieldAlias] = $data[$fieldName]; } } return $processedData; }
php
public function applyOrderAndAliases(array $data) { if ($this->orderAndAliases === null) { return $data; } $processedData = []; foreach ($this->orderAndAliases as $key => $value) { if (\is_integer($key)) { $fieldName = $value; $fieldAlias = $value; } else { $fieldName = $key; $fieldAlias = $value; } $processedData[$fieldAlias] = null; if (array_key_exists($fieldName, $data)) { $processedData[$fieldAlias] = $data[$fieldName]; } } return $processedData; }
[ "public", "function", "applyOrderAndAliases", "(", "array", "$", "data", ")", "{", "if", "(", "$", "this", "->", "orderAndAliases", "===", "null", ")", "{", "return", "$", "data", ";", "}", "$", "processedData", "=", "[", "]", ";", "foreach", "(", "$",...
Apply order and aliases on data @param array $data Raw data @return array Ordered and aliased data
[ "Apply", "order", "and", "aliases", "on", "data" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/ImportExport/Export/AbstractExport.php#L404-L428
train
thelia/core
lib/Thelia/ImportExport/Export/AbstractExport.php
AbstractExport.beforeSerialize
public function beforeSerialize(array $data) { foreach ($data as $idx => &$value) { if ($value instanceof \DateTime) { $value = $value->format('Y-m-d H:i:s'); } } return $data; }
php
public function beforeSerialize(array $data) { foreach ($data as $idx => &$value) { if ($value instanceof \DateTime) { $value = $value->format('Y-m-d H:i:s'); } } return $data; }
[ "public", "function", "beforeSerialize", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "idx", "=>", "&", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "\\", "DateTime", ")", "{", "$", "value", "=", "$...
Process data before serialization @param array $data Data before serialization @return array Processed data before serialization
[ "Process", "data", "before", "serialization" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/ImportExport/Export/AbstractExport.php#L437-L446
train
BoldGrid/library
src/Library/Filter.php
Filter.doFilter
private static function doFilter( $action, $class ) { $reflection = new \ReflectionClass( $class ); foreach ( $reflection->getMethods() as $method ) { if ( $method->isPublic() && ! $method->isConstructor() ) { $comment = $method->getDocComment(); // No hooks. if ( preg_match( '/@nohook[ \t\*\n]+/', $comment ) ) { continue; } // Set hook. preg_match_all( '/@hook:?\s+([^\s]+)/', $comment, $matches ) ? $matches[1] : $method->name; if ( empty( $matches[1] ) ) { $hooks = array( $method->name ); } else { $hooks = $matches[1]; } // Allow setting priority. $priority = preg_match( '/@priority:?\s+(\d+)/', $comment, $matches ) ? $matches[1] : 10; // Fire. foreach ( $hooks as $hook ) { call_user_func( $action, $hook, array( $class, $method->name ), $priority, $method->getNumberOfParameters() ); } } } }
php
private static function doFilter( $action, $class ) { $reflection = new \ReflectionClass( $class ); foreach ( $reflection->getMethods() as $method ) { if ( $method->isPublic() && ! $method->isConstructor() ) { $comment = $method->getDocComment(); // No hooks. if ( preg_match( '/@nohook[ \t\*\n]+/', $comment ) ) { continue; } // Set hook. preg_match_all( '/@hook:?\s+([^\s]+)/', $comment, $matches ) ? $matches[1] : $method->name; if ( empty( $matches[1] ) ) { $hooks = array( $method->name ); } else { $hooks = $matches[1]; } // Allow setting priority. $priority = preg_match( '/@priority:?\s+(\d+)/', $comment, $matches ) ? $matches[1] : 10; // Fire. foreach ( $hooks as $hook ) { call_user_func( $action, $hook, array( $class, $method->name ), $priority, $method->getNumberOfParameters() ); } } } }
[ "private", "static", "function", "doFilter", "(", "$", "action", ",", "$", "class", ")", "{", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "foreach", "(", "$", "reflection", "->", "getMethods", "(", ")", "as", "$...
Process hooks. This sets up our automatic filter binding. @since 1.0.0 @param string $action Action name. @param string $class Class name. @return null
[ "Process", "hooks", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Filter.php#L62-L90
train
BoldGrid/library
src/Library/Filter.php
Filter.removeHook
public static function removeHook( $tag, $class, $name, $priority = 10 ) { global $wp_filter; // Check that filter exists. if ( isset( $wp_filter[ $tag ] ) ) { /** * If filter config is an object, means we're using WordPress 4.7+ and the config is no longer * a simple array, and it is an object that implements the ArrayAccess interface. * * To be backwards compatible, we set $callbacks equal to the correct array as a reference (so $wp_filter is updated). * * @see https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/ */ if ( is_object( $wp_filter[ $tag ] ) && isset( $wp_filter[ $tag ]->callbacks ) ) { // Create $fob object from filter tag, to use below. $fob = $wp_filter[ $tag ]; $callbacks = &$wp_filter[ $tag ]->callbacks; } else { $callbacks = &$wp_filter[ $tag ]; } // Exit if there aren't any callbacks for specified priority. if ( ! isset( $callbacks[ $priority ] ) || empty( $callbacks[ $priority ] ) ) { return false; } // Loop through each filter for the specified priority, looking for our class & method. foreach( ( array ) $callbacks[ $priority ] as $filter_id => $filter ) { // Filter should always be an array - array( $this, 'method' ), if not goto next. if ( ! isset( $filter['function'] ) || ! is_array( $filter['function'] ) ) { continue; } // If first value in array is not an object, it can't be a class. if ( ! is_object( $filter['function'][0] ) ) { continue; } // Method doesn't match the one we're looking for, goto next. if ( $filter['function'][1] !== $name ) { continue; } // Callback method matched, so check class. if ( get_class( $filter['function'][0] ) === $class ) { // WordPress 4.7+ use core remove_filter() since we found the class object. if ( isset( $fob ) ) { // Handles removing filter, reseting callback priority keys mid-iteration, etc. $fob->remove_filter( $tag, $filter['function'], $priority ); } else { // Use legacy removal process (pre 4.7). unset( $callbacks[ $priority ][ $filter_id ] ); // If it was the only filter in that priority, unset that priority. if ( empty( $callbacks[ $priority ] ) ) { unset( $callbacks[ $priority ] ); } // If the only filter for that tag, set the tag to an empty array. if ( empty( $callbacks ) ) { $callbacks = array(); } // Remove this filter from merged_filters, which specifies if filters have been sorted. unset( $GLOBALS['merged_filters'][ $tag ] ); } return true; } } } return false; }
php
public static function removeHook( $tag, $class, $name, $priority = 10 ) { global $wp_filter; // Check that filter exists. if ( isset( $wp_filter[ $tag ] ) ) { /** * If filter config is an object, means we're using WordPress 4.7+ and the config is no longer * a simple array, and it is an object that implements the ArrayAccess interface. * * To be backwards compatible, we set $callbacks equal to the correct array as a reference (so $wp_filter is updated). * * @see https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/ */ if ( is_object( $wp_filter[ $tag ] ) && isset( $wp_filter[ $tag ]->callbacks ) ) { // Create $fob object from filter tag, to use below. $fob = $wp_filter[ $tag ]; $callbacks = &$wp_filter[ $tag ]->callbacks; } else { $callbacks = &$wp_filter[ $tag ]; } // Exit if there aren't any callbacks for specified priority. if ( ! isset( $callbacks[ $priority ] ) || empty( $callbacks[ $priority ] ) ) { return false; } // Loop through each filter for the specified priority, looking for our class & method. foreach( ( array ) $callbacks[ $priority ] as $filter_id => $filter ) { // Filter should always be an array - array( $this, 'method' ), if not goto next. if ( ! isset( $filter['function'] ) || ! is_array( $filter['function'] ) ) { continue; } // If first value in array is not an object, it can't be a class. if ( ! is_object( $filter['function'][0] ) ) { continue; } // Method doesn't match the one we're looking for, goto next. if ( $filter['function'][1] !== $name ) { continue; } // Callback method matched, so check class. if ( get_class( $filter['function'][0] ) === $class ) { // WordPress 4.7+ use core remove_filter() since we found the class object. if ( isset( $fob ) ) { // Handles removing filter, reseting callback priority keys mid-iteration, etc. $fob->remove_filter( $tag, $filter['function'], $priority ); } else { // Use legacy removal process (pre 4.7). unset( $callbacks[ $priority ][ $filter_id ] ); // If it was the only filter in that priority, unset that priority. if ( empty( $callbacks[ $priority ] ) ) { unset( $callbacks[ $priority ] ); } // If the only filter for that tag, set the tag to an empty array. if ( empty( $callbacks ) ) { $callbacks = array(); } // Remove this filter from merged_filters, which specifies if filters have been sorted. unset( $GLOBALS['merged_filters'][ $tag ] ); } return true; } } } return false; }
[ "public", "static", "function", "removeHook", "(", "$", "tag", ",", "$", "class", ",", "$", "name", ",", "$", "priority", "=", "10", ")", "{", "global", "$", "wp_filter", ";", "// Check that filter exists.", "if", "(", "isset", "(", "$", "wp_filter", "["...
Removes an anonymous object filter. @since 1.0.0 @global $wp_filter WordPress filter global. @param string $tag Hook name. @param string $class Class name @param string $method Method name @param int $priority Filter priority. @return bool Success of removing filter.
[ "Removes", "an", "anonymous", "object", "filter", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Filter.php#L106-L185
train
thelia/core
lib/Thelia/Form/Sale/SaleModificationForm.php
SaleModificationForm.checkDate
public function checkDate($value, ExecutionContextInterface $context) { $format = self::PHP_DATE_FORMAT; if (! empty($value) && false === \DateTime::createFromFormat($format, $value)) { $context->addViolation(Translator::getInstance()->trans("Date '%date' is invalid, please enter a valid date using %fmt format", [ '%fmt' => self::MOMENT_JS_DATE_FORMAT, '%date' => $value ])); } }
php
public function checkDate($value, ExecutionContextInterface $context) { $format = self::PHP_DATE_FORMAT; if (! empty($value) && false === \DateTime::createFromFormat($format, $value)) { $context->addViolation(Translator::getInstance()->trans("Date '%date' is invalid, please enter a valid date using %fmt format", [ '%fmt' => self::MOMENT_JS_DATE_FORMAT, '%date' => $value ])); } }
[ "public", "function", "checkDate", "(", "$", "value", ",", "ExecutionContextInterface", "$", "context", ")", "{", "$", "format", "=", "self", "::", "PHP_DATE_FORMAT", ";", "if", "(", "!", "empty", "(", "$", "value", ")", "&&", "false", "===", "\\", "Date...
Validate a date entered with the current edition Language date format. @param string $value @param ExecutionContextInterface $context
[ "Validate", "a", "date", "entered", "with", "the", "current", "edition", "Language", "date", "format", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Form/Sale/SaleModificationForm.php#L223-L233
train
thelia/core
lib/Thelia/Command/ContainerAwareCommand.php
ContainerAwareCommand.initRequest
protected function initRequest(Lang $lang = null) { $container = $this->getContainer(); $request = Request::create($this->getBaseUrl($lang)); $request->setSession(new Session(new MockArraySessionStorage())); $container->set("request_stack", new RequestStack()); $container->get('request_stack')->push($request); $requestContext = new RequestContext(); $requestContext->fromRequest($request); $url = $container->get('thelia.url.manager'); $url->setRequestContext($requestContext); $this->getContainer()->get('router.admin')->setContext($requestContext); }
php
protected function initRequest(Lang $lang = null) { $container = $this->getContainer(); $request = Request::create($this->getBaseUrl($lang)); $request->setSession(new Session(new MockArraySessionStorage())); $container->set("request_stack", new RequestStack()); $container->get('request_stack')->push($request); $requestContext = new RequestContext(); $requestContext->fromRequest($request); $url = $container->get('thelia.url.manager'); $url->setRequestContext($requestContext); $this->getContainer()->get('router.admin')->setContext($requestContext); }
[ "protected", "function", "initRequest", "(", "Lang", "$", "lang", "=", "null", ")", "{", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "request", "=", "Request", "::", "create", "(", "$", "this", "->", "getBaseUrl", "(",...
For init an Request, if your command has need an Request @param Lang|null $lang @since 2.3
[ "For", "init", "an", "Request", "if", "your", "command", "has", "need", "an", "Request" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Command/ContainerAwareCommand.php#L88-L102
train
thelia/core
lib/Thelia/Model/Cart.php
Cart.duplicate
public function duplicate( $token, Customer $customer = null, Currency $currency = null, EventDispatcherInterface $dispatcher = null ) { if (!$dispatcher) { return false; } $cartItems = $this->getCartItems(); $cart = new Cart(); $cart->setAddressDeliveryId($this->getAddressDeliveryId()); $cart->setAddressInvoiceId($this->getAddressInvoiceId()); $cart->setToken($token); $discount = 0; if (null === $currency) { $currencyQuery = CurrencyQuery::create(); $currency = $currencyQuery->findPk($this->getCurrencyId()) ?: $currencyQuery->findOneByByDefault(1); } $cart->setCurrency($currency); if ($customer) { $cart->setCustomer($customer); if ($customer->getDiscount() > 0) { $discount = $customer->getDiscount(); } } $cart->save(); foreach ($cartItems as $cartItem) { $product = $cartItem->getProduct(); $productSaleElements = $cartItem->getProductSaleElements(); if ($product && $productSaleElements && $product->getVisible() == 1 && ($productSaleElements->getQuantity() >= $cartItem->getQuantity() || $product->getVirtual() === 1 || ! ConfigQuery::checkAvailableStock())) { $item = new CartItem(); $item->setCart($cart); $item->setProductId($cartItem->getProductId()); $item->setQuantity($cartItem->getQuantity()); $item->setProductSaleElements($productSaleElements); $prices = $productSaleElements->getPricesByCurrency($currency, $discount); $item ->setPrice($prices->getPrice()) ->setPromoPrice($prices->getPromoPrice()) ->setPromo($productSaleElements->getPromo()); $item->save(); $dispatcher->dispatch(TheliaEvents::CART_ITEM_DUPLICATE, new CartItemDuplicationItem($item, $cartItem)); } } // Dispatche the duplication event before delting the cart from the database, $dispatcher->dispatch(TheliaEvents::CART_DUPLICATED, new CartDuplicationEvent($cart, $this)); try { $this->delete(); } catch (\Exception $e) { // just fail silently in some cases } return $cart; }
php
public function duplicate( $token, Customer $customer = null, Currency $currency = null, EventDispatcherInterface $dispatcher = null ) { if (!$dispatcher) { return false; } $cartItems = $this->getCartItems(); $cart = new Cart(); $cart->setAddressDeliveryId($this->getAddressDeliveryId()); $cart->setAddressInvoiceId($this->getAddressInvoiceId()); $cart->setToken($token); $discount = 0; if (null === $currency) { $currencyQuery = CurrencyQuery::create(); $currency = $currencyQuery->findPk($this->getCurrencyId()) ?: $currencyQuery->findOneByByDefault(1); } $cart->setCurrency($currency); if ($customer) { $cart->setCustomer($customer); if ($customer->getDiscount() > 0) { $discount = $customer->getDiscount(); } } $cart->save(); foreach ($cartItems as $cartItem) { $product = $cartItem->getProduct(); $productSaleElements = $cartItem->getProductSaleElements(); if ($product && $productSaleElements && $product->getVisible() == 1 && ($productSaleElements->getQuantity() >= $cartItem->getQuantity() || $product->getVirtual() === 1 || ! ConfigQuery::checkAvailableStock())) { $item = new CartItem(); $item->setCart($cart); $item->setProductId($cartItem->getProductId()); $item->setQuantity($cartItem->getQuantity()); $item->setProductSaleElements($productSaleElements); $prices = $productSaleElements->getPricesByCurrency($currency, $discount); $item ->setPrice($prices->getPrice()) ->setPromoPrice($prices->getPromoPrice()) ->setPromo($productSaleElements->getPromo()); $item->save(); $dispatcher->dispatch(TheliaEvents::CART_ITEM_DUPLICATE, new CartItemDuplicationItem($item, $cartItem)); } } // Dispatche the duplication event before delting the cart from the database, $dispatcher->dispatch(TheliaEvents::CART_DUPLICATED, new CartDuplicationEvent($cart, $this)); try { $this->delete(); } catch (\Exception $e) { // just fail silently in some cases } return $cart; }
[ "public", "function", "duplicate", "(", "$", "token", ",", "Customer", "$", "customer", "=", "null", ",", "Currency", "$", "currency", "=", "null", ",", "EventDispatcherInterface", "$", "dispatcher", "=", "null", ")", "{", "if", "(", "!", "$", "dispatcher"...
Duplicate the current existing cart. Only the token is changed @param string $token @param Customer $customer @param Currency $currency @param EventDispatcherInterface $dispatcher @return Cart @throws \Exception @throws \Propel\Runtime\Exception\PropelException
[ "Duplicate", "the", "current", "existing", "cart", ".", "Only", "the", "token", "is", "changed" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Cart.php#L28-L95
train
thelia/core
lib/Thelia/Model/Cart.php
Cart.getLastCartItemAdded
public function getLastCartItemAdded() { return CartItemQuery::create() ->filterByCartId($this->getId()) ->orderByCreatedAt(Criteria::DESC) ->findOne() ; }
php
public function getLastCartItemAdded() { return CartItemQuery::create() ->filterByCartId($this->getId()) ->orderByCreatedAt(Criteria::DESC) ->findOne() ; }
[ "public", "function", "getLastCartItemAdded", "(", ")", "{", "return", "CartItemQuery", "::", "create", "(", ")", "->", "filterByCartId", "(", "$", "this", "->", "getId", "(", ")", ")", "->", "orderByCreatedAt", "(", "Criteria", "::", "DESC", ")", "->", "f...
Retrieve the last item added in the cart @return CartItem
[ "Retrieve", "the", "last", "item", "added", "in", "the", "cart" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Cart.php#L102-L109
train
thelia/core
lib/Thelia/Model/Cart.php
Cart.getTotalVAT
public function getTotalVAT($taxCountry, $taxState = null) { return ($this->getTaxedAmount($taxCountry, true, $taxState) - $this->getTotalAmount(true)); }
php
public function getTotalVAT($taxCountry, $taxState = null) { return ($this->getTaxedAmount($taxCountry, true, $taxState) - $this->getTotalAmount(true)); }
[ "public", "function", "getTotalVAT", "(", "$", "taxCountry", ",", "$", "taxState", "=", "null", ")", "{", "return", "(", "$", "this", "->", "getTaxedAmount", "(", "$", "taxCountry", ",", "true", ",", "$", "taxState", ")", "-", "$", "this", "->", "getTo...
Return the VAT of all items @return float|int
[ "Return", "the", "VAT", "of", "all", "items" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Cart.php#L177-L180
train
thelia/core
lib/Thelia/Model/Cart.php
Cart.getWeight
public function getWeight() { $weight = 0; foreach ($this->getCartItems() as $cartItem) { $itemWeight = $cartItem->getProductSaleElements()->getWeight(); $itemWeight *= $cartItem->getQuantity(); $weight += $itemWeight; } return $weight; }
php
public function getWeight() { $weight = 0; foreach ($this->getCartItems() as $cartItem) { $itemWeight = $cartItem->getProductSaleElements()->getWeight(); $itemWeight *= $cartItem->getQuantity(); $weight += $itemWeight; } return $weight; }
[ "public", "function", "getWeight", "(", ")", "{", "$", "weight", "=", "0", ";", "foreach", "(", "$", "this", "->", "getCartItems", "(", ")", "as", "$", "cartItem", ")", "{", "$", "itemWeight", "=", "$", "cartItem", "->", "getProductSaleElements", "(", ...
Retrieve the total weight for all products in cart @return float|int
[ "Retrieve", "the", "total", "weight", "for", "all", "products", "in", "cart" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Cart.php#L187-L199
train
thelia/core
lib/Thelia/Model/Cart.php
Cart.isVirtual
public function isVirtual() { foreach ($this->getCartItems() as $cartItem) { if (0 < $cartItem->getProductSaleElements()->getWeight()) { return false; } $product = $cartItem->getProductSaleElements()->getProduct(); if (!$product->getVirtual()) { return false; } } return true; }
php
public function isVirtual() { foreach ($this->getCartItems() as $cartItem) { if (0 < $cartItem->getProductSaleElements()->getWeight()) { return false; } $product = $cartItem->getProductSaleElements()->getProduct(); if (!$product->getVirtual()) { return false; } } return true; }
[ "public", "function", "isVirtual", "(", ")", "{", "foreach", "(", "$", "this", "->", "getCartItems", "(", ")", "as", "$", "cartItem", ")", "{", "if", "(", "0", "<", "$", "cartItem", "->", "getProductSaleElements", "(", ")", "->", "getWeight", "(", ")",...
Tell if the cart contains only virtual products @return bool
[ "Tell", "if", "the", "cart", "contains", "only", "virtual", "products" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Cart.php#L206-L220
train
nattreid/cms
src/Control/presenters/ConfigurationPresenter.php
ConfigurationPresenter.createComponentConfigurationForm
protected function createComponentConfigurationForm(): Form { $form = $this->formFactory->create(); $form->setAjaxRequest(); $form->addGroup('cms.settings.basic'); $form->addImageUpload('cmsLogo', 'cms.settings.logo', 'cms.settings.deleteLogo') ->setNamespace('cms') ->setPreview('300x100'); $form->addCheckbox('sendNewUserPassword', 'cms.settings.sendNewUserPassword'); $form->addCheckbox('sendChangePassword', 'cms.settings.sendChangePassword'); $form->addCheckbox('dockbarAdvanced', 'cms.settings.dockbarAdvanced'); $form->addSelectUntranslated('defaultLocale', 'cms.settings.defaultLocale', $this->localeService->fetch()) ->setDefaultValue($this->localeService->defaultLocaleId); $form->addMultiSelectUntranslated('allowedLocales', 'cms.settings.allowedLocales', $this->localeService->fetch()) ->setDefaultValue($this->localeService->allowedLocaleIds) ->setRequired(); $form->addGroup('cms.settings.development'); if (!$this->tracy->isEnabled()) { $form->addLink('debugOn', 'cms.settings.debugOn') ->link($this->link('debug!', true)) ->setAjaxRequest() ->addClass('btn-success') ->setAttribute('data-ajax-off', 'history'); } else { $form->addLink('debugOff', 'cms.settings.debugOff') ->link($this->link('debug!', false)) ->setAjaxRequest() ->addClass('btn-danger') ->setAttribute('data-ajax-off', 'history'); } $form->addCheckbox('mailPanel', 'cms.settings.mailPanel') ->setDefaultValue($this->configurator->mailPanel); $form->getRenderer()->primaryButton = $form->addSubmit('save', 'form.save'); $form->onSuccess[] = [$this, 'configurationFormSucseeded']; return $form; }
php
protected function createComponentConfigurationForm(): Form { $form = $this->formFactory->create(); $form->setAjaxRequest(); $form->addGroup('cms.settings.basic'); $form->addImageUpload('cmsLogo', 'cms.settings.logo', 'cms.settings.deleteLogo') ->setNamespace('cms') ->setPreview('300x100'); $form->addCheckbox('sendNewUserPassword', 'cms.settings.sendNewUserPassword'); $form->addCheckbox('sendChangePassword', 'cms.settings.sendChangePassword'); $form->addCheckbox('dockbarAdvanced', 'cms.settings.dockbarAdvanced'); $form->addSelectUntranslated('defaultLocale', 'cms.settings.defaultLocale', $this->localeService->fetch()) ->setDefaultValue($this->localeService->defaultLocaleId); $form->addMultiSelectUntranslated('allowedLocales', 'cms.settings.allowedLocales', $this->localeService->fetch()) ->setDefaultValue($this->localeService->allowedLocaleIds) ->setRequired(); $form->addGroup('cms.settings.development'); if (!$this->tracy->isEnabled()) { $form->addLink('debugOn', 'cms.settings.debugOn') ->link($this->link('debug!', true)) ->setAjaxRequest() ->addClass('btn-success') ->setAttribute('data-ajax-off', 'history'); } else { $form->addLink('debugOff', 'cms.settings.debugOff') ->link($this->link('debug!', false)) ->setAjaxRequest() ->addClass('btn-danger') ->setAttribute('data-ajax-off', 'history'); } $form->addCheckbox('mailPanel', 'cms.settings.mailPanel') ->setDefaultValue($this->configurator->mailPanel); $form->getRenderer()->primaryButton = $form->addSubmit('save', 'form.save'); $form->onSuccess[] = [$this, 'configurationFormSucseeded']; return $form; }
[ "protected", "function", "createComponentConfigurationForm", "(", ")", ":", "Form", "{", "$", "form", "=", "$", "this", "->", "formFactory", "->", "create", "(", ")", ";", "$", "form", "->", "setAjaxRequest", "(", ")", ";", "$", "form", "->", "addGroup", ...
Komponenta formulare nastaveni @return Form
[ "Komponenta", "formulare", "nastaveni" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/src/Control/presenters/ConfigurationPresenter.php#L64-L104
train
BoldGrid/library
src/Util/Option.php
Option.init
public static function init( $name = 'boldgrid_settings', $key = 'library' ) { self::$name = $name; self::$key = $key; self::$option = self::getOption(); }
php
public static function init( $name = 'boldgrid_settings', $key = 'library' ) { self::$name = $name; self::$key = $key; self::$option = self::getOption(); }
[ "public", "static", "function", "init", "(", "$", "name", "=", "'boldgrid_settings'", ",", "$", "key", "=", "'library'", ")", "{", "self", "::", "$", "name", "=", "$", "name", ";", "self", "::", "$", "key", "=", "$", "key", ";", "self", "::", "$", ...
Initialize the option utility. @since 1.0.0 @param string $name Name of the option to use. @param string $key Key to use in option. @return null
[ "Initialize", "the", "option", "utility", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Option.php#L45-L49
train
BoldGrid/library
src/Util/Option.php
Option.set
public static function set( $key, $value ) { self::$option[ self::$key ][ $key ] = $value; return update_option( self::$name, self::$option ); }
php
public static function set( $key, $value ) { self::$option[ self::$key ][ $key ] = $value; return update_option( self::$name, self::$option ); }
[ "public", "static", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "self", "::", "$", "option", "[", "self", "::", "$", "key", "]", "[", "$", "key", "]", "=", "$", "value", ";", "return", "update_option", "(", "self", "::", "$",...
Set option key, value. @since 1.0.0 @param string $key Key to add to option. @param mixed $value Value to assign to key. @return bool Option update successful?
[ "Set", "option", "key", "value", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Option.php#L72-L75
train
BoldGrid/library
src/Util/Option.php
Option.delete
public static function delete( $key ) { unset( self::$option[ self::$key ][ $key ] ); return update_option( self::$name, self::$option ); }
php
public static function delete( $key ) { unset( self::$option[ self::$key ][ $key ] ); return update_option( self::$name, self::$option ); }
[ "public", "static", "function", "delete", "(", "$", "key", ")", "{", "unset", "(", "self", "::", "$", "option", "[", "self", "::", "$", "key", "]", "[", "$", "key", "]", ")", ";", "return", "update_option", "(", "self", "::", "$", "name", ",", "s...
Deletes by key in stored option. @since 1.0.0 @param string $key The key to delete. @return bool Delete option successful?
[ "Deletes", "by", "key", "in", "stored", "option", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Option.php#L86-L89
train
BoldGrid/library
src/Util/Option.php
Option.get
public static function get( $key = null, $default = array() ) { return $key && ! empty( self::$option[ $key ] ) ? self::$option[ $key ] : $default; }
php
public static function get( $key = null, $default = array() ) { return $key && ! empty( self::$option[ $key ] ) ? self::$option[ $key ] : $default; }
[ "public", "static", "function", "get", "(", "$", "key", "=", "null", ",", "$", "default", "=", "array", "(", ")", ")", "{", "return", "$", "key", "&&", "!", "empty", "(", "self", "::", "$", "option", "[", "$", "key", "]", ")", "?", "self", "::"...
Retrieves an option key from the array. If no key is specified, then the default value will be returned. @since 1.0.0 @param mixed $key Key to retrieve from option. @param mixed $default The default value to return if key is not found. @return mixed The key data or the default value if not found.
[ "Retrieves", "an", "option", "key", "from", "the", "array", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Option.php#L103-L105
train
thelia/core
lib/Thelia/Core/Security/SecurityContext.php
SecurityContext.hasRequiredRole
final public function hasRequiredRole(UserInterface $user = null, array $roles = []) { if ($user != null) { // Check if user's roles matches required roles $userRoles = $user->getRoles(); foreach ($userRoles as $role) { if (\in_array($role, $roles)) { return true; } } } return false; }
php
final public function hasRequiredRole(UserInterface $user = null, array $roles = []) { if ($user != null) { // Check if user's roles matches required roles $userRoles = $user->getRoles(); foreach ($userRoles as $role) { if (\in_array($role, $roles)) { return true; } } } return false; }
[ "final", "public", "function", "hasRequiredRole", "(", "UserInterface", "$", "user", "=", "null", ",", "array", "$", "roles", "=", "[", "]", ")", "{", "if", "(", "$", "user", "!=", "null", ")", "{", "// Check if user's roles matches required roles", "$", "us...
Check if a user has at least one of the required roles @param UserInterface $user the user @param array $roles the roles @return boolean true if the user has the required role, false otherwise
[ "Check", "if", "a", "user", "has", "at", "least", "one", "of", "the", "required", "roles" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Security/SecurityContext.php#L105-L119
train
thelia/core
lib/Thelia/Core/Security/SecurityContext.php
SecurityContext.isGranted
final public function isGranted(array $roles, array $resources, array $modules, array $accesses) { // Find a user which matches the required roles. $user = $this->checkRole($roles); if (null === $user) { return false; } else { return $this->isUserGranted($roles, $resources, $modules, $accesses, $user); } }
php
final public function isGranted(array $roles, array $resources, array $modules, array $accesses) { // Find a user which matches the required roles. $user = $this->checkRole($roles); if (null === $user) { return false; } else { return $this->isUserGranted($roles, $resources, $modules, $accesses, $user); } }
[ "final", "public", "function", "isGranted", "(", "array", "$", "roles", ",", "array", "$", "resources", ",", "array", "$", "modules", ",", "array", "$", "accesses", ")", "{", "// Find a user which matches the required roles.", "$", "user", "=", "$", "this", "-...
Checks if the current user is allowed @return Boolean
[ "Checks", "if", "the", "current", "user", "is", "allowed" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Security/SecurityContext.php#L189-L199
train
thelia/core
lib/Thelia/Core/Security/SecurityContext.php
SecurityContext.checkRole
public function checkRole(array $roles) { // Find a user which matches the required roles. $user = $this->getCustomerUser(); if (! $this->hasRequiredRole($user, $roles)) { $user = $this->getAdminUser(); if (! $this->hasRequiredRole($user, $roles)) { $user = null; } } return $user; }
php
public function checkRole(array $roles) { // Find a user which matches the required roles. $user = $this->getCustomerUser(); if (! $this->hasRequiredRole($user, $roles)) { $user = $this->getAdminUser(); if (! $this->hasRequiredRole($user, $roles)) { $user = null; } } return $user; }
[ "public", "function", "checkRole", "(", "array", "$", "roles", ")", "{", "// Find a user which matches the required roles.", "$", "user", "=", "$", "this", "->", "getCustomerUser", "(", ")", ";", "if", "(", "!", "$", "this", "->", "hasRequiredRole", "(", "$", ...
look if a user has the required role. @param array $roles @return null|UserInterface
[ "look", "if", "a", "user", "has", "the", "required", "role", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Security/SecurityContext.php#L207-L221
train
melisplatform/melis-cms
src/Listener/MelisCmsPageEditionSavePluginSessionListener.php
MelisCmsPageEditionSavePluginSessionListener.insertOrReplaceTag
private function insertOrReplaceTag($content, $search, $replace) { $newContent = null; $regexSearch = "/(\<$search\>\<\!\[CDATA\[([0-9.])+\]\]\>\<\/$search\>)/"; if(preg_match($regexSearch, $content)) { $newContent = preg_replace($regexSearch, $replace, $content); } else { $newContent = $content . $replace; } return $newContent; }
php
private function insertOrReplaceTag($content, $search, $replace) { $newContent = null; $regexSearch = "/(\<$search\>\<\!\[CDATA\[([0-9.])+\]\]\>\<\/$search\>)/"; if(preg_match($regexSearch, $content)) { $newContent = preg_replace($regexSearch, $replace, $content); } else { $newContent = $content . $replace; } return $newContent; }
[ "private", "function", "insertOrReplaceTag", "(", "$", "content", ",", "$", "search", ",", "$", "replace", ")", "{", "$", "newContent", "=", "null", ";", "$", "regexSearch", "=", "\"/(\\<$search\\>\\<\\!\\[CDATA\\[([0-9.])+\\]\\]\\>\\<\\/$search\\>)/\"", ";", "if", ...
This method modifies the XML plugin data and looks for width tags and replaces the value @param $content @param $search @param $replace @return mixed|null|string
[ "This", "method", "modifies", "the", "XML", "plugin", "data", "and", "looks", "for", "width", "tags", "and", "replaces", "the", "value" ]
ed470338f4c7653fd93e530013ab934eb7a52b6f
https://github.com/melisplatform/melis-cms/blob/ed470338f4c7653fd93e530013ab934eb7a52b6f/src/Listener/MelisCmsPageEditionSavePluginSessionListener.php#L142-L156
train
melisplatform/melis-cms
src/Listener/MelisCmsPageEditionSavePluginSessionListener.php
MelisCmsPageEditionSavePluginSessionListener.updateMelisPlugin
private function updateMelisPlugin($pageId, $plugin, $pluginId, $content, $updateSettings = false) { $pluginContent = $content; $pluginSessionSettings = isset($_SESSION['meliscms']['content-pages'][$pageId]['private:melisPluginSettings'][$pluginId]) ? $_SESSION['meliscms']['content-pages'][$pageId]['private:melisPluginSettings'][$pluginId] : ''; $pluginSettings = (array) json_decode($pluginSessionSettings); if($plugin == 'melisTag') { $pattern = '/type\=\"([html|media|textarea]*\")/'; if(preg_match($pattern, $pluginContent, $matches)) { $type = isset($matches[0]) ? $matches[0] : null; if($type) { // apply sizes if($pluginSettings) { /* $replacement = $type .' width_desktop="'.$pluginSettings['width_desktop']. '" width_tablet="'.$pluginSettings['width_tablet']. '" width_mobile="'.$pluginSettings['width_mobile'].'"'; $pluginContent = preg_replace($pattern, $replacement, $pluginContent); */ $pluginContent = $this->setPluginWidthXmlAttribute($pluginContent, $pluginSettings); } } } } else { $pattern = '\<'.$plugin.'\sid\=\"(.*?)*\"'; if(preg_match('/'.$pattern.'/', $pluginContent, $matches)) { $id = isset($matches[0]) ? $matches[0] : null; if($id) { if($pluginSettings) { /* $replacement = $id .' width_desktop="'.$pluginDesktop. '" width_tablet="'.$pluginTablet. '" width_mobile="'.$pluginMobile.'"'; $pluginContent = preg_replace('/'.$pattern.'/', $replacement, $pluginContent); */ $pluginContent = $this->setPluginWidthXmlAttribute($pluginContent, $pluginSettings); } } } } if(isset($_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId])) { $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $this->getPluginContentWithInsertedContainerId($pageId, $plugin, $pluginId, $pluginContent); $pluginContent = $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId]; if($updateSettings) { $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $this->reapplySettings($pageId, $plugin, $pluginId, $pluginContent); } if($plugin == 'melisTag') { $content = $this->updateContent($pageId, $plugin, $pluginId, $pluginContent); $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $content; } } }
php
private function updateMelisPlugin($pageId, $plugin, $pluginId, $content, $updateSettings = false) { $pluginContent = $content; $pluginSessionSettings = isset($_SESSION['meliscms']['content-pages'][$pageId]['private:melisPluginSettings'][$pluginId]) ? $_SESSION['meliscms']['content-pages'][$pageId]['private:melisPluginSettings'][$pluginId] : ''; $pluginSettings = (array) json_decode($pluginSessionSettings); if($plugin == 'melisTag') { $pattern = '/type\=\"([html|media|textarea]*\")/'; if(preg_match($pattern, $pluginContent, $matches)) { $type = isset($matches[0]) ? $matches[0] : null; if($type) { // apply sizes if($pluginSettings) { /* $replacement = $type .' width_desktop="'.$pluginSettings['width_desktop']. '" width_tablet="'.$pluginSettings['width_tablet']. '" width_mobile="'.$pluginSettings['width_mobile'].'"'; $pluginContent = preg_replace($pattern, $replacement, $pluginContent); */ $pluginContent = $this->setPluginWidthXmlAttribute($pluginContent, $pluginSettings); } } } } else { $pattern = '\<'.$plugin.'\sid\=\"(.*?)*\"'; if(preg_match('/'.$pattern.'/', $pluginContent, $matches)) { $id = isset($matches[0]) ? $matches[0] : null; if($id) { if($pluginSettings) { /* $replacement = $id .' width_desktop="'.$pluginDesktop. '" width_tablet="'.$pluginTablet. '" width_mobile="'.$pluginMobile.'"'; $pluginContent = preg_replace('/'.$pattern.'/', $replacement, $pluginContent); */ $pluginContent = $this->setPluginWidthXmlAttribute($pluginContent, $pluginSettings); } } } } if(isset($_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId])) { $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $this->getPluginContentWithInsertedContainerId($pageId, $plugin, $pluginId, $pluginContent); $pluginContent = $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId]; if($updateSettings) { $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $this->reapplySettings($pageId, $plugin, $pluginId, $pluginContent); } if($plugin == 'melisTag') { $content = $this->updateContent($pageId, $plugin, $pluginId, $pluginContent); $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $content; } } }
[ "private", "function", "updateMelisPlugin", "(", "$", "pageId", ",", "$", "plugin", ",", "$", "pluginId", ",", "$", "content", ",", "$", "updateSettings", "=", "false", ")", "{", "$", "pluginContent", "=", "$", "content", ";", "$", "pluginSessionSettings", ...
This method modifies the tag plugin xml attribute applying the changes of the width @param $pageId @param $plugin @param $pluginId @param $content
[ "This", "method", "modifies", "the", "tag", "plugin", "xml", "attribute", "applying", "the", "changes", "of", "the", "width" ]
ed470338f4c7653fd93e530013ab934eb7a52b6f
https://github.com/melisplatform/melis-cms/blob/ed470338f4c7653fd93e530013ab934eb7a52b6f/src/Listener/MelisCmsPageEditionSavePluginSessionListener.php#L166-L229
train
melisplatform/melis-cms
src/Listener/MelisCmsPageEditionSavePluginSessionListener.php
MelisCmsPageEditionSavePluginSessionListener.setPluginWidthXmlAttribute
private function setPluginWidthXmlAttribute($pluginXml, $pluginSettings){ try { $pluginDesktop = isset($pluginSettings['width_desktop']) ? $pluginSettings['width_desktop'] : 100; $pluginTablet = isset($pluginSettings['width_tablet']) ? $pluginSettings['width_tablet'] : 100; $pluginMobile = isset($pluginSettings['width_mobile']) ? $pluginSettings['width_mobile'] : 100; // Parsing xml string to Xml object $xml = simplexml_load_string($pluginXml); // Adding/updating plugin xml attributes if (isset($xml->attributes()->width_desktop)) $xml->attributes()->width_desktop = $pluginDesktop; else $xml->addAttribute('width_desktop', $pluginDesktop); if (isset($xml->attributes()->width_tablet)) $xml->attributes()->width_tablet = $pluginTablet; else $xml->addAttribute('width_tablet', $pluginTablet); if (isset($xml->attributes()->width_mobile)) $xml->attributes()->width_mobile = $pluginMobile; else $xml->addAttribute('width_mobile', $pluginMobile); // Geeting the Plugin xml $customXML = new \SimpleXMLElement($xml->asXML()); $dom = dom_import_simplexml($customXML); $pluginXml = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement); }catch (\Exception $e){} return $pluginXml; }
php
private function setPluginWidthXmlAttribute($pluginXml, $pluginSettings){ try { $pluginDesktop = isset($pluginSettings['width_desktop']) ? $pluginSettings['width_desktop'] : 100; $pluginTablet = isset($pluginSettings['width_tablet']) ? $pluginSettings['width_tablet'] : 100; $pluginMobile = isset($pluginSettings['width_mobile']) ? $pluginSettings['width_mobile'] : 100; // Parsing xml string to Xml object $xml = simplexml_load_string($pluginXml); // Adding/updating plugin xml attributes if (isset($xml->attributes()->width_desktop)) $xml->attributes()->width_desktop = $pluginDesktop; else $xml->addAttribute('width_desktop', $pluginDesktop); if (isset($xml->attributes()->width_tablet)) $xml->attributes()->width_tablet = $pluginTablet; else $xml->addAttribute('width_tablet', $pluginTablet); if (isset($xml->attributes()->width_mobile)) $xml->attributes()->width_mobile = $pluginMobile; else $xml->addAttribute('width_mobile', $pluginMobile); // Geeting the Plugin xml $customXML = new \SimpleXMLElement($xml->asXML()); $dom = dom_import_simplexml($customXML); $pluginXml = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement); }catch (\Exception $e){} return $pluginXml; }
[ "private", "function", "setPluginWidthXmlAttribute", "(", "$", "pluginXml", ",", "$", "pluginSettings", ")", "{", "try", "{", "$", "pluginDesktop", "=", "isset", "(", "$", "pluginSettings", "[", "'width_desktop'", "]", ")", "?", "$", "pluginSettings", "[", "'w...
This method will setup the width of the plugin xml config @param String $pluginXml @param array $pluginSettings @return string
[ "This", "method", "will", "setup", "the", "width", "of", "the", "plugin", "xml", "config" ]
ed470338f4c7653fd93e530013ab934eb7a52b6f
https://github.com/melisplatform/melis-cms/blob/ed470338f4c7653fd93e530013ab934eb7a52b6f/src/Listener/MelisCmsPageEditionSavePluginSessionListener.php#L238-L273
train
thelia/core
lib/Thelia/Model/Order.php
Order.getWeight
public function getWeight() { $weight = 0; /* browse all products */ foreach ($this->getOrderProducts() as $orderProduct) { $weight += $orderProduct->getQuantity() * (double)$orderProduct->getWeight(); } return $weight; }
php
public function getWeight() { $weight = 0; /* browse all products */ foreach ($this->getOrderProducts() as $orderProduct) { $weight += $orderProduct->getQuantity() * (double)$orderProduct->getWeight(); } return $weight; }
[ "public", "function", "getWeight", "(", ")", "{", "$", "weight", "=", "0", ";", "/* browse all products */", "foreach", "(", "$", "this", "->", "getOrderProducts", "(", ")", "as", "$", "orderProduct", ")", "{", "$", "weight", "+=", "$", "orderProduct", "->...
Compute this order weight. The order weight is only available once the order is persisted in database. During invoice process, use all cart methods instead of order methods (the order doest not exists at this moment) @return float @throws \Propel\Runtime\Exception\PropelException
[ "Compute", "this", "order", "weight", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Order.php#L202-L212
train
thelia/core
lib/Thelia/Model/Order.php
Order.getUntaxedPostage
public function getUntaxedPostage() { if (0 < $this->getPostageTax()) { $untaxedPostage = $this->getPostage() - $this->getPostageTax(); } else { $untaxedPostage = $this->getPostage(); } return $untaxedPostage; }
php
public function getUntaxedPostage() { if (0 < $this->getPostageTax()) { $untaxedPostage = $this->getPostage() - $this->getPostageTax(); } else { $untaxedPostage = $this->getPostage(); } return $untaxedPostage; }
[ "public", "function", "getUntaxedPostage", "(", ")", "{", "if", "(", "0", "<", "$", "this", "->", "getPostageTax", "(", ")", ")", "{", "$", "untaxedPostage", "=", "$", "this", "->", "getPostage", "(", ")", "-", "$", "this", "->", "getPostageTax", "(", ...
Return the postage without tax @return float|int
[ "Return", "the", "postage", "without", "tax" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Order.php#L218-L227
train
thelia/core
lib/Thelia/Model/Order.php
Order.hasVirtualProduct
public function hasVirtualProduct() { $virtualProductCount = OrderProductQuery::create() ->filterByOrderId($this->getId()) ->filterByVirtual(1, Criteria::EQUAL) ->count() ; return ($virtualProductCount !== 0); }
php
public function hasVirtualProduct() { $virtualProductCount = OrderProductQuery::create() ->filterByOrderId($this->getId()) ->filterByVirtual(1, Criteria::EQUAL) ->count() ; return ($virtualProductCount !== 0); }
[ "public", "function", "hasVirtualProduct", "(", ")", "{", "$", "virtualProductCount", "=", "OrderProductQuery", "::", "create", "(", ")", "->", "filterByOrderId", "(", "$", "this", "->", "getId", "(", ")", ")", "->", "filterByVirtual", "(", "1", ",", "Criter...
Check if the current order contains at less 1 virtual product with a file to download @return bool true if this order have at less 1 file to download, false otherwise.
[ "Check", "if", "the", "current", "order", "contains", "at", "less", "1", "virtual", "product", "with", "a", "file", "to", "download" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Order.php#L234-L243
train
thelia/core
lib/Thelia/Model/Order.php
Order.setStatusHelper
public function setStatusHelper($statusCode) { if (null !== $ordeStatus = OrderStatusQuery::create()->findOneByCode($statusCode)) { $this->setOrderStatus($ordeStatus)->save(); } }
php
public function setStatusHelper($statusCode) { if (null !== $ordeStatus = OrderStatusQuery::create()->findOneByCode($statusCode)) { $this->setOrderStatus($ordeStatus)->save(); } }
[ "public", "function", "setStatusHelper", "(", "$", "statusCode", ")", "{", "if", "(", "null", "!==", "$", "ordeStatus", "=", "OrderStatusQuery", "::", "create", "(", ")", "->", "findOneByCode", "(", "$", "statusCode", ")", ")", "{", "$", "this", "->", "s...
Set the status of the current order to the provided status @param string $statusCode the status code, one of OrderStatus::CODE_xxx constants. @throws \Propel\Runtime\Exception\PropelException
[ "Set", "the", "status", "of", "the", "current", "order", "to", "the", "provided", "status" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Order.php#L377-L382
train
thelia/core
lib/Thelia/Model/Order.php
Order.getPaymentModuleInstance
public function getPaymentModuleInstance() { if (null === $paymentModule = ModuleQuery::create()->findPk($this->getPaymentModuleId())) { throw new TheliaProcessException("Payment module ID=" . $this->getPaymentModuleId() . " was not found."); } return $paymentModule->createInstance(); }
php
public function getPaymentModuleInstance() { if (null === $paymentModule = ModuleQuery::create()->findPk($this->getPaymentModuleId())) { throw new TheliaProcessException("Payment module ID=" . $this->getPaymentModuleId() . " was not found."); } return $paymentModule->createInstance(); }
[ "public", "function", "getPaymentModuleInstance", "(", ")", "{", "if", "(", "null", "===", "$", "paymentModule", "=", "ModuleQuery", "::", "create", "(", ")", "->", "findPk", "(", "$", "this", "->", "getPaymentModuleId", "(", ")", ")", ")", "{", "throw", ...
Get an instance of the payment module @return \Thelia\Module\PaymentModuleInterface @throws TheliaProcessException
[ "Get", "an", "instance", "of", "the", "payment", "module" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Order.php#L390-L397
train
thelia/core
lib/Thelia/Model/Order.php
Order.getDeliveryModuleInstance
public function getDeliveryModuleInstance() { if (null === $deliveryModule = ModuleQuery::create()->findPk($this->getDeliveryModuleId())) { throw new TheliaProcessException("Delivery module ID=" . $this->getDeliveryModuleId() . " was not found."); } return $deliveryModule->createInstance(); }
php
public function getDeliveryModuleInstance() { if (null === $deliveryModule = ModuleQuery::create()->findPk($this->getDeliveryModuleId())) { throw new TheliaProcessException("Delivery module ID=" . $this->getDeliveryModuleId() . " was not found."); } return $deliveryModule->createInstance(); }
[ "public", "function", "getDeliveryModuleInstance", "(", ")", "{", "if", "(", "null", "===", "$", "deliveryModule", "=", "ModuleQuery", "::", "create", "(", ")", "->", "findPk", "(", "$", "this", "->", "getDeliveryModuleId", "(", ")", ")", ")", "{", "throw"...
Get an instance of the delivery module @return \Thelia\Module\DeliveryModuleInterface @throws TheliaProcessException
[ "Get", "an", "instance", "of", "the", "delivery", "module" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Order.php#L405-L412
train
thelia/core
lib/Thelia/Model/MessageQuery.php
MessageQuery.getFromName
public static function getFromName($messageName) { if (false === $message = MessageQuery::create()->filterByName($messageName)->findOne()) { throw new \Exception("Failed to load message $messageName."); } return $message; }
php
public static function getFromName($messageName) { if (false === $message = MessageQuery::create()->filterByName($messageName)->findOne()) { throw new \Exception("Failed to load message $messageName."); } return $message; }
[ "public", "static", "function", "getFromName", "(", "$", "messageName", ")", "{", "if", "(", "false", "===", "$", "message", "=", "MessageQuery", "::", "create", "(", ")", "->", "filterByName", "(", "$", "messageName", ")", "->", "findOne", "(", ")", ")"...
Load a message from its name, throwing an excemtoipn is none is found. @param string $messageName the message name @return Message the loaded message @throws \Exception if the message could not be loaded
[ "Load", "a", "message", "from", "its", "name", "throwing", "an", "excemtoipn", "is", "none", "is", "found", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/MessageQuery.php#L26-L33
train
BoldGrid/library
src/Util/Registration.php
Registration.init
protected function init( $product, $dependency = 'boldgrid/library' ) { $this->product = $product; $this->dependency = $dependency; Option::init(); $this->libraries = Option::get( 'library' ); $this->verify(); }
php
protected function init( $product, $dependency = 'boldgrid/library' ) { $this->product = $product; $this->dependency = $dependency; Option::init(); $this->libraries = Option::get( 'library' ); $this->verify(); }
[ "protected", "function", "init", "(", "$", "product", ",", "$", "dependency", "=", "'boldgrid/library'", ")", "{", "$", "this", "->", "product", "=", "$", "product", ";", "$", "this", "->", "dependency", "=", "$", "dependency", ";", "Option", "::", "init...
Initialize class and set class properties. @since 1.0.0 @param string $product The path of the product. @param string $dependency The dependency relied on by the product. @return null
[ "Initialize", "class", "and", "set", "class", "properties", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Registration.php#L46-L52
train
BoldGrid/library
src/Util/Registration.php
Registration.register
public function register() { // Check the dependency version. $version = new Version( $this->getDependency() ); Option::set( $this->getProduct(), $version->getVersion() ); }
php
public function register() { // Check the dependency version. $version = new Version( $this->getDependency() ); Option::set( $this->getProduct(), $version->getVersion() ); }
[ "public", "function", "register", "(", ")", "{", "// Check the dependency version.", "$", "version", "=", "new", "Version", "(", "$", "this", "->", "getDependency", "(", ")", ")", ";", "Option", "::", "set", "(", "$", "this", "->", "getProduct", "(", ")", ...
Register the product in WordPress options. @since 1.0.0 @return null
[ "Register", "the", "product", "in", "WordPress", "options", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Registration.php#L61-L66
train
thelia/core
lib/Thelia/Action/Payment.php
Payment.isValid
public function isValid(IsValidPaymentEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $module = $event->getModule(); // dispatch event to target specific module $dispatcher->dispatch( TheliaEvents::getModuleEvent( TheliaEvents::MODULE_PAYMENT_IS_VALID, $module->getCode() ), $event ); if ($event->isPropagationStopped()) { return; } // call legacy module method $event->setValidModule($module->isValidPayment()); }
php
public function isValid(IsValidPaymentEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $module = $event->getModule(); // dispatch event to target specific module $dispatcher->dispatch( TheliaEvents::getModuleEvent( TheliaEvents::MODULE_PAYMENT_IS_VALID, $module->getCode() ), $event ); if ($event->isPropagationStopped()) { return; } // call legacy module method $event->setValidModule($module->isValidPayment()); }
[ "public", "function", "isValid", "(", "IsValidPaymentEvent", "$", "event", ",", "$", "eventName", ",", "EventDispatcherInterface", "$", "dispatcher", ")", "{", "$", "module", "=", "$", "event", "->", "getModule", "(", ")", ";", "// dispatch event to target specifi...
Check if a module is valid @param IsValidPaymentEvent $event
[ "Check", "if", "a", "module", "is", "valid" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Payment.php#L33-L52
train
thelia/core
lib/Thelia/Tools/RememberMeTrait.php
RememberMeTrait.getRememberMeKeyFromCookie
protected function getRememberMeKeyFromCookie(Request $request, $cookieName) { $ctp = new CookieTokenProvider(); return $ctp->getKeyFromCookie($request, $cookieName); }
php
protected function getRememberMeKeyFromCookie(Request $request, $cookieName) { $ctp = new CookieTokenProvider(); return $ctp->getKeyFromCookie($request, $cookieName); }
[ "protected", "function", "getRememberMeKeyFromCookie", "(", "Request", "$", "request", ",", "$", "cookieName", ")", "{", "$", "ctp", "=", "new", "CookieTokenProvider", "(", ")", ";", "return", "$", "ctp", "->", "getKeyFromCookie", "(", "$", "request", ",", "...
Get the remember me key from the cookie. @return string hte key found, or null if no key was found.
[ "Get", "the", "remember", "me", "key", "from", "the", "cookie", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Tools/RememberMeTrait.php#L32-L37
train
thelia/core
lib/Thelia/Tools/RememberMeTrait.php
RememberMeTrait.createRememberMeCookie
protected function createRememberMeCookie(UserInterface $user, $cookieName, $cookieExpiration) { $ctp = new CookieTokenProvider(); $ctp->createCookie( $user, $cookieName, $cookieExpiration ); }
php
protected function createRememberMeCookie(UserInterface $user, $cookieName, $cookieExpiration) { $ctp = new CookieTokenProvider(); $ctp->createCookie( $user, $cookieName, $cookieExpiration ); }
[ "protected", "function", "createRememberMeCookie", "(", "UserInterface", "$", "user", ",", "$", "cookieName", ",", "$", "cookieExpiration", ")", "{", "$", "ctp", "=", "new", "CookieTokenProvider", "(", ")", ";", "$", "ctp", "->", "createCookie", "(", "$", "u...
Create the remember me cookie for the given user.
[ "Create", "the", "remember", "me", "cookie", "for", "the", "given", "user", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Tools/RememberMeTrait.php#L42-L51
train
grom358/pharborist
src/Constants/ConstantNode.php
ConstantNode.toUpperCase
public function toUpperCase() { $token = $this->getConstantName()->lastToken(); $token->setText(strtoupper($token->getText())); return $this; }
php
public function toUpperCase() { $token = $this->getConstantName()->lastToken(); $token->setText(strtoupper($token->getText())); return $this; }
[ "public", "function", "toUpperCase", "(", ")", "{", "$", "token", "=", "$", "this", "->", "getConstantName", "(", ")", "->", "lastToken", "(", ")", ";", "$", "token", "->", "setText", "(", "strtoupper", "(", "$", "token", "->", "getText", "(", ")", "...
Convert the constant into uppercase. @return $this
[ "Convert", "the", "constant", "into", "uppercase", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/Constants/ConstantNode.php#L44-L48
train
grom358/pharborist
src/Constants/ConstantNode.php
ConstantNode.toLowerCase
public function toLowerCase() { $token = $this->getConstantName()->lastToken(); $token->setText(strtolower($token->getText())); return $this; }
php
public function toLowerCase() { $token = $this->getConstantName()->lastToken(); $token->setText(strtolower($token->getText())); return $this; }
[ "public", "function", "toLowerCase", "(", ")", "{", "$", "token", "=", "$", "this", "->", "getConstantName", "(", ")", "->", "lastToken", "(", ")", ";", "$", "token", "->", "setText", "(", "strtolower", "(", "$", "token", "->", "getText", "(", ")", "...
Convert the constant into lowercase. @return $this
[ "Convert", "the", "constant", "into", "lowercase", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/Constants/ConstantNode.php#L55-L59
train
Superbalist/php-event-pubsub
src/EventManager.php
EventManager.listen
public function listen($channel, $expr, callable $handler) { $this->adapter->subscribe($channel, function ($message) use ($expr, $handler) { $this->handleSubscribeCallback($message, $expr, $handler); }); }
php
public function listen($channel, $expr, callable $handler) { $this->adapter->subscribe($channel, function ($message) use ($expr, $handler) { $this->handleSubscribeCallback($message, $expr, $handler); }); }
[ "public", "function", "listen", "(", "$", "channel", ",", "$", "expr", ",", "callable", "$", "handler", ")", "{", "$", "this", "->", "adapter", "->", "subscribe", "(", "$", "channel", ",", "function", "(", "$", "message", ")", "use", "(", "$", "expr"...
Listen for an event. @param string $channel @param string $expr @param callable $handler
[ "Listen", "for", "an", "event", "." ]
d84b8216137126d314bfaed9ab5efa1a3985e433
https://github.com/Superbalist/php-event-pubsub/blob/d84b8216137126d314bfaed9ab5efa1a3985e433/src/EventManager.php#L207-L212
train
Superbalist/php-event-pubsub
src/EventManager.php
EventManager.dispatchBatch
public function dispatchBatch($channel, array $events) { $messages = []; $validates = true; foreach ($events as $event) { /** @var EventInterface $event */ $event = $this->prepEventForDispatch($event); if ($this->validator) { $result = $this->validator->validate($event); if ($result->fails()) { $validates = false; // pass to validation fail handler? if ($this->validationFailHandler) { call_user_func($this->validationFailHandler, $result); } if ($this->throwValidationExceptionsOnDispatch) { throw new ValidationException($result); } } } $messages[] = $event->toMessage(); } if ($validates) { $this->adapter->publishBatch($channel, $messages); } }
php
public function dispatchBatch($channel, array $events) { $messages = []; $validates = true; foreach ($events as $event) { /** @var EventInterface $event */ $event = $this->prepEventForDispatch($event); if ($this->validator) { $result = $this->validator->validate($event); if ($result->fails()) { $validates = false; // pass to validation fail handler? if ($this->validationFailHandler) { call_user_func($this->validationFailHandler, $result); } if ($this->throwValidationExceptionsOnDispatch) { throw new ValidationException($result); } } } $messages[] = $event->toMessage(); } if ($validates) { $this->adapter->publishBatch($channel, $messages); } }
[ "public", "function", "dispatchBatch", "(", "$", "channel", ",", "array", "$", "events", ")", "{", "$", "messages", "=", "[", "]", ";", "$", "validates", "=", "true", ";", "foreach", "(", "$", "events", "as", "$", "event", ")", "{", "/** @var EventInte...
Dispatch multiple events. @param string $channel @param array $events @throws ValidationException
[ "Dispatch", "multiple", "events", "." ]
d84b8216137126d314bfaed9ab5efa1a3985e433
https://github.com/Superbalist/php-event-pubsub/blob/d84b8216137126d314bfaed9ab5efa1a3985e433/src/EventManager.php#L318-L349
train
NotifyMeHQ/notifyme
src/Adapters/Campfire/CampfireFactory.php
CampfireFactory.make
public function make(array $config) { Arr::requires($config, ['from', 'token']); $client = new Client(); return new CampfireGateway($client, $config); }
php
public function make(array $config) { Arr::requires($config, ['from', 'token']); $client = new Client(); return new CampfireGateway($client, $config); }
[ "public", "function", "make", "(", "array", "$", "config", ")", "{", "Arr", "::", "requires", "(", "$", "config", ",", "[", "'from'", ",", "'token'", "]", ")", ";", "$", "client", "=", "new", "Client", "(", ")", ";", "return", "new", "CampfireGateway...
Create a new campfire gateway instance. @param string[] $config @return \NotifyMeHQ\Adapters\Campfire\CampfireGateway
[ "Create", "a", "new", "campfire", "gateway", "instance", "." ]
2af4bdcfe9df6db7ea79e2dce90b106ccb285b06
https://github.com/NotifyMeHQ/notifyme/blob/2af4bdcfe9df6db7ea79e2dce90b106ccb285b06/src/Adapters/Campfire/CampfireFactory.php#L27-L34
train
MetaModels/attribute_tags
src/EventListener/BackendListener.php
BackendListener.getTableNames
public function getTableNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_table'])) { return; } $sqlTable = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.sql-table', [], 'contao_tl_metamodel_attribute' ); $translated = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.translated', [], 'contao_tl_metamodel_attribute' ); $untranslated = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.untranslated', [], 'contao_tl_metamodel_attribute' ); $result = $this->getMetaModelTableNames($translated, $untranslated); foreach ($this->connection->getSchemaManager()->listTableNames() as $table) { if (0 !== \strpos($table, 'mm_')) { $result[$sqlTable][$table] = $table; } } if (\is_array($result[$translated])) { \asort($result[$translated]); } if (\is_array($result[$untranslated])) { \asort($result[$untranslated]); } if (\is_array($result[$sqlTable])) { \asort($result[$sqlTable]); } $event->setOptions($result); }
php
public function getTableNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_table'])) { return; } $sqlTable = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.sql-table', [], 'contao_tl_metamodel_attribute' ); $translated = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.translated', [], 'contao_tl_metamodel_attribute' ); $untranslated = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.untranslated', [], 'contao_tl_metamodel_attribute' ); $result = $this->getMetaModelTableNames($translated, $untranslated); foreach ($this->connection->getSchemaManager()->listTableNames() as $table) { if (0 !== \strpos($table, 'mm_')) { $result[$sqlTable][$table] = $table; } } if (\is_array($result[$translated])) { \asort($result[$translated]); } if (\is_array($result[$untranslated])) { \asort($result[$untranslated]); } if (\is_array($result[$sqlTable])) { \asort($result[$sqlTable]); } $event->setOptions($result); }
[ "public", "function", "getTableNames", "(", "GetPropertyOptionsEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "isBackendOptionRequestFor", "(", "$", "event", ",", "[", "'tag_table'", "]", ")", ")", "{", "return", ";", "}", "$", "sqlTabl...
Retrieve all database table names and store them into the event. @param GetPropertyOptionsEvent $event The event. @return void
[ "Retrieve", "all", "database", "table", "names", "and", "store", "them", "into", "the", "event", "." ]
d09c2cd18b299a48532caa0de8c70b7944282a8e
https://github.com/MetaModels/attribute_tags/blob/d09c2cd18b299a48532caa0de8c70b7944282a8e/src/EventListener/BackendListener.php#L116-L158
train
MetaModels/attribute_tags
src/EventListener/BackendListener.php
BackendListener.getColumnNames
public function getColumnNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_column', 'tag_alias', 'tag_sorting'])) { return; } $result = $this->getColumnNamesFrom($event->getModel()->getProperty('tag_table')); if (!empty($result)) { \asort($result); $event->setOptions($result); } }
php
public function getColumnNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_column', 'tag_alias', 'tag_sorting'])) { return; } $result = $this->getColumnNamesFrom($event->getModel()->getProperty('tag_table')); if (!empty($result)) { \asort($result); $event->setOptions($result); } }
[ "public", "function", "getColumnNames", "(", "GetPropertyOptionsEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "isBackendOptionRequestFor", "(", "$", "event", ",", "[", "'tag_column'", ",", "'tag_alias'", ",", "'tag_sorting'", "]", ")", ")"...
Retrieve all column names for the current selected table. @param GetPropertyOptionsEvent $event The event. @return void
[ "Retrieve", "all", "column", "names", "for", "the", "current", "selected", "table", "." ]
d09c2cd18b299a48532caa0de8c70b7944282a8e
https://github.com/MetaModels/attribute_tags/blob/d09c2cd18b299a48532caa0de8c70b7944282a8e/src/EventListener/BackendListener.php#L167-L179
train
MetaModels/attribute_tags
src/EventListener/BackendListener.php
BackendListener.checkQuery
public function checkQuery(EncodePropertyValueFromWidgetEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (('tl_metamodel_attribute' !== $event->getEnvironment()->getDataDefinition()->getName()) || ('tag_where' !== $event->getProperty()) ) { return; } $where = $event->getValue(); $values = $event->getPropertyValueBag(); if ($where) { $query = $this->connection->createQueryBuilder() ->select($values->getPropertyValue('tag_table') . '.*') ->from($values->getPropertyValue('tag_table')) ->where($where) ->orderBy($values->getPropertyValue('tag_sorting') ?: $values->getPropertyValue('tag_id')); try { $query->execute(); } catch (\Exception $e) { throw new \RuntimeException( \sprintf( '%s %s', $this->translator->trans('sql_error', [], 'contao_tl_metamodel_attribute'), $e->getMessage() ) ); } } }
php
public function checkQuery(EncodePropertyValueFromWidgetEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (('tl_metamodel_attribute' !== $event->getEnvironment()->getDataDefinition()->getName()) || ('tag_where' !== $event->getProperty()) ) { return; } $where = $event->getValue(); $values = $event->getPropertyValueBag(); if ($where) { $query = $this->connection->createQueryBuilder() ->select($values->getPropertyValue('tag_table') . '.*') ->from($values->getPropertyValue('tag_table')) ->where($where) ->orderBy($values->getPropertyValue('tag_sorting') ?: $values->getPropertyValue('tag_id')); try { $query->execute(); } catch (\Exception $e) { throw new \RuntimeException( \sprintf( '%s %s', $this->translator->trans('sql_error', [], 'contao_tl_metamodel_attribute'), $e->getMessage() ) ); } } }
[ "public", "function", "checkQuery", "(", "EncodePropertyValueFromWidgetEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "scopeMatcher", "->", "currentScopeIsBackend", "(", ")", ")", "{", "return", ";", "}", "if", "(", "(", "'tl_metamodel_attr...
Check if the select_where value is valid by firing a test query. @param EncodePropertyValueFromWidgetEvent $event The event. @return void @throws \RuntimeException When the where condition is invalid. @SuppressWarnings(PHPMD.Superglobals) @SuppressWarnings(PHPMD.CamelCaseVariableName)
[ "Check", "if", "the", "select_where", "value", "is", "valid", "by", "firing", "a", "test", "query", "." ]
d09c2cd18b299a48532caa0de8c70b7944282a8e
https://github.com/MetaModels/attribute_tags/blob/d09c2cd18b299a48532caa0de8c70b7944282a8e/src/EventListener/BackendListener.php#L310-L344
train
MetaModels/attribute_tags
src/EventListener/BackendListener.php
BackendListener.getColumnNamesFrom
private function getColumnNamesFrom($table) { if (0 === \strpos($table, 'mm_')) { $attributes = $this->getAttributeNamesFrom($table); \asort($attributes); $sql = $this->translator->trans( 'tl_metamodel_attribute.tag_column_type.sql', [], 'contao_tl_metamodel_attribute' ); $attribute = $this->translator->trans( 'tl_metamodel_attribute.tag_column_type.attribute', [], 'contao_tl_metamodel_attribute' ); return [ $sql => \array_diff_key( $this->getColumnNamesFromTable($table), \array_flip(\array_keys($attributes)) ), $attribute => $attributes, ]; } return $this->getColumnNamesFromTable($table); }
php
private function getColumnNamesFrom($table) { if (0 === \strpos($table, 'mm_')) { $attributes = $this->getAttributeNamesFrom($table); \asort($attributes); $sql = $this->translator->trans( 'tl_metamodel_attribute.tag_column_type.sql', [], 'contao_tl_metamodel_attribute' ); $attribute = $this->translator->trans( 'tl_metamodel_attribute.tag_column_type.attribute', [], 'contao_tl_metamodel_attribute' ); return [ $sql => \array_diff_key( $this->getColumnNamesFromTable($table), \array_flip(\array_keys($attributes)) ), $attribute => $attributes, ]; } return $this->getColumnNamesFromTable($table); }
[ "private", "function", "getColumnNamesFrom", "(", "$", "table", ")", "{", "if", "(", "0", "===", "\\", "strpos", "(", "$", "table", ",", "'mm_'", ")", ")", "{", "$", "attributes", "=", "$", "this", "->", "getAttributeNamesFrom", "(", "$", "table", ")",...
Retrieve all column names for the given table. @param string $table The table name. @return array
[ "Retrieve", "all", "column", "names", "for", "the", "given", "table", "." ]
d09c2cd18b299a48532caa0de8c70b7944282a8e
https://github.com/MetaModels/attribute_tags/blob/d09c2cd18b299a48532caa0de8c70b7944282a8e/src/EventListener/BackendListener.php#L379-L406
train
MetaModels/attribute_tags
src/EventListener/BackendListener.php
BackendListener.addCondition
private function addCondition($property, $condition) { $currentCondition = $property->getVisibleCondition(); if ((!($currentCondition instanceof ConditionChainInterface)) || ($currentCondition->getConjunction() != ConditionChainInterface::OR_CONJUNCTION) ) { if ($currentCondition === null) { $currentCondition = new PropertyConditionChain([$condition]); } else { $currentCondition = new PropertyConditionChain([$currentCondition, $condition]); } $currentCondition->setConjunction(ConditionChainInterface::OR_CONJUNCTION); $property->setVisibleCondition($currentCondition); } else { $currentCondition->addCondition($condition); } }
php
private function addCondition($property, $condition) { $currentCondition = $property->getVisibleCondition(); if ((!($currentCondition instanceof ConditionChainInterface)) || ($currentCondition->getConjunction() != ConditionChainInterface::OR_CONJUNCTION) ) { if ($currentCondition === null) { $currentCondition = new PropertyConditionChain([$condition]); } else { $currentCondition = new PropertyConditionChain([$currentCondition, $condition]); } $currentCondition->setConjunction(ConditionChainInterface::OR_CONJUNCTION); $property->setVisibleCondition($currentCondition); } else { $currentCondition->addCondition($condition); } }
[ "private", "function", "addCondition", "(", "$", "property", ",", "$", "condition", ")", "{", "$", "currentCondition", "=", "$", "property", "->", "getVisibleCondition", "(", ")", ";", "if", "(", "(", "!", "(", "$", "currentCondition", "instanceof", "Conditi...
Add a condition to a property. @param PropertyInterface $property The property. @param ConditionInterface $condition The condition to add. @return void
[ "Add", "a", "condition", "to", "a", "property", "." ]
d09c2cd18b299a48532caa0de8c70b7944282a8e
https://github.com/MetaModels/attribute_tags/blob/d09c2cd18b299a48532caa0de8c70b7944282a8e/src/EventListener/BackendListener.php#L514-L530
train
MetaModels/attribute_tags
src/EventListener/BackendListener.php
BackendListener.isBackendOptionRequestFor
private function isBackendOptionRequestFor($event, $fields) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return false; } return ('tl_metamodel_attribute' === $event->getEnvironment()->getDataDefinition()->getName()) && \in_array($event->getPropertyName(), $fields); }
php
private function isBackendOptionRequestFor($event, $fields) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return false; } return ('tl_metamodel_attribute' === $event->getEnvironment()->getDataDefinition()->getName()) && \in_array($event->getPropertyName(), $fields); }
[ "private", "function", "isBackendOptionRequestFor", "(", "$", "event", ",", "$", "fields", ")", "{", "if", "(", "!", "$", "this", "->", "scopeMatcher", "->", "currentScopeIsBackend", "(", ")", ")", "{", "return", "false", ";", "}", "return", "(", "'tl_meta...
Test if the event is an option request for any of the passed fields. @param GetPropertyOptionsEvent $event The event. @param string[] $fields The field names. @return bool
[ "Test", "if", "the", "event", "is", "an", "option", "request", "for", "any", "of", "the", "passed", "fields", "." ]
d09c2cd18b299a48532caa0de8c70b7944282a8e
https://github.com/MetaModels/attribute_tags/blob/d09c2cd18b299a48532caa0de8c70b7944282a8e/src/EventListener/BackendListener.php#L540-L548
train
jomweb/ringgit
src/Concerns/Cash.php
Cash.getClosestAcceptedCashAmount
protected function getClosestAcceptedCashAmount($amount): int { $value = Number::fromString($amount)->getIntegerPart(); $cent = $amount % 5; if ($cent <= 2) { $value = $value - $cent; } else { $value = $value + (5 - $cent); } return $value; }
php
protected function getClosestAcceptedCashAmount($amount): int { $value = Number::fromString($amount)->getIntegerPart(); $cent = $amount % 5; if ($cent <= 2) { $value = $value - $cent; } else { $value = $value + (5 - $cent); } return $value; }
[ "protected", "function", "getClosestAcceptedCashAmount", "(", "$", "amount", ")", ":", "int", "{", "$", "value", "=", "Number", "::", "fromString", "(", "$", "amount", ")", "->", "getIntegerPart", "(", ")", ";", "$", "cent", "=", "$", "amount", "%", "5",...
Get closest accepted cash amount. @param int|string $amount @return int
[ "Get", "closest", "accepted", "cash", "amount", "." ]
d444f994bafabfbfa063cce2017500ebf2aa35f7
https://github.com/jomweb/ringgit/blob/d444f994bafabfbfa063cce2017500ebf2aa35f7/src/Concerns/Cash.php#L51-L63
train
mglaman/platform-docker
src/Platform.php
Platform.getUri
public static function getUri() { $nginx_port = Docker::getContainerPort(Compose::getContainerName(self::projectName(), 'nginx'), 80); if (!$nginx_port) { throw new \RuntimeException("nginx container is not running"); } return "http://localhost:$nginx_port"; }
php
public static function getUri() { $nginx_port = Docker::getContainerPort(Compose::getContainerName(self::projectName(), 'nginx'), 80); if (!$nginx_port) { throw new \RuntimeException("nginx container is not running"); } return "http://localhost:$nginx_port"; }
[ "public", "static", "function", "getUri", "(", ")", "{", "$", "nginx_port", "=", "Docker", "::", "getContainerPort", "(", "Compose", "::", "getContainerName", "(", "self", "::", "projectName", "(", ")", ",", "'nginx'", ")", ",", "80", ")", ";", "if", "("...
Gets the uri to access the site. @return string @throws \RuntimeException Thrown when the nginx container is not available.
[ "Gets", "the", "uri", "to", "access", "the", "site", "." ]
217be131f70454a0f2c62a7ae0553c432731bfdf
https://github.com/mglaman/platform-docker/blob/217be131f70454a0f2c62a7ae0553c432731bfdf/src/Platform.php#L100-L106
train
grom358/pharborist
src/Objects/ClassMethodCallNode.php
ClassMethodCallNode.create
public static function create($class_name, $method_name) { if (is_string($class_name)) { $class_name = NameNode::create($class_name); } /** @var ClassMethodCallNode $node */ $node = new static(); $node->addChild($class_name, 'className'); $node->addChild(Token::doubleColon()); $node->addChild(Token::identifier($method_name), 'methodName'); $node->addChild(Token::openParen(), 'openParen'); $node->addChild(new CommaListNode(), 'arguments'); $node->addChild(Token::closeParen(), 'closeParen'); return $node; }
php
public static function create($class_name, $method_name) { if (is_string($class_name)) { $class_name = NameNode::create($class_name); } /** @var ClassMethodCallNode $node */ $node = new static(); $node->addChild($class_name, 'className'); $node->addChild(Token::doubleColon()); $node->addChild(Token::identifier($method_name), 'methodName'); $node->addChild(Token::openParen(), 'openParen'); $node->addChild(new CommaListNode(), 'arguments'); $node->addChild(Token::closeParen(), 'closeParen'); return $node; }
[ "public", "static", "function", "create", "(", "$", "class_name", ",", "$", "method_name", ")", "{", "if", "(", "is_string", "(", "$", "class_name", ")", ")", "{", "$", "class_name", "=", "NameNode", "::", "create", "(", "$", "class_name", ")", ";", "}...
Creates a method call on a class with an empty argument list. @param Node|string $class_name The class node which is typically NameNode of class. @param string $method_name The name of the called method. @return static
[ "Creates", "a", "method", "call", "on", "a", "class", "with", "an", "empty", "argument", "list", "." ]
0db9e51299a80e95b06857ed1809f59bbbab1af6
https://github.com/grom358/pharborist/blob/0db9e51299a80e95b06857ed1809f59bbbab1af6/src/Objects/ClassMethodCallNode.php#L75-L88
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.clearCache
public function clearCache(CachedFileEvent $event) { $path = $this->getCachePath($event->getCacheSubdirectory(), false); $this->clearDirectory($path); }
php
public function clearCache(CachedFileEvent $event) { $path = $this->getCachePath($event->getCacheSubdirectory(), false); $this->clearDirectory($path); }
[ "public", "function", "clearCache", "(", "CachedFileEvent", "$", "event", ")", "{", "$", "path", "=", "$", "this", "->", "getCachePath", "(", "$", "event", "->", "getCacheSubdirectory", "(", ")", ",", "false", ")", ";", "$", "this", "->", "clearDirectory",...
Clear the file cache. Is a subdirectory is specified, only this directory is cleared. If no directory is specified, the whole cache is cleared. Only files are deleted, directories will remain. @param CachedFileEvent $event
[ "Clear", "the", "file", "cache", ".", "Is", "a", "subdirectory", "is", "specified", "only", "this", "directory", "is", "cleared", ".", "If", "no", "directory", "is", "specified", "the", "whole", "cache", "is", "cleared", ".", "Only", "files", "are", "delet...
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L80-L85
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.clearDirectory
protected function clearDirectory($path) { $iterator = new \DirectoryIterator($path); /** @var \DirectoryIterator $fileinfo */ foreach ($iterator as $fileinfo) { if ($fileinfo->isDot()) { continue; } if ($fileinfo->isFile() || $fileinfo->isLink()) { @unlink($fileinfo->getPathname()); } elseif ($fileinfo->isDir()) { $this->clearDirectory($fileinfo->getPathname()); } } }
php
protected function clearDirectory($path) { $iterator = new \DirectoryIterator($path); /** @var \DirectoryIterator $fileinfo */ foreach ($iterator as $fileinfo) { if ($fileinfo->isDot()) { continue; } if ($fileinfo->isFile() || $fileinfo->isLink()) { @unlink($fileinfo->getPathname()); } elseif ($fileinfo->isDir()) { $this->clearDirectory($fileinfo->getPathname()); } } }
[ "protected", "function", "clearDirectory", "(", "$", "path", ")", "{", "$", "iterator", "=", "new", "\\", "DirectoryIterator", "(", "$", "path", ")", ";", "/** @var \\DirectoryIterator $fileinfo */", "foreach", "(", "$", "iterator", "as", "$", "fileinfo", ")", ...
Recursively clears the specified directory. @param string $path the directory path
[ "Recursively", "clears", "the", "specified", "directory", "." ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L92-L108
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.getCacheFileURL
protected function getCacheFileURL($subdir, $safe_filename) { $path = $this->getCachePathFromWebRoot($subdir); return URL::getInstance()->absoluteUrl(sprintf("%s/%s", $path, $safe_filename), null, URL::PATH_TO_FILE, $this->cdnBaseUrl); }
php
protected function getCacheFileURL($subdir, $safe_filename) { $path = $this->getCachePathFromWebRoot($subdir); return URL::getInstance()->absoluteUrl(sprintf("%s/%s", $path, $safe_filename), null, URL::PATH_TO_FILE, $this->cdnBaseUrl); }
[ "protected", "function", "getCacheFileURL", "(", "$", "subdir", ",", "$", "safe_filename", ")", "{", "$", "path", "=", "$", "this", "->", "getCachePathFromWebRoot", "(", "$", "subdir", ")", ";", "return", "URL", "::", "getInstance", "(", ")", "->", "absolu...
Return the absolute URL to the cached file @param string $subdir the subdirectory related to cache base @param string $safe_filename the safe filename, as returned by getCacheFilePath() @return string the absolute URL to the cached file
[ "Return", "the", "absolute", "URL", "to", "the", "cached", "file" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L117-L122
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.getCacheFilePath
protected function getCacheFilePath($subdir, $filename, $forceOriginalFile = false, $hashed_options = null) { $path = $this->getCachePath($subdir); $safe_filename = preg_replace("[^:alnum:\-\._]", "-", strtolower(basename($filename))); // Keep original safe name if no tranformations are applied if ($forceOriginalFile || $hashed_options == null) { return sprintf("%s/%s", $path, $safe_filename); } else { return sprintf("%s/%s-%s", $path, $hashed_options, $safe_filename); } }
php
protected function getCacheFilePath($subdir, $filename, $forceOriginalFile = false, $hashed_options = null) { $path = $this->getCachePath($subdir); $safe_filename = preg_replace("[^:alnum:\-\._]", "-", strtolower(basename($filename))); // Keep original safe name if no tranformations are applied if ($forceOriginalFile || $hashed_options == null) { return sprintf("%s/%s", $path, $safe_filename); } else { return sprintf("%s/%s-%s", $path, $hashed_options, $safe_filename); } }
[ "protected", "function", "getCacheFilePath", "(", "$", "subdir", ",", "$", "filename", ",", "$", "forceOriginalFile", "=", "false", ",", "$", "hashed_options", "=", "null", ")", "{", "$", "path", "=", "$", "this", "->", "getCachePath", "(", "$", "subdir", ...
Return the full path of the cached file @param string $subdir the subdirectory related to cache base @param string $filename the filename @param boolean $forceOriginalFile if true, the original file path in the cache dir is returned. @param string $hashed_options a hash of transformation options, or null if no transformations have been applied @return string the cache directory path relative to Web Root
[ "Return", "the", "full", "path", "of", "the", "cached", "file" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L133-L145
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.getCachePathFromWebRoot
protected function getCachePathFromWebRoot($subdir = null) { $cache_dir_from_web_root = $this->getCacheDirFromWebRoot(); if ($subdir != null) { $safe_subdir = basename($subdir); $path = sprintf("%s/%s", $cache_dir_from_web_root, $safe_subdir); } else { $path = $cache_dir_from_web_root; } // Check if path is valid, e.g. in the cache dir return $path; }
php
protected function getCachePathFromWebRoot($subdir = null) { $cache_dir_from_web_root = $this->getCacheDirFromWebRoot(); if ($subdir != null) { $safe_subdir = basename($subdir); $path = sprintf("%s/%s", $cache_dir_from_web_root, $safe_subdir); } else { $path = $cache_dir_from_web_root; } // Check if path is valid, e.g. in the cache dir return $path; }
[ "protected", "function", "getCachePathFromWebRoot", "(", "$", "subdir", "=", "null", ")", "{", "$", "cache_dir_from_web_root", "=", "$", "this", "->", "getCacheDirFromWebRoot", "(", ")", ";", "if", "(", "$", "subdir", "!=", "null", ")", "{", "$", "safe_subdi...
Return the cache directory path relative to Web Root @param string $subdir the subdirectory related to cache base, or null to get the cache directory only. @return string the cache directory path relative to Web Root
[ "Return", "the", "cache", "directory", "path", "relative", "to", "Web", "Root" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L153-L167
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.getCachePath
protected function getCachePath($subdir = null, $create_if_not_exists = true) { $cache_base = $this->getCachePathFromWebRoot($subdir); $web_root = rtrim(THELIA_WEB_DIR, '/'); $path = sprintf("%s/%s", $web_root, $cache_base); // Create directory (recursively) if it does not exists. if ($create_if_not_exists && !is_dir($path)) { if (!@mkdir($path, 0777, true)) { throw new \RuntimeException(sprintf("Failed to create %s file in cache directory", $path)); } } // Check if path is valid, e.g. in the cache dir $cache_base = realpath(sprintf("%s/%s", $web_root, $this->getCachePathFromWebRoot())); if (strpos(realpath($path), $cache_base) !== 0) { throw new \InvalidArgumentException(sprintf("Invalid cache path %s, with subdirectory %s", $path, $subdir)); } return $path; }
php
protected function getCachePath($subdir = null, $create_if_not_exists = true) { $cache_base = $this->getCachePathFromWebRoot($subdir); $web_root = rtrim(THELIA_WEB_DIR, '/'); $path = sprintf("%s/%s", $web_root, $cache_base); // Create directory (recursively) if it does not exists. if ($create_if_not_exists && !is_dir($path)) { if (!@mkdir($path, 0777, true)) { throw new \RuntimeException(sprintf("Failed to create %s file in cache directory", $path)); } } // Check if path is valid, e.g. in the cache dir $cache_base = realpath(sprintf("%s/%s", $web_root, $this->getCachePathFromWebRoot())); if (strpos(realpath($path), $cache_base) !== 0) { throw new \InvalidArgumentException(sprintf("Invalid cache path %s, with subdirectory %s", $path, $subdir)); } return $path; }
[ "protected", "function", "getCachePath", "(", "$", "subdir", "=", "null", ",", "$", "create_if_not_exists", "=", "true", ")", "{", "$", "cache_base", "=", "$", "this", "->", "getCachePathFromWebRoot", "(", "$", "subdir", ")", ";", "$", "web_root", "=", "rt...
Return the absolute cache directory path @param string $subdir the subdirectory related to cache base, or null to get the cache base directory. @param bool $create_if_not_exists create the directory if it is not found @throws \RuntimeException if cache directory cannot be created @throws \InvalidArgumentException ii path is invalid, e.g. not in the cache dir @return string the absolute cache directory path
[ "Return", "the", "absolute", "cache", "directory", "path" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L180-L203
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.saveFile
public function saveFile(FileCreateOrUpdateEvent $event) { $model = $event->getModel(); $model->setFile(sprintf("tmp/%s", $event->getUploadedFile()->getFilename())); $con = Propel::getWriteConnection(ProductImageTableMap::DATABASE_NAME); $con->beginTransaction(); try { $nbModifiedLines = $model->save($con); $event->setModel($model); if (!$nbModifiedLines) { throw new FileException( sprintf( 'File "%s" (type %s) with parent id %s failed to be saved', $event->getParentName(), \get_class($model), $event->getParentId() ) ); } $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); $con->commit(); } catch (\Exception $e) { $con->rollBack(); throw $e; } }
php
public function saveFile(FileCreateOrUpdateEvent $event) { $model = $event->getModel(); $model->setFile(sprintf("tmp/%s", $event->getUploadedFile()->getFilename())); $con = Propel::getWriteConnection(ProductImageTableMap::DATABASE_NAME); $con->beginTransaction(); try { $nbModifiedLines = $model->save($con); $event->setModel($model); if (!$nbModifiedLines) { throw new FileException( sprintf( 'File "%s" (type %s) with parent id %s failed to be saved', $event->getParentName(), \get_class($model), $event->getParentId() ) ); } $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); $con->commit(); } catch (\Exception $e) { $con->rollBack(); throw $e; } }
[ "public", "function", "saveFile", "(", "FileCreateOrUpdateEvent", "$", "event", ")", "{", "$", "model", "=", "$", "event", "->", "getModel", "(", ")", ";", "$", "model", "->", "setFile", "(", "sprintf", "(", "\"tmp/%s\"", ",", "$", "event", "->", "getUpl...
Take care of saving a file in the database and file storage @param FileCreateOrUpdateEvent $event Image event @throws \Thelia\Exception\FileException|\Exception
[ "Take", "care", "of", "saving", "a", "file", "in", "the", "database", "and", "file", "storage" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L213-L244
train
thelia/core
lib/Thelia/Action/BaseCachedFile.php
BaseCachedFile.updateFile
public function updateFile(FileCreateOrUpdateEvent $event) { // Copy and save file if ($event->getUploadedFile()) { // Remove old picture file from file storage $url = $event->getModel()->getUploadDir() . '/' . $event->getOldModel()->getFile(); unlink(str_replace('..', '', $url)); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); } // Update image modifications $event->getModel()->save(); $event->setModel($event->getModel()); }
php
public function updateFile(FileCreateOrUpdateEvent $event) { // Copy and save file if ($event->getUploadedFile()) { // Remove old picture file from file storage $url = $event->getModel()->getUploadDir() . '/' . $event->getOldModel()->getFile(); unlink(str_replace('..', '', $url)); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); } // Update image modifications $event->getModel()->save(); $event->setModel($event->getModel()); }
[ "public", "function", "updateFile", "(", "FileCreateOrUpdateEvent", "$", "event", ")", "{", "// Copy and save file", "if", "(", "$", "event", "->", "getUploadedFile", "(", ")", ")", "{", "// Remove old picture file from file storage", "$", "url", "=", "$", "event", ...
Take care of updating file in the database and file storage @param FileCreateOrUpdateEvent $event Image event @throws \Thelia\Exception\FileException
[ "Take", "care", "of", "updating", "file", "in", "the", "database", "and", "file", "storage" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/BaseCachedFile.php#L253-L269
train
thelia/core
lib/Thelia/Core/Event/Hook/HookRenderBlockEvent.php
HookRenderBlockEvent.addFragment
public function addFragment(Fragment $fragment) { if (!empty($this->fields)) { $fragment->filter($this->fields); } $this->fragmentBag->addFragment($fragment); return $this; }
php
public function addFragment(Fragment $fragment) { if (!empty($this->fields)) { $fragment->filter($this->fields); } $this->fragmentBag->addFragment($fragment); return $this; }
[ "public", "function", "addFragment", "(", "Fragment", "$", "fragment", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "fields", ")", ")", "{", "$", "fragment", "->", "filter", "(", "$", "this", "->", "fields", ")", ";", "}", "$", "this"...
Add a new fragment @param \Thelia\Core\Hook\Fragment $fragment @return $this
[ "Add", "a", "new", "fragment" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Event/Hook/HookRenderBlockEvent.php#L59-L67
train
BoldGrid/library
src/Library/Notice/KeyPrompt.php
KeyPrompt.setMessages
private function setMessages() { // Allowed html for wp_kses. $allowed_html = array( 'a' => array( 'href' => array(), ), 'strong' => array(), ); $msg = new \stdClass(); $msg->success = sprintf( wp_kses( /* translators: The Url to the BoldGrid Connect settings page. */ __( 'Your api key has been saved. To change, see <strong>Settings &#187; <a href="%1$s">BoldGrid Connect</a></strong>.', 'boldgrid-library' ), $allowed_html ), admin_url( 'options-general.php?page=boldgrid-connect.php' ) ); $msg->error = sprintf( // translators: 1 A br / break tag. esc_html__( 'Your API key appears to be invalid!%sPlease try to enter your BoldGrid Connect Key again.', 'boldgrid-library' ), '<br />' ); $msg->nonce = esc_html__( 'Security violation! An invalid nonce was detected.', 'boldgrid-library' ); $msg->timeout = esc_html__( 'Connection timed out. Please try again.', 'boldgrid-library' ); return $this->messages = $msg; }
php
private function setMessages() { // Allowed html for wp_kses. $allowed_html = array( 'a' => array( 'href' => array(), ), 'strong' => array(), ); $msg = new \stdClass(); $msg->success = sprintf( wp_kses( /* translators: The Url to the BoldGrid Connect settings page. */ __( 'Your api key has been saved. To change, see <strong>Settings &#187; <a href="%1$s">BoldGrid Connect</a></strong>.', 'boldgrid-library' ), $allowed_html ), admin_url( 'options-general.php?page=boldgrid-connect.php' ) ); $msg->error = sprintf( // translators: 1 A br / break tag. esc_html__( 'Your API key appears to be invalid!%sPlease try to enter your BoldGrid Connect Key again.', 'boldgrid-library' ), '<br />' ); $msg->nonce = esc_html__( 'Security violation! An invalid nonce was detected.', 'boldgrid-library' ); $msg->timeout = esc_html__( 'Connection timed out. Please try again.', 'boldgrid-library' ); return $this->messages = $msg; }
[ "private", "function", "setMessages", "(", ")", "{", "// Allowed html for wp_kses.", "$", "allowed_html", "=", "array", "(", "'a'", "=>", "array", "(", "'href'", "=>", "array", "(", ")", ",", ")", ",", "'strong'", "=>", "array", "(", ")", ",", ")", ";", ...
Sets the messages returned by key prompt. @since 1.0.0 @return object $messages Messages used by key prompt.
[ "Sets", "the", "messages", "returned", "by", "key", "prompt", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Notice/KeyPrompt.php#L93-L120
train
BoldGrid/library
src/Library/Notice/KeyPrompt.php
KeyPrompt.getState
public static function getState() { $state = 'no-key-added'; $license = Configs::get( 'start' )->getKey()->getLicense(); if ( $license ) { $isPremium = $license->isPremium( 'boldgrid-inspirations' ); $license = $isPremium ? 'premium' : 'basic'; $state = $license . '-key-active'; } return $state; }
php
public static function getState() { $state = 'no-key-added'; $license = Configs::get( 'start' )->getKey()->getLicense(); if ( $license ) { $isPremium = $license->isPremium( 'boldgrid-inspirations' ); $license = $isPremium ? 'premium' : 'basic'; $state = $license . '-key-active'; } return $state; }
[ "public", "static", "function", "getState", "(", ")", "{", "$", "state", "=", "'no-key-added'", ";", "$", "license", "=", "Configs", "::", "get", "(", "'start'", ")", "->", "getKey", "(", ")", "->", "getLicense", "(", ")", ";", "if", "(", "$", "licen...
Get the current state of the BoldGrid Connect Key. @since 1.0.0 @return string State, what to display when the prompt loads.
[ "Get", "the", "current", "state", "of", "the", "BoldGrid", "Connect", "Key", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Notice/KeyPrompt.php#L164-L175
train
BoldGrid/library
src/Library/Notice/KeyPrompt.php
KeyPrompt.keyNotice
public function keyNotice() { $display_notice = apply_filters( 'Boldgrid\Library\Library\Notice\KeyPrompt_display', ( ! Library\Notice::isDismissed( $this->userNoticeKey ) ) ); if ( $display_notice ) { $current_user = wp_get_current_user(); $email = $current_user->user_email; $first_name = empty( $current_user->user_firstname ) ? '' : $current_user->user_firstname; $last_name = empty( $current_user->user_lastname ) ? '' : $current_user->user_lastname; $api = Library\Configs::get( 'api' ) . '/api/open/generateKey'; /** * Check if the Envato notice to claim a Premium Connect Key should be enabled. * * A theme can add this filter and return true, which will enable this notice. * * @since 2.1.0 */ $enableClaimMessage = apply_filters( 'Boldgrid\Library\Library\Notice\ClaimPremiumKey_enable', false ); include dirname( __DIR__ ) . '/Views/KeyPrompt.php'; self::$isDisplayed = true; } }
php
public function keyNotice() { $display_notice = apply_filters( 'Boldgrid\Library\Library\Notice\KeyPrompt_display', ( ! Library\Notice::isDismissed( $this->userNoticeKey ) ) ); if ( $display_notice ) { $current_user = wp_get_current_user(); $email = $current_user->user_email; $first_name = empty( $current_user->user_firstname ) ? '' : $current_user->user_firstname; $last_name = empty( $current_user->user_lastname ) ? '' : $current_user->user_lastname; $api = Library\Configs::get( 'api' ) . '/api/open/generateKey'; /** * Check if the Envato notice to claim a Premium Connect Key should be enabled. * * A theme can add this filter and return true, which will enable this notice. * * @since 2.1.0 */ $enableClaimMessage = apply_filters( 'Boldgrid\Library\Library\Notice\ClaimPremiumKey_enable', false ); include dirname( __DIR__ ) . '/Views/KeyPrompt.php'; self::$isDisplayed = true; } }
[ "public", "function", "keyNotice", "(", ")", "{", "$", "display_notice", "=", "apply_filters", "(", "'Boldgrid\\Library\\Library\\Notice\\KeyPrompt_display'", ",", "(", "!", "Library", "\\", "Notice", "::", "isDismissed", "(", "$", "this", "->", "userNoticeKey", ")"...
Displays the notice. @since 1.0.0 @see \Boldgrid\Library\Library\Notice::isDismissed() @hook: admin_notices
[ "Displays", "the", "notice", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Notice/KeyPrompt.php#L186-L215
train
BoldGrid/library
src/Library/Notice/KeyPrompt.php
KeyPrompt.addKey
public function addKey() { /* * @todo A section of this code has been duplicated in Boldgrid\Library\Library\Key\addKey() * because the code for saving a key should be in the Key class and not the KeyPrompt class. * This method needs to be refactored using that addKey method. */ // When adding Keys, delete the transient to make sure we get new license info. delete_site_transient( 'bg_license_data' ); delete_site_transient( 'boldgrid_api_data' ); $key = $this->validate(); $data = $this->key->callCheckVersion( array( 'key' => $key ) ); $msg = $this->getMessages(); if ( is_object( $data ) ) { $this->key->save( $data, $key ); wp_send_json_success( array( 'message' => $msg->success, 'site_hash' => $data->result->data->site_hash, 'api_key' => apply_filters( 'Boldgrid\Library\License\getApiKey', false ), ) ); } else { $is_timeout = false !== strpos( $data, 'cURL error 28:' ); wp_send_json_error( array( 'message' => $is_timeout ? $msg->timeout : $msg->error ) ); } }
php
public function addKey() { /* * @todo A section of this code has been duplicated in Boldgrid\Library\Library\Key\addKey() * because the code for saving a key should be in the Key class and not the KeyPrompt class. * This method needs to be refactored using that addKey method. */ // When adding Keys, delete the transient to make sure we get new license info. delete_site_transient( 'bg_license_data' ); delete_site_transient( 'boldgrid_api_data' ); $key = $this->validate(); $data = $this->key->callCheckVersion( array( 'key' => $key ) ); $msg = $this->getMessages(); if ( is_object( $data ) ) { $this->key->save( $data, $key ); wp_send_json_success( array( 'message' => $msg->success, 'site_hash' => $data->result->data->site_hash, 'api_key' => apply_filters( 'Boldgrid\Library\License\getApiKey', false ), ) ); } else { $is_timeout = false !== strpos( $data, 'cURL error 28:' ); wp_send_json_error( array( 'message' => $is_timeout ? $msg->timeout : $msg->error ) ); } }
[ "public", "function", "addKey", "(", ")", "{", "/*\n\t\t * @todo A section of this code has been duplicated in Boldgrid\\Library\\Library\\Key\\addKey()\n\t\t * because the code for saving a key should be in the Key class and not the KeyPrompt class.\n\t\t * This method needs to be refactored using that...
Key input handling. @since 1.0.0 @hook: wp_ajax_addKey
[ "Key", "input", "handling", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Notice/KeyPrompt.php#L224-L251
train
BoldGrid/library
src/Library/Notice/KeyPrompt.php
KeyPrompt.validate
protected function validate() { $msg = $this->getMessages(); // Validate nonce. if ( ! isset( $_POST['set_key_auth'] ) || ! check_ajax_referer( 'boldgrid_set_key', 'set_key_auth', false ) ) { wp_send_json_error( array( 'message' => $msg->nonce ) ); } // Validate user input. if ( empty( $_POST['api_key'] ) ) { wp_send_json_error( array( 'message' => $msg->error ) ); } // Validate key. $valid = new Library\Key\Validate( sanitize_text_field( $_POST['api_key'] ) ); if ( ! $valid->getValid() ) { wp_send_json_error( array( 'message' => $msg->error ) ); } return $valid->getHash(); }
php
protected function validate() { $msg = $this->getMessages(); // Validate nonce. if ( ! isset( $_POST['set_key_auth'] ) || ! check_ajax_referer( 'boldgrid_set_key', 'set_key_auth', false ) ) { wp_send_json_error( array( 'message' => $msg->nonce ) ); } // Validate user input. if ( empty( $_POST['api_key'] ) ) { wp_send_json_error( array( 'message' => $msg->error ) ); } // Validate key. $valid = new Library\Key\Validate( sanitize_text_field( $_POST['api_key'] ) ); if ( ! $valid->getValid() ) { wp_send_json_error( array( 'message' => $msg->error ) ); } return $valid->getHash(); }
[ "protected", "function", "validate", "(", ")", "{", "$", "msg", "=", "$", "this", "->", "getMessages", "(", ")", ";", "// Validate nonce.", "if", "(", "!", "isset", "(", "$", "_POST", "[", "'set_key_auth'", "]", ")", "||", "!", "check_ajax_referer", "(",...
Handles validation of user input on API key entry form. @since 1.0.0 @return string The user's validate API key hash.
[ "Handles", "validation", "of", "user", "input", "on", "API", "key", "entry", "form", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Notice/KeyPrompt.php#L260-L280
train
BoldGrid/library
src/Library/Notice/KeyPrompt.php
KeyPrompt.getIsDismissed
public function getIsDismissed() { if( is_null( self::$isDismissed ) ) { self::$isDismissed = Library\Notice::isDismissed( $this->userNoticeKey ); } return self::$isDismissed; }
php
public function getIsDismissed() { if( is_null( self::$isDismissed ) ) { self::$isDismissed = Library\Notice::isDismissed( $this->userNoticeKey ); } return self::$isDismissed; }
[ "public", "function", "getIsDismissed", "(", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "isDismissed", ")", ")", "{", "self", "::", "$", "isDismissed", "=", "Library", "\\", "Notice", "::", "isDismissed", "(", "$", "this", "->", "userNoticeK...
Get static class property isDismissed. @since 2.0.1 @hook: Boldgrid\Library\Notice\KeyPrompt\getIsDismissed
[ "Get", "static", "class", "property", "isDismissed", "." ]
51afe070e211cff9cf78454ff97912a0d943805c
https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Notice/KeyPrompt.php#L289-L295
train
thelia/core
lib/Thelia/Core/Template/TheliaTemplateHelper.php
TheliaTemplateHelper.isActive
public function isActive(TemplateDefinition $tplDefinition) { $tplVar = ''; switch ($tplDefinition->getType()) { case TemplateDefinition::FRONT_OFFICE: $tplVar = 'active-front-template'; break; case TemplateDefinition::BACK_OFFICE: $tplVar = 'active-admin-template'; break; case TemplateDefinition::PDF: $tplVar = 'active-pdf-template'; break; case TemplateDefinition::EMAIL: $tplVar = 'active-mail-template'; break; } return $tplDefinition->getName() == ConfigQuery::read($tplVar, 'default'); }
php
public function isActive(TemplateDefinition $tplDefinition) { $tplVar = ''; switch ($tplDefinition->getType()) { case TemplateDefinition::FRONT_OFFICE: $tplVar = 'active-front-template'; break; case TemplateDefinition::BACK_OFFICE: $tplVar = 'active-admin-template'; break; case TemplateDefinition::PDF: $tplVar = 'active-pdf-template'; break; case TemplateDefinition::EMAIL: $tplVar = 'active-mail-template'; break; } return $tplDefinition->getName() == ConfigQuery::read($tplVar, 'default'); }
[ "public", "function", "isActive", "(", "TemplateDefinition", "$", "tplDefinition", ")", "{", "$", "tplVar", "=", "''", ";", "switch", "(", "$", "tplDefinition", "->", "getType", "(", ")", ")", "{", "case", "TemplateDefinition", "::", "FRONT_OFFICE", ":", "$"...
Check if a template definition is the current active template @param TemplateDefinition $tplDefinition @return bool true is the given template is the active template
[ "Check", "if", "a", "template", "definition", "is", "the", "current", "active", "template" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Template/TheliaTemplateHelper.php#L41-L61
train
thelia/core
lib/Thelia/Core/Template/TheliaTemplateHelper.php
TheliaTemplateHelper.getList
public function getList($templateType, $base = THELIA_TEMPLATE_DIR) { $list = $exclude = array(); $tplIterator = TemplateDefinition::getStandardTemplatesSubdirsIterator(); foreach ($tplIterator as $type => $subdir) { if ($templateType == $type) { $baseDir = rtrim($base, DS).DS.$subdir; try { // Every subdir of the basedir is supposed to be a template. $di = new \DirectoryIterator($baseDir); /** @var \DirectoryIterator $file */ foreach ($di as $file) { // Ignore 'dot' elements if ($file->isDot() || ! $file->isDir()) { continue; } // Ignore reserved directory names if (\in_array($file->getFilename(), $exclude)) { continue; } $list[] = new TemplateDefinition($file->getFilename(), $templateType); } } catch (\UnexpectedValueException $ex) { // Ignore the exception and continue } } } return $list; }
php
public function getList($templateType, $base = THELIA_TEMPLATE_DIR) { $list = $exclude = array(); $tplIterator = TemplateDefinition::getStandardTemplatesSubdirsIterator(); foreach ($tplIterator as $type => $subdir) { if ($templateType == $type) { $baseDir = rtrim($base, DS).DS.$subdir; try { // Every subdir of the basedir is supposed to be a template. $di = new \DirectoryIterator($baseDir); /** @var \DirectoryIterator $file */ foreach ($di as $file) { // Ignore 'dot' elements if ($file->isDot() || ! $file->isDir()) { continue; } // Ignore reserved directory names if (\in_array($file->getFilename(), $exclude)) { continue; } $list[] = new TemplateDefinition($file->getFilename(), $templateType); } } catch (\UnexpectedValueException $ex) { // Ignore the exception and continue } } } return $list; }
[ "public", "function", "getList", "(", "$", "templateType", ",", "$", "base", "=", "THELIA_TEMPLATE_DIR", ")", "{", "$", "list", "=", "$", "exclude", "=", "array", "(", ")", ";", "$", "tplIterator", "=", "TemplateDefinition", "::", "getStandardTemplatesSubdirsI...
Return a list of existing templates for a given template type @param int $templateType the template type @param string $base the template base (module or core, default to core). @return TemplateDefinition[] of \Thelia\Core\Template\TemplateDefinition
[ "Return", "a", "list", "of", "existing", "templates", "for", "a", "given", "template", "type" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Template/TheliaTemplateHelper.php#L115-L150
train
thelia/core
lib/Thelia/Controller/Admin/CouponController.php
CouponController.browseAction
public function browseAction() { if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::VIEW)) { return $response; } return $this->render('coupon-list', [ 'coupon_order' => $this->getListOrderFromSession('coupon', 'coupon_order', 'code') ]); }
php
public function browseAction() { if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::VIEW)) { return $response; } return $this->render('coupon-list', [ 'coupon_order' => $this->getListOrderFromSession('coupon', 'coupon_order', 'code') ]); }
[ "public", "function", "browseAction", "(", ")", "{", "if", "(", "null", "!==", "$", "response", "=", "$", "this", "->", "checkAuth", "(", "AdminResources", "::", "COUPON", ",", "[", "]", ",", "AccessManager", "::", "VIEW", ")", ")", "{", "return", "$",...
Manage Coupons list display @return \Thelia\Core\HttpFoundation\Response
[ "Manage", "Coupons", "list", "display" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Controller/Admin/CouponController.php#L55-L64
train
thelia/core
lib/Thelia/Controller/Admin/CouponController.php
CouponController.createAction
public function createAction() { if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::CREATE)) { return $response; } // Parameters given to the template $args = []; $eventToDispatch = TheliaEvents::COUPON_CREATE; if ($this->getRequest()->isMethod('POST')) { if (null !== $response = $this->validateCreateOrUpdateForm( $eventToDispatch, 'created', 'creation' )) { return $response; } } else { // If no input for expirationDate, now + 2 months $defaultDate = new \DateTime(); $args['nowDate'] = $defaultDate->format($this->getDefaultDateFormat()); $args['defaultDate'] = $defaultDate->modify('+2 month')->format($this->getDefaultDateFormat()); } $args['dateFormat'] = $this->getDefaultDateFormat(); $args['availableCoupons'] = $this->getAvailableCoupons(); $args['urlAjaxAdminCouponDrawInputs'] = $this->getRoute( 'admin.coupon.draw.inputs.ajax', ['couponServiceId' => 'couponServiceId'], Router::ABSOLUTE_URL ); $args['formAction'] = 'admin/coupon/create'; // Setup empty data if form is already in parser context $this->getParserContext()->addForm($this->createForm(AdminForm::COUPON_CREATION)); return $this->render( 'coupon-create', $args ); }
php
public function createAction() { if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::CREATE)) { return $response; } // Parameters given to the template $args = []; $eventToDispatch = TheliaEvents::COUPON_CREATE; if ($this->getRequest()->isMethod('POST')) { if (null !== $response = $this->validateCreateOrUpdateForm( $eventToDispatch, 'created', 'creation' )) { return $response; } } else { // If no input for expirationDate, now + 2 months $defaultDate = new \DateTime(); $args['nowDate'] = $defaultDate->format($this->getDefaultDateFormat()); $args['defaultDate'] = $defaultDate->modify('+2 month')->format($this->getDefaultDateFormat()); } $args['dateFormat'] = $this->getDefaultDateFormat(); $args['availableCoupons'] = $this->getAvailableCoupons(); $args['urlAjaxAdminCouponDrawInputs'] = $this->getRoute( 'admin.coupon.draw.inputs.ajax', ['couponServiceId' => 'couponServiceId'], Router::ABSOLUTE_URL ); $args['formAction'] = 'admin/coupon/create'; // Setup empty data if form is already in parser context $this->getParserContext()->addForm($this->createForm(AdminForm::COUPON_CREATION)); return $this->render( 'coupon-create', $args ); }
[ "public", "function", "createAction", "(", ")", "{", "if", "(", "null", "!==", "$", "response", "=", "$", "this", "->", "checkAuth", "(", "AdminResources", "::", "COUPON", ",", "[", "]", ",", "AccessManager", "::", "CREATE", ")", ")", "{", "return", "$...
Manage Coupons creation display @return \Thelia\Core\HttpFoundation\Response
[ "Manage", "Coupons", "creation", "display" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Controller/Admin/CouponController.php#L71-L113
train
thelia/core
lib/Thelia/Controller/Admin/CouponController.php
CouponController.logError
protected function logError($action, $message, $e) { Tlog::getInstance()->error( sprintf( 'Error during Coupon ' . $action . ' process : %s. Exception was %s', $message, $e->getMessage() ) ); return $this; }
php
protected function logError($action, $message, $e) { Tlog::getInstance()->error( sprintf( 'Error during Coupon ' . $action . ' process : %s. Exception was %s', $message, $e->getMessage() ) ); return $this; }
[ "protected", "function", "logError", "(", "$", "action", ",", "$", "message", ",", "$", "e", ")", "{", "Tlog", "::", "getInstance", "(", ")", "->", "error", "(", "sprintf", "(", "'Error during Coupon '", ".", "$", "action", ".", "' process : %s. Exception wa...
Log error message @param string $action Creation|Update|Delete @param string $message Message to log @param \Exception $e Exception to log @return $this
[ "Log", "error", "message" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Controller/Admin/CouponController.php#L466-L477
train
thelia/core
lib/Thelia/Controller/Admin/CouponController.php
CouponController.validateCreateOrUpdateForm
protected function validateCreateOrUpdateForm($eventToDispatch, $log, $action, Coupon $model = null) { // Create the form from the request $couponForm = $this->getForm($action, $model); $response = null; $message = false; try { // Check the form against conditions violations $form = $this->validateForm($couponForm, 'POST'); $couponEvent = $this->feedCouponCreateOrUpdateEvent($form, $model); // Dispatch Event to the Action $this->dispatch( $eventToDispatch, $couponEvent ); $this->adminLogAppend( AdminResources::COUPON, AccessManager::UPDATE, sprintf( 'Coupon %s (ID ) ' . $log, $couponEvent->getTitle(), $couponEvent->getCouponModel()->getId() ), $couponEvent->getCouponModel()->getId() ); if ($this->getRequest()->get('save_mode') == 'stay') { $response = RedirectResponse::create(str_replace( '{id}', $couponEvent->getCouponModel()->getId(), $couponForm->getSuccessUrl() )); } else { // Redirect to the success URL $response = RedirectResponse::create( URL::getInstance()->absoluteUrl($this->getRoute('admin.coupon.list')) ); } } catch (FormValidationException $ex) { // Invalid data entered $message = $this->createStandardFormValidationErrorMessage($ex); } catch (\Exception $ex) { // Any other error $message = $this->getTranslator()->trans('Sorry, an error occurred: %err', ['%err' => $ex->getMessage()]); $this->logError($action, $message, $ex); } if ($message !== false) { // Mark the form as with error $couponForm->setErrorMessage($message); // Send the form and the error to the parser $this->getParserContext() ->addForm($couponForm) ->setGeneralError($message); } return $response; }
php
protected function validateCreateOrUpdateForm($eventToDispatch, $log, $action, Coupon $model = null) { // Create the form from the request $couponForm = $this->getForm($action, $model); $response = null; $message = false; try { // Check the form against conditions violations $form = $this->validateForm($couponForm, 'POST'); $couponEvent = $this->feedCouponCreateOrUpdateEvent($form, $model); // Dispatch Event to the Action $this->dispatch( $eventToDispatch, $couponEvent ); $this->adminLogAppend( AdminResources::COUPON, AccessManager::UPDATE, sprintf( 'Coupon %s (ID ) ' . $log, $couponEvent->getTitle(), $couponEvent->getCouponModel()->getId() ), $couponEvent->getCouponModel()->getId() ); if ($this->getRequest()->get('save_mode') == 'stay') { $response = RedirectResponse::create(str_replace( '{id}', $couponEvent->getCouponModel()->getId(), $couponForm->getSuccessUrl() )); } else { // Redirect to the success URL $response = RedirectResponse::create( URL::getInstance()->absoluteUrl($this->getRoute('admin.coupon.list')) ); } } catch (FormValidationException $ex) { // Invalid data entered $message = $this->createStandardFormValidationErrorMessage($ex); } catch (\Exception $ex) { // Any other error $message = $this->getTranslator()->trans('Sorry, an error occurred: %err', ['%err' => $ex->getMessage()]); $this->logError($action, $message, $ex); } if ($message !== false) { // Mark the form as with error $couponForm->setErrorMessage($message); // Send the form and the error to the parser $this->getParserContext() ->addForm($couponForm) ->setGeneralError($message); } return $response; }
[ "protected", "function", "validateCreateOrUpdateForm", "(", "$", "eventToDispatch", ",", "$", "log", ",", "$", "action", ",", "Coupon", "$", "model", "=", "null", ")", "{", "// Create the form from the request", "$", "couponForm", "=", "$", "this", "->", "getFor...
Validate the CreateOrUpdate form @param string $eventToDispatch Event which will activate actions @param string $log created|edited @param string $action creation|edition @param Coupon $model Model if in update mode @return $this
[ "Validate", "the", "CreateOrUpdate", "form" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Controller/Admin/CouponController.php#L489-L551
train
thelia/core
lib/Thelia/Controller/Admin/CouponController.php
CouponController.getAvailableConditions
protected function getAvailableConditions() { /** @var CouponManager $couponManager */ $couponManager = $this->container->get('thelia.coupon.manager'); $availableConditions = $couponManager->getAvailableConditions(); $cleanedConditions = []; /** @var ConditionInterface $availableCondition */ foreach ($availableConditions as $availableCondition) { $condition = []; $condition['serviceId'] = $availableCondition->getServiceId(); $condition['name'] = $availableCondition->getName(); $condition['toolTip'] = $availableCondition->getToolTip(); $cleanedConditions[] = $condition; } return $cleanedConditions; }
php
protected function getAvailableConditions() { /** @var CouponManager $couponManager */ $couponManager = $this->container->get('thelia.coupon.manager'); $availableConditions = $couponManager->getAvailableConditions(); $cleanedConditions = []; /** @var ConditionInterface $availableCondition */ foreach ($availableConditions as $availableCondition) { $condition = []; $condition['serviceId'] = $availableCondition->getServiceId(); $condition['name'] = $availableCondition->getName(); $condition['toolTip'] = $availableCondition->getToolTip(); $cleanedConditions[] = $condition; } return $cleanedConditions; }
[ "protected", "function", "getAvailableConditions", "(", ")", "{", "/** @var CouponManager $couponManager */", "$", "couponManager", "=", "$", "this", "->", "container", "->", "get", "(", "'thelia.coupon.manager'", ")", ";", "$", "availableConditions", "=", "$", "coupo...
Get all available conditions @return array
[ "Get", "all", "available", "conditions" ]
38fbe7d5046bad6c0af9ea7c686b4655e8d84e67
https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Controller/Admin/CouponController.php#L558-L574
train