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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
romm/configuration_object
Classes/Validation/Validator/HasValuesValidator.php
HasValuesValidator.isValid
public function isValid($value) { $acceptedValues = GeneralUtility::trimExplode('|', $this->options['values']); if (false === in_array($value, $acceptedValues)) { $errorMessage = $this->translateErrorMessage('validator.has_values.not_valid', 'configuration_object', [implode(', ', $acceptedValues)]); $this->addError($errorMessage, 1456140151); } }
php
public function isValid($value) { $acceptedValues = GeneralUtility::trimExplode('|', $this->options['values']); if (false === in_array($value, $acceptedValues)) { $errorMessage = $this->translateErrorMessage('validator.has_values.not_valid', 'configuration_object', [implode(', ', $acceptedValues)]); $this->addError($errorMessage, 1456140151); } }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "acceptedValues", "=", "GeneralUtility", "::", "trimExplode", "(", "'|'", ",", "$", "this", "->", "options", "[", "'values'", "]", ")", ";", "if", "(", "false", "===", "in_array", "(", "$", "value", ",", "$", "acceptedValues", ")", ")", "{", "$", "errorMessage", "=", "$", "this", "->", "translateErrorMessage", "(", "'validator.has_values.not_valid'", ",", "'configuration_object'", ",", "[", "implode", "(", "', '", ",", "$", "acceptedValues", ")", "]", ")", ";", "$", "this", "->", "addError", "(", "$", "errorMessage", ",", "1456140151", ")", ";", "}", "}" ]
Checks if the given values is one of the accepted values. @param mixed $value The value that should be validated.
[ "Checks", "if", "the", "given", "values", "is", "one", "of", "the", "accepted", "values", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Validation/Validator/HasValuesValidator.php#L34-L42
train
ritalin/omelet
src/Annotation/AnnotationConverterAdapter.php
AnnotationConverterAdapter.getMethodAnnotations
public function getMethodAnnotations(\ReflectionMethod $method) { return array_merge( $this->reader->getMethodAnnotations($method), $this->converter->getMethodAnnotations($method) ); }
php
public function getMethodAnnotations(\ReflectionMethod $method) { return array_merge( $this->reader->getMethodAnnotations($method), $this->converter->getMethodAnnotations($method) ); }
[ "public", "function", "getMethodAnnotations", "(", "\\", "ReflectionMethod", "$", "method", ")", "{", "return", "array_merge", "(", "$", "this", "->", "reader", "->", "getMethodAnnotations", "(", "$", "method", ")", ",", "$", "this", "->", "converter", "->", "getMethodAnnotations", "(", "$", "method", ")", ")", ";", "}" ]
Collect method annotations. @param ReflectionMethod methodName @return DaoAnnotation[]
[ "Collect", "method", "annotations", "." ]
de8e10b5c1dbc345b1d5ccb8853a2e8a8d6a43df
https://github.com/ritalin/omelet/blob/de8e10b5c1dbc345b1d5ccb8853a2e8a8d6a43df/src/Annotation/AnnotationConverterAdapter.php#L42-L48
train
ritalin/omelet
src/Annotation/AnnotationConverterAdapter.php
AnnotationConverterAdapter.getPropertyAnnotations
public function getPropertyAnnotations(\ReflectionProperty $prop) { return array_merge( $this->reader->getPropertyAnnotations($prop), $this->converter->getPropertyAnnotations($prop) ); }
php
public function getPropertyAnnotations(\ReflectionProperty $prop) { return array_merge( $this->reader->getPropertyAnnotations($prop), $this->converter->getPropertyAnnotations($prop) ); }
[ "public", "function", "getPropertyAnnotations", "(", "\\", "ReflectionProperty", "$", "prop", ")", "{", "return", "array_merge", "(", "$", "this", "->", "reader", "->", "getPropertyAnnotations", "(", "$", "prop", ")", ",", "$", "this", "->", "converter", "->", "getPropertyAnnotations", "(", "$", "prop", ")", ")", ";", "}" ]
Collect property annotations. @param ReflectionProperty methodName @return EntityFieldAnnotation[]
[ "Collect", "property", "annotations", "." ]
de8e10b5c1dbc345b1d5ccb8853a2e8a8d6a43df
https://github.com/ritalin/omelet/blob/de8e10b5c1dbc345b1d5ccb8853a2e8a8d6a43df/src/Annotation/AnnotationConverterAdapter.php#L57-L63
train
phossa/phossa-event
src/Phossa/Event/Variation/CompositeEventManager.php
CompositeEventManager.processEvent
public function processEvent( Interfaces\EventInterface $event, callable $callback = null )/*# : EventManagerInterface */ { $eventName = $event->getName(); // check self's queue $queue = $this->matchEventQueue($eventName, $this); // merge with other managers' queue $managers = $this->getOtherManagers(); foreach ($managers as $mgr) { // other manager's own queue $q = $this->matchEventQueue($eventName, $mgr); if ($q->count()) { $queue = $queue->combine($q); } } // run thru the queue return $this->runEventQueue($event, $queue, $callback); }
php
public function processEvent( Interfaces\EventInterface $event, callable $callback = null )/*# : EventManagerInterface */ { $eventName = $event->getName(); // check self's queue $queue = $this->matchEventQueue($eventName, $this); // merge with other managers' queue $managers = $this->getOtherManagers(); foreach ($managers as $mgr) { // other manager's own queue $q = $this->matchEventQueue($eventName, $mgr); if ($q->count()) { $queue = $queue->combine($q); } } // run thru the queue return $this->runEventQueue($event, $queue, $callback); }
[ "public", "function", "processEvent", "(", "Interfaces", "\\", "EventInterface", "$", "event", ",", "callable", "$", "callback", "=", "null", ")", "/*# : EventManagerInterface */", "{", "$", "eventName", "=", "$", "event", "->", "getName", "(", ")", ";", "// check self's queue", "$", "queue", "=", "$", "this", "->", "matchEventQueue", "(", "$", "eventName", ",", "$", "this", ")", ";", "// merge with other managers' queue", "$", "managers", "=", "$", "this", "->", "getOtherManagers", "(", ")", ";", "foreach", "(", "$", "managers", "as", "$", "mgr", ")", "{", "// other manager's own queue", "$", "q", "=", "$", "this", "->", "matchEventQueue", "(", "$", "eventName", ",", "$", "mgr", ")", ";", "if", "(", "$", "q", "->", "count", "(", ")", ")", "{", "$", "queue", "=", "$", "queue", "->", "combine", "(", "$", "q", ")", ";", "}", "}", "// run thru the queue", "return", "$", "this", "->", "runEventQueue", "(", "$", "event", ",", "$", "queue", ",", "$", "callback", ")", ";", "}" ]
Process events by all managers in the pool {@inheritDoc}
[ "Process", "events", "by", "all", "managers", "in", "the", "pool" ]
0044888fcc9b21584233c73cf20fc160e1b1f295
https://github.com/phossa/phossa-event/blob/0044888fcc9b21584233c73cf20fc160e1b1f295/src/Phossa/Event/Variation/CompositeEventManager.php#L107-L128
train
mikyprog/LocationBundle
Manager/ContinentManager.php
ContinentManager.updateContinent
public function updateContinent(Continent $continent, $andFlush = true) { $this->objectManager->persist($continent); if ($andFlush) { $this->objectManager->flush(); } }
php
public function updateContinent(Continent $continent, $andFlush = true) { $this->objectManager->persist($continent); if ($andFlush) { $this->objectManager->flush(); } }
[ "public", "function", "updateContinent", "(", "Continent", "$", "continent", ",", "$", "andFlush", "=", "true", ")", "{", "$", "this", "->", "objectManager", "->", "persist", "(", "$", "continent", ")", ";", "if", "(", "$", "andFlush", ")", "{", "$", "this", "->", "objectManager", "->", "flush", "(", ")", ";", "}", "}" ]
Updates a Continent. @param Continent $continent @param Boolean $andFlush Whether to flush the changes (default true)
[ "Updates", "a", "Continent", "." ]
ffbbc8e6b7c759f0dbf0dec6d36a8f3150322f23
https://github.com/mikyprog/LocationBundle/blob/ffbbc8e6b7c759f0dbf0dec6d36a8f3150322f23/Manager/ContinentManager.php#L117-L123
train
mikyprog/LocationBundle
Manager/ContinentManager.php
ContinentManager.refreshContinent
public function refreshContinent(Continent $continent) { $refreshedContinent = $this->findContinentBy(array('id' => $continent->getId())); if (null === $refreshedContinent) { throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $continent->getId())); } return $refreshedContinent; }
php
public function refreshContinent(Continent $continent) { $refreshedContinent = $this->findContinentBy(array('id' => $continent->getId())); if (null === $refreshedContinent) { throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $continent->getId())); } return $refreshedContinent; }
[ "public", "function", "refreshContinent", "(", "Continent", "$", "continent", ")", "{", "$", "refreshedContinent", "=", "$", "this", "->", "findContinentBy", "(", "array", "(", "'id'", "=>", "$", "continent", "->", "getId", "(", ")", ")", ")", ";", "if", "(", "null", "===", "$", "refreshedContinent", ")", "{", "throw", "new", "UsernameNotFoundException", "(", "sprintf", "(", "'User with ID \"%d\" could not be reloaded.'", ",", "$", "continent", "->", "getId", "(", ")", ")", ")", ";", "}", "return", "$", "refreshedContinent", ";", "}" ]
Refreshed a Continent by Continent Instance @param Continent $continent @return Ad
[ "Refreshed", "a", "Continent", "by", "Continent", "Instance" ]
ffbbc8e6b7c759f0dbf0dec6d36a8f3150322f23
https://github.com/mikyprog/LocationBundle/blob/ffbbc8e6b7c759f0dbf0dec6d36a8f3150322f23/Manager/ContinentManager.php#L144-L152
train
1HappyPlace/ansi-terminal
src/ANSI/Color/Mode.php
Mode.getModeConstant
protected static function getModeConstant($value) { // if the value coming in, is a integer, ensure it is one of the constants if (is_int($value)) { // it can be the number of colors // if it is less than or equal to 16, if ($value <= 16) { // then it is the simple VT100 return self::VT100; // if it is less than or equal to 256 } else if ($value <= 256) { // then it is the middling xterm like terminal return self::XTERM; // if it is greater than 256 } else { // then an attempt at the highest colors is made return self::RGB; } } // if the value coming in is a string else if (is_string($value)) { // trim the string $value = trim($value); // transform to uppercase $value = strtoupper($value); // make sure it matches one of the constant integer values if (in_array($value, self::$constants)) { // it is valid, return it return $value; } else { // not a valid string return self::XTERM; } } else { // something went wrong, return left return self::XTERM; } }
php
protected static function getModeConstant($value) { // if the value coming in, is a integer, ensure it is one of the constants if (is_int($value)) { // it can be the number of colors // if it is less than or equal to 16, if ($value <= 16) { // then it is the simple VT100 return self::VT100; // if it is less than or equal to 256 } else if ($value <= 256) { // then it is the middling xterm like terminal return self::XTERM; // if it is greater than 256 } else { // then an attempt at the highest colors is made return self::RGB; } } // if the value coming in is a string else if (is_string($value)) { // trim the string $value = trim($value); // transform to uppercase $value = strtoupper($value); // make sure it matches one of the constant integer values if (in_array($value, self::$constants)) { // it is valid, return it return $value; } else { // not a valid string return self::XTERM; } } else { // something went wrong, return left return self::XTERM; } }
[ "protected", "static", "function", "getModeConstant", "(", "$", "value", ")", "{", "// if the value coming in, is a integer, ensure it is one of the constants", "if", "(", "is_int", "(", "$", "value", ")", ")", "{", "// it can be the number of colors", "// if it is less than or equal to 16,", "if", "(", "$", "value", "<=", "16", ")", "{", "// then it is the simple VT100", "return", "self", "::", "VT100", ";", "// if it is less than or equal to 256", "}", "else", "if", "(", "$", "value", "<=", "256", ")", "{", "// then it is the middling xterm like terminal", "return", "self", "::", "XTERM", ";", "// if it is greater than 256", "}", "else", "{", "// then an attempt at the highest colors is made", "return", "self", "::", "RGB", ";", "}", "}", "// if the value coming in is a string", "else", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "// trim the string", "$", "value", "=", "trim", "(", "$", "value", ")", ";", "// transform to uppercase", "$", "value", "=", "strtoupper", "(", "$", "value", ")", ";", "// make sure it matches one of the constant integer values", "if", "(", "in_array", "(", "$", "value", ",", "self", "::", "$", "constants", ")", ")", "{", "// it is valid, return it", "return", "$", "value", ";", "}", "else", "{", "// not a valid string", "return", "self", "::", "XTERM", ";", "}", "}", "else", "{", "// something went wrong, return left", "return", "self", "::", "XTERM", ";", "}", "}" ]
Helper function to take a value and turn it into a valid constant integer value @param string | int $value if int - if it is any other number, it tries to ascertain the mode based on the number of colors if string - if it is one of the constants Mode::XTERM, then it returns that mode it matches the constant names (such as "xterm" or "RGB") case-insensitive, if that does not work, it defaults to xterm @return int - the constant or the $default parameter value if something went wrong
[ "Helper", "function", "to", "take", "a", "value", "and", "turn", "it", "into", "a", "valid", "constant", "integer", "value" ]
3a550eadb21bb87a6909436c3b961919d2731923
https://github.com/1HappyPlace/ansi-terminal/blob/3a550eadb21bb87a6909436c3b961919d2731923/src/ANSI/Color/Mode.php#L83-L136
train
AmericanCouncils/WebServicesBundle
EventListener/WebServiceSubscriber.php
WebServiceSubscriber.onKernelEarlyRequest
public function onKernelEarlyRequest(GetResponseEvent $e) { $request = $e->getRequest(); foreach ($this->pathConfig as $regex => $config) { if (preg_match($regex, $request->getPathInfo())) { $this->enabled = true; if (!$this->subscribed) { $e->getDispatcher()->addSubscriber($this); $this->subscribed = true; } //set other relevant values for this request $config['suppress_response_codes'] = ($config['allow_code_suppression']) ? $request->query->get('_suppress_codes', false) : false; $config['http_response_format'] = $request->get('_format', false); $config['negotiated'] = false; //subsequent listeners will check the request attributes for relevant configuration $request->attributes->set('_ac_web_service', $config); return; } } $this->enabled = false; }
php
public function onKernelEarlyRequest(GetResponseEvent $e) { $request = $e->getRequest(); foreach ($this->pathConfig as $regex => $config) { if (preg_match($regex, $request->getPathInfo())) { $this->enabled = true; if (!$this->subscribed) { $e->getDispatcher()->addSubscriber($this); $this->subscribed = true; } //set other relevant values for this request $config['suppress_response_codes'] = ($config['allow_code_suppression']) ? $request->query->get('_suppress_codes', false) : false; $config['http_response_format'] = $request->get('_format', false); $config['negotiated'] = false; //subsequent listeners will check the request attributes for relevant configuration $request->attributes->set('_ac_web_service', $config); return; } } $this->enabled = false; }
[ "public", "function", "onKernelEarlyRequest", "(", "GetResponseEvent", "$", "e", ")", "{", "$", "request", "=", "$", "e", "->", "getRequest", "(", ")", ";", "foreach", "(", "$", "this", "->", "pathConfig", "as", "$", "regex", "=>", "$", "config", ")", "{", "if", "(", "preg_match", "(", "$", "regex", ",", "$", "request", "->", "getPathInfo", "(", ")", ")", ")", "{", "$", "this", "->", "enabled", "=", "true", ";", "if", "(", "!", "$", "this", "->", "subscribed", ")", "{", "$", "e", "->", "getDispatcher", "(", ")", "->", "addSubscriber", "(", "$", "this", ")", ";", "$", "this", "->", "subscribed", "=", "true", ";", "}", "//set other relevant values for this request", "$", "config", "[", "'suppress_response_codes'", "]", "=", "(", "$", "config", "[", "'allow_code_suppression'", "]", ")", "?", "$", "request", "->", "query", "->", "get", "(", "'_suppress_codes'", ",", "false", ")", ":", "false", ";", "$", "config", "[", "'http_response_format'", "]", "=", "$", "request", "->", "get", "(", "'_format'", ",", "false", ")", ";", "$", "config", "[", "'negotiated'", "]", "=", "false", ";", "//subsequent listeners will check the request attributes for relevant configuration", "$", "request", "->", "attributes", "->", "set", "(", "'_ac_web_service'", ",", "$", "config", ")", ";", "return", ";", "}", "}", "$", "this", "->", "enabled", "=", "false", ";", "}" ]
Listens early in the `kernel.request` cycle for incoming requests and checks for a matching path. If a match is found, the rest of the kernel listeners are registered and the relevant path config is stored for use in those listeners.
[ "Listens", "early", "in", "the", "kernel", ".", "request", "cycle", "for", "incoming", "requests", "and", "checks", "for", "a", "matching", "path", ".", "If", "a", "match", "is", "found", "the", "rest", "of", "the", "kernel", "listeners", "are", "registered", "and", "the", "relevant", "path", "config", "is", "stored", "for", "use", "in", "those", "listeners", "." ]
3f6270ecf31138ba2271a94a407c0d1a05542929
https://github.com/AmericanCouncils/WebServicesBundle/blob/3f6270ecf31138ba2271a94a407c0d1a05542929/EventListener/WebServiceSubscriber.php#L126-L152
train
AmericanCouncils/WebServicesBundle
EventListener/WebServiceSubscriber.php
WebServiceSubscriber.onKernelLateRequest
public function onKernelLateRequest(GetResponseEvent $e) { if (!$this->enabled) return; $req = $e->getRequest(); if (!$config = $req->attributes->get('_ac_web_service', false)) { return; } $config = $this->negotiateResponseFormat($req, $config); $req->attributes->set('_ac_web_service', $config); if (!isset($this->formatHeaders[$config['http_response_format']])) { throw new HttpException(415); } $e->getDispatcher()->dispatch(self::API_REQUEST, $e); }
php
public function onKernelLateRequest(GetResponseEvent $e) { if (!$this->enabled) return; $req = $e->getRequest(); if (!$config = $req->attributes->get('_ac_web_service', false)) { return; } $config = $this->negotiateResponseFormat($req, $config); $req->attributes->set('_ac_web_service', $config); if (!isset($this->formatHeaders[$config['http_response_format']])) { throw new HttpException(415); } $e->getDispatcher()->dispatch(self::API_REQUEST, $e); }
[ "public", "function", "onKernelLateRequest", "(", "GetResponseEvent", "$", "e", ")", "{", "if", "(", "!", "$", "this", "->", "enabled", ")", "return", ";", "$", "req", "=", "$", "e", "->", "getRequest", "(", ")", ";", "if", "(", "!", "$", "config", "=", "$", "req", "->", "attributes", "->", "get", "(", "'_ac_web_service'", ",", "false", ")", ")", "{", "return", ";", "}", "$", "config", "=", "$", "this", "->", "negotiateResponseFormat", "(", "$", "req", ",", "$", "config", ")", ";", "$", "req", "->", "attributes", "->", "set", "(", "'_ac_web_service'", ",", "$", "config", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "formatHeaders", "[", "$", "config", "[", "'http_response_format'", "]", "]", ")", ")", "{", "throw", "new", "HttpException", "(", "415", ")", ";", "}", "$", "e", "->", "getDispatcher", "(", ")", "->", "dispatch", "(", "self", "::", "API_REQUEST", ",", "$", "e", ")", ";", "}" ]
Fires at the end of the `kernel.request` cycle - so listeners should receive a request that has already been resolved to a controller. Will throw exceptions if the response format is unknown.
[ "Fires", "at", "the", "end", "of", "the", "kernel", ".", "request", "cycle", "-", "so", "listeners", "should", "receive", "a", "request", "that", "has", "already", "been", "resolved", "to", "a", "controller", "." ]
3f6270ecf31138ba2271a94a407c0d1a05542929
https://github.com/AmericanCouncils/WebServicesBundle/blob/3f6270ecf31138ba2271a94a407c0d1a05542929/EventListener/WebServiceSubscriber.php#L161-L179
train
AmericanCouncils/WebServicesBundle
EventListener/WebServiceSubscriber.php
WebServiceSubscriber.onKernelResponse
public function onKernelResponse(FilterResponseEvent $e) { if (!$this->enabled) return; $response = $e->getResponse(); //if supression is active, always return 200 no matter what $config = $e->getRequest()->attributes->get('_ac_web_service'); if (!$config['negotiated']) { $config = $this->negotiateResponseFormat($e->getRequest(), $config); } if ($config['suppress_response_codes']) { $response = $response->setStatusCode(200); } //if JSONP, wrap use _callback param if ($config['is_jsonp']) { $response->headers->set('Content-Type', $this->formatHeaders['jsonp']); $response->setContent(sprintf("%s(%s);", $config['jsonp_callback'], $response->getContent())); } $e->getDispatcher()->dispatch(self::API_RESPONSE, $e); }
php
public function onKernelResponse(FilterResponseEvent $e) { if (!$this->enabled) return; $response = $e->getResponse(); //if supression is active, always return 200 no matter what $config = $e->getRequest()->attributes->get('_ac_web_service'); if (!$config['negotiated']) { $config = $this->negotiateResponseFormat($e->getRequest(), $config); } if ($config['suppress_response_codes']) { $response = $response->setStatusCode(200); } //if JSONP, wrap use _callback param if ($config['is_jsonp']) { $response->headers->set('Content-Type', $this->formatHeaders['jsonp']); $response->setContent(sprintf("%s(%s);", $config['jsonp_callback'], $response->getContent())); } $e->getDispatcher()->dispatch(self::API_RESPONSE, $e); }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "e", ")", "{", "if", "(", "!", "$", "this", "->", "enabled", ")", "return", ";", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "//if supression is active, always return 200 no matter what", "$", "config", "=", "$", "e", "->", "getRequest", "(", ")", "->", "attributes", "->", "get", "(", "'_ac_web_service'", ")", ";", "if", "(", "!", "$", "config", "[", "'negotiated'", "]", ")", "{", "$", "config", "=", "$", "this", "->", "negotiateResponseFormat", "(", "$", "e", "->", "getRequest", "(", ")", ",", "$", "config", ")", ";", "}", "if", "(", "$", "config", "[", "'suppress_response_codes'", "]", ")", "{", "$", "response", "=", "$", "response", "->", "setStatusCode", "(", "200", ")", ";", "}", "//if JSONP, wrap use _callback param", "if", "(", "$", "config", "[", "'is_jsonp'", "]", ")", "{", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "$", "this", "->", "formatHeaders", "[", "'jsonp'", "]", ")", ";", "$", "response", "->", "setContent", "(", "sprintf", "(", "\"%s(%s);\"", ",", "$", "config", "[", "'jsonp_callback'", "]", ",", "$", "response", "->", "getContent", "(", ")", ")", ")", ";", "}", "$", "e", "->", "getDispatcher", "(", ")", "->", "dispatch", "(", "self", "::", "API_RESPONSE", ",", "$", "e", ")", ";", "}" ]
Called when a response object has been resolved.
[ "Called", "when", "a", "response", "object", "has", "been", "resolved", "." ]
3f6270ecf31138ba2271a94a407c0d1a05542929
https://github.com/AmericanCouncils/WebServicesBundle/blob/3f6270ecf31138ba2271a94a407c0d1a05542929/EventListener/WebServiceSubscriber.php#L269-L294
train
AmericanCouncils/WebServicesBundle
EventListener/WebServiceSubscriber.php
WebServiceSubscriber.onKernelTerminate
public function onKernelTerminate(PostResponseEvent $e) { if (!$this->enabled) return; $e->getDispatcher()->dispatch(self::API_TERMINATE, $e); }
php
public function onKernelTerminate(PostResponseEvent $e) { if (!$this->enabled) return; $e->getDispatcher()->dispatch(self::API_TERMINATE, $e); }
[ "public", "function", "onKernelTerminate", "(", "PostResponseEvent", "$", "e", ")", "{", "if", "(", "!", "$", "this", "->", "enabled", ")", "return", ";", "$", "e", "->", "getDispatcher", "(", ")", "->", "dispatch", "(", "self", "::", "API_TERMINATE", ",", "$", "e", ")", ";", "}" ]
Called after a response has already been sent.
[ "Called", "after", "a", "response", "has", "already", "been", "sent", "." ]
3f6270ecf31138ba2271a94a407c0d1a05542929
https://github.com/AmericanCouncils/WebServicesBundle/blob/3f6270ecf31138ba2271a94a407c0d1a05542929/EventListener/WebServiceSubscriber.php#L388-L393
train
chee-commerce/CheeModule
src/Chee/Module/Module.php
Module.includes
protected function includes() { $moduleInclude = (array) $this->def('include'); $globalInclude = $this->app['config']->get('module::include'); $specificInclude = array($this->name.'.php'); $include = array_merge($moduleInclude, $specificInclude, $globalInclude); foreach ($include as $file) { $path = $this->path.'/'.$file; if ($this->app['files']->exists($path)) require $path; } }
php
protected function includes() { $moduleInclude = (array) $this->def('include'); $globalInclude = $this->app['config']->get('module::include'); $specificInclude = array($this->name.'.php'); $include = array_merge($moduleInclude, $specificInclude, $globalInclude); foreach ($include as $file) { $path = $this->path.'/'.$file; if ($this->app['files']->exists($path)) require $path; } }
[ "protected", "function", "includes", "(", ")", "{", "$", "moduleInclude", "=", "(", "array", ")", "$", "this", "->", "def", "(", "'include'", ")", ";", "$", "globalInclude", "=", "$", "this", "->", "app", "[", "'config'", "]", "->", "get", "(", "'module::include'", ")", ";", "$", "specificInclude", "=", "array", "(", "$", "this", "->", "name", ".", "'.php'", ")", ";", "$", "include", "=", "array_merge", "(", "$", "moduleInclude", ",", "$", "specificInclude", ",", "$", "globalInclude", ")", ";", "foreach", "(", "$", "include", "as", "$", "file", ")", "{", "$", "path", "=", "$", "this", "->", "path", ".", "'/'", ".", "$", "file", ";", "if", "(", "$", "this", "->", "app", "[", "'files'", "]", "->", "exists", "(", "$", "path", ")", ")", "require", "$", "path", ";", "}", "}" ]
Include some files determined in config.php of CheeModule and module.json of modules
[ "Include", "some", "files", "determined", "in", "config", ".", "php", "of", "CheeModule", "and", "module", ".", "json", "of", "modules" ]
ccfff426f4ecf8f13687f5acd49246ba4997deee
https://github.com/chee-commerce/CheeModule/blob/ccfff426f4ecf8f13687f5acd49246ba4997deee/src/Chee/Module/Module.php#L56-L67
train
chee-commerce/CheeModule
src/Chee/Module/Module.php
Module.registerProviders
protected function registerProviders() { $providers = $this->def('provider'); if ($providers) { if (is_array($providers)) { foreach ($providers as $provider) { $this->app->register($instance = new $provider($this->app)); } } else { $this->app->register($instence = new $providers($this->app)); } } }
php
protected function registerProviders() { $providers = $this->def('provider'); if ($providers) { if (is_array($providers)) { foreach ($providers as $provider) { $this->app->register($instance = new $provider($this->app)); } } else { $this->app->register($instence = new $providers($this->app)); } } }
[ "protected", "function", "registerProviders", "(", ")", "{", "$", "providers", "=", "$", "this", "->", "def", "(", "'provider'", ")", ";", "if", "(", "$", "providers", ")", "{", "if", "(", "is_array", "(", "$", "providers", ")", ")", "{", "foreach", "(", "$", "providers", "as", "$", "provider", ")", "{", "$", "this", "->", "app", "->", "register", "(", "$", "instance", "=", "new", "$", "provider", "(", "$", "this", "->", "app", ")", ")", ";", "}", "}", "else", "{", "$", "this", "->", "app", "->", "register", "(", "$", "instence", "=", "new", "$", "providers", "(", "$", "this", "->", "app", ")", ")", ";", "}", "}", "}" ]
Register service providers of module
[ "Register", "service", "providers", "of", "module" ]
ccfff426f4ecf8f13687f5acd49246ba4997deee
https://github.com/chee-commerce/CheeModule/blob/ccfff426f4ecf8f13687f5acd49246ba4997deee/src/Chee/Module/Module.php#L72-L90
train
mikemirten/DoctrineCriteriaSerializer
src/KatharsisQuery/KatharsisQueryDeserializer.php
KatharsisQueryDeserializer.validatePagination
protected function validatePagination($pagination): void { if (! is_array($pagination)) { throw new InvalidQueryException('Attribute "page" of query must be an array.'); } $unexpected = array_diff(array_keys($pagination), ['offset', 'limit']); if (empty($unexpected)) { return; } throw new InvalidQueryException(sprintf( 'Unexpected member(s) of "page" attribute: "%s". Only "offset" and "limit" are acceptable.', implode('", "', $unexpected) )); }
php
protected function validatePagination($pagination): void { if (! is_array($pagination)) { throw new InvalidQueryException('Attribute "page" of query must be an array.'); } $unexpected = array_diff(array_keys($pagination), ['offset', 'limit']); if (empty($unexpected)) { return; } throw new InvalidQueryException(sprintf( 'Unexpected member(s) of "page" attribute: "%s". Only "offset" and "limit" are acceptable.', implode('", "', $unexpected) )); }
[ "protected", "function", "validatePagination", "(", "$", "pagination", ")", ":", "void", "{", "if", "(", "!", "is_array", "(", "$", "pagination", ")", ")", "{", "throw", "new", "InvalidQueryException", "(", "'Attribute \"page\" of query must be an array.'", ")", ";", "}", "$", "unexpected", "=", "array_diff", "(", "array_keys", "(", "$", "pagination", ")", ",", "[", "'offset'", ",", "'limit'", "]", ")", ";", "if", "(", "empty", "(", "$", "unexpected", ")", ")", "{", "return", ";", "}", "throw", "new", "InvalidQueryException", "(", "sprintf", "(", "'Unexpected member(s) of \"page\" attribute: \"%s\". Only \"offset\" and \"limit\" are acceptable.'", ",", "implode", "(", "'\", \"'", ",", "$", "unexpected", ")", ")", ")", ";", "}" ]
Validate pagination definition @param $pagination @throws InvalidQueryException
[ "Validate", "pagination", "definition" ]
1016e8781db7b3403be18d6a2168017726c237e1
https://github.com/mikemirten/DoctrineCriteriaSerializer/blob/1016e8781db7b3403be18d6a2168017726c237e1/src/KatharsisQuery/KatharsisQueryDeserializer.php#L186-L202
train
nemundo/core
src/Type/Text/Text.php
Text.substring
public function substring($start, $length = null) { if ($length == null) { $substring = substr($this->value, $start); } else { $substring = substr($this->value, $start, $length); } $this->value = $substring; return $this; }
php
public function substring($start, $length = null) { if ($length == null) { $substring = substr($this->value, $start); } else { $substring = substr($this->value, $start, $length); } $this->value = $substring; return $this; }
[ "public", "function", "substring", "(", "$", "start", ",", "$", "length", "=", "null", ")", "{", "if", "(", "$", "length", "==", "null", ")", "{", "$", "substring", "=", "substr", "(", "$", "this", "->", "value", ",", "$", "start", ")", ";", "}", "else", "{", "$", "substring", "=", "substr", "(", "$", "this", "->", "value", ",", "$", "start", ",", "$", "length", ")", ";", "}", "$", "this", "->", "value", "=", "$", "substring", ";", "return", "$", "this", ";", "}" ]
Unterschied zu getSubstring !!!
[ "Unterschied", "zu", "getSubstring", "!!!" ]
5ca14889fdfb9155b52fedb364b34502d14e21ed
https://github.com/nemundo/core/blob/5ca14889fdfb9155b52fedb364b34502d14e21ed/src/Type/Text/Text.php#L36-L50
train
FuzeWorks/Core
src/Libraries/Cache/drivers/Cache_file.php
FW_Cache_file.save
public function save($id, $data, $ttl = 60, $raw = FALSE) { $contents = array( 'time' => time(), 'ttl' => $ttl, 'data' => $data ); if (write_file($this->_cache_path.$id, serialize($contents))) { chmod($this->_cache_path.$id, 0640); return TRUE; } return FALSE; }
php
public function save($id, $data, $ttl = 60, $raw = FALSE) { $contents = array( 'time' => time(), 'ttl' => $ttl, 'data' => $data ); if (write_file($this->_cache_path.$id, serialize($contents))) { chmod($this->_cache_path.$id, 0640); return TRUE; } return FALSE; }
[ "public", "function", "save", "(", "$", "id", ",", "$", "data", ",", "$", "ttl", "=", "60", ",", "$", "raw", "=", "FALSE", ")", "{", "$", "contents", "=", "array", "(", "'time'", "=>", "time", "(", ")", ",", "'ttl'", "=>", "$", "ttl", ",", "'data'", "=>", "$", "data", ")", ";", "if", "(", "write_file", "(", "$", "this", "->", "_cache_path", ".", "$", "id", ",", "serialize", "(", "$", "contents", ")", ")", ")", "{", "chmod", "(", "$", "this", "->", "_cache_path", ".", "$", "id", ",", "0640", ")", ";", "return", "TRUE", ";", "}", "return", "FALSE", ";", "}" ]
Save into cache @param string $id Cache ID @param mixed $data Data to store @param int $ttl Time to live in seconds @param bool $raw Whether to store the raw value (unused) @return bool TRUE on success, FALSE on failure
[ "Save", "into", "cache" ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/Libraries/Cache/drivers/Cache_file.php#L105-L120
train
FuzeWorks/Core
src/Libraries/Cache/drivers/Cache_file.php
FW_Cache_file.delete
public function delete($id) { return file_exists($this->_cache_path.$id) ? unlink($this->_cache_path.$id) : FALSE; }
php
public function delete($id) { return file_exists($this->_cache_path.$id) ? unlink($this->_cache_path.$id) : FALSE; }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "return", "file_exists", "(", "$", "this", "->", "_cache_path", ".", "$", "id", ")", "?", "unlink", "(", "$", "this", "->", "_cache_path", ".", "$", "id", ")", ":", "FALSE", ";", "}" ]
Delete from Cache @param mixed unique identifier of item in cache @return bool true on success/false on failure
[ "Delete", "from", "Cache" ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/Libraries/Cache/drivers/Cache_file.php#L130-L133
train
vaccuum/config
source/DirectoryReader.php
DirectoryReader.load
protected function load($path) { /** @noinspection PhpIncludeInspection */ $file = require($path); if (!is_array($file)) { $message = "{$path} configuration file is not readable."; throw new ConfigException($message); } return $file; }
php
protected function load($path) { /** @noinspection PhpIncludeInspection */ $file = require($path); if (!is_array($file)) { $message = "{$path} configuration file is not readable."; throw new ConfigException($message); } return $file; }
[ "protected", "function", "load", "(", "$", "path", ")", "{", "/** @noinspection PhpIncludeInspection */", "$", "file", "=", "require", "(", "$", "path", ")", ";", "if", "(", "!", "is_array", "(", "$", "file", ")", ")", "{", "$", "message", "=", "\"{$path} configuration file is not readable.\"", ";", "throw", "new", "ConfigException", "(", "$", "message", ")", ";", "}", "return", "$", "file", ";", "}" ]
Load configuration file. @param string $path @throws ConfigException @return array
[ "Load", "configuration", "file", "." ]
9ec496b0dc2584f2e7e2a4e536b2ccef8737c7bd
https://github.com/vaccuum/config/blob/9ec496b0dc2584f2e7e2a4e536b2ccef8737c7bd/source/DirectoryReader.php#L31-L43
train
ScaraMVC/Framework
src/Scara/Hashing/OpenSslHasher.php
OpenSslHasher.random_string
public function random_string($length = 32) { return substr(str_shuffle(str_repeat( $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)) )), 1, $length); }
php
public function random_string($length = 32) { return substr(str_shuffle(str_repeat( $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)) )), 1, $length); }
[ "public", "function", "random_string", "(", "$", "length", "=", "32", ")", "{", "return", "substr", "(", "str_shuffle", "(", "str_repeat", "(", "$", "x", "=", "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ",", "ceil", "(", "$", "length", "/", "strlen", "(", "$", "x", ")", ")", ")", ")", ",", "1", ",", "$", "length", ")", ";", "}" ]
Generates a random string based on given length. Blatantly taken from StackOverflow: http://stackoverflow.com/a/13212994/1524676 @param int $length @return string
[ "Generates", "a", "random", "string", "based", "on", "given", "length", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Hashing/OpenSslHasher.php#L39-L45
train
ScaraMVC/Framework
src/Scara/Hashing/OpenSslHasher.php
OpenSslHasher.tokenize
public function tokenize($iv, $string = '') { if (empty($string)) { $string = $this->random_string(); } return openssl_encrypt($string, 'AES-256-CBC', $this->_config->get('token'), 0, $iv); }
php
public function tokenize($iv, $string = '') { if (empty($string)) { $string = $this->random_string(); } return openssl_encrypt($string, 'AES-256-CBC', $this->_config->get('token'), 0, $iv); }
[ "public", "function", "tokenize", "(", "$", "iv", ",", "$", "string", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "string", ")", ")", "{", "$", "string", "=", "$", "this", "->", "random_string", "(", ")", ";", "}", "return", "openssl_encrypt", "(", "$", "string", ",", "'AES-256-CBC'", ",", "$", "this", "->", "_config", "->", "get", "(", "'token'", ")", ",", "0", ",", "$", "iv", ")", ";", "}" ]
Generate a token using OpenSSL extensions. @param string $iv @param string $string @return string
[ "Generate", "a", "token", "using", "OpenSSL", "extensions", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Hashing/OpenSslHasher.php#L65-L72
train
spoom-php/core
src/extension/Helper/Number.php
Number.isInteger
public static function isInteger( $input ): bool { return self::is( $input ) && (string) (int) $input === (string) $input; }
php
public static function isInteger( $input ): bool { return self::is( $input ) && (string) (int) $input === (string) $input; }
[ "public", "static", "function", "isInteger", "(", "$", "input", ")", ":", "bool", "{", "return", "self", "::", "is", "(", "$", "input", ")", "&&", "(", "string", ")", "(", "int", ")", "$", "input", "===", "(", "string", ")", "$", "input", ";", "}" ]
Check if the input is true integer number or can be converted from string into integer @param mixed $input @return bool
[ "Check", "if", "the", "input", "is", "true", "integer", "number", "or", "can", "be", "converted", "from", "string", "into", "integer" ]
ea7184213352fa2fad7636927a019e5798734e04
https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Helper/Number.php#L33-L35
train
spoom-php/core
src/extension/Helper/Number.php
Number.write
public static function write( $input, ?int $precision = null, $default = null ) { if( !self::is( $input ) ) return $default; else { $input = self::cast( $input ); if( is_int( $precision ) ) return number_format( $input, $precision, '.', '' ); else if( is_int( $input ) ) return (string) $input; else return str_replace( ',', '.', (string) $input ); } }
php
public static function write( $input, ?int $precision = null, $default = null ) { if( !self::is( $input ) ) return $default; else { $input = self::cast( $input ); if( is_int( $precision ) ) return number_format( $input, $precision, '.', '' ); else if( is_int( $input ) ) return (string) $input; else return str_replace( ',', '.', (string) $input ); } }
[ "public", "static", "function", "write", "(", "$", "input", ",", "?", "int", "$", "precision", "=", "null", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "self", "::", "is", "(", "$", "input", ")", ")", "return", "$", "default", ";", "else", "{", "$", "input", "=", "self", "::", "cast", "(", "$", "input", ")", ";", "if", "(", "is_int", "(", "$", "precision", ")", ")", "return", "number_format", "(", "$", "input", ",", "$", "precision", ",", "'.'", ",", "''", ")", ";", "else", "if", "(", "is_int", "(", "$", "input", ")", ")", "return", "(", "string", ")", "$", "input", ";", "else", "return", "str_replace", "(", "','", ",", "'.'", ",", "(", "string", ")", "$", "input", ")", ";", "}", "}" ]
Convert numbers to string @param mixed $input @param int|null $precision Decimal count if not null @param mixed $default Non-number inputs results @return string|mixed
[ "Convert", "numbers", "to", "string" ]
ea7184213352fa2fad7636927a019e5798734e04
https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Helper/Number.php#L86-L95
train
spoom-php/core
src/extension/Helper/Number.php
Number.equal
public static function equal( $a, $b, int $precision = 0 ): bool { return self::write( $a, $precision ) === self::write( $b, $precision ); }
php
public static function equal( $a, $b, int $precision = 0 ): bool { return self::write( $a, $precision ) === self::write( $b, $precision ); }
[ "public", "static", "function", "equal", "(", "$", "a", ",", "$", "b", ",", "int", "$", "precision", "=", "0", ")", ":", "bool", "{", "return", "self", "::", "write", "(", "$", "a", ",", "$", "precision", ")", "===", "self", "::", "write", "(", "$", "b", ",", "$", "precision", ")", ";", "}" ]
Check if two number is equals. Can handle floats with precision @param mixed $a @param mixed $b @param int $precision Precision used for the check @return bool
[ "Check", "if", "two", "number", "is", "equals", ".", "Can", "handle", "floats", "with", "precision" ]
ea7184213352fa2fad7636927a019e5798734e04
https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Helper/Number.php#L106-L108
train
agentmedia/phine-core
src/Core/Modules/Backend/UsergroupAssignmentForm.php
UsergroupAssignmentForm.BeforeInit
protected function BeforeInit() { $this->user = User::Schema()->ByID(Request::GetData('user')); if (!$this->user || !self::Guard()->Allow(BackendAction::AssignGroups(), $this->user)) { //TODO: Error message Response::Redirect(BackendRouter::ModuleUrl(new UserList())); } return parent::BeforeInit(); }
php
protected function BeforeInit() { $this->user = User::Schema()->ByID(Request::GetData('user')); if (!$this->user || !self::Guard()->Allow(BackendAction::AssignGroups(), $this->user)) { //TODO: Error message Response::Redirect(BackendRouter::ModuleUrl(new UserList())); } return parent::BeforeInit(); }
[ "protected", "function", "BeforeInit", "(", ")", "{", "$", "this", "->", "user", "=", "User", "::", "Schema", "(", ")", "->", "ByID", "(", "Request", "::", "GetData", "(", "'user'", ")", ")", ";", "if", "(", "!", "$", "this", "->", "user", "||", "!", "self", "::", "Guard", "(", ")", "->", "Allow", "(", "BackendAction", "::", "AssignGroups", "(", ")", ",", "$", "this", "->", "user", ")", ")", "{", "//TODO: Error message", "Response", "::", "Redirect", "(", "BackendRouter", "::", "ModuleUrl", "(", "new", "UserList", "(", ")", ")", ")", ";", "}", "return", "parent", "::", "BeforeInit", "(", ")", ";", "}" ]
Gets and checks the requested user @return boolean False if processing can continue
[ "Gets", "and", "checks", "the", "requested", "user" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Modules/Backend/UsergroupAssignmentForm.php#L56-L65
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.getComment
public function getComment() { if (!$this->_commentFetched) { $this->_comment = $this->_fetchComment(); $this->_commentFetched = true; } return $this->_comment; }
php
public function getComment() { if (!$this->_commentFetched) { $this->_comment = $this->_fetchComment(); $this->_commentFetched = true; } return $this->_comment; }
[ "public", "function", "getComment", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_commentFetched", ")", "{", "$", "this", "->", "_comment", "=", "$", "this", "->", "_fetchComment", "(", ")", ";", "$", "this", "->", "_commentFetched", "=", "true", ";", "}", "return", "$", "this", "->", "_comment", ";", "}" ]
Return table comment @return string table comment
[ "Return", "table", "comment" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L142-L149
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.setComment
public function setComment($comment) { if ($comment != $this->getComment() and $this->_setComment($comment)) { $this->_comment = $comment; } }
php
public function setComment($comment) { if ($comment != $this->getComment() and $this->_setComment($comment)) { $this->_comment = $comment; } }
[ "public", "function", "setComment", "(", "$", "comment", ")", "{", "if", "(", "$", "comment", "!=", "$", "this", "->", "getComment", "(", ")", "and", "$", "this", "->", "_setComment", "(", "$", "comment", ")", ")", "{", "$", "this", "->", "_comment", "=", "$", "comment", ";", "}", "}" ]
Set table comment @param string $comment table comment
[ "Set", "table", "comment" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L155-L161
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable._fetchColumns
protected function _fetchColumns() { $columns = $this->_database->query( 'SELECT ' . implode(',', $this->_informationSchemaColumns) . ' FROM information_schema.columns WHERE table_schema=? AND LOWER(table_name)=? ORDER BY ordinal_position', array( $this->_database->getTableSchema(), $this->_name, ) ); foreach ($columns as $column) { $column['column_name'] = strtolower($column['column_name']); $object = $this->_database->createColumnObject(); $object->constructFromTable($this, $column); $this->_columns[$column['column_name']] = $object; } }
php
protected function _fetchColumns() { $columns = $this->_database->query( 'SELECT ' . implode(',', $this->_informationSchemaColumns) . ' FROM information_schema.columns WHERE table_schema=? AND LOWER(table_name)=? ORDER BY ordinal_position', array( $this->_database->getTableSchema(), $this->_name, ) ); foreach ($columns as $column) { $column['column_name'] = strtolower($column['column_name']); $object = $this->_database->createColumnObject(); $object->constructFromTable($this, $column); $this->_columns[$column['column_name']] = $object; } }
[ "protected", "function", "_fetchColumns", "(", ")", "{", "$", "columns", "=", "$", "this", "->", "_database", "->", "query", "(", "'SELECT '", ".", "implode", "(", "','", ",", "$", "this", "->", "_informationSchemaColumns", ")", ".", "' FROM information_schema.columns WHERE table_schema=? AND LOWER(table_name)=? ORDER BY ordinal_position'", ",", "array", "(", "$", "this", "->", "_database", "->", "getTableSchema", "(", ")", ",", "$", "this", "->", "_name", ",", ")", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "column", "[", "'column_name'", "]", "=", "strtolower", "(", "$", "column", "[", "'column_name'", "]", ")", ";", "$", "object", "=", "$", "this", "->", "_database", "->", "createColumnObject", "(", ")", ";", "$", "object", "->", "constructFromTable", "(", "$", "this", ",", "$", "column", ")", ";", "$", "this", "->", "_columns", "[", "$", "column", "[", "'column_name'", "]", "]", "=", "$", "object", ";", "}", "}" ]
Fetch column information from the database Invoked by the constructor, the default implementation queries information_schema.columns for all columns belonging to this table. To make this functional, subclasses must set \Nada\Database\AbstractDatabase::$_tableSchema and, if necessary, extend $_informationSchemaColumns with DBMS-specific columns.
[ "Fetch", "column", "information", "from", "the", "database" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L195-L212
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable._fetchConstraints
protected function _fetchConstraints() { $constraints = $this->_database->query( <<<EOT SELECT kcu.column_name FROM information_schema.key_column_usage kcu JOIN information_schema.table_constraints tc USING (table_schema, table_name, constraint_schema, constraint_name) WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ? AND LOWER(tc.table_name) = ? ORDER BY kcu.ordinal_position EOT , array( $this->_database->getTableSchema(), $this->_name, ) ); foreach ($constraints as $constraint) { $this->_primaryKey[] = $this->_columns[strtolower($constraint['column_name'])]; } }
php
protected function _fetchConstraints() { $constraints = $this->_database->query( <<<EOT SELECT kcu.column_name FROM information_schema.key_column_usage kcu JOIN information_schema.table_constraints tc USING (table_schema, table_name, constraint_schema, constraint_name) WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ? AND LOWER(tc.table_name) = ? ORDER BY kcu.ordinal_position EOT , array( $this->_database->getTableSchema(), $this->_name, ) ); foreach ($constraints as $constraint) { $this->_primaryKey[] = $this->_columns[strtolower($constraint['column_name'])]; } }
[ "protected", "function", "_fetchConstraints", "(", ")", "{", "$", "constraints", "=", "$", "this", "->", "_database", "->", "query", "(", "\n <<<EOT\n SELECT kcu.column_name\n FROM information_schema.key_column_usage kcu\n JOIN information_schema.table_constraints tc\n USING (table_schema, table_name, constraint_schema, constraint_name)\n WHERE tc.constraint_type = 'PRIMARY KEY'\n AND tc.table_schema = ?\n AND LOWER(tc.table_name) = ?\n ORDER BY kcu.ordinal_position\nEOT", ",", "array", "(", "$", "this", "->", "_database", "->", "getTableSchema", "(", ")", ",", "$", "this", "->", "_name", ",", ")", ")", ";", "foreach", "(", "$", "constraints", "as", "$", "constraint", ")", "{", "$", "this", "->", "_primaryKey", "[", "]", "=", "$", "this", "->", "_columns", "[", "strtolower", "(", "$", "constraint", "[", "'column_name'", "]", ")", "]", ";", "}", "}" ]
Fetch constraint information from the database Invoked by the constructor, the default implementation queries information_schema.table_constraints and information_schema.key_column_usage. To make this functional, subclasses must set \Nada\Database\AbstractDatabase::$_tableSchema. Only primary keys are recognized for now. All other constraints are ignored. @todo Recognize other constraint types
[ "Fetch", "constraint", "information", "from", "the", "database" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L227-L249
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.requireColumn
public function requireColumn($name) { if ($name != strtolower($name)) { throw new \DomainException('Column name must be lowercase: ' . $name); } if (!isset($this->_columns[$name])) { throw new \RuntimeException('Undefined column: ' . $this->_name . '.' . $name); } }
php
public function requireColumn($name) { if ($name != strtolower($name)) { throw new \DomainException('Column name must be lowercase: ' . $name); } if (!isset($this->_columns[$name])) { throw new \RuntimeException('Undefined column: ' . $this->_name . '.' . $name); } }
[ "public", "function", "requireColumn", "(", "$", "name", ")", "{", "if", "(", "$", "name", "!=", "strtolower", "(", "$", "name", ")", ")", "{", "throw", "new", "\\", "DomainException", "(", "'Column name must be lowercase: '", ".", "$", "name", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "_columns", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Undefined column: '", ".", "$", "this", "->", "_name", ".", "'.'", ".", "$", "name", ")", ";", "}", "}" ]
Force presence of column @param string $name Column name to check for, must be lowercase @throws \RuntimeException if column does not exist @throws \DomainException if $name is not lowercase
[ "Force", "presence", "of", "column" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L277-L286
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.alter
public function alter($operation) { return $this->_database->exec( 'ALTER TABLE ' . $this->_database->prepareIdentifier($this->_name) . ' ' . $operation ); }
php
public function alter($operation) { return $this->_database->exec( 'ALTER TABLE ' . $this->_database->prepareIdentifier($this->_name) . ' ' . $operation ); }
[ "public", "function", "alter", "(", "$", "operation", ")", "{", "return", "$", "this", "->", "_database", "->", "exec", "(", "'ALTER TABLE '", ".", "$", "this", "->", "_database", "->", "prepareIdentifier", "(", "$", "this", "->", "_name", ")", ".", "' '", ".", "$", "operation", ")", ";", "}" ]
Compose and execute an ALTER TABLE statement This method simply appends the given operation to an "ALTER TABLE name " statement and executes it via exec(). Since the operation syntax is often DBMS-specific, this method is mostly useful for other NADA methods. @param string $operation SQL fragment @return mixed Return value of exec()
[ "Compose", "and", "execute", "an", "ALTER", "TABLE", "statement" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L336-L344
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.addColumn
public final function addColumn( $name, $type, $length=null, $notnull=false, $default=null, $autoIncrement=false, $comment = null ) { return $this->addColumnObject( $this->_database->createColumn( $name, $type, $length, $notnull, $default, $autoIncrement, $comment ) ); }
php
public final function addColumn( $name, $type, $length=null, $notnull=false, $default=null, $autoIncrement=false, $comment = null ) { return $this->addColumnObject( $this->_database->createColumn( $name, $type, $length, $notnull, $default, $autoIncrement, $comment ) ); }
[ "public", "final", "function", "addColumn", "(", "$", "name", ",", "$", "type", ",", "$", "length", "=", "null", ",", "$", "notnull", "=", "false", ",", "$", "default", "=", "null", ",", "$", "autoIncrement", "=", "false", ",", "$", "comment", "=", "null", ")", "{", "return", "$", "this", "->", "addColumnObject", "(", "$", "this", "->", "_database", "->", "createColumn", "(", "$", "name", ",", "$", "type", ",", "$", "length", ",", "$", "notnull", ",", "$", "default", ",", "$", "autoIncrement", ",", "$", "comment", ")", ")", ";", "}" ]
Add a column using parameters @param string $name Column name @param string $type Datatype, one of \Nada\Column\AbstractColumn's TYPE_* constants @param mixed $length Optional length specification @param bool $notnull NOT NULL constraint (default: FALSE) @param mixed $default Default value (DEFAULT: NULL) @param bool $autoIncrement Auto increment property (default: FALSE) @param string $comment Column comment (default: NULL) @return \Nada\Column\AbstractColumn object describing the generated column
[ "Add", "a", "column", "using", "parameters" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L357-L378
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.addColumnObject
public function addColumnObject($column) { $name = $column->getName(); $this->forbidColumn($name); $sql = 'ADD COLUMN '; $sql .= $this->_database->prepareIdentifier($name); $sql .= ' '; $sql .= $column->getDefinition(); $this->alter($sql); // Update column cache $this->_columns[$name] = $column; $this->_columns[$name]->setTable($this); return $this->_columns[$name]; }
php
public function addColumnObject($column) { $name = $column->getName(); $this->forbidColumn($name); $sql = 'ADD COLUMN '; $sql .= $this->_database->prepareIdentifier($name); $sql .= ' '; $sql .= $column->getDefinition(); $this->alter($sql); // Update column cache $this->_columns[$name] = $column; $this->_columns[$name]->setTable($this); return $this->_columns[$name]; }
[ "public", "function", "addColumnObject", "(", "$", "column", ")", "{", "$", "name", "=", "$", "column", "->", "getName", "(", ")", ";", "$", "this", "->", "forbidColumn", "(", "$", "name", ")", ";", "$", "sql", "=", "'ADD COLUMN '", ";", "$", "sql", ".=", "$", "this", "->", "_database", "->", "prepareIdentifier", "(", "$", "name", ")", ";", "$", "sql", ".=", "' '", ";", "$", "sql", ".=", "$", "column", "->", "getDefinition", "(", ")", ";", "$", "this", "->", "alter", "(", "$", "sql", ")", ";", "// Update column cache", "$", "this", "->", "_columns", "[", "$", "name", "]", "=", "$", "column", ";", "$", "this", "->", "_columns", "[", "$", "name", "]", "->", "setTable", "(", "$", "this", ")", ";", "return", "$", "this", "->", "_columns", "[", "$", "name", "]", ";", "}" ]
Add a column using a column object @param \Nada\Column\AbstractColumn $column Column object @return \Nada\Column\AbstractColumn object describing the generated column
[ "Add", "a", "column", "using", "a", "column", "object" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L387-L404
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.dropColumn
public function dropColumn($name) { $this->requireColumn($name); $this->alter('DROP COLUMN ' . $this->_database->prepareIdentifier($name)); unset($this->_columns[$name]); // Update column cache $this->_updateConstraints($name, null); }
php
public function dropColumn($name) { $this->requireColumn($name); $this->alter('DROP COLUMN ' . $this->_database->prepareIdentifier($name)); unset($this->_columns[$name]); // Update column cache $this->_updateConstraints($name, null); }
[ "public", "function", "dropColumn", "(", "$", "name", ")", "{", "$", "this", "->", "requireColumn", "(", "$", "name", ")", ";", "$", "this", "->", "alter", "(", "'DROP COLUMN '", ".", "$", "this", "->", "_database", "->", "prepareIdentifier", "(", "$", "name", ")", ")", ";", "unset", "(", "$", "this", "->", "_columns", "[", "$", "name", "]", ")", ";", "// Update column cache", "$", "this", "->", "_updateConstraints", "(", "$", "name", ",", "null", ")", ";", "}" ]
Drop a column @param string $name Column name
[ "Drop", "a", "column" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L410-L416
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable._updateConstraints
protected function _updateConstraints($oldColumnName, $newColumnName) { $columnIndex = null; foreach ($this->_primaryKey as $index => $column) { if ($oldColumnName == $column->getName()) { $columnIndex = $index; break; } } if ($columnIndex !== null) { if ($newColumnName) { $this->_primaryKey[$columnIndex] = $this->_columns[$newColumnName]; } else { unset($this->_primaryKey[$columnIndex]); $this->_primaryKey = array_values($this->_primaryKey); } } }
php
protected function _updateConstraints($oldColumnName, $newColumnName) { $columnIndex = null; foreach ($this->_primaryKey as $index => $column) { if ($oldColumnName == $column->getName()) { $columnIndex = $index; break; } } if ($columnIndex !== null) { if ($newColumnName) { $this->_primaryKey[$columnIndex] = $this->_columns[$newColumnName]; } else { unset($this->_primaryKey[$columnIndex]); $this->_primaryKey = array_values($this->_primaryKey); } } }
[ "protected", "function", "_updateConstraints", "(", "$", "oldColumnName", ",", "$", "newColumnName", ")", "{", "$", "columnIndex", "=", "null", ";", "foreach", "(", "$", "this", "->", "_primaryKey", "as", "$", "index", "=>", "$", "column", ")", "{", "if", "(", "$", "oldColumnName", "==", "$", "column", "->", "getName", "(", ")", ")", "{", "$", "columnIndex", "=", "$", "index", ";", "break", ";", "}", "}", "if", "(", "$", "columnIndex", "!==", "null", ")", "{", "if", "(", "$", "newColumnName", ")", "{", "$", "this", "->", "_primaryKey", "[", "$", "columnIndex", "]", "=", "$", "this", "->", "_columns", "[", "$", "newColumnName", "]", ";", "}", "else", "{", "unset", "(", "$", "this", "->", "_primaryKey", "[", "$", "columnIndex", "]", ")", ";", "$", "this", "->", "_primaryKey", "=", "array_values", "(", "$", "this", "->", "_primaryKey", ")", ";", "}", "}", "}" ]
Update constraints after renaming or dropping a column This updates affected column names in all constraints and must be called throm the renameColumn() and dropColumn() implementation. @param string $oldColumnName Column name before renaming/dropping @param string $newColumnName Column name after renaming, NULL for dropped column
[ "Update", "constraints", "after", "renaming", "or", "dropping", "a", "column" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L457-L474
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.hasIndex
public function hasIndex($columns, $unique=false) { if (!is_array($columns)) { $columns = array($columns); } foreach ($this->getIndexes() as $index) { if ($index->isUnique() == $unique and $index->getColumns() == $columns) { return true; } } return false; }
php
public function hasIndex($columns, $unique=false) { if (!is_array($columns)) { $columns = array($columns); } foreach ($this->getIndexes() as $index) { if ($index->isUnique() == $unique and $index->getColumns() == $columns) { return true; } } return false; }
[ "public", "function", "hasIndex", "(", "$", "columns", ",", "$", "unique", "=", "false", ")", "{", "if", "(", "!", "is_array", "(", "$", "columns", ")", ")", "{", "$", "columns", "=", "array", "(", "$", "columns", ")", ";", "}", "foreach", "(", "$", "this", "->", "getIndexes", "(", ")", "as", "$", "index", ")", "{", "if", "(", "$", "index", "->", "isUnique", "(", ")", "==", "$", "unique", "and", "$", "index", "->", "getColumns", "(", ")", "==", "$", "columns", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check for presence of index with given properties, ignoring index name @param mixed $columns Column name or array of column names @param bool $unique Unique index, default: false @return bool
[ "Check", "for", "presence", "of", "index", "with", "given", "properties", "ignoring", "index", "name" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L536-L547
train
hschletz/NADA
src/Table/AbstractTable.php
AbstractTable.toArray
public function toArray($assoc=false) { $data = array( 'name' => $this->_name, 'comment' => $this->getComment(), ); foreach ($this->_columns as $name => $column) { if ($assoc) { $data['columns'][$name] = $column->toArray(); } else { $data['columns'][] = $column->toArray(); } } if (!empty($this->_primaryKey)) { foreach ($this->_primaryKey as $name => $column) { $data['primary_key'][] = $column->getName(); } } foreach ($this->getIndexes() as $name => $index) { if ($assoc) { $data['indexes'][$name] = $index->toArray(); } else { $data['indexes'][] = $index->toArray(); } } return $data; }
php
public function toArray($assoc=false) { $data = array( 'name' => $this->_name, 'comment' => $this->getComment(), ); foreach ($this->_columns as $name => $column) { if ($assoc) { $data['columns'][$name] = $column->toArray(); } else { $data['columns'][] = $column->toArray(); } } if (!empty($this->_primaryKey)) { foreach ($this->_primaryKey as $name => $column) { $data['primary_key'][] = $column->getName(); } } foreach ($this->getIndexes() as $name => $index) { if ($assoc) { $data['indexes'][$name] = $index->toArray(); } else { $data['indexes'][] = $index->toArray(); } } return $data; }
[ "public", "function", "toArray", "(", "$", "assoc", "=", "false", ")", "{", "$", "data", "=", "array", "(", "'name'", "=>", "$", "this", "->", "_name", ",", "'comment'", "=>", "$", "this", "->", "getComment", "(", ")", ",", ")", ";", "foreach", "(", "$", "this", "->", "_columns", "as", "$", "name", "=>", "$", "column", ")", "{", "if", "(", "$", "assoc", ")", "{", "$", "data", "[", "'columns'", "]", "[", "$", "name", "]", "=", "$", "column", "->", "toArray", "(", ")", ";", "}", "else", "{", "$", "data", "[", "'columns'", "]", "[", "]", "=", "$", "column", "->", "toArray", "(", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "_primaryKey", ")", ")", "{", "foreach", "(", "$", "this", "->", "_primaryKey", "as", "$", "name", "=>", "$", "column", ")", "{", "$", "data", "[", "'primary_key'", "]", "[", "]", "=", "$", "column", "->", "getName", "(", ")", ";", "}", "}", "foreach", "(", "$", "this", "->", "getIndexes", "(", ")", "as", "$", "name", "=>", "$", "index", ")", "{", "if", "(", "$", "assoc", ")", "{", "$", "data", "[", "'indexes'", "]", "[", "$", "name", "]", "=", "$", "index", "->", "toArray", "(", ")", ";", "}", "else", "{", "$", "data", "[", "'indexes'", "]", "[", "]", "=", "$", "index", "->", "toArray", "(", ")", ";", "}", "}", "return", "$", "data", ";", "}" ]
Export table data to an associative array The returned array has the following elements: - **name**: the table name - **columns**: array of columns (numeric or associative, depending on $assoc). See \Nada\Column\AbstractColumn::toArray() for a description of keys. - **primary_key**: array of column names for primary key - **indexes**: array of indexes (numeric or associative, depending on $assoc). See \Nada\Index::toArray() for a description of keys. - **mysql**: (MySQL only) array with MySQL-specific data: - **engine**: table engine @param bool $assoc @return array
[ "Export", "table", "data", "to", "an", "associative", "array" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Table/AbstractTable.php#L567-L593
train
ScaraMVC/Framework
src/Scara/Utils/UrlGenerator.php
UrlGenerator.to
public function to($url) { if ($url == '/' && $this->getRoot() == $url) { return $url; } return $this->isValidUrl($url) ? $url : $this->generateUrl($url); }
php
public function to($url) { if ($url == '/' && $this->getRoot() == $url) { return $url; } return $this->isValidUrl($url) ? $url : $this->generateUrl($url); }
[ "public", "function", "to", "(", "$", "url", ")", "{", "if", "(", "$", "url", "==", "'/'", "&&", "$", "this", "->", "getRoot", "(", ")", "==", "$", "url", ")", "{", "return", "$", "url", ";", "}", "return", "$", "this", "->", "isValidUrl", "(", "$", "url", ")", "?", "$", "url", ":", "$", "this", "->", "generateUrl", "(", "$", "url", ")", ";", "}" ]
Generates a URL useful for anchor tags. @param string $url - URL to generate from @return string
[ "Generates", "a", "URL", "useful", "for", "anchor", "tags", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Utils/UrlGenerator.php#L57-L64
train
ScaraMVC/Framework
src/Scara/Utils/UrlGenerator.php
UrlGenerator.redirect
public function redirect($url) { if (!$this->isValidUrl($url)) { $url = $this->generateUrl($url); } header('Location: '.$url); }
php
public function redirect($url) { if (!$this->isValidUrl($url)) { $url = $this->generateUrl($url); } header('Location: '.$url); }
[ "public", "function", "redirect", "(", "$", "url", ")", "{", "if", "(", "!", "$", "this", "->", "isValidUrl", "(", "$", "url", ")", ")", "{", "$", "url", "=", "$", "this", "->", "generateUrl", "(", "$", "url", ")", ";", "}", "header", "(", "'Location: '", ".", "$", "url", ")", ";", "}" ]
Redirect to given URL. @param string $url - URL to generate from @return void
[ "Redirect", "to", "given", "URL", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Utils/UrlGenerator.php#L73-L80
train
ScaraMVC/Framework
src/Scara/Utils/UrlGenerator.php
UrlGenerator.generateUrl
public function generateUrl($url) { $extern = false; if ((0 === strrpos($url, 'http://')) || (0 === strrpos($url, 'https://'))) { $extern = true; } $http = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://'; if (!$extern) { return ($this->getRoot() == '/') ? (($this->getRoot() == $url) ? '' : $url) : $http.$_SERVER['SERVER_NAME'].$this->getRoot().$url; } else { return $url; } }
php
public function generateUrl($url) { $extern = false; if ((0 === strrpos($url, 'http://')) || (0 === strrpos($url, 'https://'))) { $extern = true; } $http = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://'; if (!$extern) { return ($this->getRoot() == '/') ? (($this->getRoot() == $url) ? '' : $url) : $http.$_SERVER['SERVER_NAME'].$this->getRoot().$url; } else { return $url; } }
[ "public", "function", "generateUrl", "(", "$", "url", ")", "{", "$", "extern", "=", "false", ";", "if", "(", "(", "0", "===", "strrpos", "(", "$", "url", ",", "'http://'", ")", ")", "||", "(", "0", "===", "strrpos", "(", "$", "url", ",", "'https://'", ")", ")", ")", "{", "$", "extern", "=", "true", ";", "}", "$", "http", "=", "(", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", ")", "?", "'https://'", ":", "'http://'", ";", "if", "(", "!", "$", "extern", ")", "{", "return", "(", "$", "this", "->", "getRoot", "(", ")", "==", "'/'", ")", "?", "(", "(", "$", "this", "->", "getRoot", "(", ")", "==", "$", "url", ")", "?", "''", ":", "$", "url", ")", ":", "$", "http", ".", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ".", "$", "this", "->", "getRoot", "(", ")", ".", "$", "url", ";", "}", "else", "{", "return", "$", "url", ";", "}", "}" ]
Used to generate a URL based on relative or absolute. @param string $url - URL to generate from @return string
[ "Used", "to", "generate", "a", "URL", "based", "on", "relative", "or", "absolute", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Utils/UrlGenerator.php#L89-L105
train
t-kanstantsin/fileupload
src/formatter/ImagineFactory.php
ImagineFactory.get
public static function get(string $type): ImagineInterface { switch ($type) { case self::GD: return new GdImagine(); case self::IMAGICK: return new ImagickImagine(); case self::GMAGICK: return new GmagickImagine(); default: throw new InvalidConfigException(sprintf('Image driver %s not found.', $type)); } }
php
public static function get(string $type): ImagineInterface { switch ($type) { case self::GD: return new GdImagine(); case self::IMAGICK: return new ImagickImagine(); case self::GMAGICK: return new GmagickImagine(); default: throw new InvalidConfigException(sprintf('Image driver %s not found.', $type)); } }
[ "public", "static", "function", "get", "(", "string", "$", "type", ")", ":", "ImagineInterface", "{", "switch", "(", "$", "type", ")", "{", "case", "self", "::", "GD", ":", "return", "new", "GdImagine", "(", ")", ";", "case", "self", "::", "IMAGICK", ":", "return", "new", "ImagickImagine", "(", ")", ";", "case", "self", "::", "GMAGICK", ":", "return", "new", "GmagickImagine", "(", ")", ";", "default", ":", "throw", "new", "InvalidConfigException", "(", "sprintf", "(", "'Image driver %s not found.'", ",", "$", "type", ")", ")", ";", "}", "}" ]
Create imagine object for given driver @param string $type @return ImagineInterface @throws \Imagine\Exception\RuntimeException @throws InvalidConfigException
[ "Create", "imagine", "object", "for", "given", "driver" ]
d6317a9b9b36d992f09affe3900ef7d7ddfd855f
https://github.com/t-kanstantsin/fileupload/blob/d6317a9b9b36d992f09affe3900ef7d7ddfd855f/src/formatter/ImagineFactory.php#L30-L42
train
wearenolte/wp-acf
src/Acf/Transforms/Image.php
Image.get_image_fields
public static function get_image_fields( $field, $attachment_id, $sub_field = false ) { $size = apply_filters( Filter::IMAGE, false, $field, $sub_field ); if ( ! $size ) { return $attachment_id; } $src = wp_get_attachment_image_src( $attachment_id, $size ); if ( ! $src ) { return $attachment_id; } return [ 'src' => $src[0], 'width' => $src[1], 'height' => $src[2], 'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), ]; }
php
public static function get_image_fields( $field, $attachment_id, $sub_field = false ) { $size = apply_filters( Filter::IMAGE, false, $field, $sub_field ); if ( ! $size ) { return $attachment_id; } $src = wp_get_attachment_image_src( $attachment_id, $size ); if ( ! $src ) { return $attachment_id; } return [ 'src' => $src[0], 'width' => $src[1], 'height' => $src[2], 'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), ]; }
[ "public", "static", "function", "get_image_fields", "(", "$", "field", ",", "$", "attachment_id", ",", "$", "sub_field", "=", "false", ")", "{", "$", "size", "=", "apply_filters", "(", "Filter", "::", "IMAGE", ",", "false", ",", "$", "field", ",", "$", "sub_field", ")", ";", "if", "(", "!", "$", "size", ")", "{", "return", "$", "attachment_id", ";", "}", "$", "src", "=", "wp_get_attachment_image_src", "(", "$", "attachment_id", ",", "$", "size", ")", ";", "if", "(", "!", "$", "src", ")", "{", "return", "$", "attachment_id", ";", "}", "return", "[", "'src'", "=>", "$", "src", "[", "0", "]", ",", "'width'", "=>", "$", "src", "[", "1", "]", ",", "'height'", "=>", "$", "src", "[", "2", "]", ",", "'alt'", "=>", "get_post_meta", "(", "$", "attachment_id", ",", "'_wp_attachment_image_alt'", ",", "true", ")", ",", "]", ";", "}" ]
Get image fields. @param string $field Field @param int $attachment_id The image id. @param bool $sub_field Sub field (only if it's a repeater) @return array
[ "Get", "image", "fields", "." ]
2f5093438d637fa0eca42ad6d10f6b433ec078b2
https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf/Transforms/Image.php#L43-L62
train
mamasu/mama-parameter
src/parameter/Session.php
Session.setFlashVar
public function setFlashVar($key, $value) { $this->flashVar[$key] = $value; $this->set($key, $value); }
php
public function setFlashVar($key, $value) { $this->flashVar[$key] = $value; $this->set($key, $value); }
[ "public", "function", "setFlashVar", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "flashVar", "[", "$", "key", "]", "=", "$", "value", ";", "$", "this", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}" ]
Set session var that is only valid for only one request. @param string $key @param mixed $value
[ "Set", "session", "var", "that", "is", "only", "valid", "for", "only", "one", "request", "." ]
d48529a75d471da2f9f80b9c2ea1fc3d57f0ba4d
https://github.com/mamasu/mama-parameter/blob/d48529a75d471da2f9f80b9c2ea1fc3d57f0ba4d/src/parameter/Session.php#L47-L50
train
mamasu/mama-parameter
src/parameter/Session.php
Session.removeFlashVar
public function removeFlashVar() { foreach ($this->flashVar as $key => $value) { unset($this->storage[$key]); } $this->flashVar = array(); }
php
public function removeFlashVar() { foreach ($this->flashVar as $key => $value) { unset($this->storage[$key]); } $this->flashVar = array(); }
[ "public", "function", "removeFlashVar", "(", ")", "{", "foreach", "(", "$", "this", "->", "flashVar", "as", "$", "key", "=>", "$", "value", ")", "{", "unset", "(", "$", "this", "->", "storage", "[", "$", "key", "]", ")", ";", "}", "$", "this", "->", "flashVar", "=", "array", "(", ")", ";", "}" ]
Remove the FlashVars and the respective vars in the storage var.
[ "Remove", "the", "FlashVars", "and", "the", "respective", "vars", "in", "the", "storage", "var", "." ]
d48529a75d471da2f9f80b9c2ea1fc3d57f0ba4d
https://github.com/mamasu/mama-parameter/blob/d48529a75d471da2f9f80b9c2ea1fc3d57f0ba4d/src/parameter/Session.php#L55-L60
train
devlabmtl/haven-core
Entity/File/File.php
File.moveToPermanent
public function moveToPermanent() { // to keep the save as it is, I need to get the path without the filename and also remove the /tmp $destination_path = str_replace($this->getFileName(), '', $this->getPathName()); // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error if (null !== $this->getPathName() && $this->getPathName() != $this->prePersistName) { $this->move($destination_path); } }
php
public function moveToPermanent() { // to keep the save as it is, I need to get the path without the filename and also remove the /tmp $destination_path = str_replace($this->getFileName(), '', $this->getPathName()); // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error if (null !== $this->getPathName() && $this->getPathName() != $this->prePersistName) { $this->move($destination_path); } }
[ "public", "function", "moveToPermanent", "(", ")", "{", "// to keep the save as it is, I need to get the path without the filename and also remove the /tmp", "$", "destination_path", "=", "str_replace", "(", "$", "this", "->", "getFileName", "(", ")", ",", "''", ",", "$", "this", "->", "getPathName", "(", ")", ")", ";", "// if there is an error when moving the file, an exception will", "// be automatically thrown by move(). This will properly prevent", "// the entity from being persisted to the database on error", "if", "(", "null", "!==", "$", "this", "->", "getPathName", "(", ")", "&&", "$", "this", "->", "getPathName", "(", ")", "!=", "$", "this", "->", "prePersistName", ")", "{", "$", "this", "->", "move", "(", "$", "destination_path", ")", ";", "}", "}" ]
When the file persists, if it is in the tmp subdir, it will be move before save. @ORM\PostPersist() @ORM\PostUpdate()
[ "When", "the", "file", "persists", "if", "it", "is", "in", "the", "tmp", "subdir", "it", "will", "be", "move", "before", "save", "." ]
f13410f996fd4002efafe482b927adadb211dec8
https://github.com/devlabmtl/haven-core/blob/f13410f996fd4002efafe482b927adadb211dec8/Entity/File/File.php#L209-L218
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/dispatcher/View.php
View.getRedirect
public function getRedirect() { if (!$this->isRedirect()) return null; if ($this->isPermanentRedirect()) return substr($this->name, 19); return substr($this->name, 9); }
php
public function getRedirect() { if (!$this->isRedirect()) return null; if ($this->isPermanentRedirect()) return substr($this->name, 19); return substr($this->name, 9); }
[ "public", "function", "getRedirect", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isRedirect", "(", ")", ")", "return", "null", ";", "if", "(", "$", "this", "->", "isPermanentRedirect", "(", ")", ")", "return", "substr", "(", "$", "this", "->", "name", ",", "19", ")", ";", "return", "substr", "(", "$", "this", "->", "name", ",", "9", ")", ";", "}" ]
Returns the redirect value for this view, providing it's a redirect @return string
[ "Returns", "the", "redirect", "value", "for", "this", "view", "providing", "it", "s", "a", "redirect" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/dispatcher/View.php#L123-L132
train
OxfordInfoLabs/kinikit-core
src/Util/Serialisation/XML/XMLToObjectConverter.php
XMLToObjectConverter.convert
public function convert($xmlString) { $dom = new \DOMDocument (); $dom->loadXML($xmlString); $documentElement = $dom->documentElement; return $documentElement ? $this->convertDOM($dom->documentElement) : $xmlString; }
php
public function convert($xmlString) { $dom = new \DOMDocument (); $dom->loadXML($xmlString); $documentElement = $dom->documentElement; return $documentElement ? $this->convertDOM($dom->documentElement) : $xmlString; }
[ "public", "function", "convert", "(", "$", "xmlString", ")", "{", "$", "dom", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "dom", "->", "loadXML", "(", "$", "xmlString", ")", ";", "$", "documentElement", "=", "$", "dom", "->", "documentElement", ";", "return", "$", "documentElement", "?", "$", "this", "->", "convertDOM", "(", "$", "dom", "->", "documentElement", ")", ":", "$", "xmlString", ";", "}" ]
Main conversion API method to convert an XML string into an object tree. @param unknown_type $xmlString
[ "Main", "conversion", "API", "method", "to", "convert", "an", "XML", "string", "into", "an", "object", "tree", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/Serialisation/XML/XMLToObjectConverter.php#L67-L74
train
zapheus/zapheus
src/Http/Message/File.php
File.stream
public function stream() { $stream = fopen($this->file, 'r'); $stream = $stream === false ? null : $stream; return new Stream($stream); }
php
public function stream() { $stream = fopen($this->file, 'r'); $stream = $stream === false ? null : $stream; return new Stream($stream); }
[ "public", "function", "stream", "(", ")", "{", "$", "stream", "=", "fopen", "(", "$", "this", "->", "file", ",", "'r'", ")", ";", "$", "stream", "=", "$", "stream", "===", "false", "?", "null", ":", "$", "stream", ";", "return", "new", "Stream", "(", "$", "stream", ")", ";", "}" ]
Returns a stream representing the uploaded file. @return \Zapheus\Http\Message\StreamInterface @throws \RuntimeException
[ "Returns", "a", "stream", "representing", "the", "uploaded", "file", "." ]
96618b5cee7d20b6700d0475e4334ae4b5163a6b
https://github.com/zapheus/zapheus/blob/96618b5cee7d20b6700d0475e4334ae4b5163a6b/src/Http/Message/File.php#L118-L125
train
Game-scan/Core
src/Request/Api/Http/Client.php
Client.getConfig
protected function getConfig() { $config = array(); $config['headers'] = $this->headers; $config['config'] = array( 'curl' => $this->curlConfig ); $config['query'] = $this->parameters; $config['cookies'] = true; return $config; }
php
protected function getConfig() { $config = array(); $config['headers'] = $this->headers; $config['config'] = array( 'curl' => $this->curlConfig ); $config['query'] = $this->parameters; $config['cookies'] = true; return $config; }
[ "protected", "function", "getConfig", "(", ")", "{", "$", "config", "=", "array", "(", ")", ";", "$", "config", "[", "'headers'", "]", "=", "$", "this", "->", "headers", ";", "$", "config", "[", "'config'", "]", "=", "array", "(", "'curl'", "=>", "$", "this", "->", "curlConfig", ")", ";", "$", "config", "[", "'query'", "]", "=", "$", "this", "->", "parameters", ";", "$", "config", "[", "'cookies'", "]", "=", "true", ";", "return", "$", "config", ";", "}" ]
Get http request config for guzzle @return array
[ "Get", "http", "request", "config", "for", "guzzle" ]
777652235678bbd9c3ea20344b998a01359339bd
https://github.com/Game-scan/Core/blob/777652235678bbd9c3ea20344b998a01359339bd/src/Request/Api/Http/Client.php#L96-L106
train
itkg/core
src/Itkg/Core/Command/Formatter/CommandLineFormatter.php
CommandLineFormatter.formatException
public function formatException(\Exception $exception, array $record = array()) { $record['msg'] = $this->normalizeException($exception); return $this->format($record); }
php
public function formatException(\Exception $exception, array $record = array()) { $record['msg'] = $this->normalizeException($exception); return $this->format($record); }
[ "public", "function", "formatException", "(", "\\", "Exception", "$", "exception", ",", "array", "$", "record", "=", "array", "(", ")", ")", "{", "$", "record", "[", "'msg'", "]", "=", "$", "this", "->", "normalizeException", "(", "$", "exception", ")", ";", "return", "$", "this", "->", "format", "(", "$", "record", ")", ";", "}" ]
Format exception with normalizer And replace msg record with formatted exception @param \Exception $exception @param array $record @return array|mixed|string
[ "Format", "exception", "with", "normalizer", "And", "replace", "msg", "record", "with", "formatted", "exception" ]
e5e4efb05feb4d23b0df41f2b21fd095103e593b
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Command/Formatter/CommandLineFormatter.php#L33-L38
train
cubicmushroom/valueobjects
src/Structure/KeyValuePair.php
KeyValuePair.fromNative
public static function fromNative() { $args = func_get_args(); if (count($args) != 2) { throw new \BadMethodCallException('This methods expects two arguments. One for the key and one for the value.'); } $keyString = \strval($args[0]); $valueString = \strval($args[1]); $key = new StringLiteral($keyString); $value = new StringLiteral($valueString); return new self($key, $value); }
php
public static function fromNative() { $args = func_get_args(); if (count($args) != 2) { throw new \BadMethodCallException('This methods expects two arguments. One for the key and one for the value.'); } $keyString = \strval($args[0]); $valueString = \strval($args[1]); $key = new StringLiteral($keyString); $value = new StringLiteral($valueString); return new self($key, $value); }
[ "public", "static", "function", "fromNative", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "if", "(", "count", "(", "$", "args", ")", "!=", "2", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'This methods expects two arguments. One for the key and one for the value.'", ")", ";", "}", "$", "keyString", "=", "\\", "strval", "(", "$", "args", "[", "0", "]", ")", ";", "$", "valueString", "=", "\\", "strval", "(", "$", "args", "[", "1", "]", ")", ";", "$", "key", "=", "new", "StringLiteral", "(", "$", "keyString", ")", ";", "$", "value", "=", "new", "StringLiteral", "(", "$", "valueString", ")", ";", "return", "new", "self", "(", "$", "key", ",", "$", "value", ")", ";", "}" ]
Returns a KeyValuePair from native PHP arguments evaluated as strings @param string $key @param string $value @return self @throws \InvalidArgumentException
[ "Returns", "a", "KeyValuePair", "from", "native", "PHP", "arguments", "evaluated", "as", "strings" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Structure/KeyValuePair.php#L25-L39
train
cubicmushroom/valueobjects
src/Structure/KeyValuePair.php
KeyValuePair.sameValueAs
public function sameValueAs(ValueObjectInterface $keyValuePair) { if (false === Util::classEquals($this, $keyValuePair)) { return false; } return $this->getKey()->sameValueAs($keyValuePair->getKey()) && $this->getValue()->sameValueAs($keyValuePair->getValue()); }
php
public function sameValueAs(ValueObjectInterface $keyValuePair) { if (false === Util::classEquals($this, $keyValuePair)) { return false; } return $this->getKey()->sameValueAs($keyValuePair->getKey()) && $this->getValue()->sameValueAs($keyValuePair->getValue()); }
[ "public", "function", "sameValueAs", "(", "ValueObjectInterface", "$", "keyValuePair", ")", "{", "if", "(", "false", "===", "Util", "::", "classEquals", "(", "$", "this", ",", "$", "keyValuePair", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "getKey", "(", ")", "->", "sameValueAs", "(", "$", "keyValuePair", "->", "getKey", "(", ")", ")", "&&", "$", "this", "->", "getValue", "(", ")", "->", "sameValueAs", "(", "$", "keyValuePair", "->", "getValue", "(", ")", ")", ";", "}" ]
Tells whether two KeyValuePair are equal @param ValueObjectInterface $keyValuePair @return bool
[ "Tells", "whether", "two", "KeyValuePair", "are", "equal" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Structure/KeyValuePair.php#L59-L66
train
Retentio/Boomgo
src/Boomgo/Builder/Definition.php
Definition.fromArray
private function fromArray(array $metadata) { // @TODO Throw exception if mandatory parameters Attribute & Key are missing !! $defaults = array('type' => 'mixed', 'mappedClass' => null); $data = array_merge($defaults, $metadata); $type = $data['type']; $mappedClass = $data['mappedClass']; $isSupported = isset(static::$supportedTypes[$type]); if ($isSupported && 'composite' === static::$supportedTypes[$type] && !empty($mappedClass)) { // Embedded collection: type => array, mappedClass => FQDN if (!static::isValidNamespace($mappedClass)) { throw new \InvalidArgumentException(sprintf('Mapped class "%s" is not a valid FQDN', $mappedClass)); } // Set the mapping type & prepend a \ on the mapped FQDN $this->mappedType = Definition::COLLECTION; $this->mappedClass = (strpos($mappedClass, '\\') === 0) ? $mappedClass : '\\'.$mappedClass; } elseif (!$isSupported) { // Embedded document: type => FQDN if (!static::isValidNamespace($type)) { throw new \InvalidArgumentException(sprintf('User type "%s" is not a valid FQDN', $type)); } // Set the mapping type & prepend a \ on the mapped FQDN $this->mappedType = Definition::DOCUMENT; $this->mappedClass = $type = (strpos($type, '\\') === 0) ? $type : '\\'.$type; } $this->type = $type; $this->attribute = $data['attribute']; $this->key = $data['key']; $this->accessor = $data['accessor']; $this->mutator = $data['mutator']; }
php
private function fromArray(array $metadata) { // @TODO Throw exception if mandatory parameters Attribute & Key are missing !! $defaults = array('type' => 'mixed', 'mappedClass' => null); $data = array_merge($defaults, $metadata); $type = $data['type']; $mappedClass = $data['mappedClass']; $isSupported = isset(static::$supportedTypes[$type]); if ($isSupported && 'composite' === static::$supportedTypes[$type] && !empty($mappedClass)) { // Embedded collection: type => array, mappedClass => FQDN if (!static::isValidNamespace($mappedClass)) { throw new \InvalidArgumentException(sprintf('Mapped class "%s" is not a valid FQDN', $mappedClass)); } // Set the mapping type & prepend a \ on the mapped FQDN $this->mappedType = Definition::COLLECTION; $this->mappedClass = (strpos($mappedClass, '\\') === 0) ? $mappedClass : '\\'.$mappedClass; } elseif (!$isSupported) { // Embedded document: type => FQDN if (!static::isValidNamespace($type)) { throw new \InvalidArgumentException(sprintf('User type "%s" is not a valid FQDN', $type)); } // Set the mapping type & prepend a \ on the mapped FQDN $this->mappedType = Definition::DOCUMENT; $this->mappedClass = $type = (strpos($type, '\\') === 0) ? $type : '\\'.$type; } $this->type = $type; $this->attribute = $data['attribute']; $this->key = $data['key']; $this->accessor = $data['accessor']; $this->mutator = $data['mutator']; }
[ "private", "function", "fromArray", "(", "array", "$", "metadata", ")", "{", "// @TODO Throw exception if mandatory parameters Attribute & Key are missing !!", "$", "defaults", "=", "array", "(", "'type'", "=>", "'mixed'", ",", "'mappedClass'", "=>", "null", ")", ";", "$", "data", "=", "array_merge", "(", "$", "defaults", ",", "$", "metadata", ")", ";", "$", "type", "=", "$", "data", "[", "'type'", "]", ";", "$", "mappedClass", "=", "$", "data", "[", "'mappedClass'", "]", ";", "$", "isSupported", "=", "isset", "(", "static", "::", "$", "supportedTypes", "[", "$", "type", "]", ")", ";", "if", "(", "$", "isSupported", "&&", "'composite'", "===", "static", "::", "$", "supportedTypes", "[", "$", "type", "]", "&&", "!", "empty", "(", "$", "mappedClass", ")", ")", "{", "// Embedded collection: type => array, mappedClass => FQDN", "if", "(", "!", "static", "::", "isValidNamespace", "(", "$", "mappedClass", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Mapped class \"%s\" is not a valid FQDN'", ",", "$", "mappedClass", ")", ")", ";", "}", "// Set the mapping type & prepend a \\ on the mapped FQDN", "$", "this", "->", "mappedType", "=", "Definition", "::", "COLLECTION", ";", "$", "this", "->", "mappedClass", "=", "(", "strpos", "(", "$", "mappedClass", ",", "'\\\\'", ")", "===", "0", ")", "?", "$", "mappedClass", ":", "'\\\\'", ".", "$", "mappedClass", ";", "}", "elseif", "(", "!", "$", "isSupported", ")", "{", "// Embedded document: type => FQDN", "if", "(", "!", "static", "::", "isValidNamespace", "(", "$", "type", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'User type \"%s\" is not a valid FQDN'", ",", "$", "type", ")", ")", ";", "}", "// Set the mapping type & prepend a \\ on the mapped FQDN", "$", "this", "->", "mappedType", "=", "Definition", "::", "DOCUMENT", ";", "$", "this", "->", "mappedClass", "=", "$", "type", "=", "(", "strpos", "(", "$", "type", ",", "'\\\\'", ")", "===", "0", ")", "?", "$", "type", ":", "'\\\\'", ".", "$", "type", ";", "}", "$", "this", "->", "type", "=", "$", "type", ";", "$", "this", "->", "attribute", "=", "$", "data", "[", "'attribute'", "]", ";", "$", "this", "->", "key", "=", "$", "data", "[", "'key'", "]", ";", "$", "this", "->", "accessor", "=", "$", "data", "[", "'accessor'", "]", ";", "$", "this", "->", "mutator", "=", "$", "data", "[", "'mutator'", "]", ";", "}" ]
Import an array of metadata @param array $metadata @return void
[ "Import", "an", "array", "of", "metadata" ]
95cc53777425dd76cd0034046fa4f9e72c04d73a
https://github.com/Retentio/Boomgo/blob/95cc53777425dd76cd0034046fa4f9e72c04d73a/src/Boomgo/Builder/Definition.php#L283-L323
train
phossa/phossa-route
src/Phossa/Route/Collector/Collector.php
Collector.filtering
protected function filtering( RouteInterface $route, RequestInterface $request ) { foreach ($route->getFilters() as $field => $filter) { list($grpName, $keyName) = explode('.', $field, 2); switch ($grpName) { case 'session': $against = isset($_SESSION[$keyName]) ? $_SESSION[$keyName] : ''; break; case 'cookie': $against = isset($_COOKIE[$keyName]) ? $_COOKIE[$keyName] : ''; break; case 'request': $against = $request->getRequestInfo($keyName); break; default: $against = $request->getServerInfo($keyName); break; } if (is_callable($filter)) { return $filter((string) $against); } elseif (!preg_match('~'.$filter.'~x', (string) $against)) { return false; } } return true; }
php
protected function filtering( RouteInterface $route, RequestInterface $request ) { foreach ($route->getFilters() as $field => $filter) { list($grpName, $keyName) = explode('.', $field, 2); switch ($grpName) { case 'session': $against = isset($_SESSION[$keyName]) ? $_SESSION[$keyName] : ''; break; case 'cookie': $against = isset($_COOKIE[$keyName]) ? $_COOKIE[$keyName] : ''; break; case 'request': $against = $request->getRequestInfo($keyName); break; default: $against = $request->getServerInfo($keyName); break; } if (is_callable($filter)) { return $filter((string) $against); } elseif (!preg_match('~'.$filter.'~x', (string) $against)) { return false; } } return true; }
[ "protected", "function", "filtering", "(", "RouteInterface", "$", "route", ",", "RequestInterface", "$", "request", ")", "{", "foreach", "(", "$", "route", "->", "getFilters", "(", ")", "as", "$", "field", "=>", "$", "filter", ")", "{", "list", "(", "$", "grpName", ",", "$", "keyName", ")", "=", "explode", "(", "'.'", ",", "$", "field", ",", "2", ")", ";", "switch", "(", "$", "grpName", ")", "{", "case", "'session'", ":", "$", "against", "=", "isset", "(", "$", "_SESSION", "[", "$", "keyName", "]", ")", "?", "$", "_SESSION", "[", "$", "keyName", "]", ":", "''", ";", "break", ";", "case", "'cookie'", ":", "$", "against", "=", "isset", "(", "$", "_COOKIE", "[", "$", "keyName", "]", ")", "?", "$", "_COOKIE", "[", "$", "keyName", "]", ":", "''", ";", "break", ";", "case", "'request'", ":", "$", "against", "=", "$", "request", "->", "getRequestInfo", "(", "$", "keyName", ")", ";", "break", ";", "default", ":", "$", "against", "=", "$", "request", "->", "getServerInfo", "(", "$", "keyName", ")", ";", "break", ";", "}", "if", "(", "is_callable", "(", "$", "filter", ")", ")", "{", "return", "$", "filter", "(", "(", "string", ")", "$", "against", ")", ";", "}", "elseif", "(", "!", "preg_match", "(", "'~'", ".", "$", "filter", ".", "'~x'", ",", "(", "string", ")", "$", "against", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Filtering in route @param RouteInterface $route @param RequestInterface $request @return bool @access protected
[ "Filtering", "in", "route" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Collector/Collector.php#L207-L237
train
freialib/hlin.tools
src/Response.php
Response.responseCode
function responseCode($code = null) { if ($code === null) { return $this->http_response_code; } else { // $code !== null, act as setter $this->http_response_code = $code; return $this; } }
php
function responseCode($code = null) { if ($code === null) { return $this->http_response_code; } else { // $code !== null, act as setter $this->http_response_code = $code; return $this; } }
[ "function", "responseCode", "(", "$", "code", "=", "null", ")", "{", "if", "(", "$", "code", "===", "null", ")", "{", "return", "$", "this", "->", "http_response_code", ";", "}", "else", "{", "// $code !== null, act as setter", "$", "this", "->", "http_response_code", "=", "$", "code", ";", "return", "$", "this", ";", "}", "}" ]
Equivalent in functionality to http_response_code from PHP @see http://www.php.net/manual/en/function.http-response-code.php @return static $this
[ "Equivalent", "in", "functionality", "to", "http_response_code", "from", "PHP" ]
42ad9e9fe081918d2ee5d52b72d174ccdcf7cbe7
https://github.com/freialib/hlin.tools/blob/42ad9e9fe081918d2ee5d52b72d174ccdcf7cbe7/src/Response.php#L25-L33
train
bseddon/XPath20
Proxy/FloatProxy.php
FloatProxy.getOtherValue
private function getOtherValue( $val ) { /** * @var XPath2Item $otherValue */ $otherValue = $val->getValue(); return $otherValue instanceof XPath2Item ? $otherValue->getValue() : $otherValue; }
php
private function getOtherValue( $val ) { /** * @var XPath2Item $otherValue */ $otherValue = $val->getValue(); return $otherValue instanceof XPath2Item ? $otherValue->getValue() : $otherValue; }
[ "private", "function", "getOtherValue", "(", "$", "val", ")", "{", "/**\r\n\t\t * @var XPath2Item $otherValue\r\n\t\t */", "$", "otherValue", "=", "$", "val", "->", "getValue", "(", ")", ";", "return", "$", "otherValue", "instanceof", "XPath2Item", "?", "$", "otherValue", "->", "getValue", "(", ")", ":", "$", "otherValue", ";", "}" ]
Convert an XPath2Item value to a native float or return the original value @param FloatProxy $val @return float
[ "Convert", "an", "XPath2Item", "value", "to", "a", "native", "float", "or", "return", "the", "original", "value" ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Proxy/FloatProxy.php#L125-L134
train
phossa/phossa-route
src/Phossa/Route/Dispatcher.php
Dispatcher.addGet
public function addGet( /*# string */ $pathPattern, $handler = null, array $defaultValues = [] ) { $this->getCollectors()[0]->addGet( $pathPattern, $handler, $defaultValues ); return $this; }
php
public function addGet( /*# string */ $pathPattern, $handler = null, array $defaultValues = [] ) { $this->getCollectors()[0]->addGet( $pathPattern, $handler, $defaultValues ); return $this; }
[ "public", "function", "addGet", "(", "/*# string */", "$", "pathPattern", ",", "$", "handler", "=", "null", ",", "array", "$", "defaultValues", "=", "[", "]", ")", "{", "$", "this", "->", "getCollectors", "(", ")", "[", "0", "]", "->", "addGet", "(", "$", "pathPattern", ",", "$", "handler", ",", "$", "defaultValues", ")", ";", "return", "$", "this", ";", "}" ]
Add a 'GET,HEAD' route to the first collector {@inheritDoc}
[ "Add", "a", "GET", "HEAD", "route", "to", "the", "first", "collector" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Dispatcher.php#L191-L202
train
phossa/phossa-route
src/Phossa/Route/Dispatcher.php
Dispatcher.addPost
public function addPost( /*# string */ $pathPattern, $handler = null, array $defaultValues = [] ) { $this->getCollectors()[0]->addPost( $pathPattern, $handler, $defaultValues ); return $this; }
php
public function addPost( /*# string */ $pathPattern, $handler = null, array $defaultValues = [] ) { $this->getCollectors()[0]->addPost( $pathPattern, $handler, $defaultValues ); return $this; }
[ "public", "function", "addPost", "(", "/*# string */", "$", "pathPattern", ",", "$", "handler", "=", "null", ",", "array", "$", "defaultValues", "=", "[", "]", ")", "{", "$", "this", "->", "getCollectors", "(", ")", "[", "0", "]", "->", "addPost", "(", "$", "pathPattern", ",", "$", "handler", ",", "$", "defaultValues", ")", ";", "return", "$", "this", ";", "}" ]
Add a 'POST' route to the first collector {@inheritDoc}
[ "Add", "a", "POST", "route", "to", "the", "first", "collector" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Dispatcher.php#L209-L220
train
phossa/phossa-route
src/Phossa/Route/Dispatcher.php
Dispatcher.matchRoute
protected function matchRoute()/*# : bool */ { foreach ($this->getCollectors() as $coll) { if ($coll->matchRoute($this->result)) { return true; } } return false; }
php
protected function matchRoute()/*# : bool */ { foreach ($this->getCollectors() as $coll) { if ($coll->matchRoute($this->result)) { return true; } } return false; }
[ "protected", "function", "matchRoute", "(", ")", "/*# : bool */", "{", "foreach", "(", "$", "this", "->", "getCollectors", "(", ")", "as", "$", "coll", ")", "{", "if", "(", "$", "coll", "->", "matchRoute", "(", "$", "this", "->", "result", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Match routes in collectors @return bool @access protected
[ "Match", "routes", "in", "collectors" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Dispatcher.php#L228-L236
train
phossa/phossa-route
src/Phossa/Route/Dispatcher.php
Dispatcher.executeHandler
protected function executeHandler()/*# : bool */ { // search handler $handler = $this->result->getHandler(); if (is_null($handler)) { // matched, but no handler found return $this->defaultHandler(); } else { $callable = $this->resolver->resolve($handler); // extension ? if (($route = $this->result->getRoute()) && $route->hasExtension()) { if ($route->runExtensions(Route::BEFORE_ROUTE, $this->result)) { $callable($this->result); $route->runExtensions(Route::AFTER_ROUTE, $this->result); } } else { $callable($this->result); } return true; } }
php
protected function executeHandler()/*# : bool */ { // search handler $handler = $this->result->getHandler(); if (is_null($handler)) { // matched, but no handler found return $this->defaultHandler(); } else { $callable = $this->resolver->resolve($handler); // extension ? if (($route = $this->result->getRoute()) && $route->hasExtension()) { if ($route->runExtensions(Route::BEFORE_ROUTE, $this->result)) { $callable($this->result); $route->runExtensions(Route::AFTER_ROUTE, $this->result); } } else { $callable($this->result); } return true; } }
[ "protected", "function", "executeHandler", "(", ")", "/*# : bool */", "{", "// search handler", "$", "handler", "=", "$", "this", "->", "result", "->", "getHandler", "(", ")", ";", "if", "(", "is_null", "(", "$", "handler", ")", ")", "{", "// matched, but no handler found", "return", "$", "this", "->", "defaultHandler", "(", ")", ";", "}", "else", "{", "$", "callable", "=", "$", "this", "->", "resolver", "->", "resolve", "(", "$", "handler", ")", ";", "// extension ?", "if", "(", "(", "$", "route", "=", "$", "this", "->", "result", "->", "getRoute", "(", ")", ")", "&&", "$", "route", "->", "hasExtension", "(", ")", ")", "{", "if", "(", "$", "route", "->", "runExtensions", "(", "Route", "::", "BEFORE_ROUTE", ",", "$", "this", "->", "result", ")", ")", "{", "$", "callable", "(", "$", "this", "->", "result", ")", ";", "$", "route", "->", "runExtensions", "(", "Route", "::", "AFTER_ROUTE", ",", "$", "this", "->", "result", ")", ";", "}", "}", "else", "{", "$", "callable", "(", "$", "this", "->", "result", ")", ";", "}", "return", "true", ";", "}", "}" ]
Execute handler from result @return bool @access protected
[ "Execute", "handler", "from", "result" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Dispatcher.php#L261-L283
train
phossa/phossa-route
src/Phossa/Route/Dispatcher.php
Dispatcher.defaultHandler
protected function defaultHandler() { if ($this->runExtensions(self::BEFORE_DEFAULT, $this->result)) { $status = $this->result->getStatus(); $handler = $this->getHandler($status); if ($handler) { $handler($this->result); } else { echo Message::get(Message::DEBUG_NEED_HANDLER, $status); } $this->runExtensions(self::AFTER_DEFAULT, $this->result); } return false; }
php
protected function defaultHandler() { if ($this->runExtensions(self::BEFORE_DEFAULT, $this->result)) { $status = $this->result->getStatus(); $handler = $this->getHandler($status); if ($handler) { $handler($this->result); } else { echo Message::get(Message::DEBUG_NEED_HANDLER, $status); } $this->runExtensions(self::AFTER_DEFAULT, $this->result); } return false; }
[ "protected", "function", "defaultHandler", "(", ")", "{", "if", "(", "$", "this", "->", "runExtensions", "(", "self", "::", "BEFORE_DEFAULT", ",", "$", "this", "->", "result", ")", ")", "{", "$", "status", "=", "$", "this", "->", "result", "->", "getStatus", "(", ")", ";", "$", "handler", "=", "$", "this", "->", "getHandler", "(", "$", "status", ")", ";", "if", "(", "$", "handler", ")", "{", "$", "handler", "(", "$", "this", "->", "result", ")", ";", "}", "else", "{", "echo", "Message", "::", "get", "(", "Message", "::", "DEBUG_NEED_HANDLER", ",", "$", "status", ")", ";", "}", "$", "this", "->", "runExtensions", "(", "self", "::", "AFTER_DEFAULT", ",", "$", "this", "->", "result", ")", ";", "}", "return", "false", ";", "}" ]
Execute dispatcher's default handler @return false @access protected
[ "Execute", "dispatcher", "s", "default", "handler" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Dispatcher.php#L291-L304
train
mylxsw/FocusPHP
src/MVC/Router.php
Router.isMatched
public function isMatched($pathinfo, $index) { $pathinfo = $this->_urlRewrite($pathinfo); if (!empty($pathinfo)) { $res = explode('/', $pathinfo); $this->_controllerName = empty($res[0]) ? $this->_controllerName : ucfirst($res[0]); if (count($res) >= 2) { $this->_actionName = empty($res[1]) ? $this->_actionName : $res[1]; } if (count($res) > 2) { $this->_pathParams = array_slice($res, 2); } } else { if (defined('FOCUS_DEBUG') && FOCUS_DEBUG) { $this->getLogger()->debug('pathinfo is empty'); } } // 检查控制器是否存在 $className = "{$this->_controllerNs}\\{$this->_controllerName}"; if (class_exists($className)) { // 检查方法是否存在,不存则则使用index方法 if (!method_exists($className, $this->_actionName.'Action')) { $this->_actionName = 'index'; if (defined('FOCUS_DEBUG') && FOCUS_DEBUG) { $this->getLogger()->debug('use default action: indexAction'); } } return true; } return false; }
php
public function isMatched($pathinfo, $index) { $pathinfo = $this->_urlRewrite($pathinfo); if (!empty($pathinfo)) { $res = explode('/', $pathinfo); $this->_controllerName = empty($res[0]) ? $this->_controllerName : ucfirst($res[0]); if (count($res) >= 2) { $this->_actionName = empty($res[1]) ? $this->_actionName : $res[1]; } if (count($res) > 2) { $this->_pathParams = array_slice($res, 2); } } else { if (defined('FOCUS_DEBUG') && FOCUS_DEBUG) { $this->getLogger()->debug('pathinfo is empty'); } } // 检查控制器是否存在 $className = "{$this->_controllerNs}\\{$this->_controllerName}"; if (class_exists($className)) { // 检查方法是否存在,不存则则使用index方法 if (!method_exists($className, $this->_actionName.'Action')) { $this->_actionName = 'index'; if (defined('FOCUS_DEBUG') && FOCUS_DEBUG) { $this->getLogger()->debug('use default action: indexAction'); } } return true; } return false; }
[ "public", "function", "isMatched", "(", "$", "pathinfo", ",", "$", "index", ")", "{", "$", "pathinfo", "=", "$", "this", "->", "_urlRewrite", "(", "$", "pathinfo", ")", ";", "if", "(", "!", "empty", "(", "$", "pathinfo", ")", ")", "{", "$", "res", "=", "explode", "(", "'/'", ",", "$", "pathinfo", ")", ";", "$", "this", "->", "_controllerName", "=", "empty", "(", "$", "res", "[", "0", "]", ")", "?", "$", "this", "->", "_controllerName", ":", "ucfirst", "(", "$", "res", "[", "0", "]", ")", ";", "if", "(", "count", "(", "$", "res", ")", ">=", "2", ")", "{", "$", "this", "->", "_actionName", "=", "empty", "(", "$", "res", "[", "1", "]", ")", "?", "$", "this", "->", "_actionName", ":", "$", "res", "[", "1", "]", ";", "}", "if", "(", "count", "(", "$", "res", ")", ">", "2", ")", "{", "$", "this", "->", "_pathParams", "=", "array_slice", "(", "$", "res", ",", "2", ")", ";", "}", "}", "else", "{", "if", "(", "defined", "(", "'FOCUS_DEBUG'", ")", "&&", "FOCUS_DEBUG", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "debug", "(", "'pathinfo is empty'", ")", ";", "}", "}", "// 检查控制器是否存在", "$", "className", "=", "\"{$this->_controllerNs}\\\\{$this->_controllerName}\"", ";", "if", "(", "class_exists", "(", "$", "className", ")", ")", "{", "// 检查方法是否存在,不存则则使用index方法", "if", "(", "!", "method_exists", "(", "$", "className", ",", "$", "this", "->", "_actionName", ".", "'Action'", ")", ")", "{", "$", "this", "->", "_actionName", "=", "'index'", ";", "if", "(", "defined", "(", "'FOCUS_DEBUG'", ")", "&&", "FOCUS_DEBUG", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "debug", "(", "'use default action: indexAction'", ")", ";", "}", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determine whether the routing rules is matched. @param string $pathinfo pathinfo @param int $index rule index @return bool
[ "Determine", "whether", "the", "routing", "rules", "is", "matched", "." ]
33922bacbea66f11f874d991d7308a36cdf5831a
https://github.com/mylxsw/FocusPHP/blob/33922bacbea66f11f874d991d7308a36cdf5831a/src/MVC/Router.php#L43-L80
train
mglaman/toolstack-helper
src/Toolstack.php
Toolstack.getStackByType
public static function getStackByType($type) { foreach (self::getStacks() as $stack) { if ($stack->isType($type)) { return $stack; } } return new Stacks\NullStack(); }
php
public static function getStackByType($type) { foreach (self::getStacks() as $stack) { if ($stack->isType($type)) { return $stack; } } return new Stacks\NullStack(); }
[ "public", "static", "function", "getStackByType", "(", "$", "type", ")", "{", "foreach", "(", "self", "::", "getStacks", "(", ")", "as", "$", "stack", ")", "{", "if", "(", "$", "stack", "->", "isType", "(", "$", "type", ")", ")", "{", "return", "$", "stack", ";", "}", "}", "return", "new", "Stacks", "\\", "NullStack", "(", ")", ";", "}" ]
Returns a stack based on type. @param $type @return \mglaman\Toolstack\Stacks\StacksInterface
[ "Returns", "a", "stack", "based", "on", "type", "." ]
1b3b93ac284a6c77286988b5d41c75509dd3dc20
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Toolstack.php#L35-L43
train
mglaman/toolstack-helper
src/Toolstack.php
Toolstack.inspect
public static function inspect($dir) { if (!is_dir($dir)) { throw new FileNotFoundException(sprintf('Directory "%s" does not exist.', $dir)); } foreach (self::getStacks() as $stack) { if ($stack->inspect($dir) === true) { return $stack; } } // Stacks were not able to identify the structure. return new Stacks\NullStack(); }
php
public static function inspect($dir) { if (!is_dir($dir)) { throw new FileNotFoundException(sprintf('Directory "%s" does not exist.', $dir)); } foreach (self::getStacks() as $stack) { if ($stack->inspect($dir) === true) { return $stack; } } // Stacks were not able to identify the structure. return new Stacks\NullStack(); }
[ "public", "static", "function", "inspect", "(", "$", "dir", ")", "{", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", "sprintf", "(", "'Directory \"%s\" does not exist.'", ",", "$", "dir", ")", ")", ";", "}", "foreach", "(", "self", "::", "getStacks", "(", ")", "as", "$", "stack", ")", "{", "if", "(", "$", "stack", "->", "inspect", "(", "$", "dir", ")", "===", "true", ")", "{", "return", "$", "stack", ";", "}", "}", "// Stacks were not able to identify the structure.", "return", "new", "Stacks", "\\", "NullStack", "(", ")", ";", "}" ]
Inspects directory with stacks. @param $dir @return \mglaman\Toolstack\Stacks\StacksInterface
[ "Inspects", "directory", "with", "stacks", "." ]
1b3b93ac284a6c77286988b5d41c75509dd3dc20
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Toolstack.php#L52-L66
train
AnonymPHP/Anonym-Route
AccessDispatcher.php
AccessDispatcher.process
public function process($access = '') { if (is_array($access)) { if (isset($access['name'])) { $name = $access['name']; if (isset($this->access[$name])) { $accessInstance = $this->access[$name]; $accessInstance = new $accessInstance; if ($accessInstance instanceof MiddlewareInterface) { $role = isset($access['role']) ? $access['role'] : ''; $next = isset($access['next']) ? $access['next'] : null; if ($accessInstance->handle($this->request, $role, $next)) { return true; } else { if ($accessInstance instanceof TerminateInterface) { $accessInstance->terminate($this->request); } } } } } } return false; }
php
public function process($access = '') { if (is_array($access)) { if (isset($access['name'])) { $name = $access['name']; if (isset($this->access[$name])) { $accessInstance = $this->access[$name]; $accessInstance = new $accessInstance; if ($accessInstance instanceof MiddlewareInterface) { $role = isset($access['role']) ? $access['role'] : ''; $next = isset($access['next']) ? $access['next'] : null; if ($accessInstance->handle($this->request, $role, $next)) { return true; } else { if ($accessInstance instanceof TerminateInterface) { $accessInstance->terminate($this->request); } } } } } } return false; }
[ "public", "function", "process", "(", "$", "access", "=", "''", ")", "{", "if", "(", "is_array", "(", "$", "access", ")", ")", "{", "if", "(", "isset", "(", "$", "access", "[", "'name'", "]", ")", ")", "{", "$", "name", "=", "$", "access", "[", "'name'", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "access", "[", "$", "name", "]", ")", ")", "{", "$", "accessInstance", "=", "$", "this", "->", "access", "[", "$", "name", "]", ";", "$", "accessInstance", "=", "new", "$", "accessInstance", ";", "if", "(", "$", "accessInstance", "instanceof", "MiddlewareInterface", ")", "{", "$", "role", "=", "isset", "(", "$", "access", "[", "'role'", "]", ")", "?", "$", "access", "[", "'role'", "]", ":", "''", ";", "$", "next", "=", "isset", "(", "$", "access", "[", "'next'", "]", ")", "?", "$", "access", "[", "'next'", "]", ":", "null", ";", "if", "(", "$", "accessInstance", "->", "handle", "(", "$", "this", "->", "request", ",", "$", "role", ",", "$", "next", ")", ")", "{", "return", "true", ";", "}", "else", "{", "if", "(", "$", "accessInstance", "instanceof", "TerminateInterface", ")", "{", "$", "accessInstance", "->", "terminate", "(", "$", "this", "->", "request", ")", ";", "}", "}", "}", "}", "}", "}", "return", "false", ";", "}" ]
Process the array @param string $access the array of route access @return bool
[ "Process", "the", "array" ]
bb7f8004fbbd2998af8b0061f404f026f11466ab
https://github.com/AnonymPHP/Anonym-Route/blob/bb7f8004fbbd2998af8b0061f404f026f11466ab/AccessDispatcher.php#L54-L81
train
DoSomething/mb-toolbox
src/MB_Toolbox_BaseConsumer.php
MB_Toolbox_BaseConsumer.isSerialized
protected function isSerialized($message) { $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_BaseConsumer: isSerialized', 1); return ($message == serialize(false) || @unserialize($message) !== false); }
php
protected function isSerialized($message) { $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_BaseConsumer: isSerialized', 1); return ($message == serialize(false) || @unserialize($message) !== false); }
[ "protected", "function", "isSerialized", "(", "$", "message", ")", "{", "$", "this", "->", "statHat", "->", "ezCount", "(", "'MB_Toolbox: MB_Toolbox_BaseConsumer: isSerialized'", ",", "1", ")", ";", "return", "(", "$", "message", "==", "serialize", "(", "false", ")", "||", "@", "unserialize", "(", "$", "message", ")", "!==", "false", ")", ";", "}" ]
Detect if the message is in seralized format. Originally the Message Broker system used seralization to format messages as all of the producers and consumers are PHP based applications. To support microservices in other languages a more genaral JSON format is being used for message formatting. @param string $message @return string
[ "Detect", "if", "the", "message", "is", "in", "seralized", "format", "." ]
ceec5fc594bae137d1ab1f447344800343b62ac6
https://github.com/DoSomething/mb-toolbox/blob/ceec5fc594bae137d1ab1f447344800343b62ac6/src/MB_Toolbox_BaseConsumer.php#L151-L155
train
DoSomething/mb-toolbox
src/MB_Toolbox_BaseConsumer.php
MB_Toolbox_BaseConsumer.reportErrorPayload
protected function reportErrorPayload() { $errorPayload = $this->message; unset($errorPayload['payload']); unset($errorPayload['original']); echo '-> message: ' . print_r($errorPayload, true), PHP_EOL; $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_BaseConsumer: reportErrorPayload', 1); }
php
protected function reportErrorPayload() { $errorPayload = $this->message; unset($errorPayload['payload']); unset($errorPayload['original']); echo '-> message: ' . print_r($errorPayload, true), PHP_EOL; $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_BaseConsumer: reportErrorPayload', 1); }
[ "protected", "function", "reportErrorPayload", "(", ")", "{", "$", "errorPayload", "=", "$", "this", "->", "message", ";", "unset", "(", "$", "errorPayload", "[", "'payload'", "]", ")", ";", "unset", "(", "$", "errorPayload", "[", "'original'", "]", ")", ";", "echo", "'-> message: '", ".", "print_r", "(", "$", "errorPayload", ",", "true", ")", ",", "PHP_EOL", ";", "$", "this", "->", "statHat", "->", "ezCount", "(", "'MB_Toolbox: MB_Toolbox_BaseConsumer: reportErrorPayload'", ",", "1", ")", ";", "}" ]
Log payload with RabbitMQ objects removed for clarity. @return null
[ "Log", "payload", "with", "RabbitMQ", "objects", "removed", "for", "clarity", "." ]
ceec5fc594bae137d1ab1f447344800343b62ac6
https://github.com/DoSomething/mb-toolbox/blob/ceec5fc594bae137d1ab1f447344800343b62ac6/src/MB_Toolbox_BaseConsumer.php#L197-L205
train
DoSomething/mb-toolbox
src/MB_Toolbox_BaseConsumer.php
MB_Toolbox_BaseConsumer.throttle
protected function throttle($maxMessageRate) { $this->throttleMessageCount++; // Reset the number of processed message by each second if ($this->throttleSecondStamp != date('s')) { $this->throttleSecondStamp = date('s'); $this->throttleMessageCount = 0; } // Trigger processing delay when max message rate is exceeded if ($this->throttleMessageCount > $maxMessageRate) { sleep(MBC_BaseConsumer::THROTTLE_TIMEOUT); echo '- Trottling activated, message rate: ' . $this->throttleMessageCount . '. Waiting for ' . MBC_BaseConsumer::THROTTLE_TIMEOUT . ' seconds.', PHP_EOL; $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_BaseConsumer: throttle', 1); $this->throttleMessageCount = 0; } }
php
protected function throttle($maxMessageRate) { $this->throttleMessageCount++; // Reset the number of processed message by each second if ($this->throttleSecondStamp != date('s')) { $this->throttleSecondStamp = date('s'); $this->throttleMessageCount = 0; } // Trigger processing delay when max message rate is exceeded if ($this->throttleMessageCount > $maxMessageRate) { sleep(MBC_BaseConsumer::THROTTLE_TIMEOUT); echo '- Trottling activated, message rate: ' . $this->throttleMessageCount . '. Waiting for ' . MBC_BaseConsumer::THROTTLE_TIMEOUT . ' seconds.', PHP_EOL; $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_BaseConsumer: throttle', 1); $this->throttleMessageCount = 0; } }
[ "protected", "function", "throttle", "(", "$", "maxMessageRate", ")", "{", "$", "this", "->", "throttleMessageCount", "++", ";", "// Reset the number of processed message by each second", "if", "(", "$", "this", "->", "throttleSecondStamp", "!=", "date", "(", "'s'", ")", ")", "{", "$", "this", "->", "throttleSecondStamp", "=", "date", "(", "'s'", ")", ";", "$", "this", "->", "throttleMessageCount", "=", "0", ";", "}", "// Trigger processing delay when max message rate is exceeded", "if", "(", "$", "this", "->", "throttleMessageCount", ">", "$", "maxMessageRate", ")", "{", "sleep", "(", "MBC_BaseConsumer", "::", "THROTTLE_TIMEOUT", ")", ";", "echo", "'- Trottling activated, message rate: '", ".", "$", "this", "->", "throttleMessageCount", ".", "'. Waiting for '", ".", "MBC_BaseConsumer", "::", "THROTTLE_TIMEOUT", ".", "' seconds.'", ",", "PHP_EOL", ";", "$", "this", "->", "statHat", "->", "ezCount", "(", "'MB_Toolbox: MB_Toolbox_BaseConsumer: throttle'", ",", "1", ")", ";", "$", "this", "->", "throttleMessageCount", "=", "0", ";", "}", "}" ]
Throddle the rate the consumer processes messages. @param integer $maxMessageRate The number of messages to process per second before triggering a "pause". Higher values allow for greater processing velosity / messages per second. @return null
[ "Throddle", "the", "rate", "the", "consumer", "processes", "messages", "." ]
ceec5fc594bae137d1ab1f447344800343b62ac6
https://github.com/DoSomething/mb-toolbox/blob/ceec5fc594bae137d1ab1f447344800343b62ac6/src/MB_Toolbox_BaseConsumer.php#L216-L236
train
SuPa86000/ZF2Assetic
src/Assetic/Util/CssUtils.php
CssUtils.extractImports
public static function extractImports($content) { $imports = array(); static::filterImports($content, function($matches) use(& $imports) { $imports[] = $matches['url']; }); return array_unique($imports); }
php
public static function extractImports($content) { $imports = array(); static::filterImports($content, function($matches) use(& $imports) { $imports[] = $matches['url']; }); return array_unique($imports); }
[ "public", "static", "function", "extractImports", "(", "$", "content", ")", "{", "$", "imports", "=", "array", "(", ")", ";", "static", "::", "filterImports", "(", "$", "content", ",", "function", "(", "$", "matches", ")", "use", "(", "&", "$", "imports", ")", "{", "$", "imports", "[", "]", "=", "$", "matches", "[", "'url'", "]", ";", "}", ")", ";", "return", "array_unique", "(", "$", "imports", ")", ";", "}" ]
Extracts all references from the supplied CSS content. @param string $content The CSS content @return array An array of unique URLs
[ "Extracts", "all", "references", "from", "the", "supplied", "CSS", "content", "." ]
3c432f321b5acdc9649f7d2cc80ce4ed98351f93
https://github.com/SuPa86000/ZF2Assetic/blob/3c432f321b5acdc9649f7d2cc80ce4ed98351f93/src/Assetic/Util/CssUtils.php#L100-L108
train
AmericanCouncils/WebServicesBundle
Debug/ImprovedStackTrace.php
ImprovedStackTrace.getTrace
static function getTrace($e, $seen = null) { $starter = $seen ? 'Caused by: ' : ''; $result = array(); if (!$seen) $seen = array(); $trace = $e->getTrace(); $prev = $e->getPrevious(); $result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage()); $file = $e->getFile(); $line = $e->getLine(); while (true) { $current = "$file:$line"; $result[] = sprintf(' at %s%s%s(%s%s%s)', count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '', count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '', count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)', $line === null ? $file : basename($file), $line === null ? '' : ':', $line === null ? '' : $line); if (is_array($seen)) $seen[] = "$file:$line"; if (!count($trace)) break; $file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source'; $line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null; array_shift($trace); } $result = join("\n", $result); if ($prev) $result .= "\n" . self::getTrace($prev, $seen); return $result; }
php
static function getTrace($e, $seen = null) { $starter = $seen ? 'Caused by: ' : ''; $result = array(); if (!$seen) $seen = array(); $trace = $e->getTrace(); $prev = $e->getPrevious(); $result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage()); $file = $e->getFile(); $line = $e->getLine(); while (true) { $current = "$file:$line"; $result[] = sprintf(' at %s%s%s(%s%s%s)', count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '', count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '', count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)', $line === null ? $file : basename($file), $line === null ? '' : ':', $line === null ? '' : $line); if (is_array($seen)) $seen[] = "$file:$line"; if (!count($trace)) break; $file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source'; $line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null; array_shift($trace); } $result = join("\n", $result); if ($prev) $result .= "\n" . self::getTrace($prev, $seen); return $result; }
[ "static", "function", "getTrace", "(", "$", "e", ",", "$", "seen", "=", "null", ")", "{", "$", "starter", "=", "$", "seen", "?", "'Caused by: '", ":", "''", ";", "$", "result", "=", "array", "(", ")", ";", "if", "(", "!", "$", "seen", ")", "$", "seen", "=", "array", "(", ")", ";", "$", "trace", "=", "$", "e", "->", "getTrace", "(", ")", ";", "$", "prev", "=", "$", "e", "->", "getPrevious", "(", ")", ";", "$", "result", "[", "]", "=", "sprintf", "(", "'%s%s: %s'", ",", "$", "starter", ",", "get_class", "(", "$", "e", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "file", "=", "$", "e", "->", "getFile", "(", ")", ";", "$", "line", "=", "$", "e", "->", "getLine", "(", ")", ";", "while", "(", "true", ")", "{", "$", "current", "=", "\"$file:$line\"", ";", "$", "result", "[", "]", "=", "sprintf", "(", "' at %s%s%s(%s%s%s)'", ",", "count", "(", "$", "trace", ")", "&&", "array_key_exists", "(", "'class'", ",", "$", "trace", "[", "0", "]", ")", "?", "str_replace", "(", "'\\\\'", ",", "'.'", ",", "$", "trace", "[", "0", "]", "[", "'class'", "]", ")", ":", "''", ",", "count", "(", "$", "trace", ")", "&&", "array_key_exists", "(", "'class'", ",", "$", "trace", "[", "0", "]", ")", "&&", "array_key_exists", "(", "'function'", ",", "$", "trace", "[", "0", "]", ")", "?", "'.'", ":", "''", ",", "count", "(", "$", "trace", ")", "&&", "array_key_exists", "(", "'function'", ",", "$", "trace", "[", "0", "]", ")", "?", "str_replace", "(", "'\\\\'", ",", "'.'", ",", "$", "trace", "[", "0", "]", "[", "'function'", "]", ")", ":", "'(main)'", ",", "$", "line", "===", "null", "?", "$", "file", ":", "basename", "(", "$", "file", ")", ",", "$", "line", "===", "null", "?", "''", ":", "':'", ",", "$", "line", "===", "null", "?", "''", ":", "$", "line", ")", ";", "if", "(", "is_array", "(", "$", "seen", ")", ")", "$", "seen", "[", "]", "=", "\"$file:$line\"", ";", "if", "(", "!", "count", "(", "$", "trace", ")", ")", "break", ";", "$", "file", "=", "array_key_exists", "(", "'file'", ",", "$", "trace", "[", "0", "]", ")", "?", "$", "trace", "[", "0", "]", "[", "'file'", "]", ":", "'Unknown Source'", ";", "$", "line", "=", "array_key_exists", "(", "'file'", ",", "$", "trace", "[", "0", "]", ")", "&&", "array_key_exists", "(", "'line'", ",", "$", "trace", "[", "0", "]", ")", "&&", "$", "trace", "[", "0", "]", "[", "'line'", "]", "?", "$", "trace", "[", "0", "]", "[", "'line'", "]", ":", "null", ";", "array_shift", "(", "$", "trace", ")", ";", "}", "$", "result", "=", "join", "(", "\"\\n\"", ",", "$", "result", ")", ";", "if", "(", "$", "prev", ")", "$", "result", ".=", "\"\\n\"", ".", "self", "::", "getTrace", "(", "$", "prev", ",", "$", "seen", ")", ";", "return", "$", "result", ";", "}" ]
Returns a string describing in detail the stack context of an exception.
[ "Returns", "a", "string", "describing", "in", "detail", "the", "stack", "context", "of", "an", "exception", "." ]
3f6270ecf31138ba2271a94a407c0d1a05542929
https://github.com/AmericanCouncils/WebServicesBundle/blob/3f6270ecf31138ba2271a94a407c0d1a05542929/Debug/ImprovedStackTrace.php#L13-L46
train
johnkrovitch/SamBundle
src/Configuration/Loader/ConfigurationLoader.php
ConfigurationLoader.loadFromFile
public function loadFromFile($path) { // the file should exists $fileSystem = new Filesystem(); if (!$fileSystem->exists($path)) { throw new FileNotFoundException(); } // the file should be a yml file $configurationFile = new SplFileInfo($path); if ($configurationFile->getExtension() !== 'yml') { throw new Exception('Only yml are allowed for assets configuration loading'); } // parse configuration using Symfony processor $configuration = Yaml::parse(file_get_contents($path)); $configurationDI = new Configuration(); $processor = new Processor(); return $processor->processConfiguration($configurationDI, $configuration); }
php
public function loadFromFile($path) { // the file should exists $fileSystem = new Filesystem(); if (!$fileSystem->exists($path)) { throw new FileNotFoundException(); } // the file should be a yml file $configurationFile = new SplFileInfo($path); if ($configurationFile->getExtension() !== 'yml') { throw new Exception('Only yml are allowed for assets configuration loading'); } // parse configuration using Symfony processor $configuration = Yaml::parse(file_get_contents($path)); $configurationDI = new Configuration(); $processor = new Processor(); return $processor->processConfiguration($configurationDI, $configuration); }
[ "public", "function", "loadFromFile", "(", "$", "path", ")", "{", "// the file should exists", "$", "fileSystem", "=", "new", "Filesystem", "(", ")", ";", "if", "(", "!", "$", "fileSystem", "->", "exists", "(", "$", "path", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", ")", ";", "}", "// the file should be a yml file", "$", "configurationFile", "=", "new", "SplFileInfo", "(", "$", "path", ")", ";", "if", "(", "$", "configurationFile", "->", "getExtension", "(", ")", "!==", "'yml'", ")", "{", "throw", "new", "Exception", "(", "'Only yml are allowed for assets configuration loading'", ")", ";", "}", "// parse configuration using Symfony processor", "$", "configuration", "=", "Yaml", "::", "parse", "(", "file_get_contents", "(", "$", "path", ")", ")", ";", "$", "configurationDI", "=", "new", "Configuration", "(", ")", ";", "$", "processor", "=", "new", "Processor", "(", ")", ";", "return", "$", "processor", "->", "processConfiguration", "(", "$", "configurationDI", ",", "$", "configuration", ")", ";", "}" ]
Load the configuration from a yaml file in the file system. @param string $path @return array @throws Exception
[ "Load", "the", "configuration", "from", "a", "yaml", "file", "in", "the", "file", "system", "." ]
6cc08ef2dd8f7cd5c33ee27818edd4697afa435e
https://github.com/johnkrovitch/SamBundle/blob/6cc08ef2dd8f7cd5c33ee27818edd4697afa435e/src/Configuration/Loader/ConfigurationLoader.php#L40-L60
train
gplcart/cli
controllers/commands/State.php
State.cmdGetState
public function cmdGetState() { $result = $this->getListState(); $this->outputFormat($result); $this->outputFormatTableState($result); $this->output(); }
php
public function cmdGetState() { $result = $this->getListState(); $this->outputFormat($result); $this->outputFormatTableState($result); $this->output(); }
[ "public", "function", "cmdGetState", "(", ")", "{", "$", "result", "=", "$", "this", "->", "getListState", "(", ")", ";", "$", "this", "->", "outputFormat", "(", "$", "result", ")", ";", "$", "this", "->", "outputFormatTableState", "(", "$", "result", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "state-get" command
[ "Callback", "for", "state", "-", "get", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/State.php#L40-L46
train
gplcart/cli
controllers/commands/State.php
State.cmdUpdateState
public function cmdUpdateState() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->validateComponent('state'); $this->updateState($params[0]); $this->output(); }
php
public function cmdUpdateState() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->validateComponent('state'); $this->updateState($params[0]); $this->output(); }
[ "public", "function", "cmdUpdateState", "(", ")", "{", "$", "params", "=", "$", "this", "->", "getParam", "(", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "0", "]", ")", "||", "count", "(", "$", "params", ")", "<", "2", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid command'", ")", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "params", "[", "0", "]", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "params", ")", ";", "$", "this", "->", "setSubmitted", "(", "'update'", ",", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "validateComponent", "(", "'state'", ")", ";", "$", "this", "->", "updateState", "(", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "state-update" command
[ "Callback", "for", "state", "-", "update", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/State.php#L101-L120
train
gplcart/cli
controllers/commands/State.php
State.getListState
protected function getListState() { $id = $this->getParam(0); if (!isset($id)) { $list = $this->state->getList(); $this->limitArray($list); return $list; } if ($this->getParam('country')) { $list = $this->state->getList(array('country' => $id)); $this->limitArray($list); return $list; } if (!is_numeric($id)) { $this->errorAndExit($this->text('Invalid argument')); } $result = $this->state->get($id); if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } return array($result); }
php
protected function getListState() { $id = $this->getParam(0); if (!isset($id)) { $list = $this->state->getList(); $this->limitArray($list); return $list; } if ($this->getParam('country')) { $list = $this->state->getList(array('country' => $id)); $this->limitArray($list); return $list; } if (!is_numeric($id)) { $this->errorAndExit($this->text('Invalid argument')); } $result = $this->state->get($id); if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } return array($result); }
[ "protected", "function", "getListState", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getParam", "(", "0", ")", ";", "if", "(", "!", "isset", "(", "$", "id", ")", ")", "{", "$", "list", "=", "$", "this", "->", "state", "->", "getList", "(", ")", ";", "$", "this", "->", "limitArray", "(", "$", "list", ")", ";", "return", "$", "list", ";", "}", "if", "(", "$", "this", "->", "getParam", "(", "'country'", ")", ")", "{", "$", "list", "=", "$", "this", "->", "state", "->", "getList", "(", "array", "(", "'country'", "=>", "$", "id", ")", ")", ";", "$", "this", "->", "limitArray", "(", "$", "list", ")", ";", "return", "$", "list", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "$", "result", "=", "$", "this", "->", "state", "->", "get", "(", "$", "id", ")", ";", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "return", "array", "(", "$", "result", ")", ";", "}" ]
Returns an array of country states @return array
[ "Returns", "an", "array", "of", "country", "states" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/State.php#L126-L153
train
gplcart/cli
controllers/commands/State.php
State.submitAddState
protected function submitAddState() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('state'); $this->addState(); }
php
protected function submitAddState() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('state'); $this->addState(); }
[ "protected", "function", "submitAddState", "(", ")", "{", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "this", "->", "getParam", "(", ")", ")", ";", "$", "this", "->", "validateComponent", "(", "'state'", ")", ";", "$", "this", "->", "addState", "(", ")", ";", "}" ]
Add a new country state at once
[ "Add", "a", "new", "country", "state", "at", "once" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/State.php#L198-L203
train
gplcart/cli
controllers/commands/State.php
State.addState
protected function addState() { if (!$this->isError()) { $state_id = $this->state->add($this->getSubmitted()); if (empty($state_id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($state_id); } }
php
protected function addState() { if (!$this->isError()) { $state_id = $this->state->add($this->getSubmitted()); if (empty($state_id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($state_id); } }
[ "protected", "function", "addState", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isError", "(", ")", ")", "{", "$", "state_id", "=", "$", "this", "->", "state", "->", "add", "(", "$", "this", "->", "getSubmitted", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "state_id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "$", "this", "->", "line", "(", "$", "state_id", ")", ";", "}", "}" ]
Add a new country state
[ "Add", "a", "new", "country", "state" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/State.php#L208-L217
train
gplcart/cli
controllers/commands/State.php
State.wizardAddState
protected function wizardAddState() { $this->validatePrompt('code', $this->text('Code'), 'state'); $this->validatePrompt('name', $this->text('Name'), 'state'); $this->validatePrompt('country', $this->text('Country'), 'state'); $this->validatePrompt('zone_id', $this->text('Zone'), 'state', 0); $this->validatePrompt('status', $this->text('Status'), 'state', 0); $this->validateComponent('state'); $this->addState(); }
php
protected function wizardAddState() { $this->validatePrompt('code', $this->text('Code'), 'state'); $this->validatePrompt('name', $this->text('Name'), 'state'); $this->validatePrompt('country', $this->text('Country'), 'state'); $this->validatePrompt('zone_id', $this->text('Zone'), 'state', 0); $this->validatePrompt('status', $this->text('Status'), 'state', 0); $this->validateComponent('state'); $this->addState(); }
[ "protected", "function", "wizardAddState", "(", ")", "{", "$", "this", "->", "validatePrompt", "(", "'code'", ",", "$", "this", "->", "text", "(", "'Code'", ")", ",", "'state'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'name'", ",", "$", "this", "->", "text", "(", "'Name'", ")", ",", "'state'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'country'", ",", "$", "this", "->", "text", "(", "'Country'", ")", ",", "'state'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'zone_id'", ",", "$", "this", "->", "text", "(", "'Zone'", ")", ",", "'state'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'status'", ",", "$", "this", "->", "text", "(", "'Status'", ")", ",", "'state'", ",", "0", ")", ";", "$", "this", "->", "validateComponent", "(", "'state'", ")", ";", "$", "this", "->", "addState", "(", ")", ";", "}" ]
Add a new country state step by step
[ "Add", "a", "new", "country", "state", "step", "by", "step" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/State.php#L222-L232
train
ndavison/groundwork-framework
src/Groundwork/Classes/Router.php
Router.matchRequest
public function matchRequest($requestedRoute, $httpMethod) { // Iterate through each route that has been registered foreach ($this->routes as $route => $callback) { // Convert the route to a regex pattern $routeRx = preg_replace( '%/:([^ /?]+)(\?)?%', '/\2(?P<\1>[^ /?]+)\2', $route); // If the route also defined a HTTP method to match against, // append the requested route with the request's method $routeMethod = strstr($route, ':', true); if ($routeMethod && substr($routeMethod, -1) != '/') { $requestPrepend = strtolower($httpMethod).':'; } else { $requestPrepend = ''; } // Check for a regex match with the requested route. Store the // matches in a variable so the Request instance can be informed. if (preg_match('%^' . $routeRx . '$%', $requestPrepend.$requestedRoute, $uriParams) ) { // A route match was found // Before returning true, store the params // that were matched, and store the matched route. foreach ($uriParams as $key => $value) { if (is_numeric($key)) unset($uriParams[$key]); } $this->params = (object) $uriParams; $this->matched = $route; return true; } } // No matches caught return false; }
php
public function matchRequest($requestedRoute, $httpMethod) { // Iterate through each route that has been registered foreach ($this->routes as $route => $callback) { // Convert the route to a regex pattern $routeRx = preg_replace( '%/:([^ /?]+)(\?)?%', '/\2(?P<\1>[^ /?]+)\2', $route); // If the route also defined a HTTP method to match against, // append the requested route with the request's method $routeMethod = strstr($route, ':', true); if ($routeMethod && substr($routeMethod, -1) != '/') { $requestPrepend = strtolower($httpMethod).':'; } else { $requestPrepend = ''; } // Check for a regex match with the requested route. Store the // matches in a variable so the Request instance can be informed. if (preg_match('%^' . $routeRx . '$%', $requestPrepend.$requestedRoute, $uriParams) ) { // A route match was found // Before returning true, store the params // that were matched, and store the matched route. foreach ($uriParams as $key => $value) { if (is_numeric($key)) unset($uriParams[$key]); } $this->params = (object) $uriParams; $this->matched = $route; return true; } } // No matches caught return false; }
[ "public", "function", "matchRequest", "(", "$", "requestedRoute", ",", "$", "httpMethod", ")", "{", "// Iterate through each route that has been registered", "foreach", "(", "$", "this", "->", "routes", "as", "$", "route", "=>", "$", "callback", ")", "{", "// Convert the route to a regex pattern", "$", "routeRx", "=", "preg_replace", "(", "'%/:([^ /?]+)(\\?)?%'", ",", "'/\\2(?P<\\1>[^ /?]+)\\2'", ",", "$", "route", ")", ";", "// If the route also defined a HTTP method to match against, ", "// append the requested route with the request's method", "$", "routeMethod", "=", "strstr", "(", "$", "route", ",", "':'", ",", "true", ")", ";", "if", "(", "$", "routeMethod", "&&", "substr", "(", "$", "routeMethod", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "requestPrepend", "=", "strtolower", "(", "$", "httpMethod", ")", ".", "':'", ";", "}", "else", "{", "$", "requestPrepend", "=", "''", ";", "}", "// Check for a regex match with the requested route. Store the ", "// matches in a variable so the Request instance can be informed.", "if", "(", "preg_match", "(", "'%^'", ".", "$", "routeRx", ".", "'$%'", ",", "$", "requestPrepend", ".", "$", "requestedRoute", ",", "$", "uriParams", ")", ")", "{", "// A route match was found", "// Before returning true, store the params ", "// that were matched, and store the matched route.", "foreach", "(", "$", "uriParams", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "unset", "(", "$", "uriParams", "[", "$", "key", "]", ")", ";", "}", "$", "this", "->", "params", "=", "(", "object", ")", "$", "uriParams", ";", "$", "this", "->", "matched", "=", "$", "route", ";", "return", "true", ";", "}", "}", "// No matches caught", "return", "false", ";", "}" ]
Compares the requested route param with the registered routes and checks whether there is a match - true on a match, false if not. @param string $requestedRoute @param string $httpMethod @return boolean
[ "Compares", "the", "requested", "route", "param", "with", "the", "registered", "routes", "and", "checks", "whether", "there", "is", "a", "match", "-", "true", "on", "a", "match", "false", "if", "not", "." ]
c3d22a1410c8d8a07b4ca1f99a35a1181516cd6c
https://github.com/ndavison/groundwork-framework/blob/c3d22a1410c8d8a07b4ca1f99a35a1181516cd6c/src/Groundwork/Classes/Router.php#L127-L169
train
ndavison/groundwork-framework
src/Groundwork/Classes/Router.php
Router.getClosure
public function getClosure($app) { // Confirm the matched property is a key in the routes array if (!isset($this->routes[$this->matched])) return false; $callback = $this->routes[$this->matched]; // Is the callback a string? If so, it should be the name of a resource // class, which will be used to build the logic inside a closure. if (is_string($callback)) { $className = 'Resources\\' . $callback; if (class_exists($className)) { // Success, so lets build a closure for executing the // requested resource's output $callback = function() use ($app, $className, $callback) { // Does this resource have a IoC alias registered? if (!$resource = $app->get($callback)) $resource = new $className( $app->get('request'), $app->get('response') ); $resource->output(); }; } else { // Oops, bad class name given to the router return false; } } // $callback should now be a closure - either because that's what the // router was given originally, or because one was built from the // string it was given. if (is_callable($callback)) { return $callback; } else { // The callback wasn't callable (that's not good). return false; } }
php
public function getClosure($app) { // Confirm the matched property is a key in the routes array if (!isset($this->routes[$this->matched])) return false; $callback = $this->routes[$this->matched]; // Is the callback a string? If so, it should be the name of a resource // class, which will be used to build the logic inside a closure. if (is_string($callback)) { $className = 'Resources\\' . $callback; if (class_exists($className)) { // Success, so lets build a closure for executing the // requested resource's output $callback = function() use ($app, $className, $callback) { // Does this resource have a IoC alias registered? if (!$resource = $app->get($callback)) $resource = new $className( $app->get('request'), $app->get('response') ); $resource->output(); }; } else { // Oops, bad class name given to the router return false; } } // $callback should now be a closure - either because that's what the // router was given originally, or because one was built from the // string it was given. if (is_callable($callback)) { return $callback; } else { // The callback wasn't callable (that's not good). return false; } }
[ "public", "function", "getClosure", "(", "$", "app", ")", "{", "// Confirm the matched property is a key in the routes array", "if", "(", "!", "isset", "(", "$", "this", "->", "routes", "[", "$", "this", "->", "matched", "]", ")", ")", "return", "false", ";", "$", "callback", "=", "$", "this", "->", "routes", "[", "$", "this", "->", "matched", "]", ";", "// Is the callback a string? If so, it should be the name of a resource ", "// class, which will be used to build the logic inside a closure.", "if", "(", "is_string", "(", "$", "callback", ")", ")", "{", "$", "className", "=", "'Resources\\\\'", ".", "$", "callback", ";", "if", "(", "class_exists", "(", "$", "className", ")", ")", "{", "// Success, so lets build a closure for executing the ", "// requested resource's output", "$", "callback", "=", "function", "(", ")", "use", "(", "$", "app", ",", "$", "className", ",", "$", "callback", ")", "{", "// Does this resource have a IoC alias registered?", "if", "(", "!", "$", "resource", "=", "$", "app", "->", "get", "(", "$", "callback", ")", ")", "$", "resource", "=", "new", "$", "className", "(", "$", "app", "->", "get", "(", "'request'", ")", ",", "$", "app", "->", "get", "(", "'response'", ")", ")", ";", "$", "resource", "->", "output", "(", ")", ";", "}", ";", "}", "else", "{", "// Oops, bad class name given to the router", "return", "false", ";", "}", "}", "// $callback should now be a closure - either because that's what the ", "// router was given originally, or because one was built from the ", "// string it was given.", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "return", "$", "callback", ";", "}", "else", "{", "// The callback wasn't callable (that's not good).", "return", "false", ";", "}", "}" ]
Returns a Closure instance which contains the logic to generate the output for the requested route, or false. @param Application $app @return \Closure|boolean
[ "Returns", "a", "Closure", "instance", "which", "contains", "the", "logic", "to", "generate", "the", "output", "for", "the", "requested", "route", "or", "false", "." ]
c3d22a1410c8d8a07b4ca1f99a35a1181516cd6c
https://github.com/ndavison/groundwork-framework/blob/c3d22a1410c8d8a07b4ca1f99a35a1181516cd6c/src/Groundwork/Classes/Router.php#L178-L219
train
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/SerializationService.php
SerializationService.jsonEncode
public function jsonEncode($object, UriBuilder $uriBuilder, $metaDataProcessorGroup = NULL) { return json_encode($this->process($object, $uriBuilder, $metaDataProcessorGroup)); }
php
public function jsonEncode($object, UriBuilder $uriBuilder, $metaDataProcessorGroup = NULL) { return json_encode($this->process($object, $uriBuilder, $metaDataProcessorGroup)); }
[ "public", "function", "jsonEncode", "(", "$", "object", ",", "UriBuilder", "$", "uriBuilder", ",", "$", "metaDataProcessorGroup", "=", "NULL", ")", "{", "return", "json_encode", "(", "$", "this", "->", "process", "(", "$", "object", ",", "$", "uriBuilder", ",", "$", "metaDataProcessorGroup", ")", ")", ";", "}" ]
Returns JsonEncode of the given object. If UriPointers are found in the DTO hierarchy, the UriBuilder is required to resolve them. @param $object @param UriBuilder $uriBuilder @param string $metaDataProcessorGroup @return string
[ "Returns", "JsonEncode", "of", "the", "given", "object", ".", "If", "UriPointers", "are", "found", "in", "the", "DTO", "hierarchy", "the", "UriBuilder", "is", "required", "to", "resolve", "them", "." ]
61438827ba6b0a7a63cd2f08a294967ed5928144
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/SerializationService.php#L134-L138
train
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/SerializationService.php
SerializationService.process
public function process($object, UriBuilder $uriBuilder, $metaDataProcessorGroup = NULL) { $formerConfigurationStackAttributes = array( 'cacheTagService', 'metaDataProcessors', 'metaDataProcessorStorage', 'uriBuilder', 'propertyPath', ); /* * Remember previous state */ array_unshift($this->formerConfigurationStack, []); foreach ($formerConfigurationStackAttributes as $formerConfigurationStackAttribute) { $this->formerConfigurationStack[0][$formerConfigurationStackAttribute] = $this->{$formerConfigurationStackAttribute}; } /* * Initialize */ $this->uriBuilder = $uriBuilder; $this->propertyPath = []; $this->initializeMetaDataProcessors($metaDataProcessorGroup); /* if ($cacheTagService) { $this->cacheTagService = $cacheTagService; $this->cacheTagService->openEnvironment(); } */ $result = $this->processInternal($object); $result = $this->applyMetaData($result, $object); /* if ($cacheTagService) { $this->cacheTagService->closeEnvironment(); $this->cacheTagService = NULL; } */ /* * Reset previous state */ foreach ($formerConfigurationStackAttributes as $formerConfigurationStackAttribute) { $this->{$formerConfigurationStackAttribute} = $this->formerConfigurationStack[0][$formerConfigurationStackAttribute]; } array_shift($this->formerConfigurationStack); return $result; }
php
public function process($object, UriBuilder $uriBuilder, $metaDataProcessorGroup = NULL) { $formerConfigurationStackAttributes = array( 'cacheTagService', 'metaDataProcessors', 'metaDataProcessorStorage', 'uriBuilder', 'propertyPath', ); /* * Remember previous state */ array_unshift($this->formerConfigurationStack, []); foreach ($formerConfigurationStackAttributes as $formerConfigurationStackAttribute) { $this->formerConfigurationStack[0][$formerConfigurationStackAttribute] = $this->{$formerConfigurationStackAttribute}; } /* * Initialize */ $this->uriBuilder = $uriBuilder; $this->propertyPath = []; $this->initializeMetaDataProcessors($metaDataProcessorGroup); /* if ($cacheTagService) { $this->cacheTagService = $cacheTagService; $this->cacheTagService->openEnvironment(); } */ $result = $this->processInternal($object); $result = $this->applyMetaData($result, $object); /* if ($cacheTagService) { $this->cacheTagService->closeEnvironment(); $this->cacheTagService = NULL; } */ /* * Reset previous state */ foreach ($formerConfigurationStackAttributes as $formerConfigurationStackAttribute) { $this->{$formerConfigurationStackAttribute} = $this->formerConfigurationStack[0][$formerConfigurationStackAttribute]; } array_shift($this->formerConfigurationStack); return $result; }
[ "public", "function", "process", "(", "$", "object", ",", "UriBuilder", "$", "uriBuilder", ",", "$", "metaDataProcessorGroup", "=", "NULL", ")", "{", "$", "formerConfigurationStackAttributes", "=", "array", "(", "'cacheTagService'", ",", "'metaDataProcessors'", ",", "'metaDataProcessorStorage'", ",", "'uriBuilder'", ",", "'propertyPath'", ",", ")", ";", "/*\n\t\t * Remember previous state\n\t\t */", "array_unshift", "(", "$", "this", "->", "formerConfigurationStack", ",", "[", "]", ")", ";", "foreach", "(", "$", "formerConfigurationStackAttributes", "as", "$", "formerConfigurationStackAttribute", ")", "{", "$", "this", "->", "formerConfigurationStack", "[", "0", "]", "[", "$", "formerConfigurationStackAttribute", "]", "=", "$", "this", "->", "{", "$", "formerConfigurationStackAttribute", "}", ";", "}", "/*\n\t\t * Initialize\n\t\t */", "$", "this", "->", "uriBuilder", "=", "$", "uriBuilder", ";", "$", "this", "->", "propertyPath", "=", "[", "]", ";", "$", "this", "->", "initializeMetaDataProcessors", "(", "$", "metaDataProcessorGroup", ")", ";", "/*\n\t\tif ($cacheTagService) {\n\t\t\t$this->cacheTagService = $cacheTagService;\n\t\t\t$this->cacheTagService->openEnvironment();\n\t\t}\n\t\t*/", "$", "result", "=", "$", "this", "->", "processInternal", "(", "$", "object", ")", ";", "$", "result", "=", "$", "this", "->", "applyMetaData", "(", "$", "result", ",", "$", "object", ")", ";", "/*\n\t\tif ($cacheTagService) {\n\t\t\t$this->cacheTagService->closeEnvironment();\n\t\t\t$this->cacheTagService = NULL;\n\t\t}\n\t\t*/", "/*\n\t\t * Reset previous state\n\t\t */", "foreach", "(", "$", "formerConfigurationStackAttributes", "as", "$", "formerConfigurationStackAttribute", ")", "{", "$", "this", "->", "{", "$", "formerConfigurationStackAttribute", "}", "=", "$", "this", "->", "formerConfigurationStack", "[", "0", "]", "[", "$", "formerConfigurationStackAttribute", "]", ";", "}", "array_shift", "(", "$", "this", "->", "formerConfigurationStack", ")", ";", "return", "$", "result", ";", "}" ]
Basically TearUp and TearDown of the processing environment. The processing mechanism is another method. @param $object @param UriBuilder $uriBuilder @param string $metaDataProcessorGroup @return mixed
[ "Basically", "TearUp", "and", "TearDown", "of", "the", "processing", "environment", ".", "The", "processing", "mechanism", "is", "another", "method", "." ]
61438827ba6b0a7a63cd2f08a294967ed5928144
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/SerializationService.php#L149-L200
train
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/SerializationService.php
SerializationService.processInternal
protected function processInternal($object) { if (is_scalar($object)) { return $object; } elseif (is_array($object)) { return $this->processCollectionType($object, array_keys($object)); } elseif ($object instanceof \DateTime) { return $object->format(DateTimeConverter::DEFAULT_DATE_FORMAT); } elseif (is_object($object) && ($object instanceof ArrayCollection)) { $arrayRepresentation = $object->toArray(); return $this->processCollectionType($arrayRepresentation, array_keys($arrayRepresentation)); } elseif ($object instanceof DataTransferInterface) { if (!$this->cacheTagService) { $content = $this->processCollectionType($object, $object->getPropertyNamesToBeApiExposed()); } else { $this->cacheTagService->openEnvironment(); $this->cacheTagService->addEnvironmentCacheTag($object); $identifier = md5($this->cacheTagService->createCacheIdentifier([$this->metaDataProcessorGroup, $object])); if (!$this->cache->has($identifier)) { $content = $this->processCollectionType($object, $object->getPropertyNamesToBeApiExposed()); $this->cache->set($identifier, $content, $this->cacheTagService->getEnvironmentTags()); } else { $content = $this->cache->get($identifier); } $this->cacheTagService->closeEnvironment(); } return $content; } elseif ($object instanceof UriPointer) { return $this->processUriPointer($object); } elseif ($object instanceof Resource) { return $this->resourceManager->getPublicPersistentResourceUri($object); } }
php
protected function processInternal($object) { if (is_scalar($object)) { return $object; } elseif (is_array($object)) { return $this->processCollectionType($object, array_keys($object)); } elseif ($object instanceof \DateTime) { return $object->format(DateTimeConverter::DEFAULT_DATE_FORMAT); } elseif (is_object($object) && ($object instanceof ArrayCollection)) { $arrayRepresentation = $object->toArray(); return $this->processCollectionType($arrayRepresentation, array_keys($arrayRepresentation)); } elseif ($object instanceof DataTransferInterface) { if (!$this->cacheTagService) { $content = $this->processCollectionType($object, $object->getPropertyNamesToBeApiExposed()); } else { $this->cacheTagService->openEnvironment(); $this->cacheTagService->addEnvironmentCacheTag($object); $identifier = md5($this->cacheTagService->createCacheIdentifier([$this->metaDataProcessorGroup, $object])); if (!$this->cache->has($identifier)) { $content = $this->processCollectionType($object, $object->getPropertyNamesToBeApiExposed()); $this->cache->set($identifier, $content, $this->cacheTagService->getEnvironmentTags()); } else { $content = $this->cache->get($identifier); } $this->cacheTagService->closeEnvironment(); } return $content; } elseif ($object instanceof UriPointer) { return $this->processUriPointer($object); } elseif ($object instanceof Resource) { return $this->resourceManager->getPublicPersistentResourceUri($object); } }
[ "protected", "function", "processInternal", "(", "$", "object", ")", "{", "if", "(", "is_scalar", "(", "$", "object", ")", ")", "{", "return", "$", "object", ";", "}", "elseif", "(", "is_array", "(", "$", "object", ")", ")", "{", "return", "$", "this", "->", "processCollectionType", "(", "$", "object", ",", "array_keys", "(", "$", "object", ")", ")", ";", "}", "elseif", "(", "$", "object", "instanceof", "\\", "DateTime", ")", "{", "return", "$", "object", "->", "format", "(", "DateTimeConverter", "::", "DEFAULT_DATE_FORMAT", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "object", ")", "&&", "(", "$", "object", "instanceof", "ArrayCollection", ")", ")", "{", "$", "arrayRepresentation", "=", "$", "object", "->", "toArray", "(", ")", ";", "return", "$", "this", "->", "processCollectionType", "(", "$", "arrayRepresentation", ",", "array_keys", "(", "$", "arrayRepresentation", ")", ")", ";", "}", "elseif", "(", "$", "object", "instanceof", "DataTransferInterface", ")", "{", "if", "(", "!", "$", "this", "->", "cacheTagService", ")", "{", "$", "content", "=", "$", "this", "->", "processCollectionType", "(", "$", "object", ",", "$", "object", "->", "getPropertyNamesToBeApiExposed", "(", ")", ")", ";", "}", "else", "{", "$", "this", "->", "cacheTagService", "->", "openEnvironment", "(", ")", ";", "$", "this", "->", "cacheTagService", "->", "addEnvironmentCacheTag", "(", "$", "object", ")", ";", "$", "identifier", "=", "md5", "(", "$", "this", "->", "cacheTagService", "->", "createCacheIdentifier", "(", "[", "$", "this", "->", "metaDataProcessorGroup", ",", "$", "object", "]", ")", ")", ";", "if", "(", "!", "$", "this", "->", "cache", "->", "has", "(", "$", "identifier", ")", ")", "{", "$", "content", "=", "$", "this", "->", "processCollectionType", "(", "$", "object", ",", "$", "object", "->", "getPropertyNamesToBeApiExposed", "(", ")", ")", ";", "$", "this", "->", "cache", "->", "set", "(", "$", "identifier", ",", "$", "content", ",", "$", "this", "->", "cacheTagService", "->", "getEnvironmentTags", "(", ")", ")", ";", "}", "else", "{", "$", "content", "=", "$", "this", "->", "cache", "->", "get", "(", "$", "identifier", ")", ";", "}", "$", "this", "->", "cacheTagService", "->", "closeEnvironment", "(", ")", ";", "}", "return", "$", "content", ";", "}", "elseif", "(", "$", "object", "instanceof", "UriPointer", ")", "{", "return", "$", "this", "->", "processUriPointer", "(", "$", "object", ")", ";", "}", "elseif", "(", "$", "object", "instanceof", "Resource", ")", "{", "return", "$", "this", "->", "resourceManager", "->", "getPublicPersistentResourceUri", "(", "$", "object", ")", ";", "}", "}" ]
Dispatcher which kind of processing has to be done. @param mixed $object @return mixed
[ "Dispatcher", "which", "kind", "of", "processing", "has", "to", "be", "done", "." ]
61438827ba6b0a7a63cd2f08a294967ed5928144
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/SerializationService.php#L208-L240
train
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/SerializationService.php
SerializationService.processCollectionType
protected function processCollectionType($collection, $collectionKeys) { $result = []; foreach ($collectionKeys as $collectionKey) { array_push($this->propertyPath, $collectionKey); $value = ObjectAccess::getProperty($collection, $collectionKey); $result[$collectionKey] = $this->processInternal($value); array_pop($this->propertyPath); } return $result; }
php
protected function processCollectionType($collection, $collectionKeys) { $result = []; foreach ($collectionKeys as $collectionKey) { array_push($this->propertyPath, $collectionKey); $value = ObjectAccess::getProperty($collection, $collectionKey); $result[$collectionKey] = $this->processInternal($value); array_pop($this->propertyPath); } return $result; }
[ "protected", "function", "processCollectionType", "(", "$", "collection", ",", "$", "collectionKeys", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "collectionKeys", "as", "$", "collectionKey", ")", "{", "array_push", "(", "$", "this", "->", "propertyPath", ",", "$", "collectionKey", ")", ";", "$", "value", "=", "ObjectAccess", "::", "getProperty", "(", "$", "collection", ",", "$", "collectionKey", ")", ";", "$", "result", "[", "$", "collectionKey", "]", "=", "$", "this", "->", "processInternal", "(", "$", "value", ")", ";", "array_pop", "(", "$", "this", "->", "propertyPath", ")", ";", "}", "return", "$", "result", ";", "}" ]
This method handles "collection types", which are DTOs and arrays. Each individual property of those collection type is processed according internal processing rules. There might be MetaData content available for each property. Although those are applied to each collection type, those work best when being applied to Dto properties but not to array properties. array( 0 => array( 'subject' => 'foo', 'content' => 'bar', 'resource' => 'http://localhost/me', 'resource$$' => 'MetaData for the "resource" property, which is "0.resource".', // good ), '0$$' => 'MetaData for this object, which is "0".', // bad ) This example shows that "resource" can be enhanced with MetaData easily because that does not change the model layout significantly. Having an additional object attribute in both, PHP and JavaScript doesn't change behavior. On the other side, adding meta data to the array ('0$$') directly makes JsonEncode convert the array to an object. Without the MetaData, the surrounding object gets encoded to '[{"subject":"x" ... }]', with having the MetaData applied, the surrounding object gets converted to '{"0":{},"0$$":"x"}'. Note that the encoded version of the surrounding object in the first situation has square brackets indication an array, the second situation has curly brackets indicating an array. So the output type of of the surrounding object changes from array to object, just because the object meta data feature is enabled. MetaData needs to be configured separately. By default, no MetaData is attached. @param $collection @param $collectionKeys @return array
[ "This", "method", "handles", "collection", "types", "which", "are", "DTOs", "and", "arrays", "." ]
61438827ba6b0a7a63cd2f08a294967ed5928144
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/SerializationService.php#L279-L290
train
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/SerializationService.php
SerializationService.processUriPointer
protected function processUriPointer(UriPointer $uriPointer) { $uri = $this->uriBuilder ->reset() ->setCreateAbsoluteUri(TRUE) ->uriFor($uriPointer->getActionName(), $uriPointer->getArguments(), $uriPointer->getControllerName(), $uriPointer->getPackageKey(), $uriPointer->getSubPackageKey()); return $uri; }
php
protected function processUriPointer(UriPointer $uriPointer) { $uri = $this->uriBuilder ->reset() ->setCreateAbsoluteUri(TRUE) ->uriFor($uriPointer->getActionName(), $uriPointer->getArguments(), $uriPointer->getControllerName(), $uriPointer->getPackageKey(), $uriPointer->getSubPackageKey()); return $uri; }
[ "protected", "function", "processUriPointer", "(", "UriPointer", "$", "uriPointer", ")", "{", "$", "uri", "=", "$", "this", "->", "uriBuilder", "->", "reset", "(", ")", "->", "setCreateAbsoluteUri", "(", "TRUE", ")", "->", "uriFor", "(", "$", "uriPointer", "->", "getActionName", "(", ")", ",", "$", "uriPointer", "->", "getArguments", "(", ")", ",", "$", "uriPointer", "->", "getControllerName", "(", ")", ",", "$", "uriPointer", "->", "getPackageKey", "(", ")", ",", "$", "uriPointer", "->", "getSubPackageKey", "(", ")", ")", ";", "return", "$", "uri", ";", "}" ]
UriPointers are a special type, because they are meant to create a very specific and unique uri string. FIXME: Introduce a service that handles this uri building. @param UriPointer $uriPointer @return string
[ "UriPointers", "are", "a", "special", "type", "because", "they", "are", "meant", "to", "create", "a", "very", "specific", "and", "unique", "uri", "string", "." ]
61438827ba6b0a7a63cd2f08a294967ed5928144
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/SerializationService.php#L300-L307
train
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/SerializationService.php
SerializationService.getMetaData
protected function getMetaData($propertyPath, $processedValue, $object) { $metaData = []; foreach ($this->metaDataProcessors as $metaDataProcessorKey => $metaDataProcessorConfiguration) { if (!isset($this->metaDataProcessorStorage[$metaDataProcessorKey])) { $this->metaDataProcessorStorage[$metaDataProcessorKey] = []; } $path = $metaDataProcessorConfiguration['path']; if (preg_match($path, $propertyPath)) { /** @var \Netlogix\Crud\Domain\Service\MetaDataProcessor\AbstractMetaDataProcessor $processor */ $processor = $metaDataProcessorConfiguration['processor']; $metaData = $processor->process($metaData, $propertyPath, $processedValue, $this->metaDataProcessorStorage[$metaDataProcessorKey], $object, $this->uriBuilder, $this->metaDataProcessorGroup); } } return $metaData; }
php
protected function getMetaData($propertyPath, $processedValue, $object) { $metaData = []; foreach ($this->metaDataProcessors as $metaDataProcessorKey => $metaDataProcessorConfiguration) { if (!isset($this->metaDataProcessorStorage[$metaDataProcessorKey])) { $this->metaDataProcessorStorage[$metaDataProcessorKey] = []; } $path = $metaDataProcessorConfiguration['path']; if (preg_match($path, $propertyPath)) { /** @var \Netlogix\Crud\Domain\Service\MetaDataProcessor\AbstractMetaDataProcessor $processor */ $processor = $metaDataProcessorConfiguration['processor']; $metaData = $processor->process($metaData, $propertyPath, $processedValue, $this->metaDataProcessorStorage[$metaDataProcessorKey], $object, $this->uriBuilder, $this->metaDataProcessorGroup); } } return $metaData; }
[ "protected", "function", "getMetaData", "(", "$", "propertyPath", ",", "$", "processedValue", ",", "$", "object", ")", "{", "$", "metaData", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "metaDataProcessors", "as", "$", "metaDataProcessorKey", "=>", "$", "metaDataProcessorConfiguration", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "metaDataProcessorStorage", "[", "$", "metaDataProcessorKey", "]", ")", ")", "{", "$", "this", "->", "metaDataProcessorStorage", "[", "$", "metaDataProcessorKey", "]", "=", "[", "]", ";", "}", "$", "path", "=", "$", "metaDataProcessorConfiguration", "[", "'path'", "]", ";", "if", "(", "preg_match", "(", "$", "path", ",", "$", "propertyPath", ")", ")", "{", "/** @var \\Netlogix\\Crud\\Domain\\Service\\MetaDataProcessor\\AbstractMetaDataProcessor $processor */", "$", "processor", "=", "$", "metaDataProcessorConfiguration", "[", "'processor'", "]", ";", "$", "metaData", "=", "$", "processor", "->", "process", "(", "$", "metaData", ",", "$", "propertyPath", ",", "$", "processedValue", ",", "$", "this", "->", "metaDataProcessorStorage", "[", "$", "metaDataProcessorKey", "]", ",", "$", "object", ",", "$", "this", "->", "uriBuilder", ",", "$", "this", "->", "metaDataProcessorGroup", ")", ";", "}", "}", "return", "$", "metaData", ";", "}" ]
Returns MetaData for the given property Additional information can be any kind of data that is necessary for the client to process its model but does not belong to the domain data. Those can be e.g. th "readOnly" attribute or pre-fetched content of an Pointer. FIXME: Define how to configure this. Maybe add configuration by $this->jsonEncode and $this->process that determines which property path shall be enhanced and which MetaData processor should be used. @param $propertyPath @param $processedValue @param mixed $object @return array
[ "Returns", "MetaData", "for", "the", "given", "property" ]
61438827ba6b0a7a63cd2f08a294967ed5928144
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/SerializationService.php#L326-L344
train
rafrsr/lib-array2object
src/Parser/ObjectParser.php
ObjectParser.extractClass
private function extractClass($regEx, $classContent) { preg_match($regEx, $classContent, $matches); if (isset($matches[1]) && class_exists($matches[1])) { return $matches[1]; } return; }
php
private function extractClass($regEx, $classContent) { preg_match($regEx, $classContent, $matches); if (isset($matches[1]) && class_exists($matches[1])) { return $matches[1]; } return; }
[ "private", "function", "extractClass", "(", "$", "regEx", ",", "$", "classContent", ")", "{", "preg_match", "(", "$", "regEx", ",", "$", "classContent", ",", "$", "matches", ")", ";", "if", "(", "isset", "(", "$", "matches", "[", "1", "]", ")", "&&", "class_exists", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "return", "$", "matches", "[", "1", "]", ";", "}", "return", ";", "}" ]
Extract class usage from origin class content using regular expresion. @param $regEx @param $classContent
[ "Extract", "class", "usage", "from", "origin", "class", "content", "using", "regular", "expresion", "." ]
d15db63b5f5740dbc7c2213373320445785856ef
https://github.com/rafrsr/lib-array2object/blob/d15db63b5f5740dbc7c2213373320445785856ef/src/Parser/ObjectParser.php#L117-L125
train
mwyatt/core
src/AbstractController.php
AbstractController.redirect
public function redirect($key, $config = [], $statusCode = 302) { $router = $this->getService('Router'); $url = $this->getService('Url'); $urlNew = $url->generate($key, $config); $router->redirect($urlNew, $statusCode); }
php
public function redirect($key, $config = [], $statusCode = 302) { $router = $this->getService('Router'); $url = $this->getService('Url'); $urlNew = $url->generate($key, $config); $router->redirect($urlNew, $statusCode); }
[ "public", "function", "redirect", "(", "$", "key", ",", "$", "config", "=", "[", "]", ",", "$", "statusCode", "=", "302", ")", "{", "$", "router", "=", "$", "this", "->", "getService", "(", "'Router'", ")", ";", "$", "url", "=", "$", "this", "->", "getService", "(", "'Url'", ")", ";", "$", "urlNew", "=", "$", "url", "->", "generate", "(", "$", "key", ",", "$", "config", ")", ";", "$", "router", "->", "redirect", "(", "$", "urlNew", ",", "$", "statusCode", ")", ";", "}" ]
deprecated and must use redirectAbs
[ "deprecated", "and", "must", "use", "redirectAbs" ]
8ea9d67cc84fe6aff17a469c703d5492dbcd93ed
https://github.com/mwyatt/core/blob/8ea9d67cc84fe6aff17a469c703d5492dbcd93ed/src/AbstractController.php#L61-L67
train
mwyatt/core
src/AbstractController.php
AbstractController.redirectAbs
public function redirectAbs($url, $statusCode = 302) { $router = $this->getService('Router'); $router->redirect($url, $statusCode); exit; }
php
public function redirectAbs($url, $statusCode = 302) { $router = $this->getService('Router'); $router->redirect($url, $statusCode); exit; }
[ "public", "function", "redirectAbs", "(", "$", "url", ",", "$", "statusCode", "=", "302", ")", "{", "$", "router", "=", "$", "this", "->", "getService", "(", "'Router'", ")", ";", "$", "router", "->", "redirect", "(", "$", "url", ",", "$", "statusCode", ")", ";", "exit", ";", "}" ]
must be renamed to redirect in next major version @param string $url absolute @param integer $statusCode
[ "must", "be", "renamed", "to", "redirect", "in", "next", "major", "version" ]
8ea9d67cc84fe6aff17a469c703d5492dbcd93ed
https://github.com/mwyatt/core/blob/8ea9d67cc84fe6aff17a469c703d5492dbcd93ed/src/AbstractController.php#L75-L80
train
Hnto/nuki
src/Handlers/Core/ThrowableHandling.php
ThrowableHandling.toOutput
private function toOutput(\Throwable $t) { //Write to output $renderer = new \Nuki\Handlers\Http\Output\Renderers\RawRenderer(); $response = new \Nuki\Handlers\Http\Output\Response($renderer); $content = get_class($t) . ': '; $content .= $t->getMessage(); $content .= ' in '; $content .= $t->getFile() . ':' . $t->getLine(); $renderer->setContent(new \Nuki\Models\IO\Output\Content($content)); $response->httpStatusCode(\Nuki\Models\IO\Output\Http::HTTP_EXPECTATION_FAILED); $response->send(); return; }
php
private function toOutput(\Throwable $t) { //Write to output $renderer = new \Nuki\Handlers\Http\Output\Renderers\RawRenderer(); $response = new \Nuki\Handlers\Http\Output\Response($renderer); $content = get_class($t) . ': '; $content .= $t->getMessage(); $content .= ' in '; $content .= $t->getFile() . ':' . $t->getLine(); $renderer->setContent(new \Nuki\Models\IO\Output\Content($content)); $response->httpStatusCode(\Nuki\Models\IO\Output\Http::HTTP_EXPECTATION_FAILED); $response->send(); return; }
[ "private", "function", "toOutput", "(", "\\", "Throwable", "$", "t", ")", "{", "//Write to output", "$", "renderer", "=", "new", "\\", "Nuki", "\\", "Handlers", "\\", "Http", "\\", "Output", "\\", "Renderers", "\\", "RawRenderer", "(", ")", ";", "$", "response", "=", "new", "\\", "Nuki", "\\", "Handlers", "\\", "Http", "\\", "Output", "\\", "Response", "(", "$", "renderer", ")", ";", "$", "content", "=", "get_class", "(", "$", "t", ")", ".", "': '", ";", "$", "content", ".=", "$", "t", "->", "getMessage", "(", ")", ";", "$", "content", ".=", "' in '", ";", "$", "content", ".=", "$", "t", "->", "getFile", "(", ")", ".", "':'", ".", "$", "t", "->", "getLine", "(", ")", ";", "$", "renderer", "->", "setContent", "(", "new", "\\", "Nuki", "\\", "Models", "\\", "IO", "\\", "Output", "\\", "Content", "(", "$", "content", ")", ")", ";", "$", "response", "->", "httpStatusCode", "(", "\\", "Nuki", "\\", "Models", "\\", "IO", "\\", "Output", "\\", "Http", "::", "HTTP_EXPECTATION_FAILED", ")", ";", "$", "response", "->", "send", "(", ")", ";", "return", ";", "}" ]
Write to output @param \Throwable $t @return mixed
[ "Write", "to", "output" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Core/ThrowableHandling.php#L46-L63
train
Hnto/nuki
src/Handlers/Core/ThrowableHandling.php
ThrowableHandling.toUserOutput
private function toUserOutput(string $msg) { $renderer = new \Nuki\Handlers\Http\Output\Renderers\RawRenderer(); $response = new \Nuki\Handlers\Http\Output\Response($renderer); $renderer->setContent(new \Nuki\Models\IO\Output\Content($msg)); $response->httpStatusCode(\Nuki\Models\IO\Output\Http::HTTP_EXPECTATION_FAILED); $response->send(); return; }
php
private function toUserOutput(string $msg) { $renderer = new \Nuki\Handlers\Http\Output\Renderers\RawRenderer(); $response = new \Nuki\Handlers\Http\Output\Response($renderer); $renderer->setContent(new \Nuki\Models\IO\Output\Content($msg)); $response->httpStatusCode(\Nuki\Models\IO\Output\Http::HTTP_EXPECTATION_FAILED); $response->send(); return; }
[ "private", "function", "toUserOutput", "(", "string", "$", "msg", ")", "{", "$", "renderer", "=", "new", "\\", "Nuki", "\\", "Handlers", "\\", "Http", "\\", "Output", "\\", "Renderers", "\\", "RawRenderer", "(", ")", ";", "$", "response", "=", "new", "\\", "Nuki", "\\", "Handlers", "\\", "Http", "\\", "Output", "\\", "Response", "(", "$", "renderer", ")", ";", "$", "renderer", "->", "setContent", "(", "new", "\\", "Nuki", "\\", "Models", "\\", "IO", "\\", "Output", "\\", "Content", "(", "$", "msg", ")", ")", ";", "$", "response", "->", "httpStatusCode", "(", "\\", "Nuki", "\\", "Models", "\\", "IO", "\\", "Output", "\\", "Http", "::", "HTTP_EXPECTATION_FAILED", ")", ";", "$", "response", "->", "send", "(", ")", ";", "return", ";", "}" ]
Write message to user output @param string $msg @return mixed
[ "Write", "message", "to", "user", "output" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Core/ThrowableHandling.php#L71-L82
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.imgUrl
public static function imgUrl($file, $folder = false) { $src = '@web/images/'; if ($folder !== false) { $src .= $folder . '/'; } $src .= $file; return Url::to($src); }
php
public static function imgUrl($file, $folder = false) { $src = '@web/images/'; if ($folder !== false) { $src .= $folder . '/'; } $src .= $file; return Url::to($src); }
[ "public", "static", "function", "imgUrl", "(", "$", "file", ",", "$", "folder", "=", "false", ")", "{", "$", "src", "=", "'@web/images/'", ";", "if", "(", "$", "folder", "!==", "false", ")", "{", "$", "src", ".=", "$", "folder", ".", "'/'", ";", "}", "$", "src", ".=", "$", "file", ";", "return", "Url", "::", "to", "(", "$", "src", ")", ";", "}" ]
Get image url by filename @param $file @param bool $folder @return string
[ "Get", "image", "url", "by", "filename" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L37-L46
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.img
public static function img($file, $folder = false, array $options = []) { return Html::img(self::imgUrl($file, $folder), $options); }
php
public static function img($file, $folder = false, array $options = []) { return Html::img(self::imgUrl($file, $folder), $options); }
[ "public", "static", "function", "img", "(", "$", "file", ",", "$", "folder", "=", "false", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "Html", "::", "img", "(", "self", "::", "imgUrl", "(", "$", "file", ",", "$", "folder", ")", ",", "$", "options", ")", ";", "}" ]
Display img tag @param string $file @param bool $folder @param array $options @return string
[ "Display", "img", "tag" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L55-L58
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.linkUrl
public static function linkUrl($pageId, $pageUrl) { if (self::$pages === null) { self::initPages(); } if ($pageUrl) { if (strpos($pageUrl, 'http') === 0) { return Url::to($pageUrl); } return Url::to([$pageUrl]); } if (isset(self::$pages[$pageId]['link'])) { if (self::$pages[$pageId]['link']) { return Url::to(['/' . self::$pages[$pageId]['link']]); } } return Url::home(); }
php
public static function linkUrl($pageId, $pageUrl) { if (self::$pages === null) { self::initPages(); } if ($pageUrl) { if (strpos($pageUrl, 'http') === 0) { return Url::to($pageUrl); } return Url::to([$pageUrl]); } if (isset(self::$pages[$pageId]['link'])) { if (self::$pages[$pageId]['link']) { return Url::to(['/' . self::$pages[$pageId]['link']]); } } return Url::home(); }
[ "public", "static", "function", "linkUrl", "(", "$", "pageId", ",", "$", "pageUrl", ")", "{", "if", "(", "self", "::", "$", "pages", "===", "null", ")", "{", "self", "::", "initPages", "(", ")", ";", "}", "if", "(", "$", "pageUrl", ")", "{", "if", "(", "strpos", "(", "$", "pageUrl", ",", "'http'", ")", "===", "0", ")", "{", "return", "Url", "::", "to", "(", "$", "pageUrl", ")", ";", "}", "return", "Url", "::", "to", "(", "[", "$", "pageUrl", "]", ")", ";", "}", "if", "(", "isset", "(", "self", "::", "$", "pages", "[", "$", "pageId", "]", "[", "'link'", "]", ")", ")", "{", "if", "(", "self", "::", "$", "pages", "[", "$", "pageId", "]", "[", "'link'", "]", ")", "{", "return", "Url", "::", "to", "(", "[", "'/'", ".", "self", "::", "$", "pages", "[", "$", "pageId", "]", "[", "'link'", "]", "]", ")", ";", "}", "}", "return", "Url", "::", "home", "(", ")", ";", "}" ]
Get page url by id @param $pageId @param $pageUrl @return string @throws \yii\base\InvalidConfigException
[ "Get", "page", "url", "by", "id" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L67-L88
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.link
public static function link($menu, $text, array $options = [], array $fields = []) { if ($menu instanceof ActiveRecord) { if (!$fields) { $fields = self::$fields; } if ($menu->{$fields['page_blank']}) { $options['target'] = '_blank'; } return Html::a($text, self::linkUrl( $menu->{$fields['page_id']}, $menu->{$fields['page_url']} ), $options); } return false; }
php
public static function link($menu, $text, array $options = [], array $fields = []) { if ($menu instanceof ActiveRecord) { if (!$fields) { $fields = self::$fields; } if ($menu->{$fields['page_blank']}) { $options['target'] = '_blank'; } return Html::a($text, self::linkUrl( $menu->{$fields['page_id']}, $menu->{$fields['page_url']} ), $options); } return false; }
[ "public", "static", "function", "link", "(", "$", "menu", ",", "$", "text", ",", "array", "$", "options", "=", "[", "]", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "if", "(", "$", "menu", "instanceof", "ActiveRecord", ")", "{", "if", "(", "!", "$", "fields", ")", "{", "$", "fields", "=", "self", "::", "$", "fields", ";", "}", "if", "(", "$", "menu", "->", "{", "$", "fields", "[", "'page_blank'", "]", "}", ")", "{", "$", "options", "[", "'target'", "]", "=", "'_blank'", ";", "}", "return", "Html", "::", "a", "(", "$", "text", ",", "self", "::", "linkUrl", "(", "$", "menu", "->", "{", "$", "fields", "[", "'page_id'", "]", "}", ",", "$", "menu", "->", "{", "$", "fields", "[", "'page_url'", "]", "}", ")", ",", "$", "options", ")", ";", "}", "return", "false", ";", "}" ]
Display link by page @param mixed $menu @param $text Html:a text @param array $options Html:a options @param array $fields @return bool|string @throws \yii\base\InvalidConfigException
[ "Display", "link", "by", "page" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L100-L119
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.isLinkActive
public static function isLinkActive($menu, array $fields = []) { if ($menu instanceof ActiveRecord) { if (self::$pages === null) { self::initPages(); } if (!$fields) { $fields = self::$fields; } /** Check if page_url is the same as current url */ $pageUrl = $menu->{$fields['page_url']}; if ($pageUrl) { if (strpos($pageUrl, 'http') === 0) { return false; } return (Url::to([$pageUrl]) === Url::current()); } if (isset(self::$pages[$menu->{$fields['page_id']}]['link'])) { if (Yii::$app->request->getQueryParam(self::$linkParam) === self::$pages[$menu->{$fields['page_id']}]['link']) { return true; } return false; } return (Url::home() === Url::current()); } return false; }
php
public static function isLinkActive($menu, array $fields = []) { if ($menu instanceof ActiveRecord) { if (self::$pages === null) { self::initPages(); } if (!$fields) { $fields = self::$fields; } /** Check if page_url is the same as current url */ $pageUrl = $menu->{$fields['page_url']}; if ($pageUrl) { if (strpos($pageUrl, 'http') === 0) { return false; } return (Url::to([$pageUrl]) === Url::current()); } if (isset(self::$pages[$menu->{$fields['page_id']}]['link'])) { if (Yii::$app->request->getQueryParam(self::$linkParam) === self::$pages[$menu->{$fields['page_id']}]['link']) { return true; } return false; } return (Url::home() === Url::current()); } return false; }
[ "public", "static", "function", "isLinkActive", "(", "$", "menu", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "if", "(", "$", "menu", "instanceof", "ActiveRecord", ")", "{", "if", "(", "self", "::", "$", "pages", "===", "null", ")", "{", "self", "::", "initPages", "(", ")", ";", "}", "if", "(", "!", "$", "fields", ")", "{", "$", "fields", "=", "self", "::", "$", "fields", ";", "}", "/** Check if page_url is the same as current url */", "$", "pageUrl", "=", "$", "menu", "->", "{", "$", "fields", "[", "'page_url'", "]", "}", ";", "if", "(", "$", "pageUrl", ")", "{", "if", "(", "strpos", "(", "$", "pageUrl", ",", "'http'", ")", "===", "0", ")", "{", "return", "false", ";", "}", "return", "(", "Url", "::", "to", "(", "[", "$", "pageUrl", "]", ")", "===", "Url", "::", "current", "(", ")", ")", ";", "}", "if", "(", "isset", "(", "self", "::", "$", "pages", "[", "$", "menu", "->", "{", "$", "fields", "[", "'page_id'", "]", "}", "]", "[", "'link'", "]", ")", ")", "{", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "getQueryParam", "(", "self", "::", "$", "linkParam", ")", "===", "self", "::", "$", "pages", "[", "$", "menu", "->", "{", "$", "fields", "[", "'page_id'", "]", "}", "]", "[", "'link'", "]", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "return", "(", "Url", "::", "home", "(", ")", "===", "Url", "::", "current", "(", ")", ")", ";", "}", "return", "false", ";", "}" ]
Check if page is active @param mixed $menu @param array $fields @return bool @throws \yii\base\InvalidConfigException
[ "Check", "if", "page", "is", "active" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L128-L162
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.youTubeId
public static function youTubeId($url) { parse_str(parse_url($url, PHP_URL_QUERY), $vars); if (isset($vars['v'])) { return $vars['v']; } return false; }
php
public static function youTubeId($url) { parse_str(parse_url($url, PHP_URL_QUERY), $vars); if (isset($vars['v'])) { return $vars['v']; } return false; }
[ "public", "static", "function", "youTubeId", "(", "$", "url", ")", "{", "parse_str", "(", "parse_url", "(", "$", "url", ",", "PHP_URL_QUERY", ")", ",", "$", "vars", ")", ";", "if", "(", "isset", "(", "$", "vars", "[", "'v'", "]", ")", ")", "{", "return", "$", "vars", "[", "'v'", "]", ";", "}", "return", "false", ";", "}" ]
Return movie ID based on YouTube url @param $url @return mixed
[ "Return", "movie", "ID", "based", "on", "YouTube", "url" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L169-L176
train
mrstroz/yii2-wavecms-page
components/helpers/Front.php
Front.initPages
private static function initPages() { $modelPage = Yii::createObject(Page::class); $pages = $modelPage::find()->getMap()->asArray()->all(); if ($pages) { foreach ($pages as $page) { self::$pages[$page['id']] = $page; } } }
php
private static function initPages() { $modelPage = Yii::createObject(Page::class); $pages = $modelPage::find()->getMap()->asArray()->all(); if ($pages) { foreach ($pages as $page) { self::$pages[$page['id']] = $page; } } }
[ "private", "static", "function", "initPages", "(", ")", "{", "$", "modelPage", "=", "Yii", "::", "createObject", "(", "Page", "::", "class", ")", ";", "$", "pages", "=", "$", "modelPage", "::", "find", "(", ")", "->", "getMap", "(", ")", "->", "asArray", "(", ")", "->", "all", "(", ")", ";", "if", "(", "$", "pages", ")", "{", "foreach", "(", "$", "pages", "as", "$", "page", ")", "{", "self", "::", "$", "pages", "[", "$", "page", "[", "'id'", "]", "]", "=", "$", "page", ";", "}", "}", "}" ]
Init pages array @throws \yii\base\InvalidConfigException
[ "Init", "pages", "array" ]
c7f867ffc5abd86814230c360aec9b30b6d2e819
https://github.com/mrstroz/yii2-wavecms-page/blob/c7f867ffc5abd86814230c360aec9b30b6d2e819/components/helpers/Front.php#L182-L193
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/NestedModel.php
NestedModel.getDescendantsAndSelf
public function getDescendantsAndSelf( $columns = ['*'] ) { if ( is_array( $columns ) ) return $this->descendantsAndSelf()->get( $columns ); $arguments = func_get_args(); $limit = intval( array_shift( $arguments ) ); $columns = array_shift( $arguments ) ?: ['*']; return $this->descendantsAndSelf()->limitDepth( $limit )->get( $columns ); }
php
public function getDescendantsAndSelf( $columns = ['*'] ) { if ( is_array( $columns ) ) return $this->descendantsAndSelf()->get( $columns ); $arguments = func_get_args(); $limit = intval( array_shift( $arguments ) ); $columns = array_shift( $arguments ) ?: ['*']; return $this->descendantsAndSelf()->limitDepth( $limit )->get( $columns ); }
[ "public", "function", "getDescendantsAndSelf", "(", "$", "columns", "=", "[", "'*'", "]", ")", "{", "if", "(", "is_array", "(", "$", "columns", ")", ")", "return", "$", "this", "->", "descendantsAndSelf", "(", ")", "->", "get", "(", "$", "columns", ")", ";", "$", "arguments", "=", "func_get_args", "(", ")", ";", "$", "limit", "=", "intval", "(", "array_shift", "(", "$", "arguments", ")", ")", ";", "$", "columns", "=", "array_shift", "(", "$", "arguments", ")", "?", ":", "[", "'*'", "]", ";", "return", "$", "this", "->", "descendantsAndSelf", "(", ")", "->", "limitDepth", "(", "$", "limit", ")", "->", "get", "(", "$", "columns", ")", ";", "}" ]
Retrieve all nested children an self. @param array $columns @return Collection
[ "Retrieve", "all", "nested", "children", "an", "self", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/NestedModel.php#L787-L798
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/NestedModel.php
NestedModel.moveToNewParent
public function moveToNewParent() { $pid = static::$moveToNewParentId; if ( is_null( $pid ) ) $this->makeRoot(); else if ( $pid !== false ) $this->makeChildOf( $pid ); }
php
public function moveToNewParent() { $pid = static::$moveToNewParentId; if ( is_null( $pid ) ) $this->makeRoot(); else if ( $pid !== false ) $this->makeChildOf( $pid ); }
[ "public", "function", "moveToNewParent", "(", ")", "{", "$", "pid", "=", "static", "::", "$", "moveToNewParentId", ";", "if", "(", "is_null", "(", "$", "pid", ")", ")", "$", "this", "->", "makeRoot", "(", ")", ";", "else", "if", "(", "$", "pid", "!==", "false", ")", "$", "this", "->", "makeChildOf", "(", "$", "pid", ")", ";", "}" ]
Move to the new parent if appropiate. @return void
[ "Move", "to", "the", "new", "parent", "if", "appropiate", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/NestedModel.php#L1117-L1125
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/NestedModel.php
NestedModel.restoreDescendants
public function restoreDescendants() { if ( is_null( $this->getRight() ) || is_null( $this->getLeft() ) ) return; $self = $this; $this->getConnection()->transaction( function () use ( $self ) { $self->newNestedSetQuery()->withTrashed()->where( $self->getLeftColumnName(), '>', $self->getLeft() )->where( $self->getRightColumnName(), '<', $self->getRight() )->update( [ $self->getDeletedAtColumn() => null, $self->getUpdatedAtColumn() => $self->{$self->getUpdatedAtColumn()} ] ); } ); }
php
public function restoreDescendants() { if ( is_null( $this->getRight() ) || is_null( $this->getLeft() ) ) return; $self = $this; $this->getConnection()->transaction( function () use ( $self ) { $self->newNestedSetQuery()->withTrashed()->where( $self->getLeftColumnName(), '>', $self->getLeft() )->where( $self->getRightColumnName(), '<', $self->getRight() )->update( [ $self->getDeletedAtColumn() => null, $self->getUpdatedAtColumn() => $self->{$self->getUpdatedAtColumn()} ] ); } ); }
[ "public", "function", "restoreDescendants", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "getRight", "(", ")", ")", "||", "is_null", "(", "$", "this", "->", "getLeft", "(", ")", ")", ")", "return", ";", "$", "self", "=", "$", "this", ";", "$", "this", "->", "getConnection", "(", ")", "->", "transaction", "(", "function", "(", ")", "use", "(", "$", "self", ")", "{", "$", "self", "->", "newNestedSetQuery", "(", ")", "->", "withTrashed", "(", ")", "->", "where", "(", "$", "self", "->", "getLeftColumnName", "(", ")", ",", "'>'", ",", "$", "self", "->", "getLeft", "(", ")", ")", "->", "where", "(", "$", "self", "->", "getRightColumnName", "(", ")", ",", "'<'", ",", "$", "self", "->", "getRight", "(", ")", ")", "->", "update", "(", "[", "$", "self", "->", "getDeletedAtColumn", "(", ")", "=>", "null", ",", "$", "self", "->", "getUpdatedAtColumn", "(", ")", "=>", "$", "self", "->", "{", "$", "self", "->", "getUpdatedAtColumn", "(", ")", "}", "]", ")", ";", "}", ")", ";", "}" ]
Restores all of the current node's descendants. @return void
[ "Restores", "all", "of", "the", "current", "node", "s", "descendants", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/NestedModel.php#L1246-L1260
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/NestedModel.php
NestedModel.determineDepth
protected function determineDepth( $node, $nesting = 0 ) { // Traverse back up the ancestry chain and add to the nesting level count while ( $parent = $node->parent()->first() ) { $nesting = $nesting + 1; $node = $parent; } return [$node, $nesting]; }
php
protected function determineDepth( $node, $nesting = 0 ) { // Traverse back up the ancestry chain and add to the nesting level count while ( $parent = $node->parent()->first() ) { $nesting = $nesting + 1; $node = $parent; } return [$node, $nesting]; }
[ "protected", "function", "determineDepth", "(", "$", "node", ",", "$", "nesting", "=", "0", ")", "{", "// Traverse back up the ancestry chain and add to the nesting level count", "while", "(", "$", "parent", "=", "$", "node", "->", "parent", "(", ")", "->", "first", "(", ")", ")", "{", "$", "nesting", "=", "$", "nesting", "+", "1", ";", "$", "node", "=", "$", "parent", ";", "}", "return", "[", "$", "node", ",", "$", "nesting", "]", ";", "}" ]
Return an array with the last node we could reach and its nesting level @param Baum\Node $node @param integer $nesting @return array
[ "Return", "an", "array", "with", "the", "last", "node", "we", "could", "reach", "and", "its", "nesting", "level" ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/NestedModel.php#L1337-L1348
train