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
Erebot/Erebot
src/Proxy/SOCKS.php
SOCKS.userpass
protected function userpass(\Erebot\URIInterface $proxyURI) { $username = $proxyURI->asParsedURL(PHP_URL_USER); $password = $proxyURI->asParsedURL(PHP_URL_PASS); if ($username === null || $password === null) { throw new \Erebot\InvalidValueException( 'No username or password supplied' ); } $ulen = strlen($username); $plen = strlen($password); if ($ulen > 255) { throw new \Erebot\InvalidValueException( 'Username too long (max. 255)' ); } if ($plen > 255) { throw new \Erebot\InvalidValueException( 'Password too long (max. 255)' ); } $this->write( "\x01".pack( "Ca*Ca*", $ulen, $username, $plen, $password ) ); $line = $this->read(2); if ($line[0] != "\x01") { throw new \Erebot\InvalidValueException( 'Bad subnegociation version' ); } if ($line[1] != "\x00") { throw new \Erebot\InvalidValueException('Bad username or password'); } }
php
protected function userpass(\Erebot\URIInterface $proxyURI) { $username = $proxyURI->asParsedURL(PHP_URL_USER); $password = $proxyURI->asParsedURL(PHP_URL_PASS); if ($username === null || $password === null) { throw new \Erebot\InvalidValueException( 'No username or password supplied' ); } $ulen = strlen($username); $plen = strlen($password); if ($ulen > 255) { throw new \Erebot\InvalidValueException( 'Username too long (max. 255)' ); } if ($plen > 255) { throw new \Erebot\InvalidValueException( 'Password too long (max. 255)' ); } $this->write( "\x01".pack( "Ca*Ca*", $ulen, $username, $plen, $password ) ); $line = $this->read(2); if ($line[0] != "\x01") { throw new \Erebot\InvalidValueException( 'Bad subnegociation version' ); } if ($line[1] != "\x00") { throw new \Erebot\InvalidValueException('Bad username or password'); } }
[ "protected", "function", "userpass", "(", "\\", "Erebot", "\\", "URIInterface", "$", "proxyURI", ")", "{", "$", "username", "=", "$", "proxyURI", "->", "asParsedURL", "(", "PHP_URL_USER", ")", ";", "$", "password", "=", "$", "proxyURI", "->", "asParsedURL", ...
Does the authentication step. \param Erebot::URIInterface $proxyURI An object representing the URI of this SOCKS proxy server, containing the credentials that will be sent during the authentication step.
[ "Does", "the", "authentication", "step", "." ]
691fc3fa8bc6f07061ff2b3798fec76bc3a039aa
https://github.com/Erebot/Erebot/blob/691fc3fa8bc6f07061ff2b3798fec76bc3a039aa/src/Proxy/SOCKS.php#L123-L168
train
Erebot/Erebot
src/Proxy/SOCKS.php
SOCKS.write
protected function write($line) { for ($written = 0, $len = strlen($line); $written < $len; $written += $fwrite) { $fwrite = fwrite($this->socket, substr($line, $written)); if ($fwrite === false) { throw new \Erebot\Exception('Connection closed by proxy'); } } return $written; }
php
protected function write($line) { for ($written = 0, $len = strlen($line); $written < $len; $written += $fwrite) { $fwrite = fwrite($this->socket, substr($line, $written)); if ($fwrite === false) { throw new \Erebot\Exception('Connection closed by proxy'); } } return $written; }
[ "protected", "function", "write", "(", "$", "line", ")", "{", "for", "(", "$", "written", "=", "0", ",", "$", "len", "=", "strlen", "(", "$", "line", ")", ";", "$", "written", "<", "$", "len", ";", "$", "written", "+=", "$", "fwrite", ")", "{",...
Passes some data to the proxy server. \param string $line Data to send. \retval int Number of bytes actually sent (this may be lower that the length of the initial $line if some bytes could not be sent).
[ "Passes", "some", "data", "to", "the", "proxy", "server", "." ]
691fc3fa8bc6f07061ff2b3798fec76bc3a039aa
https://github.com/Erebot/Erebot/blob/691fc3fa8bc6f07061ff2b3798fec76bc3a039aa/src/Proxy/SOCKS.php#L181-L190
train
Erebot/Erebot
src/Proxy/SOCKS.php
SOCKS.read
protected function read($len) { $contents = ""; $clen = 0; while (!feof($this->socket) && $clen < $len) { $read = fread($this->socket, $len - $clen); if ($read === false) { throw new \Erebot\Exception('Connection closed by proxy'); } $contents .= $read; $clen = strlen($contents); } return $contents; }
php
protected function read($len) { $contents = ""; $clen = 0; while (!feof($this->socket) && $clen < $len) { $read = fread($this->socket, $len - $clen); if ($read === false) { throw new \Erebot\Exception('Connection closed by proxy'); } $contents .= $read; $clen = strlen($contents); } return $contents; }
[ "protected", "function", "read", "(", "$", "len", ")", "{", "$", "contents", "=", "\"\"", ";", "$", "clen", "=", "0", ";", "while", "(", "!", "feof", "(", "$", "this", "->", "socket", ")", "&&", "$", "clen", "<", "$", "len", ")", "{", "$", "r...
Reads some data from the proxy server. \param int $len Number of bytes to read from the proxy server. \retval string Actual data read.
[ "Reads", "some", "data", "from", "the", "proxy", "server", "." ]
691fc3fa8bc6f07061ff2b3798fec76bc3a039aa
https://github.com/Erebot/Erebot/blob/691fc3fa8bc6f07061ff2b3798fec76bc3a039aa/src/Proxy/SOCKS.php#L201-L214
train
chameleon-system/chameleon-shop
src/ShopBundle/objects/ArticleList/State.php
State.getStateString
public function getStateString(array $varyingStateParameter = null) { $stateInput = $this->getStateArrayWithoutQueryParameter(); $parts = array(); foreach ($stateInput as $key => $value) { if (null !== $varyingStateParameter && in_array($key, $varyingStateParameter)) { continue; } $parts[] = $key.':'.$value; } if (0 === count($parts)) { return ''; } return implode(',', $parts); }
php
public function getStateString(array $varyingStateParameter = null) { $stateInput = $this->getStateArrayWithoutQueryParameter(); $parts = array(); foreach ($stateInput as $key => $value) { if (null !== $varyingStateParameter && in_array($key, $varyingStateParameter)) { continue; } $parts[] = $key.':'.$value; } if (0 === count($parts)) { return ''; } return implode(',', $parts); }
[ "public", "function", "getStateString", "(", "array", "$", "varyingStateParameter", "=", "null", ")", "{", "$", "stateInput", "=", "$", "this", "->", "getStateArrayWithoutQueryParameter", "(", ")", ";", "$", "parts", "=", "array", "(", ")", ";", "foreach", "...
returns a string representation of the state, excluding the parameter specified by varyingStateParameter. @param array|null $varyingStateParameter @return string
[ "returns", "a", "string", "representation", "of", "the", "state", "excluding", "the", "parameter", "specified", "by", "varyingStateParameter", "." ]
2e47f4eeab604449605ee1867180c9a37a8c208e
https://github.com/chameleon-system/chameleon-shop/blob/2e47f4eeab604449605ee1867180c9a37a8c208e/src/ShopBundle/objects/ArticleList/State.php#L79-L95
train
chameleon-system/chameleon-shop
src/ShopBundle/objects/ArticleList/State.php
State.setUnsetStatesOnly
public function setUnsetStatesOnly(array $stateValues) { foreach ($stateValues as $key => $value) { if (null === $this->getState($key, null)) { $this->setState($key, $value); } } }
php
public function setUnsetStatesOnly(array $stateValues) { foreach ($stateValues as $key => $value) { if (null === $this->getState($key, null)) { $this->setState($key, $value); } } }
[ "public", "function", "setUnsetStatesOnly", "(", "array", "$", "stateValues", ")", "{", "foreach", "(", "$", "stateValues", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "null", "===", "$", "this", "->", "getState", "(", "$", "key", ",", ...
sets values in stateValues that have no value in the current state. ignores all others. @param array $stateValues
[ "sets", "values", "in", "stateValues", "that", "have", "no", "value", "in", "the", "current", "state", ".", "ignores", "all", "others", "." ]
2e47f4eeab604449605ee1867180c9a37a8c208e
https://github.com/chameleon-system/chameleon-shop/blob/2e47f4eeab604449605ee1867180c9a37a8c208e/src/ShopBundle/objects/ArticleList/State.php#L171-L178
train
flash-global/mailer-common
src/Entity/Attachment.php
Attachment.getId
public function getId() { if (is_null($this->id)) { $this->id = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)) . '@mailer.generated'; } return $this->id; }
php
public function getId() { if (is_null($this->id)) { $this->id = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)) . '@mailer.generated'; } return $this->id; }
[ "public", "function", "getId", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "id", ")", ")", "{", "$", "this", "->", "id", "=", "md5", "(", "getmypid", "(", ")", ".", "'.'", ".", "time", "(", ")", ".", "'.'", ".", "uniqid", "("...
Get attachment ID @return string
[ "Get", "attachment", "ID" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Attachment.php#L90-L97
train
flash-global/mailer-common
src/Entity/Attachment.php
Attachment.getMimeType
public function getMimeType() { if (empty($this->mimeType)) { $resource = finfo_open(FILEINFO_MIME_TYPE); $this->mimeType = finfo_file($resource, $this->getRealPath()); } return $this->mimeType; }
php
public function getMimeType() { if (empty($this->mimeType)) { $resource = finfo_open(FILEINFO_MIME_TYPE); $this->mimeType = finfo_file($resource, $this->getRealPath()); } return $this->mimeType; }
[ "public", "function", "getMimeType", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "mimeType", ")", ")", "{", "$", "resource", "=", "finfo_open", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "this", "->", "mimeType", "=", "finfo_file", "(", "...
Get Mime Type @return string
[ "Get", "Mime", "Type" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Attachment.php#L128-L136
train
flash-global/mailer-common
src/Validator/MailValidator.php
MailValidator.validateAddress
public function validateAddress($address, $field, $isRequired = true) { if ($isRequired && empty($address)) { $this->addError($field, sprintf('%s is empty', ucfirst($field))); return false; } $validator = new EmailValidator(); $validation = new RFCValidation(); $success = true; foreach ($address as $email => $label) { if (!is_scalar($label)) { $this->addError( $field, sprintf('Label for %s is not scalar, `%s` given', $field, gettype($label)) ); $label = gettype($label); $success = false; } if ($validator->isValid($email, $validation) == false) { $this->addError( $field, sprintf('`%s` is not a valid email address for %s `%s`', $email, $field, $label) ); $success = false; } } return $success; }
php
public function validateAddress($address, $field, $isRequired = true) { if ($isRequired && empty($address)) { $this->addError($field, sprintf('%s is empty', ucfirst($field))); return false; } $validator = new EmailValidator(); $validation = new RFCValidation(); $success = true; foreach ($address as $email => $label) { if (!is_scalar($label)) { $this->addError( $field, sprintf('Label for %s is not scalar, `%s` given', $field, gettype($label)) ); $label = gettype($label); $success = false; } if ($validator->isValid($email, $validation) == false) { $this->addError( $field, sprintf('`%s` is not a valid email address for %s `%s`', $email, $field, $label) ); $success = false; } } return $success; }
[ "public", "function", "validateAddress", "(", "$", "address", ",", "$", "field", ",", "$", "isRequired", "=", "true", ")", "{", "if", "(", "$", "isRequired", "&&", "empty", "(", "$", "address", ")", ")", "{", "$", "this", "->", "addError", "(", "$", ...
Validate address fields @param array $address @param string $field @param bool $isRequired @return bool
[ "Validate", "address", "fields" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Validator/MailValidator.php#L93-L124
train
flash-global/mailer-common
src/Entity/Mail.php
Mail.getContext
public function getContext() { return array_filter(array( 'subject' => $this->getSubject(), 'from' => $this->addressToString((array) $this->getSender()), 'to' => $this->addressToString((array) $this->getRecipients()), 'cc' => $this->addressToString((array) $this->getCc()), 'bcc' => $this->addressToString((array) $this->getBcc()) )); }
php
public function getContext() { return array_filter(array( 'subject' => $this->getSubject(), 'from' => $this->addressToString((array) $this->getSender()), 'to' => $this->addressToString((array) $this->getRecipients()), 'cc' => $this->addressToString((array) $this->getCc()), 'bcc' => $this->addressToString((array) $this->getBcc()) )); }
[ "public", "function", "getContext", "(", ")", "{", "return", "array_filter", "(", "array", "(", "'subject'", "=>", "$", "this", "->", "getSubject", "(", ")", ",", "'from'", "=>", "$", "this", "->", "addressToString", "(", "(", "array", ")", "$", "this", ...
Get mail context @return array
[ "Get", "mail", "context" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Mail.php#L420-L429
train
flash-global/mailer-common
src/Entity/Mail.php
Mail.initAddress
protected function initAddress(array $address, $field) { $this->{$this->methodName('clear', $field)}(); foreach ($address as $email => $label) { if (is_int($email)) { $email = $label; } $this->{$this->methodName('add', $field)}($email, $label); } }
php
protected function initAddress(array $address, $field) { $this->{$this->methodName('clear', $field)}(); foreach ($address as $email => $label) { if (is_int($email)) { $email = $label; } $this->{$this->methodName('add', $field)}($email, $label); } }
[ "protected", "function", "initAddress", "(", "array", "$", "address", ",", "$", "field", ")", "{", "$", "this", "->", "{", "$", "this", "->", "methodName", "(", "'clear'", ",", "$", "field", ")", "}", "(", ")", ";", "foreach", "(", "$", "address", ...
Set address purpose property @param array $address @param string $field
[ "Set", "address", "purpose", "property" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Mail.php#L437-L448
train
flash-global/mailer-common
src/Entity/Mail.php
Mail.addAddress
protected function addAddress($address, $label, $field) { $label = is_string($label) ? trim($label) : $label; $address = is_string($address) ? trim($address) : $label; $label = $label ?: $address; if (!empty($address)) { $this->{$field}[$address] = $label; } }
php
protected function addAddress($address, $label, $field) { $label = is_string($label) ? trim($label) : $label; $address = is_string($address) ? trim($address) : $label; $label = $label ?: $address; if (!empty($address)) { $this->{$field}[$address] = $label; } }
[ "protected", "function", "addAddress", "(", "$", "address", ",", "$", "label", ",", "$", "field", ")", "{", "$", "label", "=", "is_string", "(", "$", "label", ")", "?", "trim", "(", "$", "label", ")", ":", "$", "label", ";", "$", "address", "=", ...
Add a address in a array property @param string $address @param string $label @param string $field
[ "Add", "a", "address", "in", "a", "array", "property" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Mail.php#L457-L467
train
flash-global/mailer-common
src/Entity/Mail.php
Mail.formatAddress
protected function formatAddress($address) { if (is_array($address)) { $email = is_int(key($address)) ? current($address) : key($address); return array($email => current($address)); } return array($address => $address); }
php
protected function formatAddress($address) { if (is_array($address)) { $email = is_int(key($address)) ? current($address) : key($address); return array($email => current($address)); } return array($address => $address); }
[ "protected", "function", "formatAddress", "(", "$", "address", ")", "{", "if", "(", "is_array", "(", "$", "address", ")", ")", "{", "$", "email", "=", "is_int", "(", "key", "(", "$", "address", ")", ")", "?", "current", "(", "$", "address", ")", ":...
Format a address @param string|array $address @return array
[ "Format", "a", "address" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Mail.php#L476-L484
train
flash-global/mailer-common
src/Entity/Mail.php
Mail.addressToString
protected function addressToString(array $field) { $address = array(); foreach ($field as $key => $value) { $address[] = $key == $value ? $value : sprintf('%s <%s>', $value, $key); } return empty($address) ? null : implode(', ', $address); }
php
protected function addressToString(array $field) { $address = array(); foreach ($field as $key => $value) { $address[] = $key == $value ? $value : sprintf('%s <%s>', $value, $key); } return empty($address) ? null : implode(', ', $address); }
[ "protected", "function", "addressToString", "(", "array", "$", "field", ")", "{", "$", "address", "=", "array", "(", ")", ";", "foreach", "(", "$", "field", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "address", "[", "]", "=", "$", "key", ...
Convert address container to a string representation @param array $field @return string
[ "Convert", "address", "container", "to", "a", "string", "representation" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Mail.php#L493-L501
train
flash-global/mailer-common
src/Entity/Mail.php
Mail.methodName
protected function methodName($action, $field) { if (substr($field, -1, 1) === 's' && $action != 'clear') { $field = substr($field, 0, -1); } return $action . ucfirst(strtolower($field)); }
php
protected function methodName($action, $field) { if (substr($field, -1, 1) === 's' && $action != 'clear') { $field = substr($field, 0, -1); } return $action . ucfirst(strtolower($field)); }
[ "protected", "function", "methodName", "(", "$", "action", ",", "$", "field", ")", "{", "if", "(", "substr", "(", "$", "field", ",", "-", "1", ",", "1", ")", "===", "'s'", "&&", "$", "action", "!=", "'clear'", ")", "{", "$", "field", "=", "substr...
Returns the method name given a action and a field name @param $action @param $field @return string
[ "Returns", "the", "method", "name", "given", "a", "action", "and", "a", "field", "name" ]
3240ca53570d9b346af8087c9b32d4883f3383ce
https://github.com/flash-global/mailer-common/blob/3240ca53570d9b346af8087c9b32d4883f3383ce/src/Entity/Mail.php#L511-L518
train
widop/WidopHttpAdapterBundle
DependencyInjection/WidopHttpAdapterExtension.php
WidopHttpAdapterExtension.loadMaxRedirects
private function loadMaxRedirects(array $config, ContainerBuilder $container) { $services = array('buzz', 'curl', 'guzzle', 'stream', 'zend'); foreach ($services as $service) { $container ->getDefinition(sprintf('widop_http_adapter.%s', $service)) ->addMethodCall('setMaxRedirects', array($config['max_redirects'])); } }
php
private function loadMaxRedirects(array $config, ContainerBuilder $container) { $services = array('buzz', 'curl', 'guzzle', 'stream', 'zend'); foreach ($services as $service) { $container ->getDefinition(sprintf('widop_http_adapter.%s', $service)) ->addMethodCall('setMaxRedirects', array($config['max_redirects'])); } }
[ "private", "function", "loadMaxRedirects", "(", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "services", "=", "array", "(", "'buzz'", ",", "'curl'", ",", "'guzzle'", ",", "'stream'", ",", "'zend'", ")", ";", "foreach", ...
Loads the max redirects in all http adapters. @param array $config The configuration. @param \Symfony\Component\DependencyInjection\ContainerBuilder $container The container.
[ "Loads", "the", "max", "redirects", "in", "all", "http", "adapters", "." ]
f8ff24f423ee8db7ba0a72eecafcf53dcb453d79
https://github.com/widop/WidopHttpAdapterBundle/blob/f8ff24f423ee8db7ba0a72eecafcf53dcb453d79/DependencyInjection/WidopHttpAdapterExtension.php#L44-L53
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/ListenerPattern.php
ListenerPattern.bind
public function bind(EventDispatcherInterface $dispatcher, $eventName) { if (isset($this->events[$eventName])) { return; } $dispatcher->addListener($eventName, $this->getListener(), $this->priority); $this->events[$eventName] = true; }
php
public function bind(EventDispatcherInterface $dispatcher, $eventName) { if (isset($this->events[$eventName])) { return; } $dispatcher->addListener($eventName, $this->getListener(), $this->priority); $this->events[$eventName] = true; }
[ "public", "function", "bind", "(", "EventDispatcherInterface", "$", "dispatcher", ",", "$", "eventName", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "events", "[", "$", "eventName", "]", ")", ")", "{", "return", ";", "}", "$", "dispatcher", "...
Adds this pattern's listener to an event. @param EventDispatcherInterface $dispatcher @param string $eventName
[ "Adds", "this", "pattern", "s", "listener", "to", "an", "event", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/ListenerPattern.php#L58-L66
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/ListenerPattern.php
ListenerPattern.unbind
public function unbind(EventDispatcherInterface $dispatcher) { foreach ($this->events as $eventName => $_) { $dispatcher->removeListener($eventName, $this->getListener()); } $this->events = array(); }
php
public function unbind(EventDispatcherInterface $dispatcher) { foreach ($this->events as $eventName => $_) { $dispatcher->removeListener($eventName, $this->getListener()); } $this->events = array(); }
[ "public", "function", "unbind", "(", "EventDispatcherInterface", "$", "dispatcher", ")", "{", "foreach", "(", "$", "this", "->", "events", "as", "$", "eventName", "=>", "$", "_", ")", "{", "$", "dispatcher", "->", "removeListener", "(", "$", "eventName", "...
Removes this pattern's listener from all events to which it was previously added. @param EventDispatcherInterface $dispatcher
[ "Removes", "this", "pattern", "s", "listener", "from", "all", "events", "to", "which", "it", "was", "previously", "added", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/ListenerPattern.php#L74-L81
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/ListenerPattern.php
ListenerPattern.createRegex
private function createRegex($eventPattern) { $replacements = self::getReplacements(); return sprintf('/^%s$/', preg_replace( array_keys($replacements), array_values($replacements), preg_quote($eventPattern, '/') )); }
php
private function createRegex($eventPattern) { $replacements = self::getReplacements(); return sprintf('/^%s$/', preg_replace( array_keys($replacements), array_values($replacements), preg_quote($eventPattern, '/') )); }
[ "private", "function", "createRegex", "(", "$", "eventPattern", ")", "{", "$", "replacements", "=", "self", "::", "getReplacements", "(", ")", ";", "return", "sprintf", "(", "'/^%s$/'", ",", "preg_replace", "(", "array_keys", "(", "$", "replacements", ")", "...
Transforms an event pattern into a regular expression. @param string $eventPattern @return string
[ "Transforms", "an", "event", "pattern", "into", "a", "regular", "expression", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/ListenerPattern.php#L100-L109
train
flipboxfactory/craft-ember
src/modules/LoggerTrait.php
LoggerTrait.loggerCategory
protected static function loggerCategory($category): string { /** @noinspection PhpUndefinedFieldInspection */ $prefix = static::$category ?? ''; if (empty($category)) { return $prefix; } return ($prefix ? $prefix . ':' : '') . $category; }
php
protected static function loggerCategory($category): string { /** @noinspection PhpUndefinedFieldInspection */ $prefix = static::$category ?? ''; if (empty($category)) { return $prefix; } return ($prefix ? $prefix . ':' : '') . $category; }
[ "protected", "static", "function", "loggerCategory", "(", "$", "category", ")", ":", "string", "{", "/** @noinspection PhpUndefinedFieldInspection */", "$", "prefix", "=", "static", "::", "$", "category", "??", "''", ";", "if", "(", "empty", "(", "$", "category"...
The log categories @param $category @return string
[ "The", "log", "categories" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/modules/LoggerTrait.php#L66-L76
train
flipboxfactory/craft-ember
src/modules/LoggerTrait.php
LoggerTrait.debug
public static function debug($message, $category = 'general') { Craft::getLogger()->log($message, Logger::LEVEL_TRACE, static::loggerCategory($category)); }
php
public static function debug($message, $category = 'general') { Craft::getLogger()->log($message, Logger::LEVEL_TRACE, static::loggerCategory($category)); }
[ "public", "static", "function", "debug", "(", "$", "message", ",", "$", "category", "=", "'general'", ")", "{", "Craft", "::", "getLogger", "(", ")", "->", "log", "(", "$", "message", ",", "Logger", "::", "LEVEL_TRACE", ",", "static", "::", "loggerCatego...
Logs a debug message. Trace messages are logged mainly for development purpose to see the execution work flow of some code. This method will only log a message when the application is in debug mode. @param string|array $message the message to be logged. This can be a simple string or a more complex data structure, such as array. @param string $category the category of the message. @since 2.0.14
[ "Logs", "a", "debug", "message", ".", "Trace", "messages", "are", "logged", "mainly", "for", "development", "purpose", "to", "see", "the", "execution", "work", "flow", "of", "some", "code", ".", "This", "method", "will", "only", "log", "a", "message", "whe...
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/modules/LoggerTrait.php#L88-L91
train
firebrandhq/silverstripe-hail
src/Tasks/FetchRecurringTask.php
FetchRecurringTask.sendException
public static function sendException($exception) { $emails = Config::inst()->get(self::class, 'Emails'); if ($emails) { $emails = explode(",", $emails); $email = new Email(); $email ->setTo($emails) ->setSubject('SilverStripe Hail module fetch error on ' . SiteConfig::current_site_config()->getTitle() . ' (' . gethostname() . ')') ->setBody("<p>Hi,</p><p>An error occurred while fetching from the Hail API: </p> <p>{$exception->getMessage()}</p><p>Website name: " . SiteConfig::current_site_config()->getTitle() . "</p><p>Website Folder: " . Director::baseFolder() . "</p><p>Server hostname: " . gethostname() . "</p>"); $email->send(); } }
php
public static function sendException($exception) { $emails = Config::inst()->get(self::class, 'Emails'); if ($emails) { $emails = explode(",", $emails); $email = new Email(); $email ->setTo($emails) ->setSubject('SilverStripe Hail module fetch error on ' . SiteConfig::current_site_config()->getTitle() . ' (' . gethostname() . ')') ->setBody("<p>Hi,</p><p>An error occurred while fetching from the Hail API: </p> <p>{$exception->getMessage()}</p><p>Website name: " . SiteConfig::current_site_config()->getTitle() . "</p><p>Website Folder: " . Director::baseFolder() . "</p><p>Server hostname: " . gethostname() . "</p>"); $email->send(); } }
[ "public", "static", "function", "sendException", "(", "$", "exception", ")", "{", "$", "emails", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "self", "::", "class", ",", "'Emails'", ")", ";", "if", "(", "$", "emails", ")", "{", "$", "em...
Send exception to configured emails @param \Exception $exception
[ "Send", "exception", "to", "configured", "emails" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Tasks/FetchRecurringTask.php#L119-L131
train
czim/laravel-processor
src/Contexts/ContextRepositoryTrait.php
ContextRepositoryTrait.repository
public function repository($name, $method, array $parameters = []) { return call_user_func_array( [ $this->getRepository($name), $method ], $parameters ); }
php
public function repository($name, $method, array $parameters = []) { return call_user_func_array( [ $this->getRepository($name), $method ], $parameters ); }
[ "public", "function", "repository", "(", "$", "name", ",", "$", "method", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "return", "call_user_func_array", "(", "[", "$", "this", "->", "getRepository", "(", "$", "name", ")", ",", "$", "method...
Perform a method on a repository @param string $name @param string $method @param array $parameters @return mixed @throws ContextRepositoryException if repository name not found
[ "Perform", "a", "method", "on", "a", "repository" ]
3d0025cd463653b7a8981ff52cebdafbe978f000
https://github.com/czim/laravel-processor/blob/3d0025cd463653b7a8981ff52cebdafbe978f000/src/Contexts/ContextRepositoryTrait.php#L54-L60
train
davidecesarano/Embryo-Http
Embryo/Http/Factory/UploadedFileFactory.php
UploadedFileFactory.createUploadedFile
public function createUploadedFile( StreamInterface $file, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null ): UploadedFileInterface { if (!$file->isReadable()) { throw new \InvalidArgumentException('Temporany resource must be readable'); } $size = (is_null($size)) ? $file->getSize() : $size; return new UploadedFile($file, $size, $error, $clientFilename, $clientMediaType); }
php
public function createUploadedFile( StreamInterface $file, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null ): UploadedFileInterface { if (!$file->isReadable()) { throw new \InvalidArgumentException('Temporany resource must be readable'); } $size = (is_null($size)) ? $file->getSize() : $size; return new UploadedFile($file, $size, $error, $clientFilename, $clientMediaType); }
[ "public", "function", "createUploadedFile", "(", "StreamInterface", "$", "file", ",", "int", "$", "size", "=", "null", ",", "int", "$", "error", "=", "\\", "UPLOAD_ERR_OK", ",", "string", "$", "clientFilename", "=", "null", ",", "string", "$", "clientMediaTy...
Creates a new uploaded file. If a string is used to create the file, a temporary resource will be created with the content of the string. If a size is not provided it will be determined by checking the size of the file. @param StreamInterface $file @param int|null $size @param int $error @param string|null $clientFilename @param string|null $clientMediaType @return UploadedFileInterface @throws InvalidArgumentException
[ "Creates", "a", "new", "uploaded", "file", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Factory/UploadedFileFactory.php#L38-L51
train
davidecesarano/Embryo-Http
Embryo/Http/Factory/UploadedFileFactory.php
UploadedFileFactory.createUploadedFileFromServer
public function createUploadedFileFromServer(array $files) { $normalized = []; foreach ($files as $key => $value) { if (!isset($value['error'])) { if (is_array($value)) { $normalized[$key] = $this->createUploadedFileFromServer($value); } continue; } $normalized[$key] = []; if (!is_array($value['error'])) { if ($value['error'] === 4) { $stream = (new StreamFactory)->createStream(''); } else { $stream = (new StreamFactory)->createStreamFromFile($value['tmp_name'], 'r'); } $normalized[$key] = $this->createUploadedFile( $stream, $value['size'], $value['error'], $value['name'], $value['type'] ); } else { $sub = []; foreach ($value['error'] as $id => $error) { $sub[$id]['name'] = $value['name'][$id]; $sub[$id]['type'] = $value['type'][$id]; $sub[$id]['tmp_name'] = $value['tmp_name'][$id]; $sub[$id]['error'] = $value['error'][$id]; $sub[$id]['size'] = $value['size'][$id]; $normalized[$key] = $this->createUploadedFileFromServer($sub); } } } return $normalized; }
php
public function createUploadedFileFromServer(array $files) { $normalized = []; foreach ($files as $key => $value) { if (!isset($value['error'])) { if (is_array($value)) { $normalized[$key] = $this->createUploadedFileFromServer($value); } continue; } $normalized[$key] = []; if (!is_array($value['error'])) { if ($value['error'] === 4) { $stream = (new StreamFactory)->createStream(''); } else { $stream = (new StreamFactory)->createStreamFromFile($value['tmp_name'], 'r'); } $normalized[$key] = $this->createUploadedFile( $stream, $value['size'], $value['error'], $value['name'], $value['type'] ); } else { $sub = []; foreach ($value['error'] as $id => $error) { $sub[$id]['name'] = $value['name'][$id]; $sub[$id]['type'] = $value['type'][$id]; $sub[$id]['tmp_name'] = $value['tmp_name'][$id]; $sub[$id]['error'] = $value['error'][$id]; $sub[$id]['size'] = $value['size'][$id]; $normalized[$key] = $this->createUploadedFileFromServer($sub); } } } return $normalized; }
[ "public", "function", "createUploadedFileFromServer", "(", "array", "$", "files", ")", "{", "$", "normalized", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "value...
Creates a new uploaded file from server. @param array $files @return array
[ "Creates", "a", "new", "uploaded", "file", "from", "server", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Factory/UploadedFileFactory.php#L59-L107
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Uri.php
Uri.withHost
public function withHost($host) { if(!is_string($host)){ throw new InvalidArgumentException('Uri host must be a string'); } $clone = clone $this; $clone->host = $this->removePortFromHost($host); return $clone; }
php
public function withHost($host) { if(!is_string($host)){ throw new InvalidArgumentException('Uri host must be a string'); } $clone = clone $this; $clone->host = $this->removePortFromHost($host); return $clone; }
[ "public", "function", "withHost", "(", "$", "host", ")", "{", "if", "(", "!", "is_string", "(", "$", "host", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Uri host must be a string'", ")", ";", "}", "$", "clone", "=", "clone", "$", "t...
Returns an instance with the specified host. @param string $host @return static @throws InvalidArgumentException
[ "Returns", "an", "instance", "with", "the", "specified", "host", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Uri.php#L219-L228
train
CradlePHP/cradle-system
src/Schema/Service/SqlService.php
SqlService.remove
public function remove($restorable = true) { //translate model data to sql data if (is_null($this->schema)) { throw Exception::forNoSchema(); } $data = $this->schema->toSql(); //queries to run $queries = []; // check if table is already archived if ($this->exists(sprintf('_%s', $data['name']))) { throw Exception::forSchemaArchiveExists($data['name']); } //if system exists if ($this->exists($data['name'])) { if ($restorable) { $queries[] = 'RENAME TABLE `' . $data['name'] . '` TO `_' . $data['name'] . '`;'; //determine the relation schema foreach ($data['relations'] as $table => $relation) { $queries[] = 'RENAME TABLE `' . $table . '` TO `_' . $table . '`;'; } } else { $queries[] = 'DROP TABLE IF EXISTS `' . $data['name'] . '`;'; $queries[] = 'DROP TABLE IF EXISTS `_' . $data['name'] . '`;'; //determine the relation schema foreach ($data['relations'] as $table => $relation) { $queries[] = 'DROP TABLE IF EXISTS `'. $table . '`;'; $queries[] = 'DROP TABLE IF EXISTS `_'. $table . '`;'; } } } //execute queries $results = []; foreach ($queries as $query) { $results[] = [ 'query' => $query, 'results' => $this->resource->query($query) ]; } return $results; }
php
public function remove($restorable = true) { //translate model data to sql data if (is_null($this->schema)) { throw Exception::forNoSchema(); } $data = $this->schema->toSql(); //queries to run $queries = []; // check if table is already archived if ($this->exists(sprintf('_%s', $data['name']))) { throw Exception::forSchemaArchiveExists($data['name']); } //if system exists if ($this->exists($data['name'])) { if ($restorable) { $queries[] = 'RENAME TABLE `' . $data['name'] . '` TO `_' . $data['name'] . '`;'; //determine the relation schema foreach ($data['relations'] as $table => $relation) { $queries[] = 'RENAME TABLE `' . $table . '` TO `_' . $table . '`;'; } } else { $queries[] = 'DROP TABLE IF EXISTS `' . $data['name'] . '`;'; $queries[] = 'DROP TABLE IF EXISTS `_' . $data['name'] . '`;'; //determine the relation schema foreach ($data['relations'] as $table => $relation) { $queries[] = 'DROP TABLE IF EXISTS `'. $table . '`;'; $queries[] = 'DROP TABLE IF EXISTS `_'. $table . '`;'; } } } //execute queries $results = []; foreach ($queries as $query) { $results[] = [ 'query' => $query, 'results' => $this->resource->query($query) ]; } return $results; }
[ "public", "function", "remove", "(", "$", "restorable", "=", "true", ")", "{", "//translate model data to sql data", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "Exception", "::", "forNoSchema", "(", ")", ";", "}", "$", ...
Removes a table @param array $data @return array
[ "Removes", "a", "table" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Service/SqlService.php#L172-L220
train
CradlePHP/cradle-system
src/Schema/Service/SqlService.php
SqlService.restore
public function restore() { //translate model data to sql data if (is_null($this->schema)) { throw Exception::forNoSchema(); } $data = $this->schema->toSql(); //queries to run $queries = []; // check if table is already archived if ($this->exists($data['name'])) { throw Exception::forSchemaAlreadyExists($data['name']); } //if there's no system if (!$this->exists('_' . $data['name'])) { //go to create mode return $this->create($data, true); } $queries[] = 'RENAME TABLE `_' . $data['name'] . '` TO `' . $data['name'] . '`;'; //determine the relation schema foreach ($data['relations'] as $table => $relation) { $queries[] = 'RENAME TABLE `_' . $table . '` TO `' . $table . '`;'; } //execute queries $results = []; foreach ($queries as $query) { $results[] = [ 'query' => $query, 'results' => $this->resource->query($query) ]; } return $results; }
php
public function restore() { //translate model data to sql data if (is_null($this->schema)) { throw Exception::forNoSchema(); } $data = $this->schema->toSql(); //queries to run $queries = []; // check if table is already archived if ($this->exists($data['name'])) { throw Exception::forSchemaAlreadyExists($data['name']); } //if there's no system if (!$this->exists('_' . $data['name'])) { //go to create mode return $this->create($data, true); } $queries[] = 'RENAME TABLE `_' . $data['name'] . '` TO `' . $data['name'] . '`;'; //determine the relation schema foreach ($data['relations'] as $table => $relation) { $queries[] = 'RENAME TABLE `_' . $table . '` TO `' . $table . '`;'; } //execute queries $results = []; foreach ($queries as $query) { $results[] = [ 'query' => $query, 'results' => $this->resource->query($query) ]; } return $results; }
[ "public", "function", "restore", "(", ")", "{", "//translate model data to sql data", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "Exception", "::", "forNoSchema", "(", ")", ";", "}", "$", "data", "=", "$", "this", "->...
Restores a table @param array $data @return array
[ "Restores", "a", "table" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Service/SqlService.php#L229-L269
train
CradlePHP/cradle-system
src/Schema/Service/SqlService.php
SqlService.getSchemaTableRecordCount
public function getSchemaTableRecordCount($schema = null) { // information schema query $query = sprintf( 'SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = "%s"', $schema ); // send query return $this->resource->query($query); }
php
public function getSchemaTableRecordCount($schema = null) { // information schema query $query = sprintf( 'SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = "%s"', $schema ); // send query return $this->resource->query($query); }
[ "public", "function", "getSchemaTableRecordCount", "(", "$", "schema", "=", "null", ")", "{", "// information schema query", "$", "query", "=", "sprintf", "(", "'SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = \"%s\"'", ",", "$", "schema", ")...
Returns all the table record count @return array
[ "Returns", "all", "the", "table", "record", "count" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Service/SqlService.php#L484-L494
train
flipboxfactory/craft-ember
src/queries/CacheableQuery.php
CacheableQuery.nth
public function nth(int $n, Connection $db = null) { // Cached? if (($cachedResult = $this->getCachedResult()) !== null) { return $cachedResult[$n] ?? false; } return parent::nth($n, $db); }
php
public function nth(int $n, Connection $db = null) { // Cached? if (($cachedResult = $this->getCachedResult()) !== null) { return $cachedResult[$n] ?? false; } return parent::nth($n, $db); }
[ "public", "function", "nth", "(", "int", "$", "n", ",", "Connection", "$", "db", "=", "null", ")", "{", "// Cached?", "if", "(", "(", "$", "cachedResult", "=", "$", "this", "->", "getCachedResult", "(", ")", ")", "!==", "null", ")", "{", "return", ...
Executes the query and returns a single row of result at a given offset. @param int $n The offset of the row to return. If [[offset]] is set, $offset will be added to it. @param Connection|null $db The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. @return array|bool The object or row of the query result. False is returned if the query results in nothing.
[ "Executes", "the", "query", "and", "returns", "a", "single", "row", "of", "result", "at", "a", "given", "offset", "." ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/queries/CacheableQuery.php#L81-L89
train
flipboxfactory/craft-ember
src/records/FieldLayoutAttributeTrait.php
FieldLayoutAttributeTrait.getFieldLayoutId
public function getFieldLayoutId() { $fieldLayoutId = $this->getAttribute('fieldLayoutId'); if (null === $fieldLayoutId && null !== $this->fieldLayout) { $fieldLayoutId = $this->fieldLayoutId = $this->fieldLayout->id; } return $fieldLayoutId; }
php
public function getFieldLayoutId() { $fieldLayoutId = $this->getAttribute('fieldLayoutId'); if (null === $fieldLayoutId && null !== $this->fieldLayout) { $fieldLayoutId = $this->fieldLayoutId = $this->fieldLayout->id; } return $fieldLayoutId; }
[ "public", "function", "getFieldLayoutId", "(", ")", "{", "$", "fieldLayoutId", "=", "$", "this", "->", "getAttribute", "(", "'fieldLayoutId'", ")", ";", "if", "(", "null", "===", "$", "fieldLayoutId", "&&", "null", "!==", "$", "this", "->", "fieldLayout", ...
Get associated fieldLayoutId @return int|null
[ "Get", "associated", "fieldLayoutId" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/records/FieldLayoutAttributeTrait.php#L53-L61
train
CradlePHP/cradle-system
src/Model/Service/ElasticService.php
ElasticService.create
public function create($id) { $exists = false; try { // check if index exist $exists = $this->resource->indices()->exists(['index' => $this->schema->getName()]); } catch (\Throwable $e) { // return false if something went wrong return false; } // if index doesnt exist if (!$exists) { // do nothing return false; } // set schema to sql $this->sql->setSchema($this->schema); // get data from sql $body = $this->sql->get($this->schema->getPrimaryFieldName(), $id); if (!is_array($body) || empty($body)) { return false; } try { return $this->resource->index([ 'index' => $this->schema->getName(), 'type' => static::INDEX_TYPE, 'id' => $id, 'body' => $body ]); } catch (NoNodesAvailableException $e) { return false; } catch (BadRequest400Exception $e) { return false; } catch (\Throwable $e) { // catch all throwable // if something went wrong, dont panic, just return false return false; } }
php
public function create($id) { $exists = false; try { // check if index exist $exists = $this->resource->indices()->exists(['index' => $this->schema->getName()]); } catch (\Throwable $e) { // return false if something went wrong return false; } // if index doesnt exist if (!$exists) { // do nothing return false; } // set schema to sql $this->sql->setSchema($this->schema); // get data from sql $body = $this->sql->get($this->schema->getPrimaryFieldName(), $id); if (!is_array($body) || empty($body)) { return false; } try { return $this->resource->index([ 'index' => $this->schema->getName(), 'type' => static::INDEX_TYPE, 'id' => $id, 'body' => $body ]); } catch (NoNodesAvailableException $e) { return false; } catch (BadRequest400Exception $e) { return false; } catch (\Throwable $e) { // catch all throwable // if something went wrong, dont panic, just return false return false; } }
[ "public", "function", "create", "(", "$", "id", ")", "{", "$", "exists", "=", "false", ";", "try", "{", "// check if index exist", "$", "exists", "=", "$", "this", "->", "resource", "->", "indices", "(", ")", "->", "exists", "(", "[", "'index'", "=>", ...
Create in index @param *int $id @return array
[ "Create", "in", "index" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/ElasticService.php#L59-L101
train
CradlePHP/cradle-system
src/Model/Service/ElasticService.php
ElasticService.remove
public function remove($id) { try { return $this->resource->delete([ 'index' => $this->schema->getName(), 'type' => static::INDEX_TYPE, 'id' => $id ]); } catch (NoNodesAvailableException $e) { return false; } }
php
public function remove($id) { try { return $this->resource->delete([ 'index' => $this->schema->getName(), 'type' => static::INDEX_TYPE, 'id' => $id ]); } catch (NoNodesAvailableException $e) { return false; } }
[ "public", "function", "remove", "(", "$", "id", ")", "{", "try", "{", "return", "$", "this", "->", "resource", "->", "delete", "(", "[", "'index'", "=>", "$", "this", "->", "schema", "->", "getName", "(", ")", ",", "'type'", "=>", "static", "::", "...
Remove from index @param *int $id
[ "Remove", "from", "index" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/ElasticService.php#L245-L256
train
CradlePHP/cradle-system
src/Model/Service/ElasticService.php
ElasticService.update
public function update($id) { // set schema to sql $this->sql->setSchema($this->schema); // get data from sql $body = $this->sql->get($this->schema->getPrimaryFieldName(), $id); if (!is_array($body) || empty($body)) { return false; } try { return $this->resource->update( [ 'index' => $this->schema->getName(), 'type' => static::INDEX_TYPE, 'id' => $id, 'body' => [ 'doc' => $body ] ] ); } catch (Missing404Exception $e) { return false; } catch (NoNodesAvailableException $e) { return false; } catch (\Throwable $e) { // catch all throwable // if something went wrong, dont panic, just return false return false; } }
php
public function update($id) { // set schema to sql $this->sql->setSchema($this->schema); // get data from sql $body = $this->sql->get($this->schema->getPrimaryFieldName(), $id); if (!is_array($body) || empty($body)) { return false; } try { return $this->resource->update( [ 'index' => $this->schema->getName(), 'type' => static::INDEX_TYPE, 'id' => $id, 'body' => [ 'doc' => $body ] ] ); } catch (Missing404Exception $e) { return false; } catch (NoNodesAvailableException $e) { return false; } catch (\Throwable $e) { // catch all throwable // if something went wrong, dont panic, just return false return false; } }
[ "public", "function", "update", "(", "$", "id", ")", "{", "// set schema to sql", "$", "this", "->", "sql", "->", "setSchema", "(", "$", "this", "->", "schema", ")", ";", "// get data from sql", "$", "body", "=", "$", "this", "->", "sql", "->", "get", ...
Update to index @param *int $id @return array
[ "Update", "to", "index" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/ElasticService.php#L265-L296
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.isOutdated
public function isOutdated() { if ($this->Fetched) { $fetched = new \DateTime($this->Fetched); $now = new \DateTime("now"); $diff = $now->getTimestamp() - $fetched->getTimestamp(); if ($diff > Client::getRefreshRate()) { return true; } return false; } return true; }
php
public function isOutdated() { if ($this->Fetched) { $fetched = new \DateTime($this->Fetched); $now = new \DateTime("now"); $diff = $now->getTimestamp() - $fetched->getTimestamp(); if ($diff > Client::getRefreshRate()) { return true; } return false; } return true; }
[ "public", "function", "isOutdated", "(", ")", "{", "if", "(", "$", "this", "->", "Fetched", ")", "{", "$", "fetched", "=", "new", "\\", "DateTime", "(", "$", "this", "->", "Fetched", ")", ";", "$", "now", "=", "new", "\\", "DateTime", "(", "\"now\"...
Determines if the object is outdated @return boolean
[ "Determines", "if", "the", "object", "is", "outdated" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L116-L129
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.refresh
public function refresh() { if ($this->ID && $this->HailID) { try { $api_client = new Client(); $data = $api_client->getOne($this); } catch (\Exception $ex) { return $this; } if (count($data) > 0) { $this->importHailData($data); } } return $this; }
php
public function refresh() { if ($this->ID && $this->HailID) { try { $api_client = new Client(); $data = $api_client->getOne($this); } catch (\Exception $ex) { return $this; } if (count($data) > 0) { $this->importHailData($data); } } return $this; }
[ "public", "function", "refresh", "(", ")", "{", "if", "(", "$", "this", "->", "ID", "&&", "$", "this", "->", "HailID", ")", "{", "try", "{", "$", "api_client", "=", "new", "Client", "(", ")", ";", "$", "data", "=", "$", "api_client", "->", "getOn...
Retrieves the latest version of this object from the Hail API @return ApiObject
[ "Retrieves", "the", "latest", "version", "of", "this", "object", "from", "the", "Hail", "API" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L147-L162
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.importHailData
protected function importHailData($data) { if ($this->excluded($data)) { return false; } $dataMap = array_merge( ['HailID' => 'id'], static::$api_map ); foreach ($dataMap as $ssKey => $hailKey) { $value = (isset($data[$hailKey]) && !empty($data[$hailKey])) ? $data[$hailKey] : ''; //Remove all NON UTF8 if Emoji support is disabled if (!Config::inst()->get(Client::class, 'EnableEmojiSupport')) { $value = preg_replace('/[^(\x20-\x7F)]*/', '', $value); } $this->{$ssKey} = html_entity_decode($value); } $this->Fetched = date("Y-m-d H:i:s"); $this->write(); $this->importing($data); $this->write(); return true; }
php
protected function importHailData($data) { if ($this->excluded($data)) { return false; } $dataMap = array_merge( ['HailID' => 'id'], static::$api_map ); foreach ($dataMap as $ssKey => $hailKey) { $value = (isset($data[$hailKey]) && !empty($data[$hailKey])) ? $data[$hailKey] : ''; //Remove all NON UTF8 if Emoji support is disabled if (!Config::inst()->get(Client::class, 'EnableEmojiSupport')) { $value = preg_replace('/[^(\x20-\x7F)]*/', '', $value); } $this->{$ssKey} = html_entity_decode($value); } $this->Fetched = date("Y-m-d H:i:s"); $this->write(); $this->importing($data); $this->write(); return true; }
[ "protected", "function", "importHailData", "(", "$", "data", ")", "{", "if", "(", "$", "this", "->", "excluded", "(", "$", "data", ")", ")", "{", "return", "false", ";", "}", "$", "dataMap", "=", "array_merge", "(", "[", "'HailID'", "=>", "'id'", "]"...
Process the json data from Hail API and writes to SS db Return true if the value should be saved to the database. False if it has been excluded. @param array $data JSON data from Hail @return boolean @throws
[ "Process", "the", "json", "data", "from", "Hail", "API", "and", "writes", "to", "SS", "db" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L173-L202
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.fetchAll
public static function fetchAll() { //Hail Api Client $hail_api_client = new Client(); $config = SiteConfig::current_site_config(); $orgs_ids = json_decode($config->HailOrgsIDs); if (!$orgs_ids) { //No organisations configured $hail_api_client->handleException(new \Exception("You need at least 1 Hail Organisation configured to be able to fetch")); return false; } //Fetch objects for all configured Hail organisations foreach ($orgs_ids as $org_id) { self::fetchForOrg($hail_api_client, $org_id); } }
php
public static function fetchAll() { //Hail Api Client $hail_api_client = new Client(); $config = SiteConfig::current_site_config(); $orgs_ids = json_decode($config->HailOrgsIDs); if (!$orgs_ids) { //No organisations configured $hail_api_client->handleException(new \Exception("You need at least 1 Hail Organisation configured to be able to fetch")); return false; } //Fetch objects for all configured Hail organisations foreach ($orgs_ids as $org_id) { self::fetchForOrg($hail_api_client, $org_id); } }
[ "public", "static", "function", "fetchAll", "(", ")", "{", "//Hail Api Client", "$", "hail_api_client", "=", "new", "Client", "(", ")", ";", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "$", "orgs_ids", "=", "json_decode", "(...
Fetch from Hail API for all configured organisations @throws
[ "Fetch", "from", "Hail", "API", "for", "all", "configured", "organisations" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L355-L372
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.makeRecordViewer
protected function makeRecordViewer($fields, $name, $relation, $viewComponent = 'Firebrand\Hail\Forms\GridFieldViewButton') { $config = GridFieldConfig_RecordViewer::create(); // Remove the standard GridFieldView button and replace it with our // custom button that will link to our the right action in our HailModelAdmin $config->removeComponentsByType('SilverStripe\Forms\GridField\GridFieldViewButton'); $config->addComponents(new $viewComponent()); //Relation tab names don't have spaces in SS4 $tab_name = str_replace(" ", "", $name); $grid = new GridFieldForReadonly($tab_name, $name, $relation, $config); $fields->addFieldToTab('Root.' . $tab_name, $grid); }
php
protected function makeRecordViewer($fields, $name, $relation, $viewComponent = 'Firebrand\Hail\Forms\GridFieldViewButton') { $config = GridFieldConfig_RecordViewer::create(); // Remove the standard GridFieldView button and replace it with our // custom button that will link to our the right action in our HailModelAdmin $config->removeComponentsByType('SilverStripe\Forms\GridField\GridFieldViewButton'); $config->addComponents(new $viewComponent()); //Relation tab names don't have spaces in SS4 $tab_name = str_replace(" ", "", $name); $grid = new GridFieldForReadonly($tab_name, $name, $relation, $config); $fields->addFieldToTab('Root.' . $tab_name, $grid); }
[ "protected", "function", "makeRecordViewer", "(", "$", "fields", ",", "$", "name", ",", "$", "relation", ",", "$", "viewComponent", "=", "'Firebrand\\Hail\\Forms\\GridFieldViewButton'", ")", "{", "$", "config", "=", "GridFieldConfig_RecordViewer", "::", "create", "(...
Helper function to add a ReadOnly gridfield for a relation @param FieldList $fields @param string $name Name that should be given to the GridField @param ManyManyList $relation Relation to display @param string $viewComponent Full class name of the view Component to add (button)
[ "Helper", "function", "to", "add", "a", "ReadOnly", "gridfield", "for", "a", "relation" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L421-L434
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.processPublicTags
protected function processPublicTags($data) { $tagIdList = []; // Clean tags before importing the new ones // but have not been returned this time around $this->PublicTags()->removeAll(); foreach ($data as $tagData) { $tagIdList[] = $tagData['id']; // Find a matching HailTag or create an new one $tag = PublicTag::get()->filter(['HailID' => $tagData['id']])->first(); if (!$tag) { $tag = new PublicTag(); } $tag->OrganisationID = $this->OrganisationID; $tag->HailOrgID = $this->HailOrgID; $tag->HailOrgName = $this->HailOrgName; // Update the PublicTags $tag->importHailData($tagData); if (!$this->PublicTags()->byID($tag->ID)) { $this->PublicTags()->add($tag); } } }
php
protected function processPublicTags($data) { $tagIdList = []; // Clean tags before importing the new ones // but have not been returned this time around $this->PublicTags()->removeAll(); foreach ($data as $tagData) { $tagIdList[] = $tagData['id']; // Find a matching HailTag or create an new one $tag = PublicTag::get()->filter(['HailID' => $tagData['id']])->first(); if (!$tag) { $tag = new PublicTag(); } $tag->OrganisationID = $this->OrganisationID; $tag->HailOrgID = $this->HailOrgID; $tag->HailOrgName = $this->HailOrgName; // Update the PublicTags $tag->importHailData($tagData); if (!$this->PublicTags()->byID($tag->ID)) { $this->PublicTags()->add($tag); } } }
[ "protected", "function", "processPublicTags", "(", "$", "data", ")", "{", "$", "tagIdList", "=", "[", "]", ";", "// Clean tags before importing the new ones", "// but have not been returned this time around", "$", "this", "->", "PublicTags", "(", ")", "->", "removeAll",...
Go through the list of public tags and assign them to this object. @param array $data JSON data from Hail
[ "Go", "through", "the", "list", "of", "public", "tags", "and", "assign", "them", "to", "this", "object", "." ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L441-L468
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.processPrivateTags
protected function processPrivateTags($data) { $tagIdList = []; $this->PrivateTags()->removeAll(); foreach ($data as $tagData) { $tagIdList[] = $tagData['id']; // Find a matching PrivateTag or create an new one $tag = PrivateTag::get()->filter(['HailID' => $tagData['id']])->first(); if (!$tag) { $tag = new PrivateTag(); } $tag->OrganisationID = $this->OrganisationID; $tag->HailOrgID = $this->HailOrgID; $tag->HailOrgName = $this->HailOrgName; // Update the Hail Tag $tag->importHailData($tagData); if (!$this->PrivateTags()->byID($tag->ID)) { $this->PrivateTags()->add($tag); } } }
php
protected function processPrivateTags($data) { $tagIdList = []; $this->PrivateTags()->removeAll(); foreach ($data as $tagData) { $tagIdList[] = $tagData['id']; // Find a matching PrivateTag or create an new one $tag = PrivateTag::get()->filter(['HailID' => $tagData['id']])->first(); if (!$tag) { $tag = new PrivateTag(); } $tag->OrganisationID = $this->OrganisationID; $tag->HailOrgID = $this->HailOrgID; $tag->HailOrgName = $this->HailOrgName; // Update the Hail Tag $tag->importHailData($tagData); if (!$this->PrivateTags()->byID($tag->ID)) { $this->PrivateTags()->add($tag); } } }
[ "protected", "function", "processPrivateTags", "(", "$", "data", ")", "{", "$", "tagIdList", "=", "[", "]", ";", "$", "this", "->", "PrivateTags", "(", ")", "->", "removeAll", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "tagData", ")", "{"...
Go through the list of private tags and assign them to this object. @param array $data JSON data from Hail
[ "Go", "through", "the", "list", "of", "private", "tags", "and", "assign", "them", "to", "this", "object", "." ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L475-L499
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.processHeroImage
protected function processHeroImage($heroImgData) { if ($heroImgData) { $hero = Image::get()->filter(['HailID' => $heroImgData['id']])->first(); if (!$hero) { $hero = new Image(); } $hero->OrganisationID = $this->OrganisationID; $hero->HailOrgID = $this->HailOrgID; $hero->HailOrgName = $this->HailOrgName; $hero->importHailData($heroImgData); $hero = $hero->ID; } else { $hero = null; } $this->HeroImageID = $hero; }
php
protected function processHeroImage($heroImgData) { if ($heroImgData) { $hero = Image::get()->filter(['HailID' => $heroImgData['id']])->first(); if (!$hero) { $hero = new Image(); } $hero->OrganisationID = $this->OrganisationID; $hero->HailOrgID = $this->HailOrgID; $hero->HailOrgName = $this->HailOrgName; $hero->importHailData($heroImgData); $hero = $hero->ID; } else { $hero = null; } $this->HeroImageID = $hero; }
[ "protected", "function", "processHeroImage", "(", "$", "heroImgData", ")", "{", "if", "(", "$", "heroImgData", ")", "{", "$", "hero", "=", "Image", "::", "get", "(", ")", "->", "filter", "(", "[", "'HailID'", "=>", "$", "heroImgData", "[", "'id'", "]",...
Match the hero image if there's one and assign it to this object @param array $heroImgData JSON data from Hail
[ "Match", "the", "hero", "image", "if", "there", "s", "one", "and", "assign", "it", "to", "this", "object" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L506-L524
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.processHeroVideo
protected function processHeroVideo($heroVidData) { if ($heroVidData) { $hero = Video::get()->filter(['HailID' => $heroVidData['id']])->first(); if (!$hero) { $hero = new Video(); } $hero->OrganisationID = $this->OrganisationID; $hero->HailOrgID = $this->HailOrgID; $hero->HailOrgName = $this->HailOrgName; $hero->importHailData($heroVidData); $hero = $hero->ID; } else { $hero = null; } $this->HeroVideoID = $hero; }
php
protected function processHeroVideo($heroVidData) { if ($heroVidData) { $hero = Video::get()->filter(['HailID' => $heroVidData['id']])->first(); if (!$hero) { $hero = new Video(); } $hero->OrganisationID = $this->OrganisationID; $hero->HailOrgID = $this->HailOrgID; $hero->HailOrgName = $this->HailOrgName; $hero->importHailData($heroVidData); $hero = $hero->ID; } else { $hero = null; } $this->HeroVideoID = $hero; }
[ "protected", "function", "processHeroVideo", "(", "$", "heroVidData", ")", "{", "if", "(", "$", "heroVidData", ")", "{", "$", "hero", "=", "Video", "::", "get", "(", ")", "->", "filter", "(", "[", "'HailID'", "=>", "$", "heroVidData", "[", "'id'", "]",...
Match the hero video if there's one and assign it to this object @param array $heroVidData JSON data from Hail
[ "Match", "the", "hero", "video", "if", "there", "s", "one", "and", "assign", "it", "to", "this", "object" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L531-L549
train
firebrandhq/silverstripe-hail
src/Models/ApiObject.php
ApiObject.processAttachments
protected function processAttachments($data) { $idList = []; foreach ($data as $attachmentData) { $idList[] = $attachmentData['id']; // Find a matching attachment or create it $attachment = Attachment::get()->filter(['HailID' => $attachmentData['id']])->first(); if (!$attachment) { $attachment = new Attachment(); } $attachment->OrganisationID = $this->OrganisationID; $attachment->HailOrgID = $this->HailOrgID; $attachment->HailOrgName = $this->HailOrgName; // Update the Hail Attachments $attachment->importHailData($attachmentData); if (!$this->Attachments()->byID($attachment->ID)) { $this->Attachments()->add($attachment); } } // Remove old attachments that are currently assigned to this article, // but have not been returned this time around if ($idList) { $this->Attachments()->exclude('HailID', $idList)->removeAll(); } else { // If there's no attachements, just remove everything. $this->Attachments()->removeAll(); } }
php
protected function processAttachments($data) { $idList = []; foreach ($data as $attachmentData) { $idList[] = $attachmentData['id']; // Find a matching attachment or create it $attachment = Attachment::get()->filter(['HailID' => $attachmentData['id']])->first(); if (!$attachment) { $attachment = new Attachment(); } $attachment->OrganisationID = $this->OrganisationID; $attachment->HailOrgID = $this->HailOrgID; $attachment->HailOrgName = $this->HailOrgName; // Update the Hail Attachments $attachment->importHailData($attachmentData); if (!$this->Attachments()->byID($attachment->ID)) { $this->Attachments()->add($attachment); } } // Remove old attachments that are currently assigned to this article, // but have not been returned this time around if ($idList) { $this->Attachments()->exclude('HailID', $idList)->removeAll(); } else { // If there's no attachements, just remove everything. $this->Attachments()->removeAll(); } }
[ "protected", "function", "processAttachments", "(", "$", "data", ")", "{", "$", "idList", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "attachmentData", ")", "{", "$", "idList", "[", "]", "=", "$", "attachmentData", "[", "'id'", "]", "...
Go through the attachments and assign them to this object. @param array $data JSON data from Hail
[ "Go", "through", "the", "attachments", "and", "assign", "them", "to", "this", "object", "." ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/ApiObject.php#L556-L588
train
firebrandhq/silverstripe-hail
src/Pages/HailPageController.php
HailPageController.article
public function article(HTTPRequest $request) { $params = $request->params(); if ($params['ID']) { $article = Article::get()->filter(['HailID' => $params['ID']])->first(); //Try to find the article with the database ID field, to be backward compatible with old Hail module (after upgrade) if(!isset($article) || empty($article)) { $article = Article::get()->filter(['ID' => $params['ID']])->first(); } } if (!$params['ID'] || !isset($article) || empty($article)) { return $this->httpError(404, 'That article could not be found'); } $data = [ 'Article' => $article, 'Related' => null ]; //Store the current article so we can use it in other functions in the controller $this->article = $article; //If Related Articles are enabled on the page (from the CMS) if ($this->owner->EnableRelated === "Yes") { //Try to find 3 related articles if ($article->PublicTags()->Count() > 0) { $related = Article::get()->filter(['PublicTags.ID' => $article->PublicTags()->map('ID', 'ID')->toArray()])->exclude(['HailID' => $params['ID']])->sort('Date DESC')->limit(3); if ($related->Count() > 0) { $data['Related'] = $related; } } } return $data; }
php
public function article(HTTPRequest $request) { $params = $request->params(); if ($params['ID']) { $article = Article::get()->filter(['HailID' => $params['ID']])->first(); //Try to find the article with the database ID field, to be backward compatible with old Hail module (after upgrade) if(!isset($article) || empty($article)) { $article = Article::get()->filter(['ID' => $params['ID']])->first(); } } if (!$params['ID'] || !isset($article) || empty($article)) { return $this->httpError(404, 'That article could not be found'); } $data = [ 'Article' => $article, 'Related' => null ]; //Store the current article so we can use it in other functions in the controller $this->article = $article; //If Related Articles are enabled on the page (from the CMS) if ($this->owner->EnableRelated === "Yes") { //Try to find 3 related articles if ($article->PublicTags()->Count() > 0) { $related = Article::get()->filter(['PublicTags.ID' => $article->PublicTags()->map('ID', 'ID')->toArray()])->exclude(['HailID' => $params['ID']])->sort('Date DESC')->limit(3); if ($related->Count() > 0) { $data['Related'] = $related; } } } return $data; }
[ "public", "function", "article", "(", "HTTPRequest", "$", "request", ")", "{", "$", "params", "=", "$", "request", "->", "params", "(", ")", ";", "if", "(", "$", "params", "[", "'ID'", "]", ")", "{", "$", "article", "=", "Article", "::", "get", "("...
Render a Hail Article @param HTTPRequest $request @return array @throws HTTPResponse_Exception
[ "Render", "a", "Hail", "Article" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Pages/HailPageController.php#L85-L119
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/WildcardEventDispatcher.php
WildcardEventDispatcher.bindPatterns
protected function bindPatterns($eventName) { if (isset($this->syncedEvents[$eventName])) { return; } foreach ($this->patterns as $eventPattern => $patterns) { foreach ($patterns as $pattern) { if ($pattern->test($eventName)) { $pattern->bind($this->dispatcher, $eventName); } } } $this->syncedEvents[$eventName] = true; }
php
protected function bindPatterns($eventName) { if (isset($this->syncedEvents[$eventName])) { return; } foreach ($this->patterns as $eventPattern => $patterns) { foreach ($patterns as $pattern) { if ($pattern->test($eventName)) { $pattern->bind($this->dispatcher, $eventName); } } } $this->syncedEvents[$eventName] = true; }
[ "protected", "function", "bindPatterns", "(", "$", "eventName", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "syncedEvents", "[", "$", "eventName", "]", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "this", "->", "patterns", "as", ...
Binds all patterns that match the specified event name. @param string $eventName
[ "Binds", "all", "patterns", "that", "match", "the", "specified", "event", "name", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/WildcardEventDispatcher.php#L139-L154
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/WildcardEventDispatcher.php
WildcardEventDispatcher.addListenerPattern
protected function addListenerPattern(ListenerPattern $pattern) { $this->patterns[$pattern->getEventPattern()][] = $pattern; foreach ($this->syncedEvents as $eventName => $_) { if ($pattern->test($eventName)) { unset($this->syncedEvents[$eventName]); } } }
php
protected function addListenerPattern(ListenerPattern $pattern) { $this->patterns[$pattern->getEventPattern()][] = $pattern; foreach ($this->syncedEvents as $eventName => $_) { if ($pattern->test($eventName)) { unset($this->syncedEvents[$eventName]); } } }
[ "protected", "function", "addListenerPattern", "(", "ListenerPattern", "$", "pattern", ")", "{", "$", "this", "->", "patterns", "[", "$", "pattern", "->", "getEventPattern", "(", ")", "]", "[", "]", "=", "$", "pattern", ";", "foreach", "(", "$", "this", ...
Adds an event listener for all events matching the specified pattern. This method will lazily register the listener when a matching event is dispatched. @param ListenerPattern $pattern
[ "Adds", "an", "event", "listener", "for", "all", "events", "matching", "the", "specified", "pattern", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/WildcardEventDispatcher.php#L164-L173
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/WildcardEventDispatcher.php
WildcardEventDispatcher.removeListenerPattern
protected function removeListenerPattern($eventPattern, $listener) { if (!isset($this->patterns[$eventPattern])) { return; } foreach ($this->patterns[$eventPattern] as $key => $pattern) { if ($listener == $pattern->getListener()) { $pattern->unbind($this->dispatcher); unset($this->patterns[$eventPattern][$key]); } } }
php
protected function removeListenerPattern($eventPattern, $listener) { if (!isset($this->patterns[$eventPattern])) { return; } foreach ($this->patterns[$eventPattern] as $key => $pattern) { if ($listener == $pattern->getListener()) { $pattern->unbind($this->dispatcher); unset($this->patterns[$eventPattern][$key]); } } }
[ "protected", "function", "removeListenerPattern", "(", "$", "eventPattern", ",", "$", "listener", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "patterns", "[", "$", "eventPattern", "]", ")", ")", "{", "return", ";", "}", "foreach", "(", "...
Removes an event listener from any events to which it was applied due to pattern matching. This method cannot be used to remove a listener from a pattern that was never registered. @param string $eventPattern @param callback $listener
[ "Removes", "an", "event", "listener", "from", "any", "events", "to", "which", "it", "was", "applied", "due", "to", "pattern", "matching", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/WildcardEventDispatcher.php#L185-L197
train
CradlePHP/cradle-system
src/Schema/Service/ElasticService.php
ElasticService.createMap
public function createMap() { if(is_null($this->schema)) { throw SystemException::forNoSchema(); } // translate data first to sql $data = $this->schema->toSql(); // then translate it to elastic mapping $mapping = $this->schema->toElastic($data); // get schema path $path = cradle()->package('global')->path('schema') . '/elastic'; // if elastic dir doesn't exists // create elastic folder if(!is_dir($path)) { mkdir($path, 0777); } // if elastic schema dir doesn't exist // create elastic schema dir mkdir ($path . '/' . ucwords($data['name'])); // save mapping file_put_contents( $path . '/' . ucwords($data['name']) . '/elastic.php', '<?php //-->' . "\n return " . var_export($mapping, true) . ';' ); }
php
public function createMap() { if(is_null($this->schema)) { throw SystemException::forNoSchema(); } // translate data first to sql $data = $this->schema->toSql(); // then translate it to elastic mapping $mapping = $this->schema->toElastic($data); // get schema path $path = cradle()->package('global')->path('schema') . '/elastic'; // if elastic dir doesn't exists // create elastic folder if(!is_dir($path)) { mkdir($path, 0777); } // if elastic schema dir doesn't exist // create elastic schema dir mkdir ($path . '/' . ucwords($data['name'])); // save mapping file_put_contents( $path . '/' . ucwords($data['name']) . '/elastic.php', '<?php //-->' . "\n return " . var_export($mapping, true) . ';' ); }
[ "public", "function", "createMap", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "// translate data first to sql", "$", "data", "=", "$", "this", ...
Create an elastic map @return void
[ "Create", "an", "elastic", "map" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Service/ElasticService.php#L57-L85
train
CradlePHP/cradle-system
src/Schema/Service/ElasticService.php
ElasticService.map
public function map() { // no schema validation if(is_null($this->schema)) { throw SystemException::forNoSchema(); } $table = $this->schema->getName(); $path = cradle()->package('global')->path('schema') . sprintf('/elastic/%s/elastic.php', ucwords($table)); // if mapped file doesn't exist, // do nothing if (!file_exists($path)) { return false; } $data = include_once($path); // try mapping try { $this->resource->indices()->create(['index' => $table]); $this->resource->indices()->putMapping([ 'index' => $table, 'type' => 'main', 'body' => [ '_source' => [ 'enabled' => true ], 'properties' => $data[$table] ] ]); } catch (NoNodesAvailableException $e) { //because there is no reason to continue; return false; } catch (BadRequest400Exception $e) { //already mapped return false; } catch (\Throwable $e) { // something is not right return false; } return true; }
php
public function map() { // no schema validation if(is_null($this->schema)) { throw SystemException::forNoSchema(); } $table = $this->schema->getName(); $path = cradle()->package('global')->path('schema') . sprintf('/elastic/%s/elastic.php', ucwords($table)); // if mapped file doesn't exist, // do nothing if (!file_exists($path)) { return false; } $data = include_once($path); // try mapping try { $this->resource->indices()->create(['index' => $table]); $this->resource->indices()->putMapping([ 'index' => $table, 'type' => 'main', 'body' => [ '_source' => [ 'enabled' => true ], 'properties' => $data[$table] ] ]); } catch (NoNodesAvailableException $e) { //because there is no reason to continue; return false; } catch (BadRequest400Exception $e) { //already mapped return false; } catch (\Throwable $e) { // something is not right return false; } return true; }
[ "public", "function", "map", "(", ")", "{", "// no schema validation", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "$", "table", "=", "$", "this", "->", "sc...
Map Elastic Schema @return bool
[ "Map", "Elastic", "Schema" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Service/ElasticService.php#L92-L135
train
CradlePHP/cradle-system
src/Schema/Service/ElasticService.php
ElasticService.flush
public function flush() { // no schema validation if(is_null($this->schema)) { throw SystemException::forNoSchema(); } // flush elastic schema try { $this->resource ->indices() ->delete( ['index' => $this->schema ->getName() ] ); return true; } catch(\Throwable $e) { return false; } }
php
public function flush() { // no schema validation if(is_null($this->schema)) { throw SystemException::forNoSchema(); } // flush elastic schema try { $this->resource ->indices() ->delete( ['index' => $this->schema ->getName() ] ); return true; } catch(\Throwable $e) { return false; } }
[ "public", "function", "flush", "(", ")", "{", "// no schema validation", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "// flush elastic schema", "try", "{", "$", ...
Flush Elastic Index @return bool
[ "Flush", "Elastic", "Index" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Service/ElasticService.php#L240-L260
train
oasmobile/php-http
src/ServiceProviders/Security/NullEntryPoint.php
NullEntryPoint.start
public function start(Request $request, AuthenticationException $authException = null) { $msg = $authException ? $authException->getMessage() : 'Access Denied'; throw new AccessDeniedHttpException($msg); }
php
public function start(Request $request, AuthenticationException $authException = null) { $msg = $authException ? $authException->getMessage() : 'Access Denied'; throw new AccessDeniedHttpException($msg); }
[ "public", "function", "start", "(", "Request", "$", "request", ",", "AuthenticationException", "$", "authException", "=", "null", ")", "{", "$", "msg", "=", "$", "authException", "?", "$", "authException", "->", "getMessage", "(", ")", ":", "'Access Denied'", ...
Returns a response that directs the user to authenticate. This is called when an anonymous request accesses a resource that requires authentication. The job of this method is to return some response that "helps" the user start into the authentication process. Examples: A) For a form login, you might redirect to the login page return new RedirectResponse('/login'); B) For an API token authentication system, you return a 401 response return new Response('Auth header required', 401); @param Request $request The request that resulted in an AuthenticationException @param AuthenticationException $authException The exception that started the authentication process @return Response
[ "Returns", "a", "response", "that", "directs", "the", "user", "to", "authenticate", "." ]
a7570893742286c30222c393891aeb6857064f37
https://github.com/oasmobile/php-http/blob/a7570893742286c30222c393891aeb6857064f37/src/ServiceProviders/Security/NullEntryPoint.php#L38-L42
train
MetaModels/filter_text
src/FilterSetting/Text.php
Text.doSimpleSearch
private function doSimpleSearch($strTextSearch, $objFilter, $arrFilterUrl) { $objMetaModel = $this->getMetaModel(); $objAttribute = $objMetaModel->getAttributeById($this->get('attr_id')); $arrLanguages = $this->getAvailableLanguages($objMetaModel); $strParamName = $this->getParamName(); $strParamValue = $arrFilterUrl[$strParamName]; // React on wildcard, overriding the search type. if (strpos($strParamValue, '*') !== false) { $strTextSearch = 'exact'; } // Type of search. switch ($strTextSearch) { case 'beginswith': $strWhat = $strParamValue . '*'; break; case 'endswith': $strWhat = '*' . $strParamValue; break; case 'exact': $strWhat = $strParamValue; break; default: $strWhat = '*' . $strParamValue . '*'; break; } if ($objAttribute && $strParamName && $strParamValue !== null) { $objFilter->addFilterRule(new SearchAttribute($objAttribute, $strWhat, $arrLanguages)); return; } $objFilter->addFilterRule(new StaticIdList(null)); }
php
private function doSimpleSearch($strTextSearch, $objFilter, $arrFilterUrl) { $objMetaModel = $this->getMetaModel(); $objAttribute = $objMetaModel->getAttributeById($this->get('attr_id')); $arrLanguages = $this->getAvailableLanguages($objMetaModel); $strParamName = $this->getParamName(); $strParamValue = $arrFilterUrl[$strParamName]; // React on wildcard, overriding the search type. if (strpos($strParamValue, '*') !== false) { $strTextSearch = 'exact'; } // Type of search. switch ($strTextSearch) { case 'beginswith': $strWhat = $strParamValue . '*'; break; case 'endswith': $strWhat = '*' . $strParamValue; break; case 'exact': $strWhat = $strParamValue; break; default: $strWhat = '*' . $strParamValue . '*'; break; } if ($objAttribute && $strParamName && $strParamValue !== null) { $objFilter->addFilterRule(new SearchAttribute($objAttribute, $strWhat, $arrLanguages)); return; } $objFilter->addFilterRule(new StaticIdList(null)); }
[ "private", "function", "doSimpleSearch", "(", "$", "strTextSearch", ",", "$", "objFilter", ",", "$", "arrFilterUrl", ")", "{", "$", "objMetaModel", "=", "$", "this", "->", "getMetaModel", "(", ")", ";", "$", "objAttribute", "=", "$", "objMetaModel", "->", ...
Make a simple search with a like. @param string $strTextSearch The mode for the search. @param IFilter $objFilter The filter to append the rules to. @param string[] $arrFilterUrl The parameters to evaluate. @return void
[ "Make", "a", "simple", "search", "with", "a", "like", "." ]
7537cfba0c38c9b6da84398d6109122d2d090593
https://github.com/MetaModels/filter_text/blob/7537cfba0c38c9b6da84398d6109122d2d090593/src/FilterSetting/Text.php#L103-L139
train
MetaModels/filter_text
src/FilterSetting/Text.php
Text.doComplexSearch
private function doComplexSearch($strTextSearch, $objFilter, $arrFilterUrl) { $objMetaModel = $this->getMetaModel(); $objAttribute = $objMetaModel->getAttributeById($this->get('attr_id')); $arrLanguages = $this->getAvailableLanguages($objMetaModel); $strParamName = $this->getParamName(); $strParamValue = $arrFilterUrl[$strParamName]; $parentFilter = null; $words = []; // Type of search. switch ($strTextSearch) { case 'any': $words = $this->getWords($strParamValue); $parentFilter = new ConditionOr(); break; case 'all': $words = $this->getWords($strParamValue); $parentFilter = new ConditionAnd(); break; default: // Do nothing. Because the parent function saved us. The value have to be any or all. break; } if ($objAttribute && $strParamName && $strParamValue !== null && $parentFilter) { foreach ($words as $word) { $subFilter = $objMetaModel->getEmptyFilter(); $subFilter->addFilterRule(new SearchAttribute($objAttribute, '%' . $word . '%', $arrLanguages)); $parentFilter->addChild($subFilter); } $objFilter->addFilterRule($parentFilter); return; } $objFilter->addFilterRule(new StaticIdList(null)); }
php
private function doComplexSearch($strTextSearch, $objFilter, $arrFilterUrl) { $objMetaModel = $this->getMetaModel(); $objAttribute = $objMetaModel->getAttributeById($this->get('attr_id')); $arrLanguages = $this->getAvailableLanguages($objMetaModel); $strParamName = $this->getParamName(); $strParamValue = $arrFilterUrl[$strParamName]; $parentFilter = null; $words = []; // Type of search. switch ($strTextSearch) { case 'any': $words = $this->getWords($strParamValue); $parentFilter = new ConditionOr(); break; case 'all': $words = $this->getWords($strParamValue); $parentFilter = new ConditionAnd(); break; default: // Do nothing. Because the parent function saved us. The value have to be any or all. break; } if ($objAttribute && $strParamName && $strParamValue !== null && $parentFilter) { foreach ($words as $word) { $subFilter = $objMetaModel->getEmptyFilter(); $subFilter->addFilterRule(new SearchAttribute($objAttribute, '%' . $word . '%', $arrLanguages)); $parentFilter->addChild($subFilter); } $objFilter->addFilterRule($parentFilter); return; } $objFilter->addFilterRule(new StaticIdList(null)); }
[ "private", "function", "doComplexSearch", "(", "$", "strTextSearch", ",", "$", "objFilter", ",", "$", "arrFilterUrl", ")", "{", "$", "objMetaModel", "=", "$", "this", "->", "getMetaModel", "(", ")", ";", "$", "objAttribute", "=", "$", "objMetaModel", "->", ...
Do a complex search with each word. Search for all words or for any word. @param string $strTextSearch The mode any or all. @param IFilter $objFilter The filter to append the rules to. @param string[] $arrFilterUrl The parameters to evaluate. @return void
[ "Do", "a", "complex", "search", "with", "each", "word", ".", "Search", "for", "all", "words", "or", "for", "any", "word", "." ]
7537cfba0c38c9b6da84398d6109122d2d090593
https://github.com/MetaModels/filter_text/blob/7537cfba0c38c9b6da84398d6109122d2d090593/src/FilterSetting/Text.php#L152-L191
train
MetaModels/filter_text
src/FilterSetting/Text.php
Text.getWords
private function getWords($string) { $delimiter = $this->get('delimiter'); if (empty($delimiter)) { $delimiter = ' '; } return trimsplit($delimiter, $string); }
php
private function getWords($string) { $delimiter = $this->get('delimiter'); if (empty($delimiter)) { $delimiter = ' '; } return trimsplit($delimiter, $string); }
[ "private", "function", "getWords", "(", "$", "string", ")", "{", "$", "delimiter", "=", "$", "this", "->", "get", "(", "'delimiter'", ")", ";", "if", "(", "empty", "(", "$", "delimiter", ")", ")", "{", "$", "delimiter", "=", "' '", ";", "}", "retur...
Use the delimiter from the setting and make a list of words. @param string $string The list of words as a single string. @return array The list of word split on the delimiter.
[ "Use", "the", "delimiter", "from", "the", "setting", "and", "make", "a", "list", "of", "words", "." ]
7537cfba0c38c9b6da84398d6109122d2d090593
https://github.com/MetaModels/filter_text/blob/7537cfba0c38c9b6da84398d6109122d2d090593/src/FilterSetting/Text.php#L200-L208
train
MetaModels/filter_text
src/FilterSetting/Text.php
Text.doRegexpSearch
private function doRegexpSearch($objFilter, $arrFilterUrl) { $objMetaModel = $this->getMetaModel(); $objAttribute = $objMetaModel->getAttributeById($this->get('attr_id')); $strParamName = $this->getParamName(); $strParamValue = $arrFilterUrl[$strParamName]; $strPattern = $this->get('pattern'); if ($objAttribute && $strParamName && $strParamValue !== null) { if (empty($strPattern) || substr_count($strPattern, '%s') != 1) { $strPattern = '%s'; } $strRegex = sprintf($strPattern, $strParamValue); $strQuery = sprintf( 'SELECT id FROM %s WHERE %s REGEXP \'%s\'', $objMetaModel->getTableName(), $objAttribute->getColName(), $strRegex ); $objFilter->addFilterRule(new SimpleQuery($strQuery)); return; } $objFilter->addFilterRule(new StaticIdList(null)); }
php
private function doRegexpSearch($objFilter, $arrFilterUrl) { $objMetaModel = $this->getMetaModel(); $objAttribute = $objMetaModel->getAttributeById($this->get('attr_id')); $strParamName = $this->getParamName(); $strParamValue = $arrFilterUrl[$strParamName]; $strPattern = $this->get('pattern'); if ($objAttribute && $strParamName && $strParamValue !== null) { if (empty($strPattern) || substr_count($strPattern, '%s') != 1) { $strPattern = '%s'; } $strRegex = sprintf($strPattern, $strParamValue); $strQuery = sprintf( 'SELECT id FROM %s WHERE %s REGEXP \'%s\'', $objMetaModel->getTableName(), $objAttribute->getColName(), $strRegex ); $objFilter->addFilterRule(new SimpleQuery($strQuery)); return; } $objFilter->addFilterRule(new StaticIdList(null)); }
[ "private", "function", "doRegexpSearch", "(", "$", "objFilter", ",", "$", "arrFilterUrl", ")", "{", "$", "objMetaModel", "=", "$", "this", "->", "getMetaModel", "(", ")", ";", "$", "objAttribute", "=", "$", "objMetaModel", "->", "getAttributeById", "(", "$",...
Make a simple search with a regexp. @param IFilter $objFilter The filter to append the rules to. @param string[] $arrFilterUrl The parameters to evaluate. @return void
[ "Make", "a", "simple", "search", "with", "a", "regexp", "." ]
7537cfba0c38c9b6da84398d6109122d2d090593
https://github.com/MetaModels/filter_text/blob/7537cfba0c38c9b6da84398d6109122d2d090593/src/FilterSetting/Text.php#L219-L247
train
flipboxfactory/craft-ember
src/helpers/LoggerHelper.php
LoggerHelper.targetConfigs
public static function targetConfigs(array $categories): array { $configs = []; foreach ($categories as $category) { $configs[$category] = static::targetConfig($category); } return array_filter($configs); }
php
public static function targetConfigs(array $categories): array { $configs = []; foreach ($categories as $category) { $configs[$category] = static::targetConfig($category); } return array_filter($configs); }
[ "public", "static", "function", "targetConfigs", "(", "array", "$", "categories", ")", ":", "array", "{", "$", "configs", "=", "[", "]", ";", "foreach", "(", "$", "categories", "as", "$", "category", ")", "{", "$", "configs", "[", "$", "category", "]",...
Takes an array of log categories and creates log target configs @param array $categories @return array
[ "Takes", "an", "array", "of", "log", "categories", "and", "creates", "log", "target", "configs" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/helpers/LoggerHelper.php#L28-L37
train
flipboxfactory/craft-ember
src/helpers/LoggerHelper.php
LoggerHelper.targetConfig
public static function targetConfig(string $category): array { // Only log console requests and web requests that aren't getAuthTimeout requests $isConsoleRequest = Craft::$app->getRequest()->getIsConsoleRequest(); if (!$isConsoleRequest && !Craft::$app->getUser()->enableSession) { return []; } $generalConfig = Craft::$app->getConfig()->getGeneral(); $target = [ 'class' => FileTarget::class, 'fileMode' => $generalConfig->defaultFileMode, 'dirMode' => $generalConfig->defaultDirMode, 'logVars' => [], 'categories' => [$category, $category . ':*'], 'logFile' => '@storage/logs/'.$category.'.log' ]; if (!$isConsoleRequest) { // Only log errors and warnings, unless Craft is running in Dev Mode or it's being installed/updated if (!YII_DEBUG && Craft::$app->getIsInstalled() && !Craft::$app->getUpdates()->getIsCraftDbMigrationNeeded() ) { $target['levels'] = Logger::LEVEL_ERROR | Logger::LEVEL_WARNING; } } return $target; }
php
public static function targetConfig(string $category): array { // Only log console requests and web requests that aren't getAuthTimeout requests $isConsoleRequest = Craft::$app->getRequest()->getIsConsoleRequest(); if (!$isConsoleRequest && !Craft::$app->getUser()->enableSession) { return []; } $generalConfig = Craft::$app->getConfig()->getGeneral(); $target = [ 'class' => FileTarget::class, 'fileMode' => $generalConfig->defaultFileMode, 'dirMode' => $generalConfig->defaultDirMode, 'logVars' => [], 'categories' => [$category, $category . ':*'], 'logFile' => '@storage/logs/'.$category.'.log' ]; if (!$isConsoleRequest) { // Only log errors and warnings, unless Craft is running in Dev Mode or it's being installed/updated if (!YII_DEBUG && Craft::$app->getIsInstalled() && !Craft::$app->getUpdates()->getIsCraftDbMigrationNeeded() ) { $target['levels'] = Logger::LEVEL_ERROR | Logger::LEVEL_WARNING; } } return $target; }
[ "public", "static", "function", "targetConfig", "(", "string", "$", "category", ")", ":", "array", "{", "// Only log console requests and web requests that aren't getAuthTimeout requests", "$", "isConsoleRequest", "=", "Craft", "::", "$", "app", "->", "getRequest", "(", ...
Takes a log category and creates a log target config @param string $category @return array
[ "Takes", "a", "log", "category", "and", "creates", "a", "log", "target", "config" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/helpers/LoggerHelper.php#L45-L75
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/HeadersTrait.php
HeadersTrait.setHeaderName
protected function setHeaderName(string $key) { $key = strtr(strtolower($key), '_', '-'); if (strpos($key, 'http-') === 0) { $key = substr($key, 5); } return $key; }
php
protected function setHeaderName(string $key) { $key = strtr(strtolower($key), '_', '-'); if (strpos($key, 'http-') === 0) { $key = substr($key, 5); } return $key; }
[ "protected", "function", "setHeaderName", "(", "string", "$", "key", ")", "{", "$", "key", "=", "strtr", "(", "strtolower", "(", "$", "key", ")", ",", "'_'", ",", "'-'", ")", ";", "if", "(", "strpos", "(", "$", "key", ",", "'http-'", ")", "===", ...
Sets case-insensitive header name. @param string $key @return string
[ "Sets", "case", "-", "insensitive", "header", "name", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/HeadersTrait.php#L68-L75
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/HeadersTrait.php
HeadersTrait.setPreserveHost
protected function setPreserveHost(string $headerHost, string $host) { $header = []; if ($host !== '' && $headerHost === '') { $header = [ 'original' => 'HTTP_HOST', 'values' => [$host] ]; } return $header; }
php
protected function setPreserveHost(string $headerHost, string $host) { $header = []; if ($host !== '' && $headerHost === '') { $header = [ 'original' => 'HTTP_HOST', 'values' => [$host] ]; } return $header; }
[ "protected", "function", "setPreserveHost", "(", "string", "$", "headerHost", ",", "string", "$", "host", ")", "{", "$", "header", "=", "[", "]", ";", "if", "(", "$", "host", "!==", "''", "&&", "$", "headerHost", "===", "''", ")", "{", "$", "header",...
Sets Host header if preserve host is true. @param string $headerHost @param string $host return string[][]
[ "Sets", "Host", "header", "if", "preserve", "host", "is", "true", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/HeadersTrait.php#L84-L94
train
firebrandhq/silverstripe-hail
src/Models/Image.php
Image.getRelativeCenterX
public function getRelativeCenterX() { $pos = 50; if ($this->FaceCentreX > 0 && $this->OriginalWidth > 0) { $pos = $this->FaceCentreX / $this->OriginalWidth * 100; $pos = ($pos > 100 || $pos < 0) ? 50 : $pos; } return $pos; }
php
public function getRelativeCenterX() { $pos = 50; if ($this->FaceCentreX > 0 && $this->OriginalWidth > 0) { $pos = $this->FaceCentreX / $this->OriginalWidth * 100; $pos = ($pos > 100 || $pos < 0) ? 50 : $pos; } return $pos; }
[ "public", "function", "getRelativeCenterX", "(", ")", "{", "$", "pos", "=", "50", ";", "if", "(", "$", "this", "->", "FaceCentreX", ">", "0", "&&", "$", "this", "->", "OriginalWidth", ">", "0", ")", "{", "$", "pos", "=", "$", "this", "->", "FaceCen...
Get the X axis for the relative center of this image @return int
[ "Get", "the", "X", "axis", "for", "the", "relative", "center", "of", "this", "image" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Image.php#L193-L202
train
firebrandhq/silverstripe-hail
src/Models/Image.php
Image.getRelativeCenterY
public function getRelativeCenterY() { $pos = 50; if ($this->FaceCentreY > 0 && $this->OriginalHeight > 0) { $pos = $this->FaceCentreY / $this->OriginalHeight * 100; $pos = ($pos > 100 || $pos < 0) ? 50 : $pos; } return $pos; }
php
public function getRelativeCenterY() { $pos = 50; if ($this->FaceCentreY > 0 && $this->OriginalHeight > 0) { $pos = $this->FaceCentreY / $this->OriginalHeight * 100; $pos = ($pos > 100 || $pos < 0) ? 50 : $pos; } return $pos; }
[ "public", "function", "getRelativeCenterY", "(", ")", "{", "$", "pos", "=", "50", ";", "if", "(", "$", "this", "->", "FaceCentreY", ">", "0", "&&", "$", "this", "->", "OriginalHeight", ">", "0", ")", "{", "$", "pos", "=", "$", "this", "->", "FaceCe...
Get the Y axis for the relative center of this image @return int
[ "Get", "the", "Y", "axis", "for", "the", "relative", "center", "of", "this", "image" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Image.php#L209-L218
train
oasmobile/php-http
src/ServiceProviders/Security/AbstractSimplePreAuthenticator.php
AbstractSimplePreAuthenticator.createAuthenticatedToken
protected function createAuthenticatedToken($user, $credentials, $providerKey) { return new PreAuthenticatedToken($user, $credentials, $providerKey, $user->getRoles()); }
php
protected function createAuthenticatedToken($user, $credentials, $providerKey) { return new PreAuthenticatedToken($user, $credentials, $providerKey, $user->getRoles()); }
[ "protected", "function", "createAuthenticatedToken", "(", "$", "user", ",", "$", "credentials", ",", "$", "providerKey", ")", "{", "return", "new", "PreAuthenticatedToken", "(", "$", "user", ",", "$", "credentials", ",", "$", "providerKey", ",", "$", "user", ...
Creates an authenticated token upon authentication success. Inherited class can override this method to provide their own pre-authenticated token implementation @param string|UserInterface $user The user @param mixed $credentials The user credentials @param string $providerKey The provider key @return PreAuthenticatedToken
[ "Creates", "an", "authenticated", "token", "upon", "authentication", "success", "." ]
a7570893742286c30222c393891aeb6857064f37
https://github.com/oasmobile/php-http/blob/a7570893742286c30222c393891aeb6857064f37/src/ServiceProviders/Security/AbstractSimplePreAuthenticator.php#L79-L82
train
arillo/silverstripe-elements
src/VersionedGridFieldItemRequestExtension.php
VersionedGridFieldItemRequestExtension.updateFormActions
public function updateFormActions(FieldList $actions) { if (is_a($this->owner->getRecord(), ElementBase::class)) { $actions->removeByName('action_doUnpublish'); if ($archive = $actions->fieldByName('action_doArchive')) { $archive ->setTitle(_t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action-delete') ; } } return $actions; }
php
public function updateFormActions(FieldList $actions) { if (is_a($this->owner->getRecord(), ElementBase::class)) { $actions->removeByName('action_doUnpublish'); if ($archive = $actions->fieldByName('action_doArchive')) { $archive ->setTitle(_t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action-delete') ; } } return $actions; }
[ "public", "function", "updateFormActions", "(", "FieldList", "$", "actions", ")", "{", "if", "(", "is_a", "(", "$", "this", "->", "owner", "->", "getRecord", "(", ")", ",", "ElementBase", "::", "class", ")", ")", "{", "$", "actions", "->", "removeByName"...
Remove unpublish action @param FieldList $actions @return FieldList
[ "Remove", "unpublish", "action" ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/VersionedGridFieldItemRequestExtension.php#L13-L30
train
appaydin/pd-mailer
DependencyInjection/PdMailerExtension.php
PdMailerExtension.load
public function load(array $configs, ContainerBuilder $container) { // Load Configuration $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); // Set Parameters $container->setParameter('pd_mailer.logger_active', $config['logger_active']); $container->setParameter('pd_mailer.mail_log_class', $config['mail_log_class']); $container->setParameter('pd_mailer.mail_template_class', $config['mail_template_class']); $container->setParameter('pd_mailer.mail_template_type', $config['mail_template_type']); $container->setParameter('pd_mailer.template_active', $config['template_active']); $container->setParameter('pd_mailer.sender_address', $config['sender_address']); $container->setParameter('pd_mailer.sender_name', $config['sender_name']); $container->setParameter('pd_mailer.list_count', $config['list_count']); $container->setParameter('pd_mailer.active_language', $config['active_language']); $container->setParameter('pd_mailer.base_template', $config['base_template']); // Load Services $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yaml'); // Replace Service Tags $menuListener = $container->getDefinition(MainNavListener::class); $tags = $menuListener->getTag('kernel.event_listener'); $tags[0]['event'] = $config['menu_root_name'] . '.event'; $menuListener ->setTags([ 'kernel.event_listener' => $tags ]) ->setArguments([$config['menu_name']]); }
php
public function load(array $configs, ContainerBuilder $container) { // Load Configuration $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); // Set Parameters $container->setParameter('pd_mailer.logger_active', $config['logger_active']); $container->setParameter('pd_mailer.mail_log_class', $config['mail_log_class']); $container->setParameter('pd_mailer.mail_template_class', $config['mail_template_class']); $container->setParameter('pd_mailer.mail_template_type', $config['mail_template_type']); $container->setParameter('pd_mailer.template_active', $config['template_active']); $container->setParameter('pd_mailer.sender_address', $config['sender_address']); $container->setParameter('pd_mailer.sender_name', $config['sender_name']); $container->setParameter('pd_mailer.list_count', $config['list_count']); $container->setParameter('pd_mailer.active_language', $config['active_language']); $container->setParameter('pd_mailer.base_template', $config['base_template']); // Load Services $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yaml'); // Replace Service Tags $menuListener = $container->getDefinition(MainNavListener::class); $tags = $menuListener->getTag('kernel.event_listener'); $tags[0]['event'] = $config['menu_root_name'] . '.event'; $menuListener ->setTags([ 'kernel.event_listener' => $tags ]) ->setArguments([$config['menu_name']]); }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "// Load Configuration", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "config", "=", "$", "this", "->", "processConfigura...
Load Bundle Config and Services. @param array $configs @param ContainerBuilder $container @throws \Exception
[ "Load", "Bundle", "Config", "and", "Services", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/DependencyInjection/PdMailerExtension.php#L37-L68
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Base.php
Base.find
protected function find($directory) { if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return false; } $iterator = new \RecursiveDirectoryIterator(realpath($directory)); return new \RecursiveIteratorIterator($iterator); }
php
protected function find($directory) { if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return false; } $iterator = new \RecursiveDirectoryIterator(realpath($directory)); return new \RecursiveIteratorIterator($iterator); }
[ "protected", "function", "find", "(", "$", "directory", ")", "{", "if", "(", "!", "file_exists", "(", "$", "directory", ")", "||", "!", "is_dir", "(", "$", "directory", ")", "||", "!", "is_readable", "(", "$", "directory", ")", ")", "{", "return", "f...
Lists the package contents. @param string $directory @return RecursiveIteratorIterator|bool
[ "Lists", "the", "package", "contents", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Base.php#L84-L92
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Base.php
Base.package
protected function package() { foreach ((array) $this->plugin as $plugin) { $this->package[] = base64_encode(gzencode(serialize((array) $plugin))); } }
php
protected function package() { foreach ((array) $this->plugin as $plugin) { $this->package[] = base64_encode(gzencode(serialize((array) $plugin))); } }
[ "protected", "function", "package", "(", ")", "{", "foreach", "(", "(", "array", ")", "$", "this", "->", "plugin", "as", "$", "plugin", ")", "{", "$", "this", "->", "package", "[", "]", "=", "base64_encode", "(", "gzencode", "(", "serialize", "(", "(...
Packages the plugin data.
[ "Packages", "the", "plugin", "data", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Base.php#L97-L102
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Base.php
Base.update
public function update() { foreach ((array) $this->package as $package) { $_POST['plugin64'] = $package; ob_start(); plugin_install(); ob_end_clean(); } }
php
public function update() { foreach ((array) $this->package as $package) { $_POST['plugin64'] = $package; ob_start(); plugin_install(); ob_end_clean(); } }
[ "public", "function", "update", "(", ")", "{", "foreach", "(", "(", "array", ")", "$", "this", "->", "package", "as", "$", "package", ")", "{", "$", "_POST", "[", "'plugin64'", "]", "=", "$", "package", ";", "ob_start", "(", ")", ";", "plugin_install...
Updates a plugin.
[ "Updates", "a", "plugin", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Base.php#L119-L127
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Base.php
Base.path
protected function path($path) { if (strpos($path, './') === 0) { return $this->dir . '/' . substr($path, 2); } if (strpos($path, '../') === 0) { return dirname($this->dir) . '/' . substr($path, 3); } return $path; }
php
protected function path($path) { if (strpos($path, './') === 0) { return $this->dir . '/' . substr($path, 2); } if (strpos($path, '../') === 0) { return dirname($this->dir) . '/' . substr($path, 3); } return $path; }
[ "protected", "function", "path", "(", "$", "path", ")", "{", "if", "(", "strpos", "(", "$", "path", ",", "'./'", ")", "===", "0", ")", "{", "return", "$", "this", "->", "dir", ".", "'/'", ".", "substr", "(", "$", "path", ",", "2", ")", ";", "...
Forms absolute file path. @param string $path @return string
[ "Forms", "absolute", "file", "path", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Base.php#L152-L163
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Base.php
Base.getRelativePath
protected function getRelativePath($from, $to) { $from = explode('/', str_replace('\\', '/', $from)); $to = explode('/', str_replace('\\', '/', $to)); foreach ($from as $depth => $dir) { if (isset($to[$depth]) && $dir === $to[$depth]) { unset($to[$depth], $from[$depth]); } } for ($i = 0; $i < count($from) - 1; $i++) { array_unshift($to, '..'); } return implode('/', $to); }
php
protected function getRelativePath($from, $to) { $from = explode('/', str_replace('\\', '/', $from)); $to = explode('/', str_replace('\\', '/', $to)); foreach ($from as $depth => $dir) { if (isset($to[$depth]) && $dir === $to[$depth]) { unset($to[$depth], $from[$depth]); } } for ($i = 0; $i < count($from) - 1; $i++) { array_unshift($to, '..'); } return implode('/', $to); }
[ "protected", "function", "getRelativePath", "(", "$", "from", ",", "$", "to", ")", "{", "$", "from", "=", "explode", "(", "'/'", ",", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "from", ")", ")", ";", "$", "to", "=", "explode", "(", "'/'", ...
Gets a relative path to a file. @param string $from The path from @param string $to The path to @return string
[ "Gets", "a", "relative", "path", "to", "a", "file", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Base.php#L172-L188
train
appaydin/pd-mailer
Controller/MailController.php
MailController.list
public function list(Request $request, PaginatorInterface $paginator) { // Get Query $query = $this->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_template_class')) ->createQueryBuilder('m'); // Get Result $pagination = $paginator->paginate( $query, $request->query->getInt('page', 1), $request->query->getInt('limit', $this->getParameter('pd_mailer.list_count')) ); // Set Back URL $this->get('session')->set('backUrl', $request->getRequestUri()); // Render Page return $this->render('@PdMailer/list.html.twig', [ 'templates' => $pagination, 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
php
public function list(Request $request, PaginatorInterface $paginator) { // Get Query $query = $this->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_template_class')) ->createQueryBuilder('m'); // Get Result $pagination = $paginator->paginate( $query, $request->query->getInt('page', 1), $request->query->getInt('limit', $this->getParameter('pd_mailer.list_count')) ); // Set Back URL $this->get('session')->set('backUrl', $request->getRequestUri()); // Render Page return $this->render('@PdMailer/list.html.twig', [ 'templates' => $pagination, 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
[ "public", "function", "list", "(", "Request", "$", "request", ",", "PaginatorInterface", "$", "paginator", ")", "{", "// Get Query", "$", "query", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$", "this", "->", "getParameter",...
List Mail Templates. @param Request $request @IsGranted("ROLE_MAIL_TEMPLATELIST") @return \Symfony\Component\HttpFoundation\Response
[ "List", "Mail", "Templates", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L42-L64
train
appaydin/pd-mailer
Controller/MailController.php
MailController.addTemplate
public function addTemplate(Request $request, ParameterBagInterface $bag, $id = null) { // Find Template $mailLog = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_log_class')) ->findOneBy(['id' => $id]); // Create New Mail Log if (null === $mailLog) { $class = $this->getParameter('pd_mailer.mail_log_class'); $mailLog = new $class; } // Create Mail Template $class = $this->getParameter('pd_mailer.mail_template_class'); $template = new $class; $template->setTemplateId($mailLog->getTemplateId() ?? ' '); $template->setSubject($mailLog->getSubject()); // Create Form $form = $this->createForm($this->getParameter('pd_mailer.mail_template_type'), $template, ['parameters' => $bag]); // Handle Request $form->handleRequest($request); // Submit & Valid Form if ($form->isSubmitted() && $form->isValid()) { // Add object $template->setTemplateData($mailLog->getBody()); // Save $em = $this->getDoctrine()->getManager(); $em->persist($template); $em->flush(); // Message $this->addFlash('success', 'changes_saved'); // Return Edit Page $this->redirectToRoute('admin_mail_template_edit', ['id' => $template->getId()]); } // Render Page return $this->render('@PdMailer/template.html.twig', [ 'form' => $form->createView(), 'objects' => @unserialize($mailLog->getBody()), 'title' => 'mail_manager_template_add', 'description' => 'mail_manager_template_add_desc', 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
php
public function addTemplate(Request $request, ParameterBagInterface $bag, $id = null) { // Find Template $mailLog = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_log_class')) ->findOneBy(['id' => $id]); // Create New Mail Log if (null === $mailLog) { $class = $this->getParameter('pd_mailer.mail_log_class'); $mailLog = new $class; } // Create Mail Template $class = $this->getParameter('pd_mailer.mail_template_class'); $template = new $class; $template->setTemplateId($mailLog->getTemplateId() ?? ' '); $template->setSubject($mailLog->getSubject()); // Create Form $form = $this->createForm($this->getParameter('pd_mailer.mail_template_type'), $template, ['parameters' => $bag]); // Handle Request $form->handleRequest($request); // Submit & Valid Form if ($form->isSubmitted() && $form->isValid()) { // Add object $template->setTemplateData($mailLog->getBody()); // Save $em = $this->getDoctrine()->getManager(); $em->persist($template); $em->flush(); // Message $this->addFlash('success', 'changes_saved'); // Return Edit Page $this->redirectToRoute('admin_mail_template_edit', ['id' => $template->getId()]); } // Render Page return $this->render('@PdMailer/template.html.twig', [ 'form' => $form->createView(), 'objects' => @unserialize($mailLog->getBody()), 'title' => 'mail_manager_template_add', 'description' => 'mail_manager_template_add_desc', 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
[ "public", "function", "addTemplate", "(", "Request", "$", "request", ",", "ParameterBagInterface", "$", "bag", ",", "$", "id", "=", "null", ")", "{", "// Find Template", "$", "mailLog", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", ...
Add Templates. @param Request $request @param MailLog $mailLog @IsGranted("ROLE_MAIL_TEMPLATEADD") @return \Symfony\Component\HttpFoundation\Response
[ "Add", "Templates", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L76-L127
train
appaydin/pd-mailer
Controller/MailController.php
MailController.editTemplate
public function editTemplate(Request $request, ParameterBagInterface $bag, $id) { // Find Template $mailTemplate = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_template_class')) ->findOneBy(['id' => $id]); if (!$mailTemplate) throw $this->createNotFoundException(); // Create Form $form = $this->createForm($this->getParameter('pd_mailer.mail_template_type'), $mailTemplate, ['parameters' => $bag]); // Handle Request $form->handleRequest($request); // Submit & Valid Form if ($form->isSubmitted() && $form->isValid()) { // Save $em = $this->getDoctrine()->getManager(); $em->persist($mailTemplate); $em->flush(); // Message $this->addFlash('success', 'changes_saved'); } // Render Page return $this->render('@PdMailer/template.html.twig', [ 'form' => $form->createView(), 'objects' => @unserialize($mailTemplate->getTemplateData()), 'title' => 'mail_manager_template_edit', 'description' => 'mail_manager_template_edit_desc', 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
php
public function editTemplate(Request $request, ParameterBagInterface $bag, $id) { // Find Template $mailTemplate = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_template_class')) ->findOneBy(['id' => $id]); if (!$mailTemplate) throw $this->createNotFoundException(); // Create Form $form = $this->createForm($this->getParameter('pd_mailer.mail_template_type'), $mailTemplate, ['parameters' => $bag]); // Handle Request $form->handleRequest($request); // Submit & Valid Form if ($form->isSubmitted() && $form->isValid()) { // Save $em = $this->getDoctrine()->getManager(); $em->persist($mailTemplate); $em->flush(); // Message $this->addFlash('success', 'changes_saved'); } // Render Page return $this->render('@PdMailer/template.html.twig', [ 'form' => $form->createView(), 'objects' => @unserialize($mailTemplate->getTemplateData()), 'title' => 'mail_manager_template_edit', 'description' => 'mail_manager_template_edit_desc', 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
[ "public", "function", "editTemplate", "(", "Request", "$", "request", ",", "ParameterBagInterface", "$", "bag", ",", "$", "id", ")", "{", "// Find Template", "$", "mailTemplate", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$...
Edit Templates. @param Request $request @param MailTemplate $mailTemplate @IsGranted("ROLE_MAIL_TEMPLATEEDIT") @return \Symfony\Component\HttpFoundation\Response
[ "Edit", "Templates", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L139-L173
train
appaydin/pd-mailer
Controller/MailController.php
MailController.deleteTemplate
public function deleteTemplate(Request $request, $id) { // Find Template $mailTemplate = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_template_class')) ->findOneBy(['id' => $id]); // Not Found if (null === $mailTemplate) { $this->addFlash('error', 'sorry_not_existing'); return $this->redirectToRoute('admin_mail_list'); } // Remove Template $em = $this->getDoctrine()->getManager(); $em->remove($mailTemplate); $em->flush(); // Redirect Back return $this->redirect($request->headers->get('referer') ?? $this->generateUrl('admin_mail_list')); }
php
public function deleteTemplate(Request $request, $id) { // Find Template $mailTemplate = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_template_class')) ->findOneBy(['id' => $id]); // Not Found if (null === $mailTemplate) { $this->addFlash('error', 'sorry_not_existing'); return $this->redirectToRoute('admin_mail_list'); } // Remove Template $em = $this->getDoctrine()->getManager(); $em->remove($mailTemplate); $em->flush(); // Redirect Back return $this->redirect($request->headers->get('referer') ?? $this->generateUrl('admin_mail_list')); }
[ "public", "function", "deleteTemplate", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "// Find Template", "$", "mailTemplate", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$", "this", "->", "getParameter", "(", ...
Delete Templates. @param Request $request @param MailTemplate $mailTemplate @IsGranted("ROLE_MAIL_TEMPLATEDELETE") @return \Symfony\Component\HttpFoundation\Response
[ "Delete", "Templates", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L185-L207
train
appaydin/pd-mailer
Controller/MailController.php
MailController.logger
public function logger(Request $request, PaginatorInterface $paginator) { // Get Logs $query = $this->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_log_class')) ->createQueryBuilder('m') ->orderBy('m.id', 'DESC') ->getQuery(); // Get Result $mailLog = $paginator->paginate( $query, $request->query->getInt('page', 1), $request->query->getInt('limit', $this->getParameter('pd_mailer.list_count')) ); // Render Page return $this->render('@PdMailer/logger.html.twig', [ 'maillogs' => $mailLog, 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
php
public function logger(Request $request, PaginatorInterface $paginator) { // Get Logs $query = $this->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_log_class')) ->createQueryBuilder('m') ->orderBy('m.id', 'DESC') ->getQuery(); // Get Result $mailLog = $paginator->paginate( $query, $request->query->getInt('page', 1), $request->query->getInt('limit', $this->getParameter('pd_mailer.list_count')) ); // Render Page return $this->render('@PdMailer/logger.html.twig', [ 'maillogs' => $mailLog, 'base_template' => $this->getParameter('pd_mailer.base_template') ]); }
[ "public", "function", "logger", "(", "Request", "$", "request", ",", "PaginatorInterface", "$", "paginator", ")", "{", "// Get Logs", "$", "query", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$", "this", "->", "getParameter"...
View Mail Logs. @param Request $request @IsGranted("ROLE_MAIL_LOGGER") @return \Symfony\Component\HttpFoundation\Response
[ "View", "Mail", "Logs", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L252-L273
train
appaydin/pd-mailer
Controller/MailController.php
MailController.viewLog
public function viewLog(TranslatorInterface $translator, $id) { // Find Template $log = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_log_class')) ->findOneBy(['id' => $id]); if (!$log) throw $this->createNotFoundException(); $data = [ $translator->trans('mail_templateid') => $log->getTemplateId(), $translator->trans('mail_mid') => $log->getMailId(), $translator->trans('mail_to') => implode(PHP_EOL, $this->implodeKeyValue($log->getTo(), ' -> ')), $translator->trans('mail_from') => implode(PHP_EOL, $this->implodeKeyValue($log->getFrom(), ' -> ')), $translator->trans('mail_subject') => $log->getSubject(), $translator->trans('mail_language') => $log->getLanguage(), $translator->trans('mail_content_type') => $log->getContentType(), $translator->trans('date') => date('Y-m-d H:i:s', $log->getDate()->getTimestamp()), $translator->trans('mail_reply_to') => $log->getReplyTo(), $translator->trans('mail_header') => '<code>' . str_replace(PHP_EOL, '<br/>', htmlspecialchars($log->getHeader())) . '</code>', $translator->trans('mail_status') => $log->getStatus() . ' = ' . $this->swiftEventFilter($translator, $log->getStatus()), $translator->trans('mail_exception') => str_replace(PHP_EOL, '<br/>', htmlspecialchars($log->getException())), ]; // JSON Response return $this->json($data); }
php
public function viewLog(TranslatorInterface $translator, $id) { // Find Template $log = $this ->getDoctrine() ->getRepository($this->getParameter('pd_mailer.mail_log_class')) ->findOneBy(['id' => $id]); if (!$log) throw $this->createNotFoundException(); $data = [ $translator->trans('mail_templateid') => $log->getTemplateId(), $translator->trans('mail_mid') => $log->getMailId(), $translator->trans('mail_to') => implode(PHP_EOL, $this->implodeKeyValue($log->getTo(), ' -> ')), $translator->trans('mail_from') => implode(PHP_EOL, $this->implodeKeyValue($log->getFrom(), ' -> ')), $translator->trans('mail_subject') => $log->getSubject(), $translator->trans('mail_language') => $log->getLanguage(), $translator->trans('mail_content_type') => $log->getContentType(), $translator->trans('date') => date('Y-m-d H:i:s', $log->getDate()->getTimestamp()), $translator->trans('mail_reply_to') => $log->getReplyTo(), $translator->trans('mail_header') => '<code>' . str_replace(PHP_EOL, '<br/>', htmlspecialchars($log->getHeader())) . '</code>', $translator->trans('mail_status') => $log->getStatus() . ' = ' . $this->swiftEventFilter($translator, $log->getStatus()), $translator->trans('mail_exception') => str_replace(PHP_EOL, '<br/>', htmlspecialchars($log->getException())), ]; // JSON Response return $this->json($data); }
[ "public", "function", "viewLog", "(", "TranslatorInterface", "$", "translator", ",", "$", "id", ")", "{", "// Find Template", "$", "log", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$", "this", "->", "getParameter", "(", "...
View Log. @param MailLog $log @IsGranted("ROLE_MAIL_VIEWLOG") @return \Symfony\Component\HttpFoundation\Response
[ "View", "Log", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L284-L310
train
appaydin/pd-mailer
Controller/MailController.php
MailController.deleteLog
public function deleteLog(Request $request, $mailLog) { // Not Found if (null === $mailLog && !$request->request->has('id')) { $this->addFlash('error', 'sorry_not_existing'); return $this->redirectToRoute('admin_mail_logger'); } // Convert Array $mailLog = $request->request->has('id') ? $request->request->get('id') : [$mailLog]; // Remove Mail Log if ($mailLog) { $em = $this->getDoctrine()->getManager(); $em->createQueryBuilder('') ->delete($this->getParameter('pd_mailer.mail_log_class'), 'log') ->add('where', $em->getExpressionBuilder()->in('log.id', ':logId')) ->setParameter(':logId', $mailLog) ->getQuery() ->execute(); } // Redirect Back return $this->redirect($request->headers->get('referer') ?? $this->generateUrl('admin_mail_logger')); }
php
public function deleteLog(Request $request, $mailLog) { // Not Found if (null === $mailLog && !$request->request->has('id')) { $this->addFlash('error', 'sorry_not_existing'); return $this->redirectToRoute('admin_mail_logger'); } // Convert Array $mailLog = $request->request->has('id') ? $request->request->get('id') : [$mailLog]; // Remove Mail Log if ($mailLog) { $em = $this->getDoctrine()->getManager(); $em->createQueryBuilder('') ->delete($this->getParameter('pd_mailer.mail_log_class'), 'log') ->add('where', $em->getExpressionBuilder()->in('log.id', ':logId')) ->setParameter(':logId', $mailLog) ->getQuery() ->execute(); } // Redirect Back return $this->redirect($request->headers->get('referer') ?? $this->generateUrl('admin_mail_logger')); }
[ "public", "function", "deleteLog", "(", "Request", "$", "request", ",", "$", "mailLog", ")", "{", "// Not Found", "if", "(", "null", "===", "$", "mailLog", "&&", "!", "$", "request", "->", "request", "->", "has", "(", "'id'", ")", ")", "{", "$", "thi...
Delete Logs. @param Request $request @param $mailLog @IsGranted("ROLE_MAIL_LOGDELETE") @return \Symfony\Component\HttpFoundation\Response
[ "Delete", "Logs", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L322-L347
train
appaydin/pd-mailer
Controller/MailController.php
MailController.swiftEventFilter
private function swiftEventFilter(TranslatorInterface $translator, $event): string { switch ($event) { case \Swift_Events_SendEvent::RESULT_SUCCESS: return $translator->trans('RESULT_SUCCESS'); case \Swift_Events_SendEvent::RESULT_FAILED: return $translator->trans('RESULT_FAILED'); case \Swift_Events_SendEvent::RESULT_SPOOLED: return $translator->trans('RESULT_SPOOLED'); case \Swift_Events_SendEvent::RESULT_PENDING: return $translator->trans('RESULT_PENDING'); case \Swift_Events_SendEvent::RESULT_TENTATIVE: return $translator->trans('RESULT_TENTATIVE'); case -1: return $translator->trans('RESULT_DELETED'); } return ''; }
php
private function swiftEventFilter(TranslatorInterface $translator, $event): string { switch ($event) { case \Swift_Events_SendEvent::RESULT_SUCCESS: return $translator->trans('RESULT_SUCCESS'); case \Swift_Events_SendEvent::RESULT_FAILED: return $translator->trans('RESULT_FAILED'); case \Swift_Events_SendEvent::RESULT_SPOOLED: return $translator->trans('RESULT_SPOOLED'); case \Swift_Events_SendEvent::RESULT_PENDING: return $translator->trans('RESULT_PENDING'); case \Swift_Events_SendEvent::RESULT_TENTATIVE: return $translator->trans('RESULT_TENTATIVE'); case -1: return $translator->trans('RESULT_DELETED'); } return ''; }
[ "private", "function", "swiftEventFilter", "(", "TranslatorInterface", "$", "translator", ",", "$", "event", ")", ":", "string", "{", "switch", "(", "$", "event", ")", "{", "case", "\\", "Swift_Events_SendEvent", "::", "RESULT_SUCCESS", ":", "return", "$", "tr...
Swift Event. @param $event @return string
[ "Swift", "Event", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Controller/MailController.php#L376-L394
train
arillo/silverstripe-elements
src/ElementBase.php
ElementBase.generateElementSortForHolder
public function generateElementSortForHolder() { if (!$this->Sort) { $holderFilter = ['PageID' => $this->PageID]; if ($this->ElementID) $holderFilter = ['ElementID' => $this->ElementID]; $this->Sort = self::get() ->filter($holderFilter) ->max('Sort') + 1 ; } return $this; }
php
public function generateElementSortForHolder() { if (!$this->Sort) { $holderFilter = ['PageID' => $this->PageID]; if ($this->ElementID) $holderFilter = ['ElementID' => $this->ElementID]; $this->Sort = self::get() ->filter($holderFilter) ->max('Sort') + 1 ; } return $this; }
[ "public", "function", "generateElementSortForHolder", "(", ")", "{", "if", "(", "!", "$", "this", "->", "Sort", ")", "{", "$", "holderFilter", "=", "[", "'PageID'", "=>", "$", "this", "->", "PageID", "]", ";", "if", "(", "$", "this", "->", "ElementID",...
Generate next Sort value on element creation. @return ElementBase
[ "Generate", "next", "Sort", "value", "on", "element", "creation", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementBase.php#L129-L142
train
arillo/silverstripe-elements
src/ElementBase.php
ElementBase.getCMSTypeInfo
public function getCMSTypeInfo() { $data = ArrayData::create([ 'Icon' => $this->config()->icon, 'Type' => $this->getType(), ]); // Add versioned states (rendered as a circle over the icon) if ($this->hasExtension(Versioned::class)) { $data->IsVersioned = true; if ($this->isOnDraftOnly()) { $data->VersionState = 'draft'; $data->VersionStateTitle = _t( 'SilverStripe\\Versioned\\VersionedGridFieldState\\VersionedGridFieldState.ADDEDTODRAFTHELP', 'Item has not been published yet' ); } elseif ($this->isModifiedOnDraft()) { $data->VersionState = 'modified'; $data->VersionStateTitle = $data->VersionStateTitle = _t( 'SilverStripe\\Versioned\\VersionedGridFieldState\\VersionedGridFieldState.MODIFIEDONDRAFTHELP', 'Item has unpublished changes' ); } } return $data->renderWith('Arillo\\Elements\\TypeInfo'); }
php
public function getCMSTypeInfo() { $data = ArrayData::create([ 'Icon' => $this->config()->icon, 'Type' => $this->getType(), ]); // Add versioned states (rendered as a circle over the icon) if ($this->hasExtension(Versioned::class)) { $data->IsVersioned = true; if ($this->isOnDraftOnly()) { $data->VersionState = 'draft'; $data->VersionStateTitle = _t( 'SilverStripe\\Versioned\\VersionedGridFieldState\\VersionedGridFieldState.ADDEDTODRAFTHELP', 'Item has not been published yet' ); } elseif ($this->isModifiedOnDraft()) { $data->VersionState = 'modified'; $data->VersionStateTitle = $data->VersionStateTitle = _t( 'SilverStripe\\Versioned\\VersionedGridFieldState\\VersionedGridFieldState.MODIFIEDONDRAFTHELP', 'Item has unpublished changes' ); } } return $data->renderWith('Arillo\\Elements\\TypeInfo'); }
[ "public", "function", "getCMSTypeInfo", "(", ")", "{", "$", "data", "=", "ArrayData", "::", "create", "(", "[", "'Icon'", "=>", "$", "this", "->", "config", "(", ")", "->", "icon", ",", "'Type'", "=>", "$", "this", "->", "getType", "(", ")", ",", "...
Type info for GridField usage. @return string
[ "Type", "info", "for", "GridField", "usage", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementBase.php#L207-L233
train
arillo/silverstripe-elements
src/ElementBase.php
ElementBase.getHolderPage
public function getHolderPage() { if (!$this->PageID && !$this->ElementID) return null; $holder = $this->getHolder(); while ( $holder && $holder->exists() && !is_a($holder, SiteTree::class) ) { $holder = $holder->getHolder(); } return $holder; }
php
public function getHolderPage() { if (!$this->PageID && !$this->ElementID) return null; $holder = $this->getHolder(); while ( $holder && $holder->exists() && !is_a($holder, SiteTree::class) ) { $holder = $holder->getHolder(); } return $holder; }
[ "public", "function", "getHolderPage", "(", ")", "{", "if", "(", "!", "$", "this", "->", "PageID", "&&", "!", "$", "this", "->", "ElementID", ")", "return", "null", ";", "$", "holder", "=", "$", "this", "->", "getHolder", "(", ")", ";", "while", "(...
Recursive look up for holder page.
[ "Recursive", "look", "up", "for", "holder", "page", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementBase.php#L327-L341
train
arillo/silverstripe-elements
src/ElementBase.php
ElementBase.Render
public function Render( $IsPos = null, $IsFirst = null, $IsLast = null, $IsEvenOdd = null ) { $this->IsPos = $IsPos; $this->IsFirst = $IsFirst; $this->IsLast = $IsLast; $this->IsEvenOdd = $IsEvenOdd; $controller = Controller::curr(); return $controller ->customise($this) ->renderWith($this->ClassName) ; }
php
public function Render( $IsPos = null, $IsFirst = null, $IsLast = null, $IsEvenOdd = null ) { $this->IsPos = $IsPos; $this->IsFirst = $IsFirst; $this->IsLast = $IsLast; $this->IsEvenOdd = $IsEvenOdd; $controller = Controller::curr(); return $controller ->customise($this) ->renderWith($this->ClassName) ; }
[ "public", "function", "Render", "(", "$", "IsPos", "=", "null", ",", "$", "IsFirst", "=", "null", ",", "$", "IsLast", "=", "null", ",", "$", "IsEvenOdd", "=", "null", ")", "{", "$", "this", "->", "IsPos", "=", "$", "IsPos", ";", "$", "this", "->"...
Render for template useage. @param int $IsPos @param bool $IsFirst @param bool $IsLast @param bool $IsEvenOdd
[ "Render", "for", "template", "useage", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementBase.php#L463-L478
train
arillo/silverstripe-elements
src/ElementBase.php
ElementBase.publishPage
public function publishPage() { $look = true; $parent = $this; while($look) { if ($parent = $parent->getHolder()) { if (is_a($parent, SiteTree::class)) { $look = false; } } else { $look = false; } } if ($parent->doPublish()) { return _t(__CLASS__ . '.PageAndElementsPublished', 'Page & elements published'); } return _t(__CLASS__ . '.PageAndElementsPublishError', 'There was an error publishing the page'); }
php
public function publishPage() { $look = true; $parent = $this; while($look) { if ($parent = $parent->getHolder()) { if (is_a($parent, SiteTree::class)) { $look = false; } } else { $look = false; } } if ($parent->doPublish()) { return _t(__CLASS__ . '.PageAndElementsPublished', 'Page & elements published'); } return _t(__CLASS__ . '.PageAndElementsPublishError', 'There was an error publishing the page'); }
[ "public", "function", "publishPage", "(", ")", "{", "$", "look", "=", "true", ";", "$", "parent", "=", "$", "this", ";", "while", "(", "$", "look", ")", "{", "if", "(", "$", "parent", "=", "$", "parent", "->", "getHolder", "(", ")", ")", "{", "...
Publish holder page, trigger publish all sub elements.
[ "Publish", "holder", "page", "trigger", "publish", "all", "sub", "elements", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementBase.php#L483-L505
train
arillo/silverstripe-elements
src/ElementBase.php
ElementBase.deleteLocalisedRecords
public function deleteLocalisedRecords() { if ($this->hasExtension(self::FLUENT_CLASS)) { $localisedTables = $this->getLocalisedTables(); $tableClasses = ClassInfo::ancestry($this->owner, true); foreach ($tableClasses as $class) { $table = DataObject::getSchema()->tableName($class); $rootTable = $this->getLocalisedTable($table); $rootDelete = SQLDelete::create("\"{$rootTable}\"") ->addWhere(["\"{$rootTable}\".\"ID\"" => $this->ID]); // If table isn't localised, simple delete if (!isset($localisedTables[$table])) { $baseTable = $this->getLocalisedTable($this->baseTable()); // The base table isn't localised? Delete the record then. if ($baseTable === $rootTable) { $rootDelete->execute(); continue; } $rootDelete ->setDelete("\"{$rootTable}\"") ->addLeftJoin( $baseTable, "\"{$rootTable}\".\"ID\" = \"{$baseTable}\".\"ID\"" ) // Only when join matches no localisations is it safe to delete ->addWhere("\"{$baseTable}\".\"ID\" IS NULL") ->execute(); continue; } $localisedTable = $this->getLocalisedTable($table); $localisedDelete = SQLDelete::create( "\"{$localisedTable}\"", [ '"RecordID"' => $this->ID, ] ); $localisedDelete->execute(); } } return $this; }
php
public function deleteLocalisedRecords() { if ($this->hasExtension(self::FLUENT_CLASS)) { $localisedTables = $this->getLocalisedTables(); $tableClasses = ClassInfo::ancestry($this->owner, true); foreach ($tableClasses as $class) { $table = DataObject::getSchema()->tableName($class); $rootTable = $this->getLocalisedTable($table); $rootDelete = SQLDelete::create("\"{$rootTable}\"") ->addWhere(["\"{$rootTable}\".\"ID\"" => $this->ID]); // If table isn't localised, simple delete if (!isset($localisedTables[$table])) { $baseTable = $this->getLocalisedTable($this->baseTable()); // The base table isn't localised? Delete the record then. if ($baseTable === $rootTable) { $rootDelete->execute(); continue; } $rootDelete ->setDelete("\"{$rootTable}\"") ->addLeftJoin( $baseTable, "\"{$rootTable}\".\"ID\" = \"{$baseTable}\".\"ID\"" ) // Only when join matches no localisations is it safe to delete ->addWhere("\"{$baseTable}\".\"ID\" IS NULL") ->execute(); continue; } $localisedTable = $this->getLocalisedTable($table); $localisedDelete = SQLDelete::create( "\"{$localisedTable}\"", [ '"RecordID"' => $this->ID, ] ); $localisedDelete->execute(); } } return $this; }
[ "public", "function", "deleteLocalisedRecords", "(", ")", "{", "if", "(", "$", "this", "->", "hasExtension", "(", "self", "::", "FLUENT_CLASS", ")", ")", "{", "$", "localisedTables", "=", "$", "this", "->", "getLocalisedTables", "(", ")", ";", "$", "tableC...
Execute record deletion, even when localised records in non-current locale exist. @return ElementBase
[ "Execute", "record", "deletion", "even", "when", "localised", "records", "in", "non", "-", "current", "locale", "exist", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementBase.php#L533-L585
train
appaydin/pd-mailer
Menu/MailerMenu.php
MailerMenu.createMenu
public function createMenu(array $options = []): ItemInterface { // Create Root $menu = $this->createRoot('mail_manager')->setChildAttr([ 'class' => 'nav nav-pills', 'data-parent' => 'admin_mail_list', ]); // Create Menu Items $menu ->addChild('nav_mail_template') ->setLabel('nav_mail_template') ->setRoute('admin_mail_list') ->setRoles(['ROLE_MAIL_TEMPLATELIST']) // Logger ->addChildParent('nav_mail_logger') ->setLabel('nav_mail_logger') ->setRoute('admin_mail_logger') ->setRoles(['ROLE_MAIL_LOGGER']); return $menu; }
php
public function createMenu(array $options = []): ItemInterface { // Create Root $menu = $this->createRoot('mail_manager')->setChildAttr([ 'class' => 'nav nav-pills', 'data-parent' => 'admin_mail_list', ]); // Create Menu Items $menu ->addChild('nav_mail_template') ->setLabel('nav_mail_template') ->setRoute('admin_mail_list') ->setRoles(['ROLE_MAIL_TEMPLATELIST']) // Logger ->addChildParent('nav_mail_logger') ->setLabel('nav_mail_logger') ->setRoute('admin_mail_logger') ->setRoles(['ROLE_MAIL_LOGGER']); return $menu; }
[ "public", "function", "createMenu", "(", "array", "$", "options", "=", "[", "]", ")", ":", "ItemInterface", "{", "// Create Root", "$", "menu", "=", "$", "this", "->", "createRoot", "(", "'mail_manager'", ")", "->", "setChildAttr", "(", "[", "'class'", "=>...
Mail Manager Custom Menus. @param array $options @return ItemInterface
[ "Mail", "Manager", "Custom", "Menus", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Menu/MailerMenu.php#L33-L54
train
davidecesarano/Embryo-Http
Embryo/Http/Factory/UriFactory.php
UriFactory.createUriFromServer
public function createUriFromServer(array $server): UriInterface { // scheme, host, post, user, pass $scheme = (empty($server['HTTPS']) || $server['HTTPS'] === 'off') ? 'http' : 'https'; $host = (isset($server['HTTP_HOST'])) ? $server['HTTP_HOST'] : $server['SERVER_NAME']; $port = (isset($server['SERVER_PORT'])) ? (int) $server['SERVER_PORT'] : 80; $user = (isset($server['PHP_AUTH_USER'])) ? $server['PHP_AUTH_USER'] : ''; $pass = (isset($server['PHP_AUTH_PW'])) ? $server['PHP_AUTH_PW'] : ''; // path $path = parse_url('http://example.com' . $server['REQUEST_URI'], PHP_URL_PATH); $path = rawurldecode($path); // query $query = (isset($server['QUERY_STRING'])) ? $server['QUERY_STRING'] : ''; // fragment (not available in $_SERVER) $fragment = ''; $uri = new Uri(''); $uri = $uri->withScheme($scheme); $uri = $uri->withHost($host); $uri = $uri->withPort($port); $uri = $uri->withUserInfo($user, $pass); $uri = $uri->withPath($path); $uri = $uri->withQuery($query); $uri = $uri->withFragment($fragment); return $uri; }
php
public function createUriFromServer(array $server): UriInterface { // scheme, host, post, user, pass $scheme = (empty($server['HTTPS']) || $server['HTTPS'] === 'off') ? 'http' : 'https'; $host = (isset($server['HTTP_HOST'])) ? $server['HTTP_HOST'] : $server['SERVER_NAME']; $port = (isset($server['SERVER_PORT'])) ? (int) $server['SERVER_PORT'] : 80; $user = (isset($server['PHP_AUTH_USER'])) ? $server['PHP_AUTH_USER'] : ''; $pass = (isset($server['PHP_AUTH_PW'])) ? $server['PHP_AUTH_PW'] : ''; // path $path = parse_url('http://example.com' . $server['REQUEST_URI'], PHP_URL_PATH); $path = rawurldecode($path); // query $query = (isset($server['QUERY_STRING'])) ? $server['QUERY_STRING'] : ''; // fragment (not available in $_SERVER) $fragment = ''; $uri = new Uri(''); $uri = $uri->withScheme($scheme); $uri = $uri->withHost($host); $uri = $uri->withPort($port); $uri = $uri->withUserInfo($user, $pass); $uri = $uri->withPath($path); $uri = $uri->withQuery($query); $uri = $uri->withFragment($fragment); return $uri; }
[ "public", "function", "createUriFromServer", "(", "array", "$", "server", ")", ":", "UriInterface", "{", "// scheme, host, post, user, pass", "$", "scheme", "=", "(", "empty", "(", "$", "server", "[", "'HTTPS'", "]", ")", "||", "$", "server", "[", "'HTTPS'", ...
Creates new Uri from array. @param array $server @return UriInterface
[ "Creates", "new", "Uri", "from", "array", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Factory/UriFactory.php#L38-L66
train
firebrandhq/silverstripe-hail
src/Models/Video.php
Video.importingColor
protected function importingColor($SSName, $data) { $color = $this->{$SSName}; if (!$color) { $color = new Color(); } $this->Fetched = date("Y-m-d H:i:s"); $color->OrganisationID = $this->OrganisationID; $color->HailOrgID = $this->HailOrgID; $color->HailOrgName = $this->HailOrgName; $this->{$SSName} = $color; }
php
protected function importingColor($SSName, $data) { $color = $this->{$SSName}; if (!$color) { $color = new Color(); } $this->Fetched = date("Y-m-d H:i:s"); $color->OrganisationID = $this->OrganisationID; $color->HailOrgID = $this->HailOrgID; $color->HailOrgName = $this->HailOrgName; $this->{$SSName} = $color; }
[ "protected", "function", "importingColor", "(", "$", "SSName", ",", "$", "data", ")", "{", "$", "color", "=", "$", "this", "->", "{", "$", "SSName", "}", ";", "if", "(", "!", "$", "color", ")", "{", "$", "color", "=", "new", "Color", "(", ")", ...
Process the colors @param $SSName @param $data
[ "Process", "the", "colors" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Video.php#L218-L230
train
oasmobile/php-http
src/ServiceProviders/Security/AbstractSimplePreAuthenticationPolicy.php
AbstractSimplePreAuthenticationPolicy.getAuthenticationProvider
public function getAuthenticationProvider(Container $app, $firewallName, $options) { return new SimpleAuthenticationProvider( $this->getPreAuthenticator(), $this->getUserProvider($app, $firewallName), $firewallName ); }
php
public function getAuthenticationProvider(Container $app, $firewallName, $options) { return new SimpleAuthenticationProvider( $this->getPreAuthenticator(), $this->getUserProvider($app, $firewallName), $firewallName ); }
[ "public", "function", "getAuthenticationProvider", "(", "Container", "$", "app", ",", "$", "firewallName", ",", "$", "options", ")", "{", "return", "new", "SimpleAuthenticationProvider", "(", "$", "this", "->", "getPreAuthenticator", "(", ")", ",", "$", "this", ...
If string is returned, it must be either "anonymous" or "dao" @param Container $app @param $firewallName @param $options @return string|AuthenticationProviderInterface
[ "If", "string", "is", "returned", "it", "must", "be", "either", "anonymous", "or", "dao" ]
a7570893742286c30222c393891aeb6857064f37
https://github.com/oasmobile/php-http/blob/a7570893742286c30222c393891aeb6857064f37/src/ServiceProviders/Security/AbstractSimplePreAuthenticationPolicy.php#L35-L42
train
oasmobile/php-http
src/ExtendedArgumentValueResolver.php
ExtendedArgumentValueResolver.supports
public function supports(Request $request, ArgumentMetadata $argument) { $classname = $argument->getType(); if (!\class_exists($classname)) { return false; } if (\array_key_exists($classname, $this->mappingParameters)) { return true; } else { foreach ($this->mappingParameters as $value) { if ($value instanceof $classname) { return true; } } return false; } }
php
public function supports(Request $request, ArgumentMetadata $argument) { $classname = $argument->getType(); if (!\class_exists($classname)) { return false; } if (\array_key_exists($classname, $this->mappingParameters)) { return true; } else { foreach ($this->mappingParameters as $value) { if ($value instanceof $classname) { return true; } } return false; } }
[ "public", "function", "supports", "(", "Request", "$", "request", ",", "ArgumentMetadata", "$", "argument", ")", "{", "$", "classname", "=", "$", "argument", "->", "getType", "(", ")", ";", "if", "(", "!", "\\", "class_exists", "(", "$", "classname", ")"...
Whether this resolver can resolve the value for the given ArgumentMetadata. @param Request $request @param ArgumentMetadata $argument @return bool
[ "Whether", "this", "resolver", "can", "resolve", "the", "value", "for", "the", "given", "ArgumentMetadata", "." ]
a7570893742286c30222c393891aeb6857064f37
https://github.com/oasmobile/php-http/blob/a7570893742286c30222c393891aeb6857064f37/src/ExtendedArgumentValueResolver.php#L37-L55
train
appaydin/pd-mailer
SwiftMailer/PdSwiftMessage.php
PdSwiftMessage.setTemplateId
public function setTemplateId(string $templateId = null) { if (!$this->setHeaderFieldModel('TemplateID', $templateId)) { $this->getHeaders()->addTextHeader('TemplateID', $templateId); } return $this; }
php
public function setTemplateId(string $templateId = null) { if (!$this->setHeaderFieldModel('TemplateID', $templateId)) { $this->getHeaders()->addTextHeader('TemplateID', $templateId); } return $this; }
[ "public", "function", "setTemplateId", "(", "string", "$", "templateId", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "setHeaderFieldModel", "(", "'TemplateID'", ",", "$", "templateId", ")", ")", "{", "$", "this", "->", "getHeaders", "(", ")...
Set Message Content Template ID. @param string|null $templateId @return $this
[ "Set", "Message", "Content", "Template", "ID", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/SwiftMailer/PdSwiftMessage.php#L30-L37
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Installer/Base.php
Base.install
public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { new Textpattern(); parent::install($repo, $package); $plugin = new $this->textpatternPackager($this->getInstallPath($package), $package); $plugin->install(); }
php
public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { new Textpattern(); parent::install($repo, $package); $plugin = new $this->textpatternPackager($this->getInstallPath($package), $package); $plugin->install(); }
[ "public", "function", "install", "(", "InstalledRepositoryInterface", "$", "repo", ",", "PackageInterface", "$", "package", ")", "{", "new", "Textpattern", "(", ")", ";", "parent", "::", "install", "(", "$", "repo", ",", "$", "package", ")", ";", "$", "plu...
Writes the plugin package to the database on install. @param InstalledRepositoryInterface $repo @param PackageInterface $package
[ "Writes", "the", "plugin", "package", "to", "the", "database", "on", "install", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Installer/Base.php#L68-L74
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Installer/Base.php
Base.update
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { new Textpattern(); parent::update($repo, $initial, $target); $plugin = new $this->textpatternPackager($this->getInstallPath($target), $target); $plugin->update(); }
php
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { new Textpattern(); parent::update($repo, $initial, $target); $plugin = new $this->textpatternPackager($this->getInstallPath($target), $target); $plugin->update(); }
[ "public", "function", "update", "(", "InstalledRepositoryInterface", "$", "repo", ",", "PackageInterface", "$", "initial", ",", "PackageInterface", "$", "target", ")", "{", "new", "Textpattern", "(", ")", ";", "parent", "::", "update", "(", "$", "repo", ",", ...
Runs updater on package updates. @param InstalledRepositoryInterface $repo @param PackageInterface $initial @param PackageInterface $target
[ "Runs", "updater", "on", "package", "updates", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Installer/Base.php#L83-L89
train
davidecesarano/Embryo-Http
Embryo/Http/Message/UploadedFile.php
UploadedFile.getStream
public function getStream(): StreamInterface { if ($this->moved) { throw new \RuntimeException(sprintf('Uploaded file %1s has already been moved', $this->clientFilename)); } return $this->file; }
php
public function getStream(): StreamInterface { if ($this->moved) { throw new \RuntimeException(sprintf('Uploaded file %1s has already been moved', $this->clientFilename)); } return $this->file; }
[ "public", "function", "getStream", "(", ")", ":", "StreamInterface", "{", "if", "(", "$", "this", "->", "moved", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Uploaded file %1s has already been moved'", ",", "$", "this", "->", "cli...
Retrieves a stream representing the uploaded file. This method returns a StreamInterface instance, representing the uploaded file. @return StreamInterface @throws RuntimeException
[ "Retrieves", "a", "stream", "representing", "the", "uploaded", "file", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/UploadedFile.php#L84-L90
train
davidecesarano/Embryo-Http
Embryo/Http/Message/UploadedFile.php
UploadedFile.moveTo
public function moveTo($targetPath) { if ($this->moved) { throw new \RuntimeException('Uploaded file already moved'); } if (!is_string($targetPath) || $targetPath === '') { throw new \InvalidArgumentException('Target path must be a non empty string'); } $stream = $this->getStream(); $file = $stream->getMetadata('uri'); if (is_dir($targetPath)) { if (!is_writable($targetPath)) { throw new \InvalidArgumentException('Target path is not writable'); } $target = rtrim($targetPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $this->clientFilename; } else { if (!is_writable(dirname($targetPath))) { throw new \InvalidArgumentException('Target path is not writable'); } $target = $targetPath; } if (!copy($file, $target)) { throw new \RuntimeException(sprintf('Error coping uploaded file %1s to %2s', $this->clientFilename, $targetPath)); } $this->moved = true; if (!$this->moved) { throw new \RuntimeException(sprintf('Uploaded file could not be moved to %s', $targetPath)); } }
php
public function moveTo($targetPath) { if ($this->moved) { throw new \RuntimeException('Uploaded file already moved'); } if (!is_string($targetPath) || $targetPath === '') { throw new \InvalidArgumentException('Target path must be a non empty string'); } $stream = $this->getStream(); $file = $stream->getMetadata('uri'); if (is_dir($targetPath)) { if (!is_writable($targetPath)) { throw new \InvalidArgumentException('Target path is not writable'); } $target = rtrim($targetPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $this->clientFilename; } else { if (!is_writable(dirname($targetPath))) { throw new \InvalidArgumentException('Target path is not writable'); } $target = $targetPath; } if (!copy($file, $target)) { throw new \RuntimeException(sprintf('Error coping uploaded file %1s to %2s', $this->clientFilename, $targetPath)); } $this->moved = true; if (!$this->moved) { throw new \RuntimeException(sprintf('Uploaded file could not be moved to %s', $targetPath)); } }
[ "public", "function", "moveTo", "(", "$", "targetPath", ")", "{", "if", "(", "$", "this", "->", "moved", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Uploaded file already moved'", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "targ...
Moves the uploaded file to a new location. @see http://php.net/is_uploaded_file @see http://php.net/move_uploaded_file @param string $targetPath @throws InvalidArgumentException @throws RuntimeException
[ "Moves", "the", "uploaded", "file", "to", "a", "new", "location", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/UploadedFile.php#L101-L138
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Manifest.php
Manifest.find
protected function find($directory) { if ($iterator = parent::find($directory)) { new Textpattern(); foreach ($this->manifestNames as $manifestName) { foreach ($iterator as $file) { if (basename($file) === $manifestName && $this->isManifest($file)) { $this->dir = dirname($file); $this->import(); } } if (!empty($this->plugin)) { return true; } } } return false; }
php
protected function find($directory) { if ($iterator = parent::find($directory)) { new Textpattern(); foreach ($this->manifestNames as $manifestName) { foreach ($iterator as $file) { if (basename($file) === $manifestName && $this->isManifest($file)) { $this->dir = dirname($file); $this->import(); } } if (!empty($this->plugin)) { return true; } } } return false; }
[ "protected", "function", "find", "(", "$", "directory", ")", "{", "if", "(", "$", "iterator", "=", "parent", "::", "find", "(", "$", "directory", ")", ")", "{", "new", "Textpattern", "(", ")", ";", "foreach", "(", "$", "this", "->", "manifestNames", ...
Find the plugin project directory and manifest from the package. @param string $directory @return bool
[ "Find", "the", "plugin", "project", "directory", "and", "manifest", "from", "the", "package", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Manifest.php#L75-L95
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Manifest.php
Manifest.isManifest
protected function isManifest($file) { if (is_file($file) && is_readable($file)) { if ($contents = file_get_contents($file)) { $this->manifest = @json_decode($contents); if ($this->manifest && isset($this->manifest->name) && is_string($this->manifest->name)) { $this->manifest->name = basename($this->manifest->name); if ($this->manifest->name === basename(dirname($file))) { return (bool) preg_match($this->pluginNamePattern, $this->manifest->name); } } } } return false; }
php
protected function isManifest($file) { if (is_file($file) && is_readable($file)) { if ($contents = file_get_contents($file)) { $this->manifest = @json_decode($contents); if ($this->manifest && isset($this->manifest->name) && is_string($this->manifest->name)) { $this->manifest->name = basename($this->manifest->name); if ($this->manifest->name === basename(dirname($file))) { return (bool) preg_match($this->pluginNamePattern, $this->manifest->name); } } } } return false; }
[ "protected", "function", "isManifest", "(", "$", "file", ")", "{", "if", "(", "is_file", "(", "$", "file", ")", "&&", "is_readable", "(", "$", "file", ")", ")", "{", "if", "(", "$", "contents", "=", "file_get_contents", "(", "$", "file", ")", ")", ...
Whether a file is a valid plugin manifest. This function makes sure the file contains JSON, the name property follows plugin naming convention and the parent directory is the same as the name property. A valid plugin name follows the pattern {pfx}_{pluginName}, where the {pfx} is the plugin author prefix and the {pluginName} is the name of the plugin consisting of up to 64 ASCII letter and numbers. @param string $file Full resolved pathname to the file @return bool TRUE if valid, FALSE otherwise
[ "Whether", "a", "file", "is", "a", "valid", "plugin", "manifest", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Manifest.php#L111-L128
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Manifest.php
Manifest.code
protected function code() { $files = $out = []; if (isset($this->manifest->code->file)) { $files = array_map([$this, 'path'], (array) $this->manifest->code->file); } else { if (($cwd = getcwd()) !== false && chdir($this->dir)) { $files = (array) glob('*.php'); } } $pathFrom = (string) new FindTextpattern() . '/index.php'; foreach ($files as $path) { if (file_exists($path) && is_file($path) && is_readable($path)) { $includePath = $this->getRelativePath($pathFrom, realpath($path)); if ($includePath !== $path) { $out[] = "include txpath.'/".addslashes($includePath)."';"; } else { $out[] = "include '".addslashes($includePath)."';"; } } } if (isset($cwd) && $cwd !== false) { chdir($cwd); } return implode("\n", $out); }
php
protected function code() { $files = $out = []; if (isset($this->manifest->code->file)) { $files = array_map([$this, 'path'], (array) $this->manifest->code->file); } else { if (($cwd = getcwd()) !== false && chdir($this->dir)) { $files = (array) glob('*.php'); } } $pathFrom = (string) new FindTextpattern() . '/index.php'; foreach ($files as $path) { if (file_exists($path) && is_file($path) && is_readable($path)) { $includePath = $this->getRelativePath($pathFrom, realpath($path)); if ($includePath !== $path) { $out[] = "include txpath.'/".addslashes($includePath)."';"; } else { $out[] = "include '".addslashes($includePath)."';"; } } } if (isset($cwd) && $cwd !== false) { chdir($cwd); } return implode("\n", $out); }
[ "protected", "function", "code", "(", ")", "{", "$", "files", "=", "$", "out", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "manifest", "->", "code", "->", "file", ")", ")", "{", "$", "files", "=", "array_map", "(", "[", "$",...
Plugin code template. Generates PHP source code that either imports .php files in the directory or the files specified with the 'file' property of 'code'. @return string
[ "Plugin", "code", "template", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Manifest.php#L213-L244
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Manifest.php
Manifest.textpack
protected function textpack() { $textpacks = $this->dir . '/textpacks'; if (!file_exists($textpacks) || !is_dir($textpacks) || !is_readable($textpacks)) { return ''; } if (($cwd = getcwd()) === false || !chdir($textpacks)) { return ''; } $out = []; foreach ((array) glob('*.textpack', GLOB_NOSORT) as $file) { if (!is_file($file) || !is_readable($file)) { continue; } $file = file_get_contents($file); if (!preg_match('/^#@language|\n#@language\s/', $file)) { array_unshift($out, $file); continue; } $out[] = $file; } chdir($cwd); return implode("\n", $out); }
php
protected function textpack() { $textpacks = $this->dir . '/textpacks'; if (!file_exists($textpacks) || !is_dir($textpacks) || !is_readable($textpacks)) { return ''; } if (($cwd = getcwd()) === false || !chdir($textpacks)) { return ''; } $out = []; foreach ((array) glob('*.textpack', GLOB_NOSORT) as $file) { if (!is_file($file) || !is_readable($file)) { continue; } $file = file_get_contents($file); if (!preg_match('/^#@language|\n#@language\s/', $file)) { array_unshift($out, $file); continue; } $out[] = $file; } chdir($cwd); return implode("\n", $out); }
[ "protected", "function", "textpack", "(", ")", "{", "$", "textpacks", "=", "$", "this", "->", "dir", ".", "'/textpacks'", ";", "if", "(", "!", "file_exists", "(", "$", "textpacks", ")", "||", "!", "is_dir", "(", "$", "textpacks", ")", "||", "!", "is_...
Gets Textpacks. @return string
[ "Gets", "Textpacks", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Manifest.php#L251-L282
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Manifest.php
Manifest.help
protected function help() { $out = []; if (isset($this->manifest->help) && is_string($this->manifest->help)) { return (string) $this->manifest->help; } if (empty($this->manifest->help->file)) { $files = $this->helpNames; } else { $files = $this->manifest->help->file; } foreach ((array) $files as $file) { $file = $this->path($file); if (file_exists($file) && is_file($file) && is_readable($file)) { $out[strtolower($file)] = file_get_contents($file); } } return implode("\n\n", $out); }
php
protected function help() { $out = []; if (isset($this->manifest->help) && is_string($this->manifest->help)) { return (string) $this->manifest->help; } if (empty($this->manifest->help->file)) { $files = $this->helpNames; } else { $files = $this->manifest->help->file; } foreach ((array) $files as $file) { $file = $this->path($file); if (file_exists($file) && is_file($file) && is_readable($file)) { $out[strtolower($file)] = file_get_contents($file); } } return implode("\n\n", $out); }
[ "protected", "function", "help", "(", ")", "{", "$", "out", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "manifest", "->", "help", ")", "&&", "is_string", "(", "$", "this", "->", "manifest", "->", "help", ")", ")", "{", "return...
Gets help files. @return string
[ "Gets", "help", "files", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Manifest.php#L289-L312
train
flipboxfactory/craft-ember
src/objects/SiteMutatorTrait.php
SiteMutatorTrait.getSiteId
public function getSiteId() { if (null === $this->siteId && null !== $this->site) { $this->siteId = $this->site->id; } return $this->siteId; }
php
public function getSiteId() { if (null === $this->siteId && null !== $this->site) { $this->siteId = $this->site->id; } return $this->siteId; }
[ "public", "function", "getSiteId", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "siteId", "&&", "null", "!==", "$", "this", "->", "site", ")", "{", "$", "this", "->", "siteId", "=", "$", "this", "->", "site", "->", "id", ";", "}", ...
Get associated siteId @return int|null
[ "Get", "associated", "siteId" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/objects/SiteMutatorTrait.php#L45-L52
train
ninjify/nunjuck
src/Environment.php
Environment.setup
public static function setup(string $dir): void { self::setupTester(); self::setupTimezone(); self::setupVariables($dir); self::setupGlobalVariables(); }
php
public static function setup(string $dir): void { self::setupTester(); self::setupTimezone(); self::setupVariables($dir); self::setupGlobalVariables(); }
[ "public", "static", "function", "setup", "(", "string", "$", "dir", ")", ":", "void", "{", "self", "::", "setupTester", "(", ")", ";", "self", "::", "setupTimezone", "(", ")", ";", "self", "::", "setupVariables", "(", "$", "dir", ")", ";", "self", ":...
Magic setup method
[ "Magic", "setup", "method" ]
0381d3330e769c4712ab063b32200a1d52333a5c
https://github.com/ninjify/nunjuck/blob/0381d3330e769c4712ab063b32200a1d52333a5c/src/Environment.php#L30-L36
train