repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
c9s/Pux
src/Controller/Controller.php
Controller.getRequest
protected function getRequest($recreate = false) { if (!$recreate && $this->_request) { return $this->_request; } return $this->_request = HttpRequest::createFromGlobals($this->environment); }
php
protected function getRequest($recreate = false) { if (!$recreate && $this->_request) { return $this->_request; } return $this->_request = HttpRequest::createFromGlobals($this->environment); }
[ "protected", "function", "getRequest", "(", "$", "recreate", "=", "false", ")", "{", "if", "(", "!", "$", "recreate", "&&", "$", "this", "->", "_request", ")", "{", "return", "$", "this", "->", "_request", ";", "}", "return", "$", "this", "->", "_request", "=", "HttpRequest", "::", "createFromGlobals", "(", "$", "this", "->", "environment", ")", ";", "}" ]
Create and Return HttpRequest object from the environment @param boolean $recreate @return Universal\Http\HttpRequest
[ "Create", "and", "Return", "HttpRequest", "object", "from", "the", "environment" ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Controller/Controller.php#L92-L98
c9s/Pux
src/Controller/Controller.php
Controller.runAction
public function runAction($action, array $vars = array()) { $method = "{$action}Action"; if (! method_exists($this,$method)) { throw new Exception("Controller method $method does not exist."); } $ro = new ReflectionObject( $this ); $rm = $ro->getMethod($method); // Map vars to function arguments $parameters = $rm->getParameters(); $arguments = array(); foreach ($parameters as $param) { if (isset($vars[$param->getName()])) { $arguments[] = $vars[ $param->getName() ]; } } return call_user_func_array( array($this,$method) , $arguments ); }
php
public function runAction($action, array $vars = array()) { $method = "{$action}Action"; if (! method_exists($this,$method)) { throw new Exception("Controller method $method does not exist."); } $ro = new ReflectionObject( $this ); $rm = $ro->getMethod($method); // Map vars to function arguments $parameters = $rm->getParameters(); $arguments = array(); foreach ($parameters as $param) { if (isset($vars[$param->getName()])) { $arguments[] = $vars[ $param->getName() ]; } } return call_user_func_array( array($this,$method) , $arguments ); }
[ "public", "function", "runAction", "(", "$", "action", ",", "array", "$", "vars", "=", "array", "(", ")", ")", "{", "$", "method", "=", "\"{$action}Action\"", ";", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "throw", "new", "Exception", "(", "\"Controller method $method does not exist.\"", ")", ";", "}", "$", "ro", "=", "new", "ReflectionObject", "(", "$", "this", ")", ";", "$", "rm", "=", "$", "ro", "->", "getMethod", "(", "$", "method", ")", ";", "// Map vars to function arguments", "$", "parameters", "=", "$", "rm", "->", "getParameters", "(", ")", ";", "$", "arguments", "=", "array", "(", ")", ";", "foreach", "(", "$", "parameters", "as", "$", "param", ")", "{", "if", "(", "isset", "(", "$", "vars", "[", "$", "param", "->", "getName", "(", ")", "]", ")", ")", "{", "$", "arguments", "[", "]", "=", "$", "vars", "[", "$", "param", "->", "getName", "(", ")", "]", ";", "}", "}", "return", "call_user_func_array", "(", "array", "(", "$", "this", ",", "$", "method", ")", ",", "$", "arguments", ")", ";", "}" ]
Run controller action @param string $action Action name, the action name should not include "Action" as its suffix. @param array $vars Action method parameters, which will be applied to the method parameters by their names. @return string Return execution result in string format.
[ "Run", "controller", "action" ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Controller/Controller.php#L116-L136
c9s/Pux
src/Controller/Controller.php
Controller.forward
public function forward($controller, $actionName = 'index' , $parameters = array()) { if (is_string($controller)) { $controller = new $controller; } return $controller->runAction($actionName, $parameters); }
php
public function forward($controller, $actionName = 'index' , $parameters = array()) { if (is_string($controller)) { $controller = new $controller; } return $controller->runAction($actionName, $parameters); }
[ "public", "function", "forward", "(", "$", "controller", ",", "$", "actionName", "=", "'index'", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "is_string", "(", "$", "controller", ")", ")", "{", "$", "controller", "=", "new", "$", "controller", ";", "}", "return", "$", "controller", "->", "runAction", "(", "$", "actionName", ",", "$", "parameters", ")", ";", "}" ]
Forward to another controller action @param string|Controller $controller A controller class name or a controller instance. @param string $actionName The action name @param array $parameters Parameters for the action method return $this->forward('\OAuthPlugin\Controller\AuthenticationErrorPage','index',array( 'vars' => array( 'message' => $e->lastResponse ) ));
[ "Forward", "to", "another", "controller", "action" ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Controller/Controller.php#L152-L158
c9s/Pux
src/RouteRequest.php
RouteRequest.matchConstraints
public function matchConstraints(array $constraints) { foreach ($constraints as $constraint) { $result = true; if (isset($constraints['host_match'])) { $result = $result && $this->hostMatch($constraints['host_match']); } if (isset($constraints['host'])) { $result = $result && $this->hostEqual($constraints['host']); } if (isset($constraints['request_method'])) { $result = $result && $this->requestMethodEqual($constraints['request_method']); } if (isset($constraints['path_match'])) { $result = $result && $this->pathMatch($constraints['path_match']); } if (isset($constraints['path'])) { $result = $result && $this->pathEqual($constraints['path']); } // If it matches all constraints, we simply return true and skip other constraints if ($result) { return true; } // try next one } return false; }
php
public function matchConstraints(array $constraints) { foreach ($constraints as $constraint) { $result = true; if (isset($constraints['host_match'])) { $result = $result && $this->hostMatch($constraints['host_match']); } if (isset($constraints['host'])) { $result = $result && $this->hostEqual($constraints['host']); } if (isset($constraints['request_method'])) { $result = $result && $this->requestMethodEqual($constraints['request_method']); } if (isset($constraints['path_match'])) { $result = $result && $this->pathMatch($constraints['path_match']); } if (isset($constraints['path'])) { $result = $result && $this->pathEqual($constraints['path']); } // If it matches all constraints, we simply return true and skip other constraints if ($result) { return true; } // try next one } return false; }
[ "public", "function", "matchConstraints", "(", "array", "$", "constraints", ")", "{", "foreach", "(", "$", "constraints", "as", "$", "constraint", ")", "{", "$", "result", "=", "true", ";", "if", "(", "isset", "(", "$", "constraints", "[", "'host_match'", "]", ")", ")", "{", "$", "result", "=", "$", "result", "&&", "$", "this", "->", "hostMatch", "(", "$", "constraints", "[", "'host_match'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "constraints", "[", "'host'", "]", ")", ")", "{", "$", "result", "=", "$", "result", "&&", "$", "this", "->", "hostEqual", "(", "$", "constraints", "[", "'host'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "constraints", "[", "'request_method'", "]", ")", ")", "{", "$", "result", "=", "$", "result", "&&", "$", "this", "->", "requestMethodEqual", "(", "$", "constraints", "[", "'request_method'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "constraints", "[", "'path_match'", "]", ")", ")", "{", "$", "result", "=", "$", "result", "&&", "$", "this", "->", "pathMatch", "(", "$", "constraints", "[", "'path_match'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "constraints", "[", "'path'", "]", ")", ")", "{", "$", "result", "=", "$", "result", "&&", "$", "this", "->", "pathEqual", "(", "$", "constraints", "[", "'path'", "]", ")", ";", "}", "// If it matches all constraints, we simply return true and skip other constraints", "if", "(", "$", "result", ")", "{", "return", "true", ";", "}", "// try next one", "}", "return", "false", ";", "}" ]
@param contraints[] @return boolean true on match
[ "@param", "contraints", "[]" ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/RouteRequest.php#L70-L102
c9s/Pux
src/RouteRequest.php
RouteRequest.isOneOfHosts
public function isOneOfHosts(array $hosts) { foreach ($hosts as $host) { if ($this->matchHost($host)) { return true; } } return false; }
php
public function isOneOfHosts(array $hosts) { foreach ($hosts as $host) { if ($this->matchHost($host)) { return true; } } return false; }
[ "public", "function", "isOneOfHosts", "(", "array", "$", "hosts", ")", "{", "foreach", "(", "$", "hosts", "as", "$", "host", ")", "{", "if", "(", "$", "this", "->", "matchHost", "(", "$", "host", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if the request host is in the list of host. @param array $hosts @return bool
[ "Check", "if", "the", "request", "host", "is", "in", "the", "list", "of", "host", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/RouteRequest.php#L123-L132
c9s/Pux
src/RouteRequest.php
RouteRequest.create
public static function create($method, $path, array $env = array()) { $request = new self($method, $path); if (function_exists('getallheaders')) { $request->headers = getallheaders(); } else { // TODO: filter array keys by their prefix, consider adding an extension function for this. $request->headers = self::createHeadersFromServerGlobal($env); } if (isset($env['_SERVER'])) { $request->serverParameters = $env['_SERVER']; } else { $request->serverParameters = $env; } $request->parameters = isset($env['_REQUEST']) ? $env['_REQUEST'] : array(); $request->queryParameters = isset($env['_GET']) ? $env['_GET'] : array(); $request->bodyParameters = isset($env['_POST']) ? $env['_POST'] : array(); $request->cookieParameters = isset($env['_COOKIE']) ? $env['_COOKIE'] : array(); $request->sessionParameters = isset($env['_SESSION']) ? $env['_SESSION'] : array(); return $request; }
php
public static function create($method, $path, array $env = array()) { $request = new self($method, $path); if (function_exists('getallheaders')) { $request->headers = getallheaders(); } else { // TODO: filter array keys by their prefix, consider adding an extension function for this. $request->headers = self::createHeadersFromServerGlobal($env); } if (isset($env['_SERVER'])) { $request->serverParameters = $env['_SERVER']; } else { $request->serverParameters = $env; } $request->parameters = isset($env['_REQUEST']) ? $env['_REQUEST'] : array(); $request->queryParameters = isset($env['_GET']) ? $env['_GET'] : array(); $request->bodyParameters = isset($env['_POST']) ? $env['_POST'] : array(); $request->cookieParameters = isset($env['_COOKIE']) ? $env['_COOKIE'] : array(); $request->sessionParameters = isset($env['_SESSION']) ? $env['_SESSION'] : array(); return $request; }
[ "public", "static", "function", "create", "(", "$", "method", ",", "$", "path", ",", "array", "$", "env", "=", "array", "(", ")", ")", "{", "$", "request", "=", "new", "self", "(", "$", "method", ",", "$", "path", ")", ";", "if", "(", "function_exists", "(", "'getallheaders'", ")", ")", "{", "$", "request", "->", "headers", "=", "getallheaders", "(", ")", ";", "}", "else", "{", "// TODO: filter array keys by their prefix, consider adding an extension function for this.", "$", "request", "->", "headers", "=", "self", "::", "createHeadersFromServerGlobal", "(", "$", "env", ")", ";", "}", "if", "(", "isset", "(", "$", "env", "[", "'_SERVER'", "]", ")", ")", "{", "$", "request", "->", "serverParameters", "=", "$", "env", "[", "'_SERVER'", "]", ";", "}", "else", "{", "$", "request", "->", "serverParameters", "=", "$", "env", ";", "}", "$", "request", "->", "parameters", "=", "isset", "(", "$", "env", "[", "'_REQUEST'", "]", ")", "?", "$", "env", "[", "'_REQUEST'", "]", ":", "array", "(", ")", ";", "$", "request", "->", "queryParameters", "=", "isset", "(", "$", "env", "[", "'_GET'", "]", ")", "?", "$", "env", "[", "'_GET'", "]", ":", "array", "(", ")", ";", "$", "request", "->", "bodyParameters", "=", "isset", "(", "$", "env", "[", "'_POST'", "]", ")", "?", "$", "env", "[", "'_POST'", "]", ":", "array", "(", ")", ";", "$", "request", "->", "cookieParameters", "=", "isset", "(", "$", "env", "[", "'_COOKIE'", "]", ")", "?", "$", "env", "[", "'_COOKIE'", "]", ":", "array", "(", ")", ";", "$", "request", "->", "sessionParameters", "=", "isset", "(", "$", "env", "[", "'_SESSION'", "]", ")", "?", "$", "env", "[", "'_SESSION'", "]", ":", "array", "(", ")", ";", "return", "$", "request", ";", "}" ]
A helper function for creating request object based on request method and request uri. @param string $method @param string $path @param array $headers The headers will be built on $_SERVER if the argument is null. @return RouteRequest
[ "A", "helper", "function", "for", "creating", "request", "object", "based", "on", "request", "method", "and", "request", "uri", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/RouteRequest.php#L205-L228
c9s/Pux
src/RouteRequest.php
RouteRequest.createFromEnv
public static function createFromEnv(array $env) { // cache if (isset($env['__request_object'])) { return $env['__request_object']; } if (isset($env['PATH_INFO'])) { $path = $env['PATH_INFO']; } elseif (isset($env['REQUEST_URI'])) { $path = $env['REQUEST_URI']; } elseif (isset($env['_SERVER']['PATH_INFO'])) { $path = $env['_SERVER']['PATH_INFO']; } elseif (isset($env['_SERVER']['REQUEST_URI'])) { $path = $env['_SERVER']['REQUEST_URI']; } else { // XXX: check path or throw exception $path = '/'; } $requestMethod = 'GET'; if (isset($env['REQUEST_METHOD'])) { $requestMethod = $env['REQUEST_METHOD']; } else if (isset($env['_SERVER']['REQUEST_METHOD'])) { // compatibility for superglobal $requestMethod = $env['_SERVER']['REQUEST_METHOD']; } // create request object with request method and path, // we can assign other parameters later. $request = new self($requestMethod, $path); if (function_exists('getallheaders')) { $request->headers = getallheaders(); } else { // TODO: filter array keys by their prefix, consider adding an extension function for this. $request->headers = self::createHeadersFromServerGlobal($env); } if (isset($env['_SERVER'])) { $request->serverParameters = $env['_SERVER']; } else { $request->serverParameters = $env; } $request->parameters = $env['_REQUEST']; $request->queryParameters = $env['_GET']; $request->bodyParameters = $env['_POST']; $request->cookieParameters = $env['_COOKIE']; $request->sessionParameters = $env['_SESSION']; return $env['__request_object'] = $request; }
php
public static function createFromEnv(array $env) { // cache if (isset($env['__request_object'])) { return $env['__request_object']; } if (isset($env['PATH_INFO'])) { $path = $env['PATH_INFO']; } elseif (isset($env['REQUEST_URI'])) { $path = $env['REQUEST_URI']; } elseif (isset($env['_SERVER']['PATH_INFO'])) { $path = $env['_SERVER']['PATH_INFO']; } elseif (isset($env['_SERVER']['REQUEST_URI'])) { $path = $env['_SERVER']['REQUEST_URI']; } else { // XXX: check path or throw exception $path = '/'; } $requestMethod = 'GET'; if (isset($env['REQUEST_METHOD'])) { $requestMethod = $env['REQUEST_METHOD']; } else if (isset($env['_SERVER']['REQUEST_METHOD'])) { // compatibility for superglobal $requestMethod = $env['_SERVER']['REQUEST_METHOD']; } // create request object with request method and path, // we can assign other parameters later. $request = new self($requestMethod, $path); if (function_exists('getallheaders')) { $request->headers = getallheaders(); } else { // TODO: filter array keys by their prefix, consider adding an extension function for this. $request->headers = self::createHeadersFromServerGlobal($env); } if (isset($env['_SERVER'])) { $request->serverParameters = $env['_SERVER']; } else { $request->serverParameters = $env; } $request->parameters = $env['_REQUEST']; $request->queryParameters = $env['_GET']; $request->bodyParameters = $env['_POST']; $request->cookieParameters = $env['_COOKIE']; $request->sessionParameters = $env['_SESSION']; return $env['__request_object'] = $request; }
[ "public", "static", "function", "createFromEnv", "(", "array", "$", "env", ")", "{", "// cache", "if", "(", "isset", "(", "$", "env", "[", "'__request_object'", "]", ")", ")", "{", "return", "$", "env", "[", "'__request_object'", "]", ";", "}", "if", "(", "isset", "(", "$", "env", "[", "'PATH_INFO'", "]", ")", ")", "{", "$", "path", "=", "$", "env", "[", "'PATH_INFO'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "env", "[", "'REQUEST_URI'", "]", ")", ")", "{", "$", "path", "=", "$", "env", "[", "'REQUEST_URI'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "env", "[", "'_SERVER'", "]", "[", "'PATH_INFO'", "]", ")", ")", "{", "$", "path", "=", "$", "env", "[", "'_SERVER'", "]", "[", "'PATH_INFO'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "env", "[", "'_SERVER'", "]", "[", "'REQUEST_URI'", "]", ")", ")", "{", "$", "path", "=", "$", "env", "[", "'_SERVER'", "]", "[", "'REQUEST_URI'", "]", ";", "}", "else", "{", "// XXX: check path or throw exception", "$", "path", "=", "'/'", ";", "}", "$", "requestMethod", "=", "'GET'", ";", "if", "(", "isset", "(", "$", "env", "[", "'REQUEST_METHOD'", "]", ")", ")", "{", "$", "requestMethod", "=", "$", "env", "[", "'REQUEST_METHOD'", "]", ";", "}", "else", "if", "(", "isset", "(", "$", "env", "[", "'_SERVER'", "]", "[", "'REQUEST_METHOD'", "]", ")", ")", "{", "// compatibility for superglobal", "$", "requestMethod", "=", "$", "env", "[", "'_SERVER'", "]", "[", "'REQUEST_METHOD'", "]", ";", "}", "// create request object with request method and path,", "// we can assign other parameters later.", "$", "request", "=", "new", "self", "(", "$", "requestMethod", ",", "$", "path", ")", ";", "if", "(", "function_exists", "(", "'getallheaders'", ")", ")", "{", "$", "request", "->", "headers", "=", "getallheaders", "(", ")", ";", "}", "else", "{", "// TODO: filter array keys by their prefix, consider adding an extension function for this.", "$", "request", "->", "headers", "=", "self", "::", "createHeadersFromServerGlobal", "(", "$", "env", ")", ";", "}", "if", "(", "isset", "(", "$", "env", "[", "'_SERVER'", "]", ")", ")", "{", "$", "request", "->", "serverParameters", "=", "$", "env", "[", "'_SERVER'", "]", ";", "}", "else", "{", "$", "request", "->", "serverParameters", "=", "$", "env", ";", "}", "$", "request", "->", "parameters", "=", "$", "env", "[", "'_REQUEST'", "]", ";", "$", "request", "->", "queryParameters", "=", "$", "env", "[", "'_GET'", "]", ";", "$", "request", "->", "bodyParameters", "=", "$", "env", "[", "'_POST'", "]", ";", "$", "request", "->", "cookieParameters", "=", "$", "env", "[", "'_COOKIE'", "]", ";", "$", "request", "->", "sessionParameters", "=", "$", "env", "[", "'_SESSION'", "]", ";", "return", "$", "env", "[", "'__request_object'", "]", "=", "$", "request", ";", "}" ]
Create request object from global variables. @param array $env @return RouteRequest
[ "Create", "request", "object", "from", "global", "variables", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/RouteRequest.php#L236-L285
c9s/Pux
src/Mux.php
Mux.mount
public function mount($pattern, $mux, array $options = array()) { // Save the mount path in options array $options['mount_path'] = $pattern; if ($mux instanceof Expandable) { $mux = $mux->expand($options); } else if ($mux instanceof Closure) { // we pass the newly created Mux object to the builder closure to initialize routes. if ($ret = $mux($mux = new Mux())) { if ($ret instanceof Mux) { $mux = $ret; } else { throw new LogicException('Invalid object returned from Closure.'); } } } elseif ((!is_object($mux) || !($mux instanceof self)) && is_callable($mux)) { $mux($mux = new self()); } // Save the constructed mux object in options array, so we can fetch // the expanded mux object in controller object later. $mux->setParent($this); $options['mux'] = $mux; if ($this->expand) { $pcre = strpos($pattern,':') !== false; // rewrite submux routes foreach ($mux->routes as $route) { // process for pcre if ($route[0] || $pcre) { $newPattern = $pattern . ( $route[0] ? $route[3]['pattern'] : $route[1] ); $routeArgs = PatternCompiler::compile($newPattern, array_replace_recursive($options, $route[3]) ); $this->appendPCRERoute( $routeArgs, $route[2] ); } else { $this->routes[] = array( false, $pattern . $route[1], $route[2], isset($route[3]) ? array_replace_recursive($options, $route[3]) : $options, ); } } } else { $muxId = $mux->getId(); $this->add($pattern, $muxId, $options); $this->submux[ $muxId ] = $mux; } }
php
public function mount($pattern, $mux, array $options = array()) { // Save the mount path in options array $options['mount_path'] = $pattern; if ($mux instanceof Expandable) { $mux = $mux->expand($options); } else if ($mux instanceof Closure) { // we pass the newly created Mux object to the builder closure to initialize routes. if ($ret = $mux($mux = new Mux())) { if ($ret instanceof Mux) { $mux = $ret; } else { throw new LogicException('Invalid object returned from Closure.'); } } } elseif ((!is_object($mux) || !($mux instanceof self)) && is_callable($mux)) { $mux($mux = new self()); } // Save the constructed mux object in options array, so we can fetch // the expanded mux object in controller object later. $mux->setParent($this); $options['mux'] = $mux; if ($this->expand) { $pcre = strpos($pattern,':') !== false; // rewrite submux routes foreach ($mux->routes as $route) { // process for pcre if ($route[0] || $pcre) { $newPattern = $pattern . ( $route[0] ? $route[3]['pattern'] : $route[1] ); $routeArgs = PatternCompiler::compile($newPattern, array_replace_recursive($options, $route[3]) ); $this->appendPCRERoute( $routeArgs, $route[2] ); } else { $this->routes[] = array( false, $pattern . $route[1], $route[2], isset($route[3]) ? array_replace_recursive($options, $route[3]) : $options, ); } } } else { $muxId = $mux->getId(); $this->add($pattern, $muxId, $options); $this->submux[ $muxId ] = $mux; } }
[ "public", "function", "mount", "(", "$", "pattern", ",", "$", "mux", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "// Save the mount path in options array", "$", "options", "[", "'mount_path'", "]", "=", "$", "pattern", ";", "if", "(", "$", "mux", "instanceof", "Expandable", ")", "{", "$", "mux", "=", "$", "mux", "->", "expand", "(", "$", "options", ")", ";", "}", "else", "if", "(", "$", "mux", "instanceof", "Closure", ")", "{", "// we pass the newly created Mux object to the builder closure to initialize routes.", "if", "(", "$", "ret", "=", "$", "mux", "(", "$", "mux", "=", "new", "Mux", "(", ")", ")", ")", "{", "if", "(", "$", "ret", "instanceof", "Mux", ")", "{", "$", "mux", "=", "$", "ret", ";", "}", "else", "{", "throw", "new", "LogicException", "(", "'Invalid object returned from Closure.'", ")", ";", "}", "}", "}", "elseif", "(", "(", "!", "is_object", "(", "$", "mux", ")", "||", "!", "(", "$", "mux", "instanceof", "self", ")", ")", "&&", "is_callable", "(", "$", "mux", ")", ")", "{", "$", "mux", "(", "$", "mux", "=", "new", "self", "(", ")", ")", ";", "}", "// Save the constructed mux object in options array, so we can fetch", "// the expanded mux object in controller object later.", "$", "mux", "->", "setParent", "(", "$", "this", ")", ";", "$", "options", "[", "'mux'", "]", "=", "$", "mux", ";", "if", "(", "$", "this", "->", "expand", ")", "{", "$", "pcre", "=", "strpos", "(", "$", "pattern", ",", "':'", ")", "!==", "false", ";", "// rewrite submux routes", "foreach", "(", "$", "mux", "->", "routes", "as", "$", "route", ")", "{", "// process for pcre", "if", "(", "$", "route", "[", "0", "]", "||", "$", "pcre", ")", "{", "$", "newPattern", "=", "$", "pattern", ".", "(", "$", "route", "[", "0", "]", "?", "$", "route", "[", "3", "]", "[", "'pattern'", "]", ":", "$", "route", "[", "1", "]", ")", ";", "$", "routeArgs", "=", "PatternCompiler", "::", "compile", "(", "$", "newPattern", ",", "array_replace_recursive", "(", "$", "options", ",", "$", "route", "[", "3", "]", ")", ")", ";", "$", "this", "->", "appendPCRERoute", "(", "$", "routeArgs", ",", "$", "route", "[", "2", "]", ")", ";", "}", "else", "{", "$", "this", "->", "routes", "[", "]", "=", "array", "(", "false", ",", "$", "pattern", ".", "$", "route", "[", "1", "]", ",", "$", "route", "[", "2", "]", ",", "isset", "(", "$", "route", "[", "3", "]", ")", "?", "array_replace_recursive", "(", "$", "options", ",", "$", "route", "[", "3", "]", ")", ":", "$", "options", ",", ")", ";", "}", "}", "}", "else", "{", "$", "muxId", "=", "$", "mux", "->", "getId", "(", ")", ";", "$", "this", "->", "add", "(", "$", "pattern", ",", "$", "muxId", ",", "$", "options", ")", ";", "$", "this", "->", "submux", "[", "$", "muxId", "]", "=", "$", "mux", ";", "}", "}" ]
Mount a Mux or a Controller object on a specific path. @param string $pattern @param Mux|Controller $mux @param array $options
[ "Mount", "a", "Mux", "or", "a", "Controller", "object", "on", "a", "specific", "path", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Mux.php#L132-L188
c9s/Pux
src/Mux.php
Mux.match
public function match($path, RouteRequest $request = null) { $requestMethod = null; if ($request) { $requestMethod = self::convertRequestMethodConstant($request->getRequestMethod()); } else if (isset($_SERVER['REQUEST_METHOD'])) { $requestMethod = self::convertRequestMethodConstant($_SERVER['REQUEST_METHOD']); } foreach ($this->routes as $route) { // If the route is using pcre pattern marching... if ($route[0]) { if (!preg_match($route[1], $path, $matches)) { continue; } $route[3]['vars'] = $matches; // validate request method if (isset($route[3]['method']) && $route[3]['method'] != $requestMethod) { continue; } if (isset($route[3]['domain']) && $route[3]['domain'] != $_SERVER['HTTP_HOST']) { continue; } if (isset($route[3]['secure']) && $route[3]['secure'] && $_SERVER['HTTPS']) { continue; } return $route; } else { // prefix match is used when expanding is not enabled. if (( (is_int($route[2]) || $route[2] instanceof self || $route[2] instanceof \PHPSGI\App) && strncmp($route[1], $path, strlen($route[1])) === 0 ) || $route[1] == $path) { // validate request method if (isset($route[3]['method']) && $route[3]['method'] != $requestMethod) { continue; } if (isset($route[3]['domain']) && $route[3]['domain'] != $_SERVER['HTTP_HOST']) { continue; } if (isset($route[3]['secure']) && $route[3]['secure'] && $_SERVER['HTTPS']) { continue; } return $route; } continue; } } }
php
public function match($path, RouteRequest $request = null) { $requestMethod = null; if ($request) { $requestMethod = self::convertRequestMethodConstant($request->getRequestMethod()); } else if (isset($_SERVER['REQUEST_METHOD'])) { $requestMethod = self::convertRequestMethodConstant($_SERVER['REQUEST_METHOD']); } foreach ($this->routes as $route) { // If the route is using pcre pattern marching... if ($route[0]) { if (!preg_match($route[1], $path, $matches)) { continue; } $route[3]['vars'] = $matches; // validate request method if (isset($route[3]['method']) && $route[3]['method'] != $requestMethod) { continue; } if (isset($route[3]['domain']) && $route[3]['domain'] != $_SERVER['HTTP_HOST']) { continue; } if (isset($route[3]['secure']) && $route[3]['secure'] && $_SERVER['HTTPS']) { continue; } return $route; } else { // prefix match is used when expanding is not enabled. if (( (is_int($route[2]) || $route[2] instanceof self || $route[2] instanceof \PHPSGI\App) && strncmp($route[1], $path, strlen($route[1])) === 0 ) || $route[1] == $path) { // validate request method if (isset($route[3]['method']) && $route[3]['method'] != $requestMethod) { continue; } if (isset($route[3]['domain']) && $route[3]['domain'] != $_SERVER['HTTP_HOST']) { continue; } if (isset($route[3]['secure']) && $route[3]['secure'] && $_SERVER['HTTPS']) { continue; } return $route; } continue; } } }
[ "public", "function", "match", "(", "$", "path", ",", "RouteRequest", "$", "request", "=", "null", ")", "{", "$", "requestMethod", "=", "null", ";", "if", "(", "$", "request", ")", "{", "$", "requestMethod", "=", "self", "::", "convertRequestMethodConstant", "(", "$", "request", "->", "getRequestMethod", "(", ")", ")", ";", "}", "else", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ")", ")", "{", "$", "requestMethod", "=", "self", "::", "convertRequestMethodConstant", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ")", ";", "}", "foreach", "(", "$", "this", "->", "routes", "as", "$", "route", ")", "{", "// If the route is using pcre pattern marching...", "if", "(", "$", "route", "[", "0", "]", ")", "{", "if", "(", "!", "preg_match", "(", "$", "route", "[", "1", "]", ",", "$", "path", ",", "$", "matches", ")", ")", "{", "continue", ";", "}", "$", "route", "[", "3", "]", "[", "'vars'", "]", "=", "$", "matches", ";", "// validate request method", "if", "(", "isset", "(", "$", "route", "[", "3", "]", "[", "'method'", "]", ")", "&&", "$", "route", "[", "3", "]", "[", "'method'", "]", "!=", "$", "requestMethod", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "route", "[", "3", "]", "[", "'domain'", "]", ")", "&&", "$", "route", "[", "3", "]", "[", "'domain'", "]", "!=", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "route", "[", "3", "]", "[", "'secure'", "]", ")", "&&", "$", "route", "[", "3", "]", "[", "'secure'", "]", "&&", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "{", "continue", ";", "}", "return", "$", "route", ";", "}", "else", "{", "// prefix match is used when expanding is not enabled.", "if", "(", "(", "(", "is_int", "(", "$", "route", "[", "2", "]", ")", "||", "$", "route", "[", "2", "]", "instanceof", "self", "||", "$", "route", "[", "2", "]", "instanceof", "\\", "PHPSGI", "\\", "App", ")", "&&", "strncmp", "(", "$", "route", "[", "1", "]", ",", "$", "path", ",", "strlen", "(", "$", "route", "[", "1", "]", ")", ")", "===", "0", ")", "||", "$", "route", "[", "1", "]", "==", "$", "path", ")", "{", "// validate request method", "if", "(", "isset", "(", "$", "route", "[", "3", "]", "[", "'method'", "]", ")", "&&", "$", "route", "[", "3", "]", "[", "'method'", "]", "!=", "$", "requestMethod", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "route", "[", "3", "]", "[", "'domain'", "]", ")", "&&", "$", "route", "[", "3", "]", "[", "'domain'", "]", "!=", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "route", "[", "3", "]", "[", "'secure'", "]", ")", "&&", "$", "route", "[", "3", "]", "[", "'secure'", "]", "&&", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "{", "continue", ";", "}", "return", "$", "route", ";", "}", "continue", ";", "}", "}", "}" ]
Find a matched route with the path constraint in the current mux object. @param string $path @param RouteRequest $request @return array
[ "Find", "a", "matched", "route", "with", "the", "path", "constraint", "in", "the", "current", "mux", "object", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Mux.php#L362-L418
c9s/Pux
src/Mux.php
Mux.dispatch
public function dispatch($path, RouteRequest $request = null) { if ($route = $this->match($path)) { // When the callback is an integer, it's refereing to a submux object. if (is_integer($route[2])) { $submux = $this->submux[$route[2]]; $options = $route[3]; // sub-path and call submux to dispatch // for pcre pattern? if ($route[0]) { $matchedString = $route[3]['vars'][0]; return $submux->dispatch(substr($path, strlen($matchedString))); } else { $s = substr($path, strlen($route[1])); return $submux->dispatch( substr($path, strlen($route[1])) ?: '' ); } } return $route; } }
php
public function dispatch($path, RouteRequest $request = null) { if ($route = $this->match($path)) { // When the callback is an integer, it's refereing to a submux object. if (is_integer($route[2])) { $submux = $this->submux[$route[2]]; $options = $route[3]; // sub-path and call submux to dispatch // for pcre pattern? if ($route[0]) { $matchedString = $route[3]['vars'][0]; return $submux->dispatch(substr($path, strlen($matchedString))); } else { $s = substr($path, strlen($route[1])); return $submux->dispatch( substr($path, strlen($route[1])) ?: '' ); } } return $route; } }
[ "public", "function", "dispatch", "(", "$", "path", ",", "RouteRequest", "$", "request", "=", "null", ")", "{", "if", "(", "$", "route", "=", "$", "this", "->", "match", "(", "$", "path", ")", ")", "{", "// When the callback is an integer, it's refereing to a submux object.", "if", "(", "is_integer", "(", "$", "route", "[", "2", "]", ")", ")", "{", "$", "submux", "=", "$", "this", "->", "submux", "[", "$", "route", "[", "2", "]", "]", ";", "$", "options", "=", "$", "route", "[", "3", "]", ";", "// sub-path and call submux to dispatch", "// for pcre pattern?", "if", "(", "$", "route", "[", "0", "]", ")", "{", "$", "matchedString", "=", "$", "route", "[", "3", "]", "[", "'vars'", "]", "[", "0", "]", ";", "return", "$", "submux", "->", "dispatch", "(", "substr", "(", "$", "path", ",", "strlen", "(", "$", "matchedString", ")", ")", ")", ";", "}", "else", "{", "$", "s", "=", "substr", "(", "$", "path", ",", "strlen", "(", "$", "route", "[", "1", "]", ")", ")", ";", "return", "$", "submux", "->", "dispatch", "(", "substr", "(", "$", "path", ",", "strlen", "(", "$", "route", "[", "1", "]", ")", ")", "?", ":", "''", ")", ";", "}", "}", "return", "$", "route", ";", "}", "}" ]
Match route in the current Mux and submuxes recursively. The RouteRequest object is used for serving request method, host name and other route information. @param string $path @param Pux\RouteRequest $request @return array
[ "Match", "route", "in", "the", "current", "Mux", "and", "submuxes", "recursively", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Mux.php#L436-L463
c9s/Pux
src/Mux.php
Mux.url
public function url($id, array $params = array()) { $route = $this->getRoute($id); if (!isset($route)) { throw new \RuntimeException('Named route not found for id: '.$id); } $search = array(); foreach ($params as $key => $value) { // try to match ':{key}' fragments and replace it with value $search[] = '#:'.preg_quote($key, '#').'\+?(?!\w)#'; } $pattern = preg_replace($search, $params, $route[3]['pattern']); // Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern); }
php
public function url($id, array $params = array()) { $route = $this->getRoute($id); if (!isset($route)) { throw new \RuntimeException('Named route not found for id: '.$id); } $search = array(); foreach ($params as $key => $value) { // try to match ':{key}' fragments and replace it with value $search[] = '#:'.preg_quote($key, '#').'\+?(?!\w)#'; } $pattern = preg_replace($search, $params, $route[3]['pattern']); // Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern); }
[ "public", "function", "url", "(", "$", "id", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "route", "=", "$", "this", "->", "getRoute", "(", "$", "id", ")", ";", "if", "(", "!", "isset", "(", "$", "route", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Named route not found for id: '", ".", "$", "id", ")", ";", "}", "$", "search", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "value", ")", "{", "// try to match ':{key}' fragments and replace it with value", "$", "search", "[", "]", "=", "'#:'", ".", "preg_quote", "(", "$", "key", ",", "'#'", ")", ".", "'\\+?(?!\\w)#'", ";", "}", "$", "pattern", "=", "preg_replace", "(", "$", "search", ",", "$", "params", ",", "$", "route", "[", "3", "]", "[", "'pattern'", "]", ")", ";", "// Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters", "return", "preg_replace", "(", "'#\\(/?:.+\\)|\\(|\\)|\\\\\\\\#'", ",", "''", ",", "$", "pattern", ")", ";", "}" ]
url method generates the related URL for a route. XXX: Untested @see https://github.com/c9s/Pux/issues/4 @param string $id route id @param array $params the parameters for an url @return string
[ "url", "method", "generates", "the", "related", "URL", "for", "a", "route", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Mux.php#L497-L515
c9s/Pux
src/PatternCompiler.php
PatternCompiler.compilePattern
static function compilePattern($pattern, array $options = array()) { $len = strlen($pattern); /** * contains: * * array( 'text', $text ), * array( 'variable', $match[0][0][0], $regexp, $var); * */ $tokens = array(); $variables = array(); $pos = 0; /** * the path like: * * /blog/to/:year/:month * * will be separated like: * * [ * '/blog/to', (text token) * '/:year', (reg exp token) * '/:month', (reg exp token) * ] */ $matches = self::splitTokens($pattern); // build tokens foreach ($matches as $matchIdx => $match) { // match[0][1] // matched position for pattern. /* * Split tokens from abstract pattern * to rebuild regexp pattern. */ if ($text = substr($pattern, $pos, $match[0][1] - $pos)) { $tokens[] = array( self::TOKEN_TYPE_TEXT, $text); } // the first char from pattern (which is the seperater) // and the first char from the next match pattern $seps = array($pattern[$pos]); // collect the separator tokens from the next matched pattern if (isset($matches[$matchIdx + 1])) { $nextMatch = $matches[$matchIdx + 1]; // check if the next pattern is an optional pattern if ($nextMatch[0][0][0] === '(') { $r = self::compilePattern($nextMatch[2][0] ,array()); if (isset($r['tokens'][0][1])) { $seps[] = $r['tokens'][0][1][0]; } } else if ($nextMatch[0][0][0] === ':') { // variable token } else { $seps[] = $nextMatch[0][0][0]; } } $pos = $match[0][1] + strlen($match[0][0]); // generate optional pattern recursively if ($match[0][0][0] == '(' ){ $optional = $match[2][0]; $subroute = self::compilePattern($optional ,array( 'default' => isset($options['default']) ? $options['default'] : null, 'require' => isset($options['require']) ? $options['require'] : null, 'variables' => isset($options['variables']) ? $options['variables'] : null, )); $tokens[] = array( self::TOKEN_TYPE_OPTIONAL, $optional[0], $subroute['regex'], ); foreach( $subroute['variables'] as $var ) { $variables[] = $var; } } else { // generate a variable token $varName = $match[1][0]; // if we defined a pattern for this variable, we should use the given pattern.. if ( isset( $options['require'][$varName] ) && $req = $options['require'][$varName]) { $regexp = $req; } else { if ($pos !== $len) { $seps[] = $pattern[$pos]; } // use the default pattern (which is based on the separater charactors we got) $regexp = sprintf('[^%s]+', preg_quote(implode('', array_unique($seps)), '#')); } // append token item $tokens[] = array(self::TOKEN_TYPE_VARIABLE, $match[0][0][0], $regexp, $varName); // append variable name $variables[] = $varName; } } if ($pos < $len) { $tokens[] = array(self::TOKEN_TYPE_TEXT, substr($pattern, $pos)); } // find the first optional token $firstOptional = INF; for ($i = count($tokens) - 1; $i >= 0; $i--) { if ( self::TOKEN_TYPE_VARIABLE === $tokens[$i][0] && isset($options['default'][ $tokens[$i][3] ]) ) { $firstOptional = $i; } else { break; } } // compute the matching regexp $regex = ''; // indentation level $indent = 1; // token item structure: // [0] => token type, // [1] => separator // [2] => pattern // [3] => name, // first optional token and only one token. if (1 === count($tokens) && 0 === $firstOptional) { $token = $tokens[0]; ++$indent; // output regexp with separator and $regex .= str_repeat(' ', $indent * 4) . sprintf("%s(?:\n", preg_quote($token[1], '#')); // regular expression with place holder name. (?P<name>pattern) $regex .= str_repeat(' ', $indent * 4) . sprintf("(?P<%s>%s)\n", $token[3], $token[2]); } else { foreach ($tokens as $i => $token) { switch ( $token[0] ) { case self::TOKEN_TYPE_TEXT: $regex .= str_repeat(' ', $indent * 4) . preg_quote($token[1], '#')."\n"; break; case self::TOKEN_TYPE_OPTIONAL: // the question mark is for optional, the optional item may contains multiple tokens and patterns $regex .= str_repeat(' ', $indent * 4) . "(?:\n" . $token[2] . str_repeat(' ', $indent * 4) . ")?\n"; break; default: // append new pattern group for the optional pattern if ($i >= $firstOptional) { $regex .= str_repeat(' ', $indent * 4) . "(?:\n"; ++$indent; } $regex .= str_repeat(' ', $indent * 4). sprintf("%s(?P<%s>%s)\n", preg_quote($token[1], '#'), $token[3], $token[2]); break; } } } // close groups while (--$indent) { $regex .= str_repeat(' ', $indent * 4).")?\n"; } // save variables $options['variables'] = $variables; $options['regex'] = $regex; $options['tokens'] = $tokens; return $options; }
php
static function compilePattern($pattern, array $options = array()) { $len = strlen($pattern); /** * contains: * * array( 'text', $text ), * array( 'variable', $match[0][0][0], $regexp, $var); * */ $tokens = array(); $variables = array(); $pos = 0; /** * the path like: * * /blog/to/:year/:month * * will be separated like: * * [ * '/blog/to', (text token) * '/:year', (reg exp token) * '/:month', (reg exp token) * ] */ $matches = self::splitTokens($pattern); // build tokens foreach ($matches as $matchIdx => $match) { // match[0][1] // matched position for pattern. /* * Split tokens from abstract pattern * to rebuild regexp pattern. */ if ($text = substr($pattern, $pos, $match[0][1] - $pos)) { $tokens[] = array( self::TOKEN_TYPE_TEXT, $text); } // the first char from pattern (which is the seperater) // and the first char from the next match pattern $seps = array($pattern[$pos]); // collect the separator tokens from the next matched pattern if (isset($matches[$matchIdx + 1])) { $nextMatch = $matches[$matchIdx + 1]; // check if the next pattern is an optional pattern if ($nextMatch[0][0][0] === '(') { $r = self::compilePattern($nextMatch[2][0] ,array()); if (isset($r['tokens'][0][1])) { $seps[] = $r['tokens'][0][1][0]; } } else if ($nextMatch[0][0][0] === ':') { // variable token } else { $seps[] = $nextMatch[0][0][0]; } } $pos = $match[0][1] + strlen($match[0][0]); // generate optional pattern recursively if ($match[0][0][0] == '(' ){ $optional = $match[2][0]; $subroute = self::compilePattern($optional ,array( 'default' => isset($options['default']) ? $options['default'] : null, 'require' => isset($options['require']) ? $options['require'] : null, 'variables' => isset($options['variables']) ? $options['variables'] : null, )); $tokens[] = array( self::TOKEN_TYPE_OPTIONAL, $optional[0], $subroute['regex'], ); foreach( $subroute['variables'] as $var ) { $variables[] = $var; } } else { // generate a variable token $varName = $match[1][0]; // if we defined a pattern for this variable, we should use the given pattern.. if ( isset( $options['require'][$varName] ) && $req = $options['require'][$varName]) { $regexp = $req; } else { if ($pos !== $len) { $seps[] = $pattern[$pos]; } // use the default pattern (which is based on the separater charactors we got) $regexp = sprintf('[^%s]+', preg_quote(implode('', array_unique($seps)), '#')); } // append token item $tokens[] = array(self::TOKEN_TYPE_VARIABLE, $match[0][0][0], $regexp, $varName); // append variable name $variables[] = $varName; } } if ($pos < $len) { $tokens[] = array(self::TOKEN_TYPE_TEXT, substr($pattern, $pos)); } // find the first optional token $firstOptional = INF; for ($i = count($tokens) - 1; $i >= 0; $i--) { if ( self::TOKEN_TYPE_VARIABLE === $tokens[$i][0] && isset($options['default'][ $tokens[$i][3] ]) ) { $firstOptional = $i; } else { break; } } // compute the matching regexp $regex = ''; // indentation level $indent = 1; // token item structure: // [0] => token type, // [1] => separator // [2] => pattern // [3] => name, // first optional token and only one token. if (1 === count($tokens) && 0 === $firstOptional) { $token = $tokens[0]; ++$indent; // output regexp with separator and $regex .= str_repeat(' ', $indent * 4) . sprintf("%s(?:\n", preg_quote($token[1], '#')); // regular expression with place holder name. (?P<name>pattern) $regex .= str_repeat(' ', $indent * 4) . sprintf("(?P<%s>%s)\n", $token[3], $token[2]); } else { foreach ($tokens as $i => $token) { switch ( $token[0] ) { case self::TOKEN_TYPE_TEXT: $regex .= str_repeat(' ', $indent * 4) . preg_quote($token[1], '#')."\n"; break; case self::TOKEN_TYPE_OPTIONAL: // the question mark is for optional, the optional item may contains multiple tokens and patterns $regex .= str_repeat(' ', $indent * 4) . "(?:\n" . $token[2] . str_repeat(' ', $indent * 4) . ")?\n"; break; default: // append new pattern group for the optional pattern if ($i >= $firstOptional) { $regex .= str_repeat(' ', $indent * 4) . "(?:\n"; ++$indent; } $regex .= str_repeat(' ', $indent * 4). sprintf("%s(?P<%s>%s)\n", preg_quote($token[1], '#'), $token[3], $token[2]); break; } } } // close groups while (--$indent) { $regex .= str_repeat(' ', $indent * 4).")?\n"; } // save variables $options['variables'] = $variables; $options['regex'] = $regex; $options['tokens'] = $tokens; return $options; }
[ "static", "function", "compilePattern", "(", "$", "pattern", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "len", "=", "strlen", "(", "$", "pattern", ")", ";", "/**\n * contains:\n *\n * array( 'text', $text ),\n * array( 'variable', $match[0][0][0], $regexp, $var);\n *\n */", "$", "tokens", "=", "array", "(", ")", ";", "$", "variables", "=", "array", "(", ")", ";", "$", "pos", "=", "0", ";", "/**\n * the path like:\n *\n * /blog/to/:year/:month\n *\n * will be separated like:\n * \n * [\n * '/blog/to', (text token)\n * '/:year', (reg exp token)\n * '/:month', (reg exp token)\n * ]\n */", "$", "matches", "=", "self", "::", "splitTokens", "(", "$", "pattern", ")", ";", "// build tokens", "foreach", "(", "$", "matches", "as", "$", "matchIdx", "=>", "$", "match", ")", "{", "// match[0][1] // matched position for pattern.", "/*\n * Split tokens from abstract pattern\n * to rebuild regexp pattern.\n */", "if", "(", "$", "text", "=", "substr", "(", "$", "pattern", ",", "$", "pos", ",", "$", "match", "[", "0", "]", "[", "1", "]", "-", "$", "pos", ")", ")", "{", "$", "tokens", "[", "]", "=", "array", "(", "self", "::", "TOKEN_TYPE_TEXT", ",", "$", "text", ")", ";", "}", "// the first char from pattern (which is the seperater)", "// and the first char from the next match pattern", "$", "seps", "=", "array", "(", "$", "pattern", "[", "$", "pos", "]", ")", ";", "// collect the separator tokens from the next matched pattern", "if", "(", "isset", "(", "$", "matches", "[", "$", "matchIdx", "+", "1", "]", ")", ")", "{", "$", "nextMatch", "=", "$", "matches", "[", "$", "matchIdx", "+", "1", "]", ";", "// check if the next pattern is an optional pattern", "if", "(", "$", "nextMatch", "[", "0", "]", "[", "0", "]", "[", "0", "]", "===", "'('", ")", "{", "$", "r", "=", "self", "::", "compilePattern", "(", "$", "nextMatch", "[", "2", "]", "[", "0", "]", ",", "array", "(", ")", ")", ";", "if", "(", "isset", "(", "$", "r", "[", "'tokens'", "]", "[", "0", "]", "[", "1", "]", ")", ")", "{", "$", "seps", "[", "]", "=", "$", "r", "[", "'tokens'", "]", "[", "0", "]", "[", "1", "]", "[", "0", "]", ";", "}", "}", "else", "if", "(", "$", "nextMatch", "[", "0", "]", "[", "0", "]", "[", "0", "]", "===", "':'", ")", "{", "// variable token", "}", "else", "{", "$", "seps", "[", "]", "=", "$", "nextMatch", "[", "0", "]", "[", "0", "]", "[", "0", "]", ";", "}", "}", "$", "pos", "=", "$", "match", "[", "0", "]", "[", "1", "]", "+", "strlen", "(", "$", "match", "[", "0", "]", "[", "0", "]", ")", ";", "// generate optional pattern recursively", "if", "(", "$", "match", "[", "0", "]", "[", "0", "]", "[", "0", "]", "==", "'('", ")", "{", "$", "optional", "=", "$", "match", "[", "2", "]", "[", "0", "]", ";", "$", "subroute", "=", "self", "::", "compilePattern", "(", "$", "optional", ",", "array", "(", "'default'", "=>", "isset", "(", "$", "options", "[", "'default'", "]", ")", "?", "$", "options", "[", "'default'", "]", ":", "null", ",", "'require'", "=>", "isset", "(", "$", "options", "[", "'require'", "]", ")", "?", "$", "options", "[", "'require'", "]", ":", "null", ",", "'variables'", "=>", "isset", "(", "$", "options", "[", "'variables'", "]", ")", "?", "$", "options", "[", "'variables'", "]", ":", "null", ",", ")", ")", ";", "$", "tokens", "[", "]", "=", "array", "(", "self", "::", "TOKEN_TYPE_OPTIONAL", ",", "$", "optional", "[", "0", "]", ",", "$", "subroute", "[", "'regex'", "]", ",", ")", ";", "foreach", "(", "$", "subroute", "[", "'variables'", "]", "as", "$", "var", ")", "{", "$", "variables", "[", "]", "=", "$", "var", ";", "}", "}", "else", "{", "// generate a variable token ", "$", "varName", "=", "$", "match", "[", "1", "]", "[", "0", "]", ";", "// if we defined a pattern for this variable, we should use the given pattern..", "if", "(", "isset", "(", "$", "options", "[", "'require'", "]", "[", "$", "varName", "]", ")", "&&", "$", "req", "=", "$", "options", "[", "'require'", "]", "[", "$", "varName", "]", ")", "{", "$", "regexp", "=", "$", "req", ";", "}", "else", "{", "if", "(", "$", "pos", "!==", "$", "len", ")", "{", "$", "seps", "[", "]", "=", "$", "pattern", "[", "$", "pos", "]", ";", "}", "// use the default pattern (which is based on the separater charactors we got)", "$", "regexp", "=", "sprintf", "(", "'[^%s]+'", ",", "preg_quote", "(", "implode", "(", "''", ",", "array_unique", "(", "$", "seps", ")", ")", ",", "'#'", ")", ")", ";", "}", "// append token item", "$", "tokens", "[", "]", "=", "array", "(", "self", "::", "TOKEN_TYPE_VARIABLE", ",", "$", "match", "[", "0", "]", "[", "0", "]", "[", "0", "]", ",", "$", "regexp", ",", "$", "varName", ")", ";", "// append variable name", "$", "variables", "[", "]", "=", "$", "varName", ";", "}", "}", "if", "(", "$", "pos", "<", "$", "len", ")", "{", "$", "tokens", "[", "]", "=", "array", "(", "self", "::", "TOKEN_TYPE_TEXT", ",", "substr", "(", "$", "pattern", ",", "$", "pos", ")", ")", ";", "}", "// find the first optional token", "$", "firstOptional", "=", "INF", ";", "for", "(", "$", "i", "=", "count", "(", "$", "tokens", ")", "-", "1", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "if", "(", "self", "::", "TOKEN_TYPE_VARIABLE", "===", "$", "tokens", "[", "$", "i", "]", "[", "0", "]", "&&", "isset", "(", "$", "options", "[", "'default'", "]", "[", "$", "tokens", "[", "$", "i", "]", "[", "3", "]", "]", ")", ")", "{", "$", "firstOptional", "=", "$", "i", ";", "}", "else", "{", "break", ";", "}", "}", "// compute the matching regexp", "$", "regex", "=", "''", ";", "// indentation level", "$", "indent", "=", "1", ";", "// token item structure:", "// [0] => token type,", "// [1] => separator", "// [2] => pattern", "// [3] => name, ", "// first optional token and only one token.", "if", "(", "1", "===", "count", "(", "$", "tokens", ")", "&&", "0", "===", "$", "firstOptional", ")", "{", "$", "token", "=", "$", "tokens", "[", "0", "]", ";", "++", "$", "indent", ";", "// output regexp with separator and", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "sprintf", "(", "\"%s(?:\\n\"", ",", "preg_quote", "(", "$", "token", "[", "1", "]", ",", "'#'", ")", ")", ";", "// regular expression with place holder name. (?P<name>pattern)", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "sprintf", "(", "\"(?P<%s>%s)\\n\"", ",", "$", "token", "[", "3", "]", ",", "$", "token", "[", "2", "]", ")", ";", "}", "else", "{", "foreach", "(", "$", "tokens", "as", "$", "i", "=>", "$", "token", ")", "{", "switch", "(", "$", "token", "[", "0", "]", ")", "{", "case", "self", "::", "TOKEN_TYPE_TEXT", ":", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "preg_quote", "(", "$", "token", "[", "1", "]", ",", "'#'", ")", ".", "\"\\n\"", ";", "break", ";", "case", "self", "::", "TOKEN_TYPE_OPTIONAL", ":", "// the question mark is for optional, the optional item may contains multiple tokens and patterns", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "\"(?:\\n\"", ".", "$", "token", "[", "2", "]", ".", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "\")?\\n\"", ";", "break", ";", "default", ":", "// append new pattern group for the optional pattern", "if", "(", "$", "i", ">=", "$", "firstOptional", ")", "{", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "\"(?:\\n\"", ";", "++", "$", "indent", ";", "}", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "sprintf", "(", "\"%s(?P<%s>%s)\\n\"", ",", "preg_quote", "(", "$", "token", "[", "1", "]", ",", "'#'", ")", ",", "$", "token", "[", "3", "]", ",", "$", "token", "[", "2", "]", ")", ";", "break", ";", "}", "}", "}", "// close groups", "while", "(", "--", "$", "indent", ")", "{", "$", "regex", ".=", "str_repeat", "(", "' '", ",", "$", "indent", "*", "4", ")", ".", "\")?\\n\"", ";", "}", "// save variables", "$", "options", "[", "'variables'", "]", "=", "$", "variables", ";", "$", "options", "[", "'regex'", "]", "=", "$", "regex", ";", "$", "options", "[", "'tokens'", "]", "=", "$", "tokens", ";", "return", "$", "options", ";", "}" ]
compile pattern @param string $pattern @param array $options
[ "compile", "pattern" ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/PatternCompiler.php#L25-L214
c9s/Pux
src/PatternCompiler.php
PatternCompiler.compile
static function compile($pattern, array $options = array()) { $route = self::compilePattern($pattern, $options); // save compiled pattern $route['compiled'] = sprintf("#^%s$#xs", $route['regex']); $route['pattern'] = $pattern; // save pattern return $route; }
php
static function compile($pattern, array $options = array()) { $route = self::compilePattern($pattern, $options); // save compiled pattern $route['compiled'] = sprintf("#^%s$#xs", $route['regex']); $route['pattern'] = $pattern; // save pattern return $route; }
[ "static", "function", "compile", "(", "$", "pattern", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "route", "=", "self", "::", "compilePattern", "(", "$", "pattern", ",", "$", "options", ")", ";", "// save compiled pattern", "$", "route", "[", "'compiled'", "]", "=", "sprintf", "(", "\"#^%s$#xs\"", ",", "$", "route", "[", "'regex'", "]", ")", ";", "$", "route", "[", "'pattern'", "]", "=", "$", "pattern", ";", "// save pattern", "return", "$", "route", ";", "}" ]
Compiles the current route instance. @param array $route route info @return array compiled route info, with newly added 'compiled' key.
[ "Compiles", "the", "current", "route", "instance", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/PatternCompiler.php#L245-L253
c9s/Pux
src/MuxCompiler.php
MuxCompiler.validateRouteCallback
public function validateRouteCallback(array $routes) { foreach ($routes as $route) { $callback = $route[2]; if (is_array($callback)) { $class = $callback[0]; $method = $callback[1]; if (!class_exists($class, true)) { throw new Exception("Controller {$class} does not exist."); } // rebless a controller (extract this to common method) $controller = new $class(); if (!method_exists($controller, $method)) { throw new Exception("Method $method not found in controller $class."); } } } }
php
public function validateRouteCallback(array $routes) { foreach ($routes as $route) { $callback = $route[2]; if (is_array($callback)) { $class = $callback[0]; $method = $callback[1]; if (!class_exists($class, true)) { throw new Exception("Controller {$class} does not exist."); } // rebless a controller (extract this to common method) $controller = new $class(); if (!method_exists($controller, $method)) { throw new Exception("Method $method not found in controller $class."); } } } }
[ "public", "function", "validateRouteCallback", "(", "array", "$", "routes", ")", "{", "foreach", "(", "$", "routes", "as", "$", "route", ")", "{", "$", "callback", "=", "$", "route", "[", "2", "]", ";", "if", "(", "is_array", "(", "$", "callback", ")", ")", "{", "$", "class", "=", "$", "callback", "[", "0", "]", ";", "$", "method", "=", "$", "callback", "[", "1", "]", ";", "if", "(", "!", "class_exists", "(", "$", "class", ",", "true", ")", ")", "{", "throw", "new", "Exception", "(", "\"Controller {$class} does not exist.\"", ")", ";", "}", "// rebless a controller (extract this to common method)", "$", "controller", "=", "new", "$", "class", "(", ")", ";", "if", "(", "!", "method_exists", "(", "$", "controller", ",", "$", "method", ")", ")", "{", "throw", "new", "Exception", "(", "\"Method $method not found in controller $class.\"", ")", ";", "}", "}", "}", "}" ]
validate controller classes and controller methods before compiling to route cache.
[ "validate", "controller", "classes", "and", "controller", "methods", "before", "compiling", "to", "route", "cache", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/MuxCompiler.php#L91-L108
c9s/Pux
src/MuxCompiler.php
MuxCompiler.compile
public function compile($outFile) { // compile routes to php file as a cache. usort($this->mux->routes, array('Pux\\MuxCompiler', 'sort_routes')); $code = $this->mux->export(); return file_put_contents($outFile, '<?php return '.$code.'; /* version */'); }
php
public function compile($outFile) { // compile routes to php file as a cache. usort($this->mux->routes, array('Pux\\MuxCompiler', 'sort_routes')); $code = $this->mux->export(); return file_put_contents($outFile, '<?php return '.$code.'; /* version */'); }
[ "public", "function", "compile", "(", "$", "outFile", ")", "{", "// compile routes to php file as a cache.", "usort", "(", "$", "this", "->", "mux", "->", "routes", ",", "array", "(", "'Pux\\\\MuxCompiler'", ",", "'sort_routes'", ")", ")", ";", "$", "code", "=", "$", "this", "->", "mux", "->", "export", "(", ")", ";", "return", "file_put_contents", "(", "$", "outFile", ",", "'<?php return '", ".", "$", "code", ".", "'; /* version */'", ")", ";", "}" ]
Compile merged routes to file.
[ "Compile", "merged", "routes", "to", "file", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/MuxCompiler.php#L148-L156
c9s/Pux
src/Controller/RESTfulController.php
RESTfulController.expand
public function expand(array $options = array(), $dynamic = false) { $mux = new Mux(); $target = $dynamic ? $this : $this->getClass(); $mux->add('/:id', [$target, 'updateAction'], array_merge($options, array('method' => REQUEST_METHOD_POST ))); $mux->add('/:id', [$target, 'loadAction'], array_merge($options, array('method' => REQUEST_METHOD_GET ))); $mux->add('/:id', [$target, 'deleteAction'], array_merge($options, array('method' => REQUEST_METHOD_DELETE ))); $mux->add('', [$target, 'createAction'], array_merge($options, array('method' => REQUEST_METHOD_POST ))); $mux->add('', [$target, 'collectionAction'], array_merge($options, array('method' => REQUEST_METHOD_GET ))); return $mux; }
php
public function expand(array $options = array(), $dynamic = false) { $mux = new Mux(); $target = $dynamic ? $this : $this->getClass(); $mux->add('/:id', [$target, 'updateAction'], array_merge($options, array('method' => REQUEST_METHOD_POST ))); $mux->add('/:id', [$target, 'loadAction'], array_merge($options, array('method' => REQUEST_METHOD_GET ))); $mux->add('/:id', [$target, 'deleteAction'], array_merge($options, array('method' => REQUEST_METHOD_DELETE ))); $mux->add('', [$target, 'createAction'], array_merge($options, array('method' => REQUEST_METHOD_POST ))); $mux->add('', [$target, 'collectionAction'], array_merge($options, array('method' => REQUEST_METHOD_GET ))); return $mux; }
[ "public", "function", "expand", "(", "array", "$", "options", "=", "array", "(", ")", ",", "$", "dynamic", "=", "false", ")", "{", "$", "mux", "=", "new", "Mux", "(", ")", ";", "$", "target", "=", "$", "dynamic", "?", "$", "this", ":", "$", "this", "->", "getClass", "(", ")", ";", "$", "mux", "->", "add", "(", "'/:id'", ",", "[", "$", "target", ",", "'updateAction'", "]", ",", "array_merge", "(", "$", "options", ",", "array", "(", "'method'", "=>", "REQUEST_METHOD_POST", ")", ")", ")", ";", "$", "mux", "->", "add", "(", "'/:id'", ",", "[", "$", "target", ",", "'loadAction'", "]", ",", "array_merge", "(", "$", "options", ",", "array", "(", "'method'", "=>", "REQUEST_METHOD_GET", ")", ")", ")", ";", "$", "mux", "->", "add", "(", "'/:id'", ",", "[", "$", "target", ",", "'deleteAction'", "]", ",", "array_merge", "(", "$", "options", ",", "array", "(", "'method'", "=>", "REQUEST_METHOD_DELETE", ")", ")", ")", ";", "$", "mux", "->", "add", "(", "''", ",", "[", "$", "target", ",", "'createAction'", "]", ",", "array_merge", "(", "$", "options", ",", "array", "(", "'method'", "=>", "REQUEST_METHOD_POST", ")", ")", ")", ";", "$", "mux", "->", "add", "(", "''", ",", "[", "$", "target", ",", "'collectionAction'", "]", ",", "array_merge", "(", "$", "options", ",", "array", "(", "'method'", "=>", "REQUEST_METHOD_GET", ")", ")", ")", ";", "return", "$", "mux", ";", "}" ]
Expand controller actions into Mux object @return Mux
[ "Expand", "controller", "actions", "into", "Mux", "object" ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/Controller/RESTfulController.php#L61-L71
c9s/Pux
src/MuxBuilder/RESTfulMuxBuilder.php
RESTfulMuxBuilder.addResource
public function addResource($resourceId, Expandable $controller) { $this->resources[$resourceId] = $controller; $prefix = $this->options['prefix']; $resourceMux = $controller->expand(); $path = $prefix . '/' . $resourceId; $this->mux->mount($path, $resourceMux); }
php
public function addResource($resourceId, Expandable $controller) { $this->resources[$resourceId] = $controller; $prefix = $this->options['prefix']; $resourceMux = $controller->expand(); $path = $prefix . '/' . $resourceId; $this->mux->mount($path, $resourceMux); }
[ "public", "function", "addResource", "(", "$", "resourceId", ",", "Expandable", "$", "controller", ")", "{", "$", "this", "->", "resources", "[", "$", "resourceId", "]", "=", "$", "controller", ";", "$", "prefix", "=", "$", "this", "->", "options", "[", "'prefix'", "]", ";", "$", "resourceMux", "=", "$", "controller", "->", "expand", "(", ")", ";", "$", "path", "=", "$", "prefix", ".", "'/'", ".", "$", "resourceId", ";", "$", "this", "->", "mux", "->", "mount", "(", "$", "path", ",", "$", "resourceMux", ")", ";", "}" ]
Register a RESTful resource into the Mux object. @param string $resourceId the RESTful resource ID @param Expandable $controller a controller object that implements Expandable interface.
[ "Register", "a", "RESTful", "resource", "into", "the", "Mux", "object", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/MuxBuilder/RESTfulMuxBuilder.php#L46-L54
c9s/Pux
src/MuxBuilder/RESTfulMuxBuilder.php
RESTfulMuxBuilder.build
public function build() { $prefix = $this->options['prefix']; foreach ($this->resources as $resId => $controller) { $resourceMux = $controller->expand(); $path = $prefix . '/' . $resId; $this->mux->mount($path, $resourceMux); } return $this->mux; }
php
public function build() { $prefix = $this->options['prefix']; foreach ($this->resources as $resId => $controller) { $resourceMux = $controller->expand(); $path = $prefix . '/' . $resId; $this->mux->mount($path, $resourceMux); } return $this->mux; }
[ "public", "function", "build", "(", ")", "{", "$", "prefix", "=", "$", "this", "->", "options", "[", "'prefix'", "]", ";", "foreach", "(", "$", "this", "->", "resources", "as", "$", "resId", "=>", "$", "controller", ")", "{", "$", "resourceMux", "=", "$", "controller", "->", "expand", "(", ")", ";", "$", "path", "=", "$", "prefix", ".", "'/'", ".", "$", "resId", ";", "$", "this", "->", "mux", "->", "mount", "(", "$", "path", ",", "$", "resourceMux", ")", ";", "}", "return", "$", "this", "->", "mux", ";", "}" ]
build method returns a Mux object with registered resources. @return Pux\Mux
[ "build", "method", "returns", "a", "Mux", "object", "with", "registered", "resources", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/MuxBuilder/RESTfulMuxBuilder.php#L62-L71
c9s/Pux
src/RouteExecutor.php
RouteExecutor.callback
public static function callback($handler) { if ($handler instanceof Closure) { return $handler; } if (is_object($handler[0])) { return $handler; } // If the first argument is a class name string, // then create the controller object. if (is_string($handler[0])) { // If users define the constructor arguments in options array. $constructArgs = []; $rc = new ReflectionClass($handler[0]); if (isset($options['constructor_args'])) { $con = $handler[0] = $rc->newInstanceArgs($constructArgs); } else { $con = $handler[0] = $rc->newInstance(); } return $handler; } throw new LogicException('Unsupported handler type'); }
php
public static function callback($handler) { if ($handler instanceof Closure) { return $handler; } if (is_object($handler[0])) { return $handler; } // If the first argument is a class name string, // then create the controller object. if (is_string($handler[0])) { // If users define the constructor arguments in options array. $constructArgs = []; $rc = new ReflectionClass($handler[0]); if (isset($options['constructor_args'])) { $con = $handler[0] = $rc->newInstanceArgs($constructArgs); } else { $con = $handler[0] = $rc->newInstance(); } return $handler; } throw new LogicException('Unsupported handler type'); }
[ "public", "static", "function", "callback", "(", "$", "handler", ")", "{", "if", "(", "$", "handler", "instanceof", "Closure", ")", "{", "return", "$", "handler", ";", "}", "if", "(", "is_object", "(", "$", "handler", "[", "0", "]", ")", ")", "{", "return", "$", "handler", ";", "}", "// If the first argument is a class name string,", "// then create the controller object.", "if", "(", "is_string", "(", "$", "handler", "[", "0", "]", ")", ")", "{", "// If users define the constructor arguments in options array.", "$", "constructArgs", "=", "[", "]", ";", "$", "rc", "=", "new", "ReflectionClass", "(", "$", "handler", "[", "0", "]", ")", ";", "if", "(", "isset", "(", "$", "options", "[", "'constructor_args'", "]", ")", ")", "{", "$", "con", "=", "$", "handler", "[", "0", "]", "=", "$", "rc", "->", "newInstanceArgs", "(", "$", "constructArgs", ")", ";", "}", "else", "{", "$", "con", "=", "$", "handler", "[", "0", "]", "=", "$", "rc", "->", "newInstance", "(", ")", ";", "}", "return", "$", "handler", ";", "}", "throw", "new", "LogicException", "(", "'Unsupported handler type'", ")", ";", "}" ]
When creating the controller instance, we don't care about the environment. The returned object should be a PHPSGI app, so that we can always execute "call" on the returned object. @return Closure|PHPSGI\App|Controller
[ "When", "creating", "the", "controller", "instance", "we", "don", "t", "care", "about", "the", "environment", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/RouteExecutor.php#L21-L47
c9s/Pux
src/RouteExecutor.php
RouteExecutor.execute
public static function execute(array $route, array $environment = array(), array $response = array()) { list($pcre, $pattern, $callbackArg, $options) = $route; $callback = self::callback($callbackArg); $environment['pux.route'] = $route; if (is_array($callback) && $callback[0] instanceof Controller) { $environment['pux.controller'] = $callback[0]; $environment['pux.controller_action'] = $callback[1]; } if ($callback instanceof Closure) { $return = $callback($environment, $response); } else if ($callback[0] instanceof \PHPSGI\App) { $return = $callback[0]->call($environment, $response); } else if (is_callable($callback)) { $return = call_user_func($callback, $environment, $response); } else { throw new \LogicException("Invalid callback type."); } // Response fix if (is_string($return)) { if (!isset($response[0])) { $response[0] = 200; } if (!isset($response[1])) { $response[1] = []; } if (!isset($response[2])) { $response[2] = $return; } return $response; } return $return; }
php
public static function execute(array $route, array $environment = array(), array $response = array()) { list($pcre, $pattern, $callbackArg, $options) = $route; $callback = self::callback($callbackArg); $environment['pux.route'] = $route; if (is_array($callback) && $callback[0] instanceof Controller) { $environment['pux.controller'] = $callback[0]; $environment['pux.controller_action'] = $callback[1]; } if ($callback instanceof Closure) { $return = $callback($environment, $response); } else if ($callback[0] instanceof \PHPSGI\App) { $return = $callback[0]->call($environment, $response); } else if (is_callable($callback)) { $return = call_user_func($callback, $environment, $response); } else { throw new \LogicException("Invalid callback type."); } // Response fix if (is_string($return)) { if (!isset($response[0])) { $response[0] = 200; } if (!isset($response[1])) { $response[1] = []; } if (!isset($response[2])) { $response[2] = $return; } return $response; } return $return; }
[ "public", "static", "function", "execute", "(", "array", "$", "route", ",", "array", "$", "environment", "=", "array", "(", ")", ",", "array", "$", "response", "=", "array", "(", ")", ")", "{", "list", "(", "$", "pcre", ",", "$", "pattern", ",", "$", "callbackArg", ",", "$", "options", ")", "=", "$", "route", ";", "$", "callback", "=", "self", "::", "callback", "(", "$", "callbackArg", ")", ";", "$", "environment", "[", "'pux.route'", "]", "=", "$", "route", ";", "if", "(", "is_array", "(", "$", "callback", ")", "&&", "$", "callback", "[", "0", "]", "instanceof", "Controller", ")", "{", "$", "environment", "[", "'pux.controller'", "]", "=", "$", "callback", "[", "0", "]", ";", "$", "environment", "[", "'pux.controller_action'", "]", "=", "$", "callback", "[", "1", "]", ";", "}", "if", "(", "$", "callback", "instanceof", "Closure", ")", "{", "$", "return", "=", "$", "callback", "(", "$", "environment", ",", "$", "response", ")", ";", "}", "else", "if", "(", "$", "callback", "[", "0", "]", "instanceof", "\\", "PHPSGI", "\\", "App", ")", "{", "$", "return", "=", "$", "callback", "[", "0", "]", "->", "call", "(", "$", "environment", ",", "$", "response", ")", ";", "}", "else", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "return", "=", "call_user_func", "(", "$", "callback", ",", "$", "environment", ",", "$", "response", ")", ";", "}", "else", "{", "throw", "new", "\\", "LogicException", "(", "\"Invalid callback type.\"", ")", ";", "}", "// Response fix", "if", "(", "is_string", "(", "$", "return", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "response", "[", "0", "]", ")", ")", "{", "$", "response", "[", "0", "]", "=", "200", ";", "}", "if", "(", "!", "isset", "(", "$", "response", "[", "1", "]", ")", ")", "{", "$", "response", "[", "1", "]", "=", "[", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "response", "[", "2", "]", ")", ")", "{", "$", "response", "[", "2", "]", "=", "$", "return", ";", "}", "return", "$", "response", ";", "}", "return", "$", "return", ";", "}" ]
Execute the matched route. This method currently do two things: 1. create the controller from the route arguments. 2. executet the controller method by the config defined in route arguments. $route: {pcre flag}, {pattern}, {callback}, {options} *callback*: The callback argument can be an array that contains a class name and a method name to be called. a closure object or a function name. *options*: 'constructor_args': arguments for constructing controller object. @return string the response
[ "Execute", "the", "matched", "route", "." ]
train
https://github.com/c9s/Pux/blob/a59bf0c72738859159900990c80e10f533f18109/src/RouteExecutor.php#L71-L108
grasmash/expander
src/Expander.php
Expander.expandArrayProperties
public function expandArrayProperties($array, $reference_array = []) { $data = new Data($array); if ($reference_array) { $reference_data = new Data($reference_array); $this->doExpandArrayProperties($data, $array, '', $reference_data); } else { $this->doExpandArrayProperties($data, $array); } return $data->export(); }
php
public function expandArrayProperties($array, $reference_array = []) { $data = new Data($array); if ($reference_array) { $reference_data = new Data($reference_array); $this->doExpandArrayProperties($data, $array, '', $reference_data); } else { $this->doExpandArrayProperties($data, $array); } return $data->export(); }
[ "public", "function", "expandArrayProperties", "(", "$", "array", ",", "$", "reference_array", "=", "[", "]", ")", "{", "$", "data", "=", "new", "Data", "(", "$", "array", ")", ";", "if", "(", "$", "reference_array", ")", "{", "$", "reference_data", "=", "new", "Data", "(", "$", "reference_array", ")", ";", "$", "this", "->", "doExpandArrayProperties", "(", "$", "data", ",", "$", "array", ",", "''", ",", "$", "reference_data", ")", ";", "}", "else", "{", "$", "this", "->", "doExpandArrayProperties", "(", "$", "data", ",", "$", "array", ")", ";", "}", "return", "$", "data", "->", "export", "(", ")", ";", "}" ]
Expands property placeholders in an array. Placeholders should formatted as ${parent.child}. @param array $array An array containing properties to expand. @return array The modified array in which placeholders have been replaced with values.
[ "Expands", "property", "placeholders", "in", "an", "array", "." ]
train
https://github.com/grasmash/expander/blob/ce639d6772233a5aa3c8362b1cb4b30fa156735f/src/Expander.php#L74-L85
grasmash/expander
src/Expander.php
Expander.doExpandArrayProperties
protected function doExpandArrayProperties( $data, $array, $parent_keys = '', $reference_data = null ) { foreach ($array as $key => $value) { // Boundary condition(s). if (is_null($value) || is_bool($value)) { continue; } // Recursive case. if (is_array($value)) { $this->doExpandArrayProperties($data, $value, $parent_keys . "$key.", $reference_data); } // Base case. else { $this->expandStringProperties($data, $parent_keys, $reference_data, $value, $key); } } }
php
protected function doExpandArrayProperties( $data, $array, $parent_keys = '', $reference_data = null ) { foreach ($array as $key => $value) { // Boundary condition(s). if (is_null($value) || is_bool($value)) { continue; } // Recursive case. if (is_array($value)) { $this->doExpandArrayProperties($data, $value, $parent_keys . "$key.", $reference_data); } // Base case. else { $this->expandStringProperties($data, $parent_keys, $reference_data, $value, $key); } } }
[ "protected", "function", "doExpandArrayProperties", "(", "$", "data", ",", "$", "array", ",", "$", "parent_keys", "=", "''", ",", "$", "reference_data", "=", "null", ")", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "// Boundary condition(s).", "if", "(", "is_null", "(", "$", "value", ")", "||", "is_bool", "(", "$", "value", ")", ")", "{", "continue", ";", "}", "// Recursive case.", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "doExpandArrayProperties", "(", "$", "data", ",", "$", "value", ",", "$", "parent_keys", ".", "\"$key.\"", ",", "$", "reference_data", ")", ";", "}", "// Base case.", "else", "{", "$", "this", "->", "expandStringProperties", "(", "$", "data", ",", "$", "parent_keys", ",", "$", "reference_data", ",", "$", "value", ",", "$", "key", ")", ";", "}", "}", "}" ]
Performs the actual property expansion. @param Data $data A data object, containing the $array. @param array $array The original, unmodified array. @param string $parent_keys The parent keys of the current key in dot notation. This is used to track the absolute path to the current key in recursive cases. @param Data|null $reference_data A reference data object. This is not operated upon but is used as a reference to provide supplemental values for property expansion.
[ "Performs", "the", "actual", "property", "expansion", "." ]
train
https://github.com/grasmash/expander/blob/ce639d6772233a5aa3c8362b1cb4b30fa156735f/src/Expander.php#L101-L120
grasmash/expander
src/Expander.php
Expander.expandStringProperties
protected function expandStringProperties( $data, $parent_keys, $reference_data, $value, $key ) { // We loop through all placeholders in a given string. // E.g., '${placeholder1} ${placeholder2}' requires two replacements. while (strpos($value, '${') !== false) { $original_value = $value; $value = preg_replace_callback( '/\$\{([^\$}]+)\}/', function ($matches) use ($data, $reference_data) { return $this->expandStringPropertiesCallback( $matches, $data, $reference_data ); }, $value ); // If no replacement occurred at all, break to prevent // infinite loop. if ($original_value == $value) { break; } // Set value on $data object. if ($parent_keys) { $full_key = $parent_keys . "$key"; } else { $full_key = $key; } $data->set($full_key, $value); } return $value; }
php
protected function expandStringProperties( $data, $parent_keys, $reference_data, $value, $key ) { // We loop through all placeholders in a given string. // E.g., '${placeholder1} ${placeholder2}' requires two replacements. while (strpos($value, '${') !== false) { $original_value = $value; $value = preg_replace_callback( '/\$\{([^\$}]+)\}/', function ($matches) use ($data, $reference_data) { return $this->expandStringPropertiesCallback( $matches, $data, $reference_data ); }, $value ); // If no replacement occurred at all, break to prevent // infinite loop. if ($original_value == $value) { break; } // Set value on $data object. if ($parent_keys) { $full_key = $parent_keys . "$key"; } else { $full_key = $key; } $data->set($full_key, $value); } return $value; }
[ "protected", "function", "expandStringProperties", "(", "$", "data", ",", "$", "parent_keys", ",", "$", "reference_data", ",", "$", "value", ",", "$", "key", ")", "{", "// We loop through all placeholders in a given string.", "// E.g., '${placeholder1} ${placeholder2}' requires two replacements.", "while", "(", "strpos", "(", "$", "value", ",", "'${'", ")", "!==", "false", ")", "{", "$", "original_value", "=", "$", "value", ";", "$", "value", "=", "preg_replace_callback", "(", "'/\\$\\{([^\\$}]+)\\}/'", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "data", ",", "$", "reference_data", ")", "{", "return", "$", "this", "->", "expandStringPropertiesCallback", "(", "$", "matches", ",", "$", "data", ",", "$", "reference_data", ")", ";", "}", ",", "$", "value", ")", ";", "// If no replacement occurred at all, break to prevent", "// infinite loop.", "if", "(", "$", "original_value", "==", "$", "value", ")", "{", "break", ";", "}", "// Set value on $data object.", "if", "(", "$", "parent_keys", ")", "{", "$", "full_key", "=", "$", "parent_keys", ".", "\"$key\"", ";", "}", "else", "{", "$", "full_key", "=", "$", "key", ";", "}", "$", "data", "->", "set", "(", "$", "full_key", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Expand a single property. @param Data $data A data object, containing the $array. @param string $parent_keys The parent keys of the current key in dot notation. This is used to track the absolute path to the current key in recursive cases. @param Data|null $reference_data A reference data object. This is not operated upon but is used as a reference to provide supplemental values for property expansion. @param string $value The unexpanded property value. @param string $key The immediate key of the property. @return mixed
[ "Expand", "a", "single", "property", "." ]
train
https://github.com/grasmash/expander/blob/ce639d6772233a5aa3c8362b1cb4b30fa156735f/src/Expander.php#L140-L178
grasmash/expander
src/Expander.php
Expander.expandStringPropertiesCallback
public function expandStringPropertiesCallback( $matches, $data, $reference_data = null ) { $property_name = $matches[1]; $unexpanded_value = $matches[0]; // Use only values within the subject array's data. if (!$reference_data) { return $this->expandProperty($property_name, $unexpanded_value, $data); } // Search both the subject array's data and the reference data for a value. else { return $this->expandPropertyWithReferenceData( $property_name, $unexpanded_value, $data, $reference_data ); } }
php
public function expandStringPropertiesCallback( $matches, $data, $reference_data = null ) { $property_name = $matches[1]; $unexpanded_value = $matches[0]; // Use only values within the subject array's data. if (!$reference_data) { return $this->expandProperty($property_name, $unexpanded_value, $data); } // Search both the subject array's data and the reference data for a value. else { return $this->expandPropertyWithReferenceData( $property_name, $unexpanded_value, $data, $reference_data ); } }
[ "public", "function", "expandStringPropertiesCallback", "(", "$", "matches", ",", "$", "data", ",", "$", "reference_data", "=", "null", ")", "{", "$", "property_name", "=", "$", "matches", "[", "1", "]", ";", "$", "unexpanded_value", "=", "$", "matches", "[", "0", "]", ";", "// Use only values within the subject array's data.", "if", "(", "!", "$", "reference_data", ")", "{", "return", "$", "this", "->", "expandProperty", "(", "$", "property_name", ",", "$", "unexpanded_value", ",", "$", "data", ")", ";", "}", "// Search both the subject array's data and the reference data for a value.", "else", "{", "return", "$", "this", "->", "expandPropertyWithReferenceData", "(", "$", "property_name", ",", "$", "unexpanded_value", ",", "$", "data", ",", "$", "reference_data", ")", ";", "}", "}" ]
Expansion callback used by preg_replace_callback() in expandProperty(). @param array $matches An array of matches created by preg_replace_callback(). @param Data $data A data object containing the complete array being operated upon. @param Data|null $reference_data A reference data object. This is not operated upon but is used as a reference to provide supplemental values for property expansion. @return mixed
[ "Expansion", "callback", "used", "by", "preg_replace_callback", "()", "in", "expandProperty", "()", "." ]
train
https://github.com/grasmash/expander/blob/ce639d6772233a5aa3c8362b1cb4b30fa156735f/src/Expander.php#L193-L213
grasmash/expander
src/Expander.php
Expander.expandPropertyWithReferenceData
public function expandPropertyWithReferenceData( $property_name, $unexpanded_value, $data, $reference_data ) { $expanded_value = $this->expandProperty( $property_name, $unexpanded_value, $data ); // If the string was not changed using the subject data, try using // the reference data. if ($expanded_value == $unexpanded_value) { $expanded_value = $this->expandProperty( $property_name, $unexpanded_value, $reference_data ); } return $expanded_value; }
php
public function expandPropertyWithReferenceData( $property_name, $unexpanded_value, $data, $reference_data ) { $expanded_value = $this->expandProperty( $property_name, $unexpanded_value, $data ); // If the string was not changed using the subject data, try using // the reference data. if ($expanded_value == $unexpanded_value) { $expanded_value = $this->expandProperty( $property_name, $unexpanded_value, $reference_data ); } return $expanded_value; }
[ "public", "function", "expandPropertyWithReferenceData", "(", "$", "property_name", ",", "$", "unexpanded_value", ",", "$", "data", ",", "$", "reference_data", ")", "{", "$", "expanded_value", "=", "$", "this", "->", "expandProperty", "(", "$", "property_name", ",", "$", "unexpanded_value", ",", "$", "data", ")", ";", "// If the string was not changed using the subject data, try using", "// the reference data.", "if", "(", "$", "expanded_value", "==", "$", "unexpanded_value", ")", "{", "$", "expanded_value", "=", "$", "this", "->", "expandProperty", "(", "$", "property_name", ",", "$", "unexpanded_value", ",", "$", "reference_data", ")", ";", "}", "return", "$", "expanded_value", ";", "}" ]
Searches both the subject data and the reference data for value. @param string $property_name The name of the value for which to search. @param string $unexpanded_value The original, unexpanded value, containing the placeholder. @param Data $data A data object containing the complete array being operated upon. @param Data|null $reference_data A reference data object. This is not operated upon but is used as a reference to provide supplemental values for property expansion. @return string The expanded string.
[ "Searches", "both", "the", "subject", "data", "and", "the", "reference", "data", "for", "value", "." ]
train
https://github.com/grasmash/expander/blob/ce639d6772233a5aa3c8362b1cb4b30fa156735f/src/Expander.php#L231-L253
grasmash/expander
src/Expander.php
Expander.expandProperty
public function expandProperty($property_name, $unexpanded_value, $data) { if (strpos($property_name, "env.") === 0 && !$data->has($property_name)) { $env_key = substr($property_name, 4); if (getenv($env_key)) { $data->set($property_name, getenv($env_key)); } } if (!$data->has($property_name)) { $this->log("Property \${'$property_name'} could not be expanded."); return $unexpanded_value; } else { $expanded_value = $data->get($property_name); if (is_array($expanded_value)) { $expanded_value = $this->getStringifier()->stringifyArray($expanded_value); return $expanded_value; } $this->log("Expanding property \${'$property_name'} => $expanded_value."); return $expanded_value; } }
php
public function expandProperty($property_name, $unexpanded_value, $data) { if (strpos($property_name, "env.") === 0 && !$data->has($property_name)) { $env_key = substr($property_name, 4); if (getenv($env_key)) { $data->set($property_name, getenv($env_key)); } } if (!$data->has($property_name)) { $this->log("Property \${'$property_name'} could not be expanded."); return $unexpanded_value; } else { $expanded_value = $data->get($property_name); if (is_array($expanded_value)) { $expanded_value = $this->getStringifier()->stringifyArray($expanded_value); return $expanded_value; } $this->log("Expanding property \${'$property_name'} => $expanded_value."); return $expanded_value; } }
[ "public", "function", "expandProperty", "(", "$", "property_name", ",", "$", "unexpanded_value", ",", "$", "data", ")", "{", "if", "(", "strpos", "(", "$", "property_name", ",", "\"env.\"", ")", "===", "0", "&&", "!", "$", "data", "->", "has", "(", "$", "property_name", ")", ")", "{", "$", "env_key", "=", "substr", "(", "$", "property_name", ",", "4", ")", ";", "if", "(", "getenv", "(", "$", "env_key", ")", ")", "{", "$", "data", "->", "set", "(", "$", "property_name", ",", "getenv", "(", "$", "env_key", ")", ")", ";", "}", "}", "if", "(", "!", "$", "data", "->", "has", "(", "$", "property_name", ")", ")", "{", "$", "this", "->", "log", "(", "\"Property \\${'$property_name'} could not be expanded.\"", ")", ";", "return", "$", "unexpanded_value", ";", "}", "else", "{", "$", "expanded_value", "=", "$", "data", "->", "get", "(", "$", "property_name", ")", ";", "if", "(", "is_array", "(", "$", "expanded_value", ")", ")", "{", "$", "expanded_value", "=", "$", "this", "->", "getStringifier", "(", ")", "->", "stringifyArray", "(", "$", "expanded_value", ")", ";", "return", "$", "expanded_value", ";", "}", "$", "this", "->", "log", "(", "\"Expanding property \\${'$property_name'} => $expanded_value.\"", ")", ";", "return", "$", "expanded_value", ";", "}", "}" ]
Searches a data object for a value. @param string $property_name The name of the value for which to search. @param string $unexpanded_value The original, unexpanded value, containing the placeholder. @param Data $data A data object containing possible replacement values. @return mixed
[ "Searches", "a", "data", "object", "for", "a", "value", "." ]
train
https://github.com/grasmash/expander/blob/ce639d6772233a5aa3c8362b1cb4b30fa156735f/src/Expander.php#L267-L289
eymengunay/php-passbook
src/Passbook/PassValidator.php
PassValidator.validate
public function validate(PassInterface $pass) { $this->errors = array(); $this->validateRequiredFields($pass); $this->validateBeaconKeys($pass); $this->validateLocationKeys($pass); $this->validateBarcodeKeys($pass); $this->validateWebServiceKeys($pass); $this->validateIcon($pass); $this->validateImageType($pass); $this->validateAssociatedStoreIdentifiers($pass); $this->validateGroupingIdentity($pass); return count($this->errors) === 0; }
php
public function validate(PassInterface $pass) { $this->errors = array(); $this->validateRequiredFields($pass); $this->validateBeaconKeys($pass); $this->validateLocationKeys($pass); $this->validateBarcodeKeys($pass); $this->validateWebServiceKeys($pass); $this->validateIcon($pass); $this->validateImageType($pass); $this->validateAssociatedStoreIdentifiers($pass); $this->validateGroupingIdentity($pass); return count($this->errors) === 0; }
[ "public", "function", "validate", "(", "PassInterface", "$", "pass", ")", "{", "$", "this", "->", "errors", "=", "array", "(", ")", ";", "$", "this", "->", "validateRequiredFields", "(", "$", "pass", ")", ";", "$", "this", "->", "validateBeaconKeys", "(", "$", "pass", ")", ";", "$", "this", "->", "validateLocationKeys", "(", "$", "pass", ")", ";", "$", "this", "->", "validateBarcodeKeys", "(", "$", "pass", ")", ";", "$", "this", "->", "validateWebServiceKeys", "(", "$", "pass", ")", ";", "$", "this", "->", "validateIcon", "(", "$", "pass", ")", ";", "$", "this", "->", "validateImageType", "(", "$", "pass", ")", ";", "$", "this", "->", "validateAssociatedStoreIdentifiers", "(", "$", "pass", ")", ";", "$", "this", "->", "validateGroupingIdentity", "(", "$", "pass", ")", ";", "return", "count", "(", "$", "this", "->", "errors", ")", "===", "0", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/PassValidator.php#L51-L66
eymengunay/php-passbook
src/Passbook/Pass/Localization.php
Localization.getStringsFileOutput
public function getStringsFileOutput() { $output = ''; foreach ($this->strings as $token => $value) { $output .= '"' . addslashes($token) . '" = "' . addslashes($value) . '";' . PHP_EOL; } return $output; }
php
public function getStringsFileOutput() { $output = ''; foreach ($this->strings as $token => $value) { $output .= '"' . addslashes($token) . '" = "' . addslashes($value) . '";' . PHP_EOL; } return $output; }
[ "public", "function", "getStringsFileOutput", "(", ")", "{", "$", "output", "=", "''", ";", "foreach", "(", "$", "this", "->", "strings", "as", "$", "token", "=>", "$", "value", ")", "{", "$", "output", ".=", "'\"'", ".", "addslashes", "(", "$", "token", ")", ".", "'\" = \"'", ".", "addslashes", "(", "$", "value", ")", ".", "'\";'", ".", "PHP_EOL", ";", "}", "return", "$", "output", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/Pass/Localization.php#L92-L100
eymengunay/php-passbook
src/Passbook/PassFactory.php
PassFactory.package
public function package(PassInterface $pass, $passName = '') { if ($pass->getSerialNumber() == '') { throw new \InvalidArgumentException('Pass must have a serial number to be packaged'); } $this->populateRequiredInformation($pass); if ($this->passValidator) { if (!$this->passValidator->validate($pass)){ throw new PassInvalidException('Failed to validate passbook', $this->passValidator->getErrors()); }; } $passDir = $this->preparePassDirectory($pass); // Serialize pass file_put_contents($passDir . 'pass.json', self::serialize($pass)); // Images $this->prepareImages($pass, $passDir); // Localizations $this->prepareLocalizations($pass, $passDir); // Manifest.json - recursive, also add files in sub directories $manifestJSONFile = $this->prepareManifest($passDir); // Signature $this->sign($passDir, $manifestJSONFile); // Zip pass $zipFile = $this->getNormalizedOutputPath() . $this->getPassName($passName, $pass) . self::PASS_EXTENSION; $this->zip($passDir, $zipFile); // Remove temporary pass directory $this->rrmdir($passDir); return new SplFileObject($zipFile); }
php
public function package(PassInterface $pass, $passName = '') { if ($pass->getSerialNumber() == '') { throw new \InvalidArgumentException('Pass must have a serial number to be packaged'); } $this->populateRequiredInformation($pass); if ($this->passValidator) { if (!$this->passValidator->validate($pass)){ throw new PassInvalidException('Failed to validate passbook', $this->passValidator->getErrors()); }; } $passDir = $this->preparePassDirectory($pass); // Serialize pass file_put_contents($passDir . 'pass.json', self::serialize($pass)); // Images $this->prepareImages($pass, $passDir); // Localizations $this->prepareLocalizations($pass, $passDir); // Manifest.json - recursive, also add files in sub directories $manifestJSONFile = $this->prepareManifest($passDir); // Signature $this->sign($passDir, $manifestJSONFile); // Zip pass $zipFile = $this->getNormalizedOutputPath() . $this->getPassName($passName, $pass) . self::PASS_EXTENSION; $this->zip($passDir, $zipFile); // Remove temporary pass directory $this->rrmdir($passDir); return new SplFileObject($zipFile); }
[ "public", "function", "package", "(", "PassInterface", "$", "pass", ",", "$", "passName", "=", "''", ")", "{", "if", "(", "$", "pass", "->", "getSerialNumber", "(", ")", "==", "''", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Pass must have a serial number to be packaged'", ")", ";", "}", "$", "this", "->", "populateRequiredInformation", "(", "$", "pass", ")", ";", "if", "(", "$", "this", "->", "passValidator", ")", "{", "if", "(", "!", "$", "this", "->", "passValidator", "->", "validate", "(", "$", "pass", ")", ")", "{", "throw", "new", "PassInvalidException", "(", "'Failed to validate passbook'", ",", "$", "this", "->", "passValidator", "->", "getErrors", "(", ")", ")", ";", "}", ";", "}", "$", "passDir", "=", "$", "this", "->", "preparePassDirectory", "(", "$", "pass", ")", ";", "// Serialize pass", "file_put_contents", "(", "$", "passDir", ".", "'pass.json'", ",", "self", "::", "serialize", "(", "$", "pass", ")", ")", ";", "// Images", "$", "this", "->", "prepareImages", "(", "$", "pass", ",", "$", "passDir", ")", ";", "// Localizations", "$", "this", "->", "prepareLocalizations", "(", "$", "pass", ",", "$", "passDir", ")", ";", "// Manifest.json - recursive, also add files in sub directories", "$", "manifestJSONFile", "=", "$", "this", "->", "prepareManifest", "(", "$", "passDir", ")", ";", "// Signature", "$", "this", "->", "sign", "(", "$", "passDir", ",", "$", "manifestJSONFile", ")", ";", "// Zip pass", "$", "zipFile", "=", "$", "this", "->", "getNormalizedOutputPath", "(", ")", ".", "$", "this", "->", "getPassName", "(", "$", "passName", ",", "$", "pass", ")", ".", "self", "::", "PASS_EXTENSION", ";", "$", "this", "->", "zip", "(", "$", "passDir", ",", "$", "zipFile", ")", ";", "// Remove temporary pass directory", "$", "this", "->", "rrmdir", "(", "$", "passDir", ")", ";", "return", "new", "SplFileObject", "(", "$", "zipFile", ")", ";", "}" ]
Creates a pkpass file @param PassInterface $pass - the pass to be packaged into a .pkpass file @param string $passName - filename to be used for the pass; if blank the serial number will be used @return SplFileObject If an IO error occurred @throws Exception
[ "Creates", "a", "pkpass", "file" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/PassFactory.php#L244-L283
eymengunay/php-passbook
src/Passbook/PassFactory.php
PassFactory.zip
private function zip($source, $destination) { if (!extension_loaded('zip')) { throw new Exception("ZIP extension not available"); } $source = realpath($source); if (!is_dir($source)) { throw new FileException("Source must be a directory."); } $zip = new ZipArchive(); $shouldOverwrite = $this->isOverwrite() ? ZipArchive::OVERWRITE : 0; if (!$zip->open($destination, ZipArchive::CREATE | $shouldOverwrite)) { throw new FileException("Couldn't open zip file."); } /* @var $iterator RecursiveIteratorIterator|RecursiveDirectoryIterator */ $dirIterator = new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS); $iterator = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST); while ($iterator->valid()) { if ($iterator->isDir()) { $zip->addEmptyDir($iterator->getSubPathName()); } else if ($iterator->isFile()) { $zip->addFromString($iterator->getSubPathName(), file_get_contents($iterator->key())); } $iterator->next(); } return $zip->close(); }
php
private function zip($source, $destination) { if (!extension_loaded('zip')) { throw new Exception("ZIP extension not available"); } $source = realpath($source); if (!is_dir($source)) { throw new FileException("Source must be a directory."); } $zip = new ZipArchive(); $shouldOverwrite = $this->isOverwrite() ? ZipArchive::OVERWRITE : 0; if (!$zip->open($destination, ZipArchive::CREATE | $shouldOverwrite)) { throw new FileException("Couldn't open zip file."); } /* @var $iterator RecursiveIteratorIterator|RecursiveDirectoryIterator */ $dirIterator = new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS); $iterator = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST); while ($iterator->valid()) { if ($iterator->isDir()) { $zip->addEmptyDir($iterator->getSubPathName()); } else if ($iterator->isFile()) { $zip->addFromString($iterator->getSubPathName(), file_get_contents($iterator->key())); } $iterator->next(); } return $zip->close(); }
[ "private", "function", "zip", "(", "$", "source", ",", "$", "destination", ")", "{", "if", "(", "!", "extension_loaded", "(", "'zip'", ")", ")", "{", "throw", "new", "Exception", "(", "\"ZIP extension not available\"", ")", ";", "}", "$", "source", "=", "realpath", "(", "$", "source", ")", ";", "if", "(", "!", "is_dir", "(", "$", "source", ")", ")", "{", "throw", "new", "FileException", "(", "\"Source must be a directory.\"", ")", ";", "}", "$", "zip", "=", "new", "ZipArchive", "(", ")", ";", "$", "shouldOverwrite", "=", "$", "this", "->", "isOverwrite", "(", ")", "?", "ZipArchive", "::", "OVERWRITE", ":", "0", ";", "if", "(", "!", "$", "zip", "->", "open", "(", "$", "destination", ",", "ZipArchive", "::", "CREATE", "|", "$", "shouldOverwrite", ")", ")", "{", "throw", "new", "FileException", "(", "\"Couldn't open zip file.\"", ")", ";", "}", "/* @var $iterator RecursiveIteratorIterator|RecursiveDirectoryIterator */", "$", "dirIterator", "=", "new", "RecursiveDirectoryIterator", "(", "$", "source", ",", "FilesystemIterator", "::", "SKIP_DOTS", ")", ";", "$", "iterator", "=", "new", "RecursiveIteratorIterator", "(", "$", "dirIterator", ",", "RecursiveIteratorIterator", "::", "SELF_FIRST", ")", ";", "while", "(", "$", "iterator", "->", "valid", "(", ")", ")", "{", "if", "(", "$", "iterator", "->", "isDir", "(", ")", ")", "{", "$", "zip", "->", "addEmptyDir", "(", "$", "iterator", "->", "getSubPathName", "(", ")", ")", ";", "}", "else", "if", "(", "$", "iterator", "->", "isFile", "(", ")", ")", "{", "$", "zip", "->", "addFromString", "(", "$", "iterator", "->", "getSubPathName", "(", ")", ",", "file_get_contents", "(", "$", "iterator", "->", "key", "(", ")", ")", ")", ";", "}", "$", "iterator", "->", "next", "(", ")", ";", "}", "return", "$", "zip", "->", "close", "(", ")", ";", "}" ]
Creates a zip of a directory including all sub directories (recursive) @param $source - path to the source directory @param $destination - output directory @return bool @throws Exception
[ "Creates", "a", "zip", "of", "a", "directory", "including", "all", "sub", "directories", "(", "recursive", ")" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/PassFactory.php#L341-L371
eymengunay/php-passbook
src/Passbook/PassFactory.php
PassFactory.getPassName
public function getPassName($passName, PassInterface $pass) { $passNameSanitised = preg_replace("/[^a-zA-Z0-9]+/", "", $passName); return strlen($passNameSanitised) != 0 ? $passNameSanitised : $pass->getSerialNumber(); }
php
public function getPassName($passName, PassInterface $pass) { $passNameSanitised = preg_replace("/[^a-zA-Z0-9]+/", "", $passName); return strlen($passNameSanitised) != 0 ? $passNameSanitised : $pass->getSerialNumber(); }
[ "public", "function", "getPassName", "(", "$", "passName", ",", "PassInterface", "$", "pass", ")", "{", "$", "passNameSanitised", "=", "preg_replace", "(", "\"/[^a-zA-Z0-9]+/\"", ",", "\"\"", ",", "$", "passName", ")", ";", "return", "strlen", "(", "$", "passNameSanitised", ")", "!=", "0", "?", "$", "passNameSanitised", ":", "$", "pass", "->", "getSerialNumber", "(", ")", ";", "}" ]
@param $passName @param PassInterface $pass @return string
[ "@param", "$passName", "@param", "PassInterface", "$pass" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/PassFactory.php#L426-L430
eymengunay/php-passbook
src/Passbook/PassFactory.php
PassFactory.prepareManifest
private function prepareManifest($passDir) { $manifestJSONFile = $passDir . 'manifest.json'; $manifest = array(); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($passDir), RecursiveIteratorIterator::SELF_FIRST ); foreach ($files as $file) { // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } // $filePath = realpath($file); if (is_file($filePath) === true) { $relativePathName = str_replace($passDir, '', $file->getPathname()); $manifest[$relativePathName] = sha1_file($filePath); } } file_put_contents($manifestJSONFile, $this->jsonEncode($manifest)); return $manifestJSONFile; }
php
private function prepareManifest($passDir) { $manifestJSONFile = $passDir . 'manifest.json'; $manifest = array(); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($passDir), RecursiveIteratorIterator::SELF_FIRST ); foreach ($files as $file) { // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } // $filePath = realpath($file); if (is_file($filePath) === true) { $relativePathName = str_replace($passDir, '', $file->getPathname()); $manifest[$relativePathName] = sha1_file($filePath); } } file_put_contents($manifestJSONFile, $this->jsonEncode($manifest)); return $manifestJSONFile; }
[ "private", "function", "prepareManifest", "(", "$", "passDir", ")", "{", "$", "manifestJSONFile", "=", "$", "passDir", ".", "'manifest.json'", ";", "$", "manifest", "=", "array", "(", ")", ";", "$", "files", "=", "new", "RecursiveIteratorIterator", "(", "new", "RecursiveDirectoryIterator", "(", "$", "passDir", ")", ",", "RecursiveIteratorIterator", "::", "SELF_FIRST", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "// Ignore \".\" and \"..\" folders", "if", "(", "in_array", "(", "substr", "(", "$", "file", ",", "strrpos", "(", "$", "file", ",", "'/'", ")", "+", "1", ")", ",", "array", "(", "'.'", ",", "'..'", ")", ")", ")", "{", "continue", ";", "}", "//", "$", "filePath", "=", "realpath", "(", "$", "file", ")", ";", "if", "(", "is_file", "(", "$", "filePath", ")", "===", "true", ")", "{", "$", "relativePathName", "=", "str_replace", "(", "$", "passDir", ",", "''", ",", "$", "file", "->", "getPathname", "(", ")", ")", ";", "$", "manifest", "[", "$", "relativePathName", "]", "=", "sha1_file", "(", "$", "filePath", ")", ";", "}", "}", "file_put_contents", "(", "$", "manifestJSONFile", ",", "$", "this", "->", "jsonEncode", "(", "$", "manifest", ")", ")", ";", "return", "$", "manifestJSONFile", ";", "}" ]
@param $passDir @return string
[ "@param", "$passDir" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/PassFactory.php#L437-L460
eymengunay/php-passbook
src/Passbook/PassFactory.php
PassFactory.preparePassDirectory
private function preparePassDirectory(PassInterface $pass) { $passDir = $this->getNormalizedOutputPath() . $pass->getSerialNumber() . DIRECTORY_SEPARATOR; $passDirExists = file_exists($passDir); if ($passDirExists && !$this->isOverwrite()) { throw new FileException("Temporary pass directory already exists"); } elseif (!$passDirExists && !mkdir($passDir, 0777, true)) { throw new FileException("Couldn't create temporary pass directory"); } return $passDir; }
php
private function preparePassDirectory(PassInterface $pass) { $passDir = $this->getNormalizedOutputPath() . $pass->getSerialNumber() . DIRECTORY_SEPARATOR; $passDirExists = file_exists($passDir); if ($passDirExists && !$this->isOverwrite()) { throw new FileException("Temporary pass directory already exists"); } elseif (!$passDirExists && !mkdir($passDir, 0777, true)) { throw new FileException("Couldn't create temporary pass directory"); } return $passDir; }
[ "private", "function", "preparePassDirectory", "(", "PassInterface", "$", "pass", ")", "{", "$", "passDir", "=", "$", "this", "->", "getNormalizedOutputPath", "(", ")", ".", "$", "pass", "->", "getSerialNumber", "(", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "passDirExists", "=", "file_exists", "(", "$", "passDir", ")", ";", "if", "(", "$", "passDirExists", "&&", "!", "$", "this", "->", "isOverwrite", "(", ")", ")", "{", "throw", "new", "FileException", "(", "\"Temporary pass directory already exists\"", ")", ";", "}", "elseif", "(", "!", "$", "passDirExists", "&&", "!", "mkdir", "(", "$", "passDir", ",", "0777", ",", "true", ")", ")", "{", "throw", "new", "FileException", "(", "\"Couldn't create temporary pass directory\"", ")", ";", "}", "return", "$", "passDir", ";", "}" ]
@param PassInterface $pass @return string
[ "@param", "PassInterface", "$pass" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/PassFactory.php#L467-L478
eymengunay/php-passbook
src/Passbook/Pass.php
Pass.setBarcode
public function setBarcode(BarcodeInterface $barcode) { $this->barcode = $barcode; array_unshift($this->barcodes, $barcode); return $this; }
php
public function setBarcode(BarcodeInterface $barcode) { $this->barcode = $barcode; array_unshift($this->barcodes, $barcode); return $this; }
[ "public", "function", "setBarcode", "(", "BarcodeInterface", "$", "barcode", ")", "{", "$", "this", "->", "barcode", "=", "$", "barcode", ";", "array_unshift", "(", "$", "this", "->", "barcodes", ",", "$", "barcode", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/Pass.php#L553-L559
eymengunay/php-passbook
src/Passbook/Pass.php
Pass.addBarcode
public function addBarcode(BarcodeInterface $barcode) { $this->barcodes[] = $barcode; if (empty($this->barcode)) { $this->barcode = $barcode; } return $this; }
php
public function addBarcode(BarcodeInterface $barcode) { $this->barcodes[] = $barcode; if (empty($this->barcode)) { $this->barcode = $barcode; } return $this; }
[ "public", "function", "addBarcode", "(", "BarcodeInterface", "$", "barcode", ")", "{", "$", "this", "->", "barcodes", "[", "]", "=", "$", "barcode", ";", "if", "(", "empty", "(", "$", "this", "->", "barcode", ")", ")", "{", "$", "this", "->", "barcode", "=", "$", "barcode", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/eymengunay/php-passbook/blob/a5b05f3ddedf20f41c5c7f5eda38ea362732190d/src/Passbook/Pass.php#L572-L581
DusanKasan/Knapsack
src/Collection.php
Collection.range
public static function range($start = 0, $end = null, $step = 1) { return \DusanKasan\Knapsack\range($start, $end, $step); }
php
public static function range($start = 0, $end = null, $step = 1) { return \DusanKasan\Knapsack\range($start, $end, $step); }
[ "public", "static", "function", "range", "(", "$", "start", "=", "0", ",", "$", "end", "=", "null", ",", "$", "step", "=", "1", ")", "{", "return", "\\", "DusanKasan", "\\", "Knapsack", "\\", "range", "(", "$", "start", ",", "$", "end", ",", "$", "step", ")", ";", "}" ]
Returns a lazy collection of numbers starting at $start, incremented by $step until $end is reached. @param int $start @param int|null $end @param int $step @return Collection
[ "Returns", "a", "lazy", "collection", "of", "numbers", "starting", "at", "$start", "incremented", "by", "$step", "until", "$end", "is", "reached", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/Collection.php#L89-L92
DusanKasan/Knapsack
src/Collection.php
Collection.getIterator
public function getIterator() { if ($this->inputFactory) { $input = call_user_func($this->inputFactory); if (is_array($input)) { $input = new ArrayIterator($input); } if (!($input instanceof Traversable)) { throw new InvalidReturnValue; } $this->input = $input; } return $this->input; }
php
public function getIterator() { if ($this->inputFactory) { $input = call_user_func($this->inputFactory); if (is_array($input)) { $input = new ArrayIterator($input); } if (!($input instanceof Traversable)) { throw new InvalidReturnValue; } $this->input = $input; } return $this->input; }
[ "public", "function", "getIterator", "(", ")", "{", "if", "(", "$", "this", "->", "inputFactory", ")", "{", "$", "input", "=", "call_user_func", "(", "$", "this", "->", "inputFactory", ")", ";", "if", "(", "is_array", "(", "$", "input", ")", ")", "{", "$", "input", "=", "new", "ArrayIterator", "(", "$", "input", ")", ";", "}", "if", "(", "!", "(", "$", "input", "instanceof", "Traversable", ")", ")", "{", "throw", "new", "InvalidReturnValue", ";", "}", "$", "this", "->", "input", "=", "$", "input", ";", "}", "return", "$", "this", "->", "input", ";", "}" ]
{@inheritdoc} @throws InvalidReturnValue
[ "{" ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/Collection.php#L98-L115
DusanKasan/Knapsack
src/Collection.php
Collection.serialize
public function serialize() { return serialize( toArray( map( $this->input, function ($value, $key) { return [$key, $value]; } ) ) ); }
php
public function serialize() { return serialize( toArray( map( $this->input, function ($value, $key) { return [$key, $value]; } ) ) ); }
[ "public", "function", "serialize", "(", ")", "{", "return", "serialize", "(", "toArray", "(", "map", "(", "$", "this", "->", "input", ",", "function", "(", "$", "value", ",", "$", "key", ")", "{", "return", "[", "$", "key", ",", "$", "value", "]", ";", "}", ")", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/Collection.php#L120-L132
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.reduce
public function reduce(callable $function, $startValue, $convertToCollection = false) { $result = reduce($this->getItems(), $function, $startValue); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function reduce(callable $function, $startValue, $convertToCollection = false) { $result = reduce($this->getItems(), $function, $startValue); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "reduce", "(", "callable", "$", "function", ",", "$", "startValue", ",", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "reduce", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "function", ",", "$", "startValue", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Reduces the collection to single value by iterating over the collection and calling $function while passing $startValue and current key/item as parameters. The output of $function is used as $startValue in next iteration. The output of $function on last element is the return value of this function. If $convertToCollection is true and the return value is a collection (array|Traversable) an instance of Collection is returned. @param callable $function ($tmpValue, $value, $key) @param mixed $startValue @param bool $convertToCollection @return mixed|Collection
[ "Reduces", "the", "collection", "to", "single", "value", "by", "iterating", "over", "the", "collection", "and", "calling", "$function", "while", "passing", "$startValue", "and", "current", "key", "/", "item", "as", "parameters", ".", "The", "output", "of", "$function", "is", "used", "as", "$startValue", "in", "next", "iteration", ".", "The", "output", "of", "$function", "on", "last", "element", "is", "the", "return", "value", "of", "this", "function", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "an", "instance", "of", "Collection", "is", "returned", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L74-L79
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.get
public function get($key, $convertToCollection = false) { $result = get($this->getItems(), $key); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function get($key, $convertToCollection = false) { $result = get($this->getItems(), $key); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "get", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "key", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Returns value at the key $key. If multiple values have this key, return first. If no value has this key, throw ItemNotFound. If $convertToCollection is true and the return value is a collection (array|Traversable) an instance of Collection will be returned. @param mixed $key @param bool $convertToCollection @return mixed|Collection @throws \DusanKasan\Knapsack\Exceptions\ItemNotFound
[ "Returns", "value", "at", "the", "key", "$key", ".", "If", "multiple", "values", "have", "this", "key", "return", "first", ".", "If", "no", "value", "has", "this", "key", "throw", "ItemNotFound", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "an", "instance", "of", "Collection", "will", "be", "returned", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L171-L176
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.getOrDefault
public function getOrDefault($key, $default = null, $convertToCollection = false) { $result = getOrDefault($this->getItems(), $key, $default); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function getOrDefault($key, $default = null, $convertToCollection = false) { $result = getOrDefault($this->getItems(), $key, $default); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "getOrDefault", "(", "$", "key", ",", "$", "default", "=", "null", ",", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "getOrDefault", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "key", ",", "$", "default", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Returns item at the key $key. If multiple items have this key, return first. If no item has this key, return $ifNotFound. If no value has this key, throw ItemNotFound. If $convertToCollection is true and the return value is a collection (array|Traversable) an instance of Collection will be returned. @param mixed $key @param mixed $default @param bool $convertToCollection @return mixed|Collection @throws \DusanKasan\Knapsack\Exceptions\ItemNotFound
[ "Returns", "item", "at", "the", "key", "$key", ".", "If", "multiple", "items", "have", "this", "key", "return", "first", ".", "If", "no", "item", "has", "this", "key", "return", "$ifNotFound", ".", "If", "no", "value", "has", "this", "key", "throw", "ItemNotFound", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "an", "instance", "of", "Collection", "will", "be", "returned", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L189-L194
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.find
public function find(callable $function, $default = null, $convertToCollection = false) { $result = find($this->getItems(), $function, $default); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function find(callable $function, $default = null, $convertToCollection = false) { $result = find($this->getItems(), $function, $default); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "find", "(", "callable", "$", "function", ",", "$", "default", "=", "null", ",", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "find", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "function", ",", "$", "default", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Returns first value matched by $function. If no value matches, return $default. If $convertToCollection is true and the return value is a collection (array|Traversable) an instance of Collection will be returned. @param callable $function @param mixed|null $default @param bool $convertToCollection @return mixed|Collection
[ "Returns", "first", "value", "matched", "by", "$function", ".", "If", "no", "value", "matches", "return", "$default", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "an", "instance", "of", "Collection", "will", "be", "returned", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L205-L210
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.partition
public function partition($numberOfItems, $step = 0, $padding = []) { return partition($this->getItems(), $numberOfItems, $step, $padding); }
php
public function partition($numberOfItems, $step = 0, $padding = []) { return partition($this->getItems(), $numberOfItems, $step, $padding); }
[ "public", "function", "partition", "(", "$", "numberOfItems", ",", "$", "step", "=", "0", ",", "$", "padding", "=", "[", "]", ")", "{", "return", "partition", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "numberOfItems", ",", "$", "step", ",", "$", "padding", ")", ";", "}" ]
Returns a lazy collection of collections of $numberOfItems items each, at $step step apart. If $step is not supplied, defaults to $numberOfItems, i.e. the partitions do not overlap. If a $padding collection is supplied, use its elements as necessary to complete last partition up to $numberOfItems items. In case there are not enough padding elements, return a partition with less than $numberOfItems items. @param int $numberOfItems @param int $step @param array|\Traversable $padding @return Collection
[ "Returns", "a", "lazy", "collection", "of", "collections", "of", "$numberOfItems", "items", "each", "at", "$step", "step", "apart", ".", "If", "$step", "is", "not", "supplied", "defaults", "to", "$numberOfItems", "i", ".", "e", ".", "the", "partitions", "do", "not", "overlap", ".", "If", "a", "$padding", "collection", "is", "supplied", "use", "its", "elements", "as", "necessary", "to", "complete", "last", "partition", "up", "to", "$numberOfItems", "items", ".", "In", "case", "there", "are", "not", "enough", "padding", "elements", "return", "a", "partition", "with", "less", "than", "$numberOfItems", "items", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L532-L535
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.first
public function first($convertToCollection = false) { $result = first($this->getItems()); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function first($convertToCollection = false) { $result = first($this->getItems()); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "first", "(", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "first", "(", "$", "this", "->", "getItems", "(", ")", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Returns first item of this collection. If the collection is empty, throws ItemNotFound. If $convertToCollection is true and the return value is a collection (array|Traversable) an instance of Collection is returned. @param bool $convertToCollection @return mixed|Collection @throws \DusanKasan\Knapsack\Exceptions\ItemNotFound
[ "Returns", "first", "item", "of", "this", "collection", ".", "If", "the", "collection", "is", "empty", "throws", "ItemNotFound", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "an", "instance", "of", "Collection", "is", "returned", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L588-L593
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.last
public function last($convertToCollection = false) { $result = last($this->getItems()); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function last($convertToCollection = false) { $result = last($this->getItems()); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "last", "(", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "last", "(", "$", "this", "->", "getItems", "(", ")", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Returns last item of this collection. If the collection is empty, throws ItemNotFound. If $convertToCollection is true and the return value is a collection (array|Traversable) it is converted to Collection. @param bool $convertToCollection @return mixed|Collection @throws \DusanKasan\Knapsack\Exceptions\ItemNotFound
[ "Returns", "last", "item", "of", "this", "collection", ".", "If", "the", "collection", "is", "empty", "throws", "ItemNotFound", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "it", "is", "converted", "to", "Collection", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L603-L608
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.second
public function second($convertToCollection = false) { $result = second($this->getItems()); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
php
public function second($convertToCollection = false) { $result = second($this->getItems()); return ($convertToCollection && isCollection($result)) ? new Collection($result) : $result; }
[ "public", "function", "second", "(", "$", "convertToCollection", "=", "false", ")", "{", "$", "result", "=", "second", "(", "$", "this", "->", "getItems", "(", ")", ")", ";", "return", "(", "$", "convertToCollection", "&&", "isCollection", "(", "$", "result", ")", ")", "?", "new", "Collection", "(", "$", "result", ")", ":", "$", "result", ";", "}" ]
Returns the second item in this collection or throws ItemNotFound if the collection is empty or has 1 item. If $convertToCollection is true and the return value is a collection (array|Traversable) it is converted to Collection. @param bool $convertToCollection @return mixed|Collection @throws \DusanKasan\Knapsack\Exceptions\ItemNotFound
[ "Returns", "the", "second", "item", "in", "this", "collection", "or", "throws", "ItemNotFound", "if", "the", "collection", "is", "empty", "or", "has", "1", "item", ".", "If", "$convertToCollection", "is", "true", "and", "the", "return", "value", "is", "a", "collection", "(", "array|Traversable", ")", "it", "is", "converted", "to", "Collection", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L629-L634
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.transform
public function transform(callable $transformer) { $items = $this->getItems(); $transformed = $transformer($items instanceof Collection ? $items : new Collection($items)); if (!($transformed instanceof Collection)) { throw new InvalidReturnValue; } return $transformed; }
php
public function transform(callable $transformer) { $items = $this->getItems(); $transformed = $transformer($items instanceof Collection ? $items : new Collection($items)); if (!($transformed instanceof Collection)) { throw new InvalidReturnValue; } return $transformed; }
[ "public", "function", "transform", "(", "callable", "$", "transformer", ")", "{", "$", "items", "=", "$", "this", "->", "getItems", "(", ")", ";", "$", "transformed", "=", "$", "transformer", "(", "$", "items", "instanceof", "Collection", "?", "$", "items", ":", "new", "Collection", "(", "$", "items", ")", ")", ";", "if", "(", "!", "(", "$", "transformed", "instanceof", "Collection", ")", ")", "{", "throw", "new", "InvalidReturnValue", ";", "}", "return", "$", "transformed", ";", "}" ]
Uses a $transformer callable that takes a Collection and returns Collection on itself. @param callable $transformer Collection => Collection @return Collection @throws InvalidReturnValue
[ "Uses", "a", "$transformer", "callable", "that", "takes", "a", "Collection", "and", "returns", "Collection", "on", "itself", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L725-L736
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.dump
public function dump($maxItemsPerCollection = null, $maxDepth = null) { return dump($this->getItems(), $maxItemsPerCollection, $maxDepth); }
php
public function dump($maxItemsPerCollection = null, $maxDepth = null) { return dump($this->getItems(), $maxItemsPerCollection, $maxDepth); }
[ "public", "function", "dump", "(", "$", "maxItemsPerCollection", "=", "null", ",", "$", "maxDepth", "=", "null", ")", "{", "return", "dump", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "maxItemsPerCollection", ",", "$", "maxDepth", ")", ";", "}" ]
/** Dumps this collection into array (recursively). - scalars are returned as they are, - array of class name => properties (name => value and only properties accessible for this class) is returned for objects, - arrays or Traversables are returned as arrays, - for anything else result of calling gettype($input) is returned If specified, $maxItemsPerCollection will only leave specified number of items in collection, appending a new element at end '>>>' if original collection was longer. If specified, $maxDepth will only leave specified n levels of nesting, replacing elements with '^^^' once the maximum nesting level was reached. If a collection with duplicate keys is encountered, the duplicate keys (except the first one) will be change into a format originalKey//duplicateCounter where duplicateCounter starts from 1 at the first duplicate. So [0 => 1, 0 => 2] will become [0 => 1, '0//1' => 2] @param int|null $maxItemsPerCollection @param int|null $maxDepth @return array
[ "/", "**", "Dumps", "this", "collection", "into", "array", "(", "recursively", ")", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L905-L908
DusanKasan/Knapsack
src/CollectionTrait.php
CollectionTrait.printDump
public function printDump($maxItemsPerCollection = null, $maxDepth = null) { return printDump($this->getItems(), $maxItemsPerCollection, $maxDepth); }
php
public function printDump($maxItemsPerCollection = null, $maxDepth = null) { return printDump($this->getItems(), $maxItemsPerCollection, $maxDepth); }
[ "public", "function", "printDump", "(", "$", "maxItemsPerCollection", "=", "null", ",", "$", "maxDepth", "=", "null", ")", "{", "return", "printDump", "(", "$", "this", "->", "getItems", "(", ")", ",", "$", "maxItemsPerCollection", ",", "$", "maxDepth", ")", ";", "}" ]
Calls dump on this collection and then prints it using the var_export. @param int|null $maxItemsPerCollection @param int|null $maxDepth @return Collection
[ "Calls", "dump", "on", "this", "collection", "and", "then", "prints", "it", "using", "the", "var_export", "." ]
train
https://github.com/DusanKasan/Knapsack/blob/15856c5c1601d00b00232803ae9e418406825cbd/src/CollectionTrait.php#L917-L920
benwilkins/laravel-fcm-notification
src/FcmNotificationServiceProvider.php
FcmNotificationServiceProvider.register
public function register() { $this->app->make(ChannelManager::class)->extend('fcm', function () { return new FcmChannel(app(Client::class), config('services.fcm.key')); }); }
php
public function register() { $this->app->make(ChannelManager::class)->extend('fcm', function () { return new FcmChannel(app(Client::class), config('services.fcm.key')); }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "make", "(", "ChannelManager", "::", "class", ")", "->", "extend", "(", "'fcm'", ",", "function", "(", ")", "{", "return", "new", "FcmChannel", "(", "app", "(", "Client", "::", "class", ")", ",", "config", "(", "'services.fcm.key'", ")", ")", ";", "}", ")", ";", "}" ]
Register.
[ "Register", "." ]
train
https://github.com/benwilkins/laravel-fcm-notification/blob/60db6d140881781b57686a4e34600ea21979764f/src/FcmNotificationServiceProvider.php#L17-L22
dusterio/laravel-aws-worker
src/Controllers/WorkerController.php
WorkerController.schedule
public function schedule(Container $laravel, Kernel $kernel, Schedule $schedule) { $events = $schedule->dueEvents($laravel); $eventsRan = 0; $messages = []; foreach ($events as $event) { if (method_exists($event, 'filtersPass') && (new \ReflectionMethod($event, 'filtersPass'))->isPublic() && ! $event->filtersPass($laravel)) { continue; } $messages[] = 'Running: '.$event->getSummaryForDisplay(); $event->run($laravel); ++$eventsRan; } if (count($events) === 0 || $eventsRan === 0) { $messages[] = 'No scheduled commands are ready to run.'; } return $this->response($messages); }
php
public function schedule(Container $laravel, Kernel $kernel, Schedule $schedule) { $events = $schedule->dueEvents($laravel); $eventsRan = 0; $messages = []; foreach ($events as $event) { if (method_exists($event, 'filtersPass') && (new \ReflectionMethod($event, 'filtersPass'))->isPublic() && ! $event->filtersPass($laravel)) { continue; } $messages[] = 'Running: '.$event->getSummaryForDisplay(); $event->run($laravel); ++$eventsRan; } if (count($events) === 0 || $eventsRan === 0) { $messages[] = 'No scheduled commands are ready to run.'; } return $this->response($messages); }
[ "public", "function", "schedule", "(", "Container", "$", "laravel", ",", "Kernel", "$", "kernel", ",", "Schedule", "$", "schedule", ")", "{", "$", "events", "=", "$", "schedule", "->", "dueEvents", "(", "$", "laravel", ")", ";", "$", "eventsRan", "=", "0", ";", "$", "messages", "=", "[", "]", ";", "foreach", "(", "$", "events", "as", "$", "event", ")", "{", "if", "(", "method_exists", "(", "$", "event", ",", "'filtersPass'", ")", "&&", "(", "new", "\\", "ReflectionMethod", "(", "$", "event", ",", "'filtersPass'", ")", ")", "->", "isPublic", "(", ")", "&&", "!", "$", "event", "->", "filtersPass", "(", "$", "laravel", ")", ")", "{", "continue", ";", "}", "$", "messages", "[", "]", "=", "'Running: '", ".", "$", "event", "->", "getSummaryForDisplay", "(", ")", ";", "$", "event", "->", "run", "(", "$", "laravel", ")", ";", "++", "$", "eventsRan", ";", "}", "if", "(", "count", "(", "$", "events", ")", "===", "0", "||", "$", "eventsRan", "===", "0", ")", "{", "$", "messages", "[", "]", "=", "'No scheduled commands are ready to run.'", ";", "}", "return", "$", "this", "->", "response", "(", "$", "messages", ")", ";", "}" ]
This method is nearly identical to ScheduleRunCommand shipped with Laravel, but since we are not interested in console output we couldn't reuse it @param Container $laravel @param Kernel $kernel @param Schedule $schedule @return array
[ "This", "method", "is", "nearly", "identical", "to", "ScheduleRunCommand", "shipped", "with", "Laravel", "but", "since", "we", "are", "not", "interested", "in", "console", "output", "we", "couldn", "t", "reuse", "it" ]
train
https://github.com/dusterio/laravel-aws-worker/blob/356103318badb5af8b7c154bb4fc9eaefd3b41d8/src/Controllers/WorkerController.php#L34-L57
robgridley/zebra
src/Zpl/Builder.php
Builder.command
public function command(): self { $parameters = func_get_args(); $command = strtoupper(array_shift($parameters)); $parameters = array_map([$this, 'parameter'], $parameters); $this->zpl[] = '^' . $command . implode(',', $parameters); return $this; }
php
public function command(): self { $parameters = func_get_args(); $command = strtoupper(array_shift($parameters)); $parameters = array_map([$this, 'parameter'], $parameters); $this->zpl[] = '^' . $command . implode(',', $parameters); return $this; }
[ "public", "function", "command", "(", ")", ":", "self", "{", "$", "parameters", "=", "func_get_args", "(", ")", ";", "$", "command", "=", "strtoupper", "(", "array_shift", "(", "$", "parameters", ")", ")", ";", "$", "parameters", "=", "array_map", "(", "[", "$", "this", ",", "'parameter'", "]", ",", "$", "parameters", ")", ";", "$", "this", "->", "zpl", "[", "]", "=", "'^'", ".", "$", "command", ".", "implode", "(", "','", ",", "$", "parameters", ")", ";", "return", "$", "this", ";", "}" ]
Add a command. @return Builder
[ "Add", "a", "command", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/Builder.php#L21-L30
robgridley/zebra
src/Zpl/Builder.php
Builder.gf
public function gf(): self { $arguments = func_get_args(); if (func_num_args() === 1 && ($image = $arguments[0]) instanceof ImageContract) { $bytesPerRow = $image->width(); $byteCount = $fieldCount = $bytesPerRow * $image->height(); return $this->command('GF', 'A', $byteCount, $fieldCount, $bytesPerRow, $image->toAscii()); } array_unshift($arguments, 'GF'); return call_user_func_array([$this, 'command'], $arguments); }
php
public function gf(): self { $arguments = func_get_args(); if (func_num_args() === 1 && ($image = $arguments[0]) instanceof ImageContract) { $bytesPerRow = $image->width(); $byteCount = $fieldCount = $bytesPerRow * $image->height(); return $this->command('GF', 'A', $byteCount, $fieldCount, $bytesPerRow, $image->toAscii()); } array_unshift($arguments, 'GF'); return call_user_func_array([$this, 'command'], $arguments); }
[ "public", "function", "gf", "(", ")", ":", "self", "{", "$", "arguments", "=", "func_get_args", "(", ")", ";", "if", "(", "func_num_args", "(", ")", "===", "1", "&&", "(", "$", "image", "=", "$", "arguments", "[", "0", "]", ")", "instanceof", "ImageContract", ")", "{", "$", "bytesPerRow", "=", "$", "image", "->", "width", "(", ")", ";", "$", "byteCount", "=", "$", "fieldCount", "=", "$", "bytesPerRow", "*", "$", "image", "->", "height", "(", ")", ";", "return", "$", "this", "->", "command", "(", "'GF'", ",", "'A'", ",", "$", "byteCount", ",", "$", "fieldCount", ",", "$", "bytesPerRow", ",", "$", "image", "->", "toAscii", "(", ")", ")", ";", "}", "array_unshift", "(", "$", "arguments", ",", "'GF'", ")", ";", "return", "call_user_func_array", "(", "[", "$", "this", ",", "'command'", "]", ",", "$", "arguments", ")", ";", "}" ]
Add GF command. @return Builder
[ "Add", "GF", "command", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/Builder.php#L66-L80
robgridley/zebra
src/Zpl/Builder.php
Builder.toZpl
public function toZpl(bool $newlines = false): string { return implode($newlines ? "\n" : '', array_merge(['^XA'], $this->zpl, ['^XZ'])); }
php
public function toZpl(bool $newlines = false): string { return implode($newlines ? "\n" : '', array_merge(['^XA'], $this->zpl, ['^XZ'])); }
[ "public", "function", "toZpl", "(", "bool", "$", "newlines", "=", "false", ")", ":", "string", "{", "return", "implode", "(", "$", "newlines", "?", "\"\\n\"", ":", "''", ",", "array_merge", "(", "[", "'^XA'", "]", ",", "$", "this", "->", "zpl", ",", "[", "'^XZ'", "]", ")", ")", ";", "}" ]
Convert instance to ZPL. @param bool $newlines @return string
[ "Convert", "instance", "to", "ZPL", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/Builder.php#L88-L91
robgridley/zebra
src/Client.php
Client.connect
protected function connect(string $host, int $port): void { $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$this->socket || !@socket_connect($this->socket, $host, $port)) { $error = $this->getLastError(); throw new CommunicationException($error['message'], $error['code']); } }
php
protected function connect(string $host, int $port): void { $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$this->socket || !@socket_connect($this->socket, $host, $port)) { $error = $this->getLastError(); throw new CommunicationException($error['message'], $error['code']); } }
[ "protected", "function", "connect", "(", "string", "$", "host", ",", "int", "$", "port", ")", ":", "void", "{", "$", "this", "->", "socket", "=", "@", "socket_create", "(", "AF_INET", ",", "SOCK_STREAM", ",", "SOL_TCP", ")", ";", "if", "(", "!", "$", "this", "->", "socket", "||", "!", "@", "socket_connect", "(", "$", "this", "->", "socket", ",", "$", "host", ",", "$", "port", ")", ")", "{", "$", "error", "=", "$", "this", "->", "getLastError", "(", ")", ";", "throw", "new", "CommunicationException", "(", "$", "error", "[", "'message'", "]", ",", "$", "error", "[", "'code'", "]", ")", ";", "}", "}" ]
Connect to printer. @param string $host @param int $port @throws CommunicationException if the connection fails.
[ "Connect", "to", "printer", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Client.php#L52-L60
robgridley/zebra
src/Client.php
Client.send
public function send(string $zpl): void { if (false === @socket_write($this->socket, $zpl)) { $error = $this->getLastError(); throw new CommunicationException($error['message'], $error['code']); } }
php
public function send(string $zpl): void { if (false === @socket_write($this->socket, $zpl)) { $error = $this->getLastError(); throw new CommunicationException($error['message'], $error['code']); } }
[ "public", "function", "send", "(", "string", "$", "zpl", ")", ":", "void", "{", "if", "(", "false", "===", "@", "socket_write", "(", "$", "this", "->", "socket", ",", "$", "zpl", ")", ")", "{", "$", "error", "=", "$", "this", "->", "getLastError", "(", ")", ";", "throw", "new", "CommunicationException", "(", "$", "error", "[", "'message'", "]", ",", "$", "error", "[", "'code'", "]", ")", ";", "}", "}" ]
Send ZPL data to printer. @param string $zpl @throws CommunicationException if writing to the socket fails.
[ "Send", "ZPL", "data", "to", "printer", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Client.php#L76-L82
robgridley/zebra
src/Zpl/Image.php
Image.encode
protected function encode(): string { $bitmap = null; $lastRow = null; for ($y = 0; $y < $this->height; $y++) { $bits = null; for ($x = 0; $x < $this->width; $x++) { $bits .= $this->decoder->getBitAt($x, $y); } $bytes = str_split($bits, 8); $bytes[] = str_pad(array_pop($bytes), 8, '0'); $row = null; foreach ($bytes as $byte) { $row .= sprintf('%02X', bindec($byte)); } $bitmap .= $this->compress($row, $lastRow); $lastRow = $row; } return $bitmap; }
php
protected function encode(): string { $bitmap = null; $lastRow = null; for ($y = 0; $y < $this->height; $y++) { $bits = null; for ($x = 0; $x < $this->width; $x++) { $bits .= $this->decoder->getBitAt($x, $y); } $bytes = str_split($bits, 8); $bytes[] = str_pad(array_pop($bytes), 8, '0'); $row = null; foreach ($bytes as $byte) { $row .= sprintf('%02X', bindec($byte)); } $bitmap .= $this->compress($row, $lastRow); $lastRow = $row; } return $bitmap; }
[ "protected", "function", "encode", "(", ")", ":", "string", "{", "$", "bitmap", "=", "null", ";", "$", "lastRow", "=", "null", ";", "for", "(", "$", "y", "=", "0", ";", "$", "y", "<", "$", "this", "->", "height", ";", "$", "y", "++", ")", "{", "$", "bits", "=", "null", ";", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<", "$", "this", "->", "width", ";", "$", "x", "++", ")", "{", "$", "bits", ".=", "$", "this", "->", "decoder", "->", "getBitAt", "(", "$", "x", ",", "$", "y", ")", ";", "}", "$", "bytes", "=", "str_split", "(", "$", "bits", ",", "8", ")", ";", "$", "bytes", "[", "]", "=", "str_pad", "(", "array_pop", "(", "$", "bytes", ")", ",", "8", ",", "'0'", ")", ";", "$", "row", "=", "null", ";", "foreach", "(", "$", "bytes", "as", "$", "byte", ")", "{", "$", "row", ".=", "sprintf", "(", "'%02X'", ",", "bindec", "(", "$", "byte", ")", ")", ";", "}", "$", "bitmap", ".=", "$", "this", "->", "compress", "(", "$", "row", ",", "$", "lastRow", ")", ";", "$", "lastRow", "=", "$", "row", ";", "}", "return", "$", "bitmap", ";", "}" ]
Encode the image in ASCII hexadecimal by looping over every pixel. @return string
[ "Encode", "the", "image", "in", "ASCII", "hexadecimal", "by", "looping", "over", "every", "pixel", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/Image.php#L85-L111
robgridley/zebra
src/Zpl/Image.php
Image.compress
protected function compress(string $row, ?string $lastRow): string { if ($row === $lastRow) { return ':'; } $row = $this->compressTrailingZerosOrOnes($row); $row = $this->compressRepeatingCharacters($row); return $row; }
php
protected function compress(string $row, ?string $lastRow): string { if ($row === $lastRow) { return ':'; } $row = $this->compressTrailingZerosOrOnes($row); $row = $this->compressRepeatingCharacters($row); return $row; }
[ "protected", "function", "compress", "(", "string", "$", "row", ",", "?", "string", "$", "lastRow", ")", ":", "string", "{", "if", "(", "$", "row", "===", "$", "lastRow", ")", "{", "return", "':'", ";", "}", "$", "row", "=", "$", "this", "->", "compressTrailingZerosOrOnes", "(", "$", "row", ")", ";", "$", "row", "=", "$", "this", "->", "compressRepeatingCharacters", "(", "$", "row", ")", ";", "return", "$", "row", ";", "}" ]
Compress a row of ASCII hexadecimal data. @param string $row @param string $lastRow @return string
[ "Compress", "a", "row", "of", "ASCII", "hexadecimal", "data", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/Image.php#L120-L130
robgridley/zebra
src/Zpl/Image.php
Image.compressRepeatingCharacters
protected function compressRepeatingCharacters(string $row): string { $callback = function ($matches) { $original = $matches[0]; $repeat = strlen($original); $count = null; if ($repeat > 400) { $count .= str_repeat('z', floor($repeat / 400)); $repeat %= 400; } if ($repeat > 19) { $count .= chr(ord('f') + floor($repeat / 20)); $repeat %= 20; } if ($repeat > 0) { $count .= chr(ord('F') + $repeat); } return $count . substr($original, 1, 1); }; return preg_replace_callback('/(.)(\1{2,})/', $callback, $row); }
php
protected function compressRepeatingCharacters(string $row): string { $callback = function ($matches) { $original = $matches[0]; $repeat = strlen($original); $count = null; if ($repeat > 400) { $count .= str_repeat('z', floor($repeat / 400)); $repeat %= 400; } if ($repeat > 19) { $count .= chr(ord('f') + floor($repeat / 20)); $repeat %= 20; } if ($repeat > 0) { $count .= chr(ord('F') + $repeat); } return $count . substr($original, 1, 1); }; return preg_replace_callback('/(.)(\1{2,})/', $callback, $row); }
[ "protected", "function", "compressRepeatingCharacters", "(", "string", "$", "row", ")", ":", "string", "{", "$", "callback", "=", "function", "(", "$", "matches", ")", "{", "$", "original", "=", "$", "matches", "[", "0", "]", ";", "$", "repeat", "=", "strlen", "(", "$", "original", ")", ";", "$", "count", "=", "null", ";", "if", "(", "$", "repeat", ">", "400", ")", "{", "$", "count", ".=", "str_repeat", "(", "'z'", ",", "floor", "(", "$", "repeat", "/", "400", ")", ")", ";", "$", "repeat", "%=", "400", ";", "}", "if", "(", "$", "repeat", ">", "19", ")", "{", "$", "count", ".=", "chr", "(", "ord", "(", "'f'", ")", "+", "floor", "(", "$", "repeat", "/", "20", ")", ")", ";", "$", "repeat", "%=", "20", ";", "}", "if", "(", "$", "repeat", ">", "0", ")", "{", "$", "count", ".=", "chr", "(", "ord", "(", "'F'", ")", "+", "$", "repeat", ")", ";", "}", "return", "$", "count", ".", "substr", "(", "$", "original", ",", "1", ",", "1", ")", ";", "}", ";", "return", "preg_replace_callback", "(", "'/(.)(\\1{2,})/'", ",", "$", "callback", ",", "$", "row", ")", ";", "}" ]
Compress characters which repeat. @param string $row @return string
[ "Compress", "characters", "which", "repeat", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/Image.php#L149-L174
robgridley/zebra
src/Zpl/GdDecoder.php
GdDecoder.fromString
public static function fromString(string $data): self { if (false === $image = imagecreatefromstring($data)) { throw new InvalidArgumentException('Could not read image'); } return new static($image); }
php
public static function fromString(string $data): self { if (false === $image = imagecreatefromstring($data)) { throw new InvalidArgumentException('Could not read image'); } return new static($image); }
[ "public", "static", "function", "fromString", "(", "string", "$", "data", ")", ":", "self", "{", "if", "(", "false", "===", "$", "image", "=", "imagecreatefromstring", "(", "$", "data", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Could not read image'", ")", ";", "}", "return", "new", "static", "(", "$", "image", ")", ";", "}" ]
Create a new decoder instance from the specified string. @param string $data @return GdDecoder
[ "Create", "a", "new", "decoder", "instance", "from", "the", "specified", "string", "." ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/GdDecoder.php#L89-L96
robgridley/zebra
src/Zpl/GdDecoder.php
GdDecoder.getBitAt
public function getBitAt(int $x, int $y): int { return (imagecolorat($this->image, $x, $y) & 0xFF) < 127 ? 1 : 0; }
php
public function getBitAt(int $x, int $y): int { return (imagecolorat($this->image, $x, $y) & 0xFF) < 127 ? 1 : 0; }
[ "public", "function", "getBitAt", "(", "int", "$", "x", ",", "int", "$", "y", ")", ":", "int", "{", "return", "(", "imagecolorat", "(", "$", "this", "->", "image", ",", "$", "x", ",", "$", "y", ")", "&", "0xFF", ")", "<", "127", "?", "1", ":", "0", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/robgridley/zebra/blob/c02e740388438f5c8b66e4f66936350bc4b4af37/src/Zpl/GdDecoder.php#L117-L120
robclancy/presenter
src/Decorator.php
Decorator.decorate
public function decorate($value) { if ($value instanceof PresentableInterface) { return $value->getPresenter(); } if (is_array($value) or ($value instanceof IteratorAggregate and $value instanceof ArrayAccess)) { foreach ($value as $k => $v) { $value[$k] = $this->decorate($v); } } return $value; }
php
public function decorate($value) { if ($value instanceof PresentableInterface) { return $value->getPresenter(); } if (is_array($value) or ($value instanceof IteratorAggregate and $value instanceof ArrayAccess)) { foreach ($value as $k => $v) { $value[$k] = $this->decorate($v); } } return $value; }
[ "public", "function", "decorate", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "PresentableInterface", ")", "{", "return", "$", "value", "->", "getPresenter", "(", ")", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", "or", "(", "$", "value", "instanceof", "IteratorAggregate", "and", "$", "value", "instanceof", "ArrayAccess", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "value", "[", "$", "k", "]", "=", "$", "this", "->", "decorate", "(", "$", "v", ")", ";", "}", "}", "return", "$", "value", ";", "}" ]
/* If this variable implements Robbo\Presenter\PresentableInterface then turn it into a presenter. @param mixed $value @return mixed $value
[ "/", "*", "If", "this", "variable", "implements", "Robbo", "\\", "Presenter", "\\", "PresentableInterface", "then", "turn", "it", "into", "a", "presenter", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/Decorator.php#L16-L29
robclancy/presenter
src/View/Factory.php
Factory.share
public function share($key, $value = null) { if (! is_array($key)) { return parent::share($key, $this->decorate($value)); } return parent::share($this->decorate($key)); }
php
public function share($key, $value = null) { if (! is_array($key)) { return parent::share($key, $this->decorate($value)); } return parent::share($this->decorate($key)); }
[ "public", "function", "share", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "key", ")", ")", "{", "return", "parent", "::", "share", "(", "$", "key", ",", "$", "this", "->", "decorate", "(", "$", "value", ")", ")", ";", "}", "return", "parent", "::", "share", "(", "$", "this", "->", "decorate", "(", "$", "key", ")", ")", ";", "}" ]
Add a piece of shared data to the factory. @param string $key @param mixed $value
[ "Add", "a", "piece", "of", "shared", "data", "to", "the", "factory", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/View/Factory.php#L60-L67
robclancy/presenter
src/Presenter.php
Presenter.offsetExists
public function offsetExists($offset) { // We only check isset on the array, if it is an object we return true as the object could be overloaded if (! is_array($this->object)) { return true; } if ($method = $this->getPresenterMethodFromVariable($offset)) { $result = $this->$method(); return isset($result); } return isset($this->object[$offset]); }
php
public function offsetExists($offset) { // We only check isset on the array, if it is an object we return true as the object could be overloaded if (! is_array($this->object)) { return true; } if ($method = $this->getPresenterMethodFromVariable($offset)) { $result = $this->$method(); return isset($result); } return isset($this->object[$offset]); }
[ "public", "function", "offsetExists", "(", "$", "offset", ")", "{", "// We only check isset on the array, if it is an object we return true as the object could be overloaded", "if", "(", "!", "is_array", "(", "$", "this", "->", "object", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "method", "=", "$", "this", "->", "getPresenterMethodFromVariable", "(", "$", "offset", ")", ")", "{", "$", "result", "=", "$", "this", "->", "$", "method", "(", ")", ";", "return", "isset", "(", "$", "result", ")", ";", "}", "return", "isset", "(", "$", "this", "->", "object", "[", "$", "offset", "]", ")", ";", "}" ]
/* This will be called when isset() is called via array access. @param mixed $offset @return boolean
[ "/", "*", "This", "will", "be", "called", "when", "isset", "()", "is", "called", "via", "array", "access", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/Presenter.php#L75-L89
robclancy/presenter
src/Presenter.php
Presenter.offsetSet
public function offsetSet($offset, $value) { if (is_array($this->object)) { $this->object[$offset] = $value; return; } $this->object->$offset = $value; }
php
public function offsetSet($offset, $value) { if (is_array($this->object)) { $this->object[$offset] = $value; return; } $this->object->$offset = $value; }
[ "public", "function", "offsetSet", "(", "$", "offset", ",", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "object", ")", ")", "{", "$", "this", "->", "object", "[", "$", "offset", "]", "=", "$", "value", ";", "return", ";", "}", "$", "this", "->", "object", "->", "$", "offset", "=", "$", "value", ";", "}" ]
Set variable or key value using array access. @param mixed $offset @param mixed $value
[ "Set", "variable", "or", "key", "value", "using", "array", "access", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/Presenter.php#L109-L118
robclancy/presenter
src/Presenter.php
Presenter.offsetUnset
public function offsetUnset($offset) { if (is_array($this->object)) { unset($this->object[$offset]); return; } unset($this->object->$offset); }
php
public function offsetUnset($offset) { if (is_array($this->object)) { unset($this->object[$offset]); return; } unset($this->object->$offset); }
[ "public", "function", "offsetUnset", "(", "$", "offset", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "object", ")", ")", "{", "unset", "(", "$", "this", "->", "object", "[", "$", "offset", "]", ")", ";", "return", ";", "}", "unset", "(", "$", "this", "->", "object", "->", "$", "offset", ")", ";", "}" ]
Unset a variable or key value using array access. @param mixed $offset
[ "Unset", "a", "variable", "or", "key", "value", "using", "array", "access", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/Presenter.php#L125-L134
robclancy/presenter
src/Presenter.php
Presenter.__isset
public function __isset($name) { if ($method = $this->getPresenterMethodFromVariable($name)) { $result = $this->$method(); return isset($result); } if (is_array($this->object)) { return isset($this->object[$name]); } return isset($this->object->$name); }
php
public function __isset($name) { if ($method = $this->getPresenterMethodFromVariable($name)) { $result = $this->$method(); return isset($result); } if (is_array($this->object)) { return isset($this->object[$name]); } return isset($this->object->$name); }
[ "public", "function", "__isset", "(", "$", "name", ")", "{", "if", "(", "$", "method", "=", "$", "this", "->", "getPresenterMethodFromVariable", "(", "$", "name", ")", ")", "{", "$", "result", "=", "$", "this", "->", "$", "method", "(", ")", ";", "return", "isset", "(", "$", "result", ")", ";", "}", "if", "(", "is_array", "(", "$", "this", "->", "object", ")", ")", "{", "return", "isset", "(", "$", "this", "->", "object", "[", "$", "name", "]", ")", ";", "}", "return", "isset", "(", "$", "this", "->", "object", "->", "$", "name", ")", ";", "}" ]
Allow ability to run isset() on a variable. @param string $name @return bool
[ "Allow", "ability", "to", "run", "isset", "()", "on", "a", "variable", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/Presenter.php#L178-L191
robclancy/presenter
src/Presenter.php
Presenter.getPresenterMethodFromVariable
protected function getPresenterMethodFromVariable($variable) { $method = 'present'.str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $variable))); if (method_exists($this, $method)) { return $method; } }
php
protected function getPresenterMethodFromVariable($variable) { $method = 'present'.str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $variable))); if (method_exists($this, $method)) { return $method; } }
[ "protected", "function", "getPresenterMethodFromVariable", "(", "$", "variable", ")", "{", "$", "method", "=", "'present'", ".", "str_replace", "(", "' '", ",", "''", ",", "ucwords", "(", "str_replace", "(", "[", "'-'", ",", "'_'", "]", ",", "' '", ",", "$", "variable", ")", ")", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "return", "$", "method", ";", "}", "}" ]
Fetch the 'present' method name for the given variable. @param string $variable @return string|null
[ "Fetch", "the", "present", "method", "name", "for", "the", "given", "variable", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/Presenter.php#L216-L222
robclancy/presenter
src/View/View.php
View.with
public function with($key, $value = null) { if (is_array($key)) { return parent::with($this->factory->decorate($key)); } return parent::with($key, $this->factory->decorate($value)); }
php
public function with($key, $value = null) { if (is_array($key)) { return parent::with($this->factory->decorate($key)); } return parent::with($key, $this->factory->decorate($value)); }
[ "public", "function", "with", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "return", "parent", "::", "with", "(", "$", "this", "->", "factory", "->", "decorate", "(", "$", "key", ")", ")", ";", "}", "return", "parent", "::", "with", "(", "$", "key", ",", "$", "this", "->", "factory", "->", "decorate", "(", "$", "value", ")", ")", ";", "}" ]
Add a piece of data to the view. @param string|array $key @param mixed $value @return \Illuminate\View\View
[ "Add", "a", "piece", "of", "data", "to", "the", "view", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/View/View.php#L17-L24
robclancy/presenter
src/PresenterServiceProvider.php
PresenterServiceProvider.registerDecorator
public function registerDecorator() { $this->app->singleton('presenter.decorator', function ($app) { $decorator = new Decorator(); // This isn't really doing anything here however if you want to extend the decorator // with your own instance then you need to do it like this in your own service // provider or in start/global.php. Presenter::setExtendedDecorator($decorator); return $decorator; }); }
php
public function registerDecorator() { $this->app->singleton('presenter.decorator', function ($app) { $decorator = new Decorator(); // This isn't really doing anything here however if you want to extend the decorator // with your own instance then you need to do it like this in your own service // provider or in start/global.php. Presenter::setExtendedDecorator($decorator); return $decorator; }); }
[ "public", "function", "registerDecorator", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'presenter.decorator'", ",", "function", "(", "$", "app", ")", "{", "$", "decorator", "=", "new", "Decorator", "(", ")", ";", "// This isn't really doing anything here however if you want to extend the decorator", "// with your own instance then you need to do it like this in your own service", "// provider or in start/global.php.", "Presenter", "::", "setExtendedDecorator", "(", "$", "decorator", ")", ";", "return", "$", "decorator", ";", "}", ")", ";", "}" ]
Register the decorator. If you want to extend the decorator you would basically copy what this method does in start/global.php or your own service provider.
[ "Register", "the", "decorator", ".", "If", "you", "want", "to", "extend", "the", "decorator", "you", "would", "basically", "copy", "what", "this", "method", "does", "in", "start", "/", "global", ".", "php", "or", "your", "own", "service", "provider", "." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/PresenterServiceProvider.php#L30-L42
robclancy/presenter
src/PresenterServiceProvider.php
PresenterServiceProvider.registerFactory
public function registerFactory() { $this->app->singleton('view', function ($app) { // Next we need to grab the engine resolver instance that will be used by the // factory. The resolver will be used by a factory to get each of // the various engine implementations such as plain PHP or Blade engine. $resolver = $app['view.engine.resolver']; $finder = $app['view.finder']; $factory = new View\Factory($resolver, $finder, $app['events'], $app['presenter.decorator']); // We will also set the container instance on this view factory since the // view composers may be classes registered in the container, which allows // for great testable, flexible composers for the application developer. $factory->setContainer($app); $factory->share('app', $app); return $factory; }); }
php
public function registerFactory() { $this->app->singleton('view', function ($app) { // Next we need to grab the engine resolver instance that will be used by the // factory. The resolver will be used by a factory to get each of // the various engine implementations such as plain PHP or Blade engine. $resolver = $app['view.engine.resolver']; $finder = $app['view.finder']; $factory = new View\Factory($resolver, $finder, $app['events'], $app['presenter.decorator']); // We will also set the container instance on this view factory since the // view composers may be classes registered in the container, which allows // for great testable, flexible composers for the application developer. $factory->setContainer($app); $factory->share('app', $app); return $factory; }); }
[ "public", "function", "registerFactory", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'view'", ",", "function", "(", "$", "app", ")", "{", "// Next we need to grab the engine resolver instance that will be used by the", "// factory. The resolver will be used by a factory to get each of", "// the various engine implementations such as plain PHP or Blade engine.", "$", "resolver", "=", "$", "app", "[", "'view.engine.resolver'", "]", ";", "$", "finder", "=", "$", "app", "[", "'view.finder'", "]", ";", "$", "factory", "=", "new", "View", "\\", "Factory", "(", "$", "resolver", ",", "$", "finder", ",", "$", "app", "[", "'events'", "]", ",", "$", "app", "[", "'presenter.decorator'", "]", ")", ";", "// We will also set the container instance on this view factory since the", "// view composers may be classes registered in the container, which allows", "// for great testable, flexible composers for the application developer.", "$", "factory", "->", "setContainer", "(", "$", "app", ")", ";", "$", "factory", "->", "share", "(", "'app'", ",", "$", "app", ")", ";", "return", "$", "factory", ";", "}", ")", ";", "}" ]
Copied from the view service provider... Register the view factory.
[ "Copied", "from", "the", "view", "service", "provider", "..." ]
train
https://github.com/robclancy/presenter/blob/5307e62339145f552cca0c98e4b7ea3ba914082c/src/PresenterServiceProvider.php#L49-L70
kirkbushell/eloquence
src/Behaviours/SumCache/Summable.php
Summable.bootSummable
public static function bootSummable() { static::created(function ($model) { $sumCache = new SumCache($model); $sumCache->apply(function ($config) use ($model, $sumCache) { $sumCache->updateCacheRecord($config, '+', $model->{$config['columnToSum']}, $model->{$config['foreignKey']}); }); }); static::updated(function ($model) { (new SumCache($model))->update(); }); static::deleted(function ($model) { $sumCache = new SumCache($model); $sumCache->apply(function ($config) use ($model, $sumCache) { $sumCache->updateCacheRecord($config, '-', $model->{$config['columnToSum']}, $model->{$config['foreignKey']}); }); }); }
php
public static function bootSummable() { static::created(function ($model) { $sumCache = new SumCache($model); $sumCache->apply(function ($config) use ($model, $sumCache) { $sumCache->updateCacheRecord($config, '+', $model->{$config['columnToSum']}, $model->{$config['foreignKey']}); }); }); static::updated(function ($model) { (new SumCache($model))->update(); }); static::deleted(function ($model) { $sumCache = new SumCache($model); $sumCache->apply(function ($config) use ($model, $sumCache) { $sumCache->updateCacheRecord($config, '-', $model->{$config['columnToSum']}, $model->{$config['foreignKey']}); }); }); }
[ "public", "static", "function", "bootSummable", "(", ")", "{", "static", "::", "created", "(", "function", "(", "$", "model", ")", "{", "$", "sumCache", "=", "new", "SumCache", "(", "$", "model", ")", ";", "$", "sumCache", "->", "apply", "(", "function", "(", "$", "config", ")", "use", "(", "$", "model", ",", "$", "sumCache", ")", "{", "$", "sumCache", "->", "updateCacheRecord", "(", "$", "config", ",", "'+'", ",", "$", "model", "->", "{", "$", "config", "[", "'columnToSum'", "]", "}", ",", "$", "model", "->", "{", "$", "config", "[", "'foreignKey'", "]", "}", ")", ";", "}", ")", ";", "}", ")", ";", "static", "::", "updated", "(", "function", "(", "$", "model", ")", "{", "(", "new", "SumCache", "(", "$", "model", ")", ")", "->", "update", "(", ")", ";", "}", ")", ";", "static", "::", "deleted", "(", "function", "(", "$", "model", ")", "{", "$", "sumCache", "=", "new", "SumCache", "(", "$", "model", ")", ";", "$", "sumCache", "->", "apply", "(", "function", "(", "$", "config", ")", "use", "(", "$", "model", ",", "$", "sumCache", ")", "{", "$", "sumCache", "->", "updateCacheRecord", "(", "$", "config", ",", "'-'", ",", "$", "model", "->", "{", "$", "config", "[", "'columnToSum'", "]", "}", ",", "$", "model", "->", "{", "$", "config", "[", "'foreignKey'", "]", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Boot the trait and its event bindings when a model is created.
[ "Boot", "the", "trait", "and", "its", "event", "bindings", "when", "a", "model", "is", "created", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/SumCache/Summable.php#L13-L32
kirkbushell/eloquence
src/Behaviours/Slug.php
Slug.fromId
public static function fromId($id) { $salt = md5(uniqid().$id); $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $slug = with(new Hashids($salt, $length = 8, $alphabet))->encode($id); return new Slug($slug); }
php
public static function fromId($id) { $salt = md5(uniqid().$id); $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $slug = with(new Hashids($salt, $length = 8, $alphabet))->encode($id); return new Slug($slug); }
[ "public", "static", "function", "fromId", "(", "$", "id", ")", "{", "$", "salt", "=", "md5", "(", "uniqid", "(", ")", ".", "$", "id", ")", ";", "$", "alphabet", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "$", "slug", "=", "with", "(", "new", "Hashids", "(", "$", "salt", ",", "$", "length", "=", "8", ",", "$", "alphabet", ")", ")", "->", "encode", "(", "$", "id", ")", ";", "return", "new", "Slug", "(", "$", "slug", ")", ";", "}" ]
Generate a new 8-character slug. @param integer $id @return Slug
[ "Generate", "a", "new", "8", "-", "character", "slug", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Slug.php#L32-L39
kirkbushell/eloquence
src/Behaviours/CamelCasing.php
CamelCasing.getAttribute
public function getAttribute($key) { if (method_exists($this, $key)) { return $this->getRelationValue($key); } return parent::getAttribute($this->getSnakeKey($key)); }
php
public function getAttribute($key) { if (method_exists($this, $key)) { return $this->getRelationValue($key); } return parent::getAttribute($this->getSnakeKey($key)); }
[ "public", "function", "getAttribute", "(", "$", "key", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "$", "key", ")", ")", "{", "return", "$", "this", "->", "getRelationValue", "(", "$", "key", ")", ";", "}", "return", "parent", "::", "getAttribute", "(", "$", "this", "->", "getSnakeKey", "(", "$", "key", ")", ")", ";", "}" ]
Retrieve a given attribute but allow it to be accessed via alternative case methods (such as camelCase). @param string $key @return mixed
[ "Retrieve", "a", "given", "attribute", "but", "allow", "it", "to", "be", "accessed", "via", "alternative", "case", "methods", "(", "such", "as", "camelCase", ")", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CamelCasing.php#L33-L40
kirkbushell/eloquence
src/Behaviours/CamelCasing.php
CamelCasing.toCamelCase
public function toCamelCase($attributes) { $convertedAttributes = []; foreach ($attributes as $key => $value) { $key = $this->getTrueKey($key); $convertedAttributes[$key] = $value; } return $convertedAttributes; }
php
public function toCamelCase($attributes) { $convertedAttributes = []; foreach ($attributes as $key => $value) { $key = $this->getTrueKey($key); $convertedAttributes[$key] = $value; } return $convertedAttributes; }
[ "public", "function", "toCamelCase", "(", "$", "attributes", ")", "{", "$", "convertedAttributes", "=", "[", "]", ";", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "key", "=", "$", "this", "->", "getTrueKey", "(", "$", "key", ")", ";", "$", "convertedAttributes", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "convertedAttributes", ";", "}" ]
Converts a given array of attribute keys to the casing required by CamelCaseModel. @param mixed $attributes @return array
[ "Converts", "a", "given", "array", "of", "attribute", "keys", "to", "the", "casing", "required", "by", "CamelCaseModel", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CamelCasing.php#L92-L102
kirkbushell/eloquence
src/Behaviours/CamelCasing.php
CamelCasing.toSnakeCase
public function toSnakeCase($attributes) { $convertedAttributes = []; foreach ($attributes as $key => $value) { $convertedAttributes[$this->getSnakeKey($key)] = $value; } return $convertedAttributes; }
php
public function toSnakeCase($attributes) { $convertedAttributes = []; foreach ($attributes as $key => $value) { $convertedAttributes[$this->getSnakeKey($key)] = $value; } return $convertedAttributes; }
[ "public", "function", "toSnakeCase", "(", "$", "attributes", ")", "{", "$", "convertedAttributes", "=", "[", "]", ";", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "convertedAttributes", "[", "$", "this", "->", "getSnakeKey", "(", "$", "key", ")", "]", "=", "$", "value", ";", "}", "return", "$", "convertedAttributes", ";", "}" ]
Converts a given array of attribute keys to the casing required by CamelCaseModel. @param $attributes @return array
[ "Converts", "a", "given", "array", "of", "attribute", "keys", "to", "the", "casing", "required", "by", "CamelCaseModel", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CamelCasing.php#L110-L119
kirkbushell/eloquence
src/Behaviours/CamelCasing.php
CamelCasing.getTrueKey
public function getTrueKey($key) { // If the key is a pivot key, leave it alone - this is required internal behaviour // of Eloquent for dealing with many:many relationships. if ($this->isCamelCase() && strpos($key, 'pivot_') === false) { $key = camel_case($key); } return $key; }
php
public function getTrueKey($key) { // If the key is a pivot key, leave it alone - this is required internal behaviour // of Eloquent for dealing with many:many relationships. if ($this->isCamelCase() && strpos($key, 'pivot_') === false) { $key = camel_case($key); } return $key; }
[ "public", "function", "getTrueKey", "(", "$", "key", ")", "{", "// If the key is a pivot key, leave it alone - this is required internal behaviour", "// of Eloquent for dealing with many:many relationships.", "if", "(", "$", "this", "->", "isCamelCase", "(", ")", "&&", "strpos", "(", "$", "key", ",", "'pivot_'", ")", "===", "false", ")", "{", "$", "key", "=", "camel_case", "(", "$", "key", ")", ";", "}", "return", "$", "key", ";", "}" ]
Retrieves the true key name for a key. @param $key @return string
[ "Retrieves", "the", "true", "key", "name", "for", "a", "key", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CamelCasing.php#L127-L136
kirkbushell/eloquence
src/Behaviours/CamelCasing.php
CamelCasing.isCamelCase
public function isCamelCase() { return $this->enforceCamelCase or (isset($this->parent) && method_exists($this->parent, 'isCamelCase') && $this->parent->isCamelCase()); }
php
public function isCamelCase() { return $this->enforceCamelCase or (isset($this->parent) && method_exists($this->parent, 'isCamelCase') && $this->parent->isCamelCase()); }
[ "public", "function", "isCamelCase", "(", ")", "{", "return", "$", "this", "->", "enforceCamelCase", "or", "(", "isset", "(", "$", "this", "->", "parent", ")", "&&", "method_exists", "(", "$", "this", "->", "parent", ",", "'isCamelCase'", ")", "&&", "$", "this", "->", "parent", "->", "isCamelCase", "(", ")", ")", ";", "}" ]
Determines whether the model (or its parent) requires camelcasing. This is required for pivot models whereby they actually depend on their parents for this feature. @return bool
[ "Determines", "whether", "the", "model", "(", "or", "its", "parent", ")", "requires", "camelcasing", ".", "This", "is", "required", "for", "pivot", "models", "whereby", "they", "actually", "depend", "on", "their", "parents", "for", "this", "feature", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CamelCasing.php#L144-L147
kirkbushell/eloquence
src/Behaviours/CamelCasing.php
CamelCasing.__isset
public function __isset($key) { return parent::__isset($key) || parent::__isset($this->getSnakeKey($key)); }
php
public function __isset($key) { return parent::__isset($key) || parent::__isset($this->getSnakeKey($key)); }
[ "public", "function", "__isset", "(", "$", "key", ")", "{", "return", "parent", "::", "__isset", "(", "$", "key", ")", "||", "parent", "::", "__isset", "(", "$", "this", "->", "getSnakeKey", "(", "$", "key", ")", ")", ";", "}" ]
Because we are changing the case of keys and want to use camelCase throughout the application, whenever we do isset checks we need to ensure that we check using snake_case. @param $key @return mixed
[ "Because", "we", "are", "changing", "the", "case", "of", "keys", "and", "want", "to", "use", "camelCase", "throughout", "the", "application", "whenever", "we", "do", "isset", "checks", "we", "need", "to", "ensure", "that", "we", "check", "using", "snake_case", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CamelCasing.php#L167-L170
kirkbushell/eloquence
src/Commands/RebuildCaches.php
RebuildCaches.handle
public function handle() { if ($class = $this->option('class')) { $classes = [$class]; } else { $directory = $this->option('dir') ?: app_path(); $classes = (new FindCacheableClasses($directory))->getAllCacheableClasses(); } foreach ($classes as $className) { $this->rebuild($className); } }
php
public function handle() { if ($class = $this->option('class')) { $classes = [$class]; } else { $directory = $this->option('dir') ?: app_path(); $classes = (new FindCacheableClasses($directory))->getAllCacheableClasses(); } foreach ($classes as $className) { $this->rebuild($className); } }
[ "public", "function", "handle", "(", ")", "{", "if", "(", "$", "class", "=", "$", "this", "->", "option", "(", "'class'", ")", ")", "{", "$", "classes", "=", "[", "$", "class", "]", ";", "}", "else", "{", "$", "directory", "=", "$", "this", "->", "option", "(", "'dir'", ")", "?", ":", "app_path", "(", ")", ";", "$", "classes", "=", "(", "new", "FindCacheableClasses", "(", "$", "directory", ")", ")", "->", "getAllCacheableClasses", "(", ")", ";", "}", "foreach", "(", "$", "classes", "as", "$", "className", ")", "{", "$", "this", "->", "rebuild", "(", "$", "className", ")", ";", "}", "}" ]
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Commands/RebuildCaches.php#L41-L53
kirkbushell/eloquence
src/Commands/RebuildCaches.php
RebuildCaches.rebuild
private function rebuild($className) { $instance = new $className; if (method_exists($instance, 'countCaches')) { $this->info("Rebuilding [$className] count caches"); $countCache = new CountCache($instance); $countCache->rebuild(); } if (method_exists($instance, 'sumCaches')) { $this->info("Rebuilding [$className] sum caches"); $sumCache = new SumCache($instance); $sumCache->rebuild(); } }
php
private function rebuild($className) { $instance = new $className; if (method_exists($instance, 'countCaches')) { $this->info("Rebuilding [$className] count caches"); $countCache = new CountCache($instance); $countCache->rebuild(); } if (method_exists($instance, 'sumCaches')) { $this->info("Rebuilding [$className] sum caches"); $sumCache = new SumCache($instance); $sumCache->rebuild(); } }
[ "private", "function", "rebuild", "(", "$", "className", ")", "{", "$", "instance", "=", "new", "$", "className", ";", "if", "(", "method_exists", "(", "$", "instance", ",", "'countCaches'", ")", ")", "{", "$", "this", "->", "info", "(", "\"Rebuilding [$className] count caches\"", ")", ";", "$", "countCache", "=", "new", "CountCache", "(", "$", "instance", ")", ";", "$", "countCache", "->", "rebuild", "(", ")", ";", "}", "if", "(", "method_exists", "(", "$", "instance", ",", "'sumCaches'", ")", ")", "{", "$", "this", "->", "info", "(", "\"Rebuilding [$className] sum caches\"", ")", ";", "$", "sumCache", "=", "new", "SumCache", "(", "$", "instance", ")", ";", "$", "sumCache", "->", "rebuild", "(", ")", ";", "}", "}" ]
Rebuilds the caches for the given class. @param string $className
[ "Rebuilds", "the", "caches", "for", "the", "given", "class", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Commands/RebuildCaches.php#L60-L75
kirkbushell/eloquence
src/Behaviours/Sluggable.php
Sluggable.bootSluggable
public static function bootSluggable() { static::creating(function ($model) { $model->generateSlug(); }); static::created(function ($model) { if ($model->slugStrategy() == 'id') { $model->generateIdSlug(); $model->save(); } }); }
php
public static function bootSluggable() { static::creating(function ($model) { $model->generateSlug(); }); static::created(function ($model) { if ($model->slugStrategy() == 'id') { $model->generateIdSlug(); $model->save(); } }); }
[ "public", "static", "function", "bootSluggable", "(", ")", "{", "static", "::", "creating", "(", "function", "(", "$", "model", ")", "{", "$", "model", "->", "generateSlug", "(", ")", ";", "}", ")", ";", "static", "::", "created", "(", "function", "(", "$", "model", ")", "{", "if", "(", "$", "model", "->", "slugStrategy", "(", ")", "==", "'id'", ")", "{", "$", "model", "->", "generateIdSlug", "(", ")", ";", "$", "model", "->", "save", "(", ")", ";", "}", "}", ")", ";", "}" ]
When added to a model, the trait will bind to the creating and created events, generating the appropriate slugs as necessary.
[ "When", "added", "to", "a", "model", "the", "trait", "will", "bind", "to", "the", "creating", "and", "created", "events", "generating", "the", "appropriate", "slugs", "as", "necessary", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Sluggable.php#L13-L25
kirkbushell/eloquence
src/Behaviours/Sluggable.php
Sluggable.generateIdSlug
public function generateIdSlug() { $slug = Slug::fromId($this->getKey()); // Ensure slug is unique (since the fromId() algorithm doesn't produce unique slugs) $attempts = 10; while ($this->isExistingSlug($slug)) { if ($attempts <= 0) { throw new UnableToCreateSlugException( "Unable to find unique slug for record '{$this->getKey()}', tried 10 times..." ); } $slug = Slug::random(); $attempts--; } $this->setSlugValue($slug); }
php
public function generateIdSlug() { $slug = Slug::fromId($this->getKey()); // Ensure slug is unique (since the fromId() algorithm doesn't produce unique slugs) $attempts = 10; while ($this->isExistingSlug($slug)) { if ($attempts <= 0) { throw new UnableToCreateSlugException( "Unable to find unique slug for record '{$this->getKey()}', tried 10 times..." ); } $slug = Slug::random(); $attempts--; } $this->setSlugValue($slug); }
[ "public", "function", "generateIdSlug", "(", ")", "{", "$", "slug", "=", "Slug", "::", "fromId", "(", "$", "this", "->", "getKey", "(", ")", ")", ";", "// Ensure slug is unique (since the fromId() algorithm doesn't produce unique slugs)", "$", "attempts", "=", "10", ";", "while", "(", "$", "this", "->", "isExistingSlug", "(", "$", "slug", ")", ")", "{", "if", "(", "$", "attempts", "<=", "0", ")", "{", "throw", "new", "UnableToCreateSlugException", "(", "\"Unable to find unique slug for record '{$this->getKey()}', tried 10 times...\"", ")", ";", "}", "$", "slug", "=", "Slug", "::", "random", "(", ")", ";", "$", "attempts", "--", ";", "}", "$", "this", "->", "setSlugValue", "(", "$", "slug", ")", ";", "}" ]
Generate a slug based on the main model key.
[ "Generate", "a", "slug", "based", "on", "the", "main", "model", "key", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Sluggable.php#L30-L48
kirkbushell/eloquence
src/Behaviours/Sluggable.php
Sluggable.generateTitleSlug
public function generateTitleSlug(array $fields) { static $attempts = 0; $titleSlug = Slug::fromTitle(implode('-', $this->getTitleFields($fields))); // This is not the first time we've attempted to create a title slug, so - let's make it more unique if ($attempts > 0) { $titleSlug . "-{$attempts}"; } $this->setSlugValue($titleSlug); $attempts++; }
php
public function generateTitleSlug(array $fields) { static $attempts = 0; $titleSlug = Slug::fromTitle(implode('-', $this->getTitleFields($fields))); // This is not the first time we've attempted to create a title slug, so - let's make it more unique if ($attempts > 0) { $titleSlug . "-{$attempts}"; } $this->setSlugValue($titleSlug); $attempts++; }
[ "public", "function", "generateTitleSlug", "(", "array", "$", "fields", ")", "{", "static", "$", "attempts", "=", "0", ";", "$", "titleSlug", "=", "Slug", "::", "fromTitle", "(", "implode", "(", "'-'", ",", "$", "this", "->", "getTitleFields", "(", "$", "fields", ")", ")", ")", ";", "// This is not the first time we've attempted to create a title slug, so - let's make it more unique", "if", "(", "$", "attempts", ">", "0", ")", "{", "$", "titleSlug", ".", "\"-{$attempts}\"", ";", "}", "$", "this", "->", "setSlugValue", "(", "$", "titleSlug", ")", ";", "$", "attempts", "++", ";", "}" ]
Generate a slug string based on the fields required.
[ "Generate", "a", "slug", "string", "based", "on", "the", "fields", "required", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Sluggable.php#L53-L67
kirkbushell/eloquence
src/Behaviours/Sluggable.php
Sluggable.getTitleFields
public function getTitleFields(array $fields) { $fields = array_map(function ($field) { if (str_contains($field, '.')) { return object_get($this, $field); // this acts as a delimiter, which we can replace with / } else { return $this->{$field}; } }, $fields); return $fields; }
php
public function getTitleFields(array $fields) { $fields = array_map(function ($field) { if (str_contains($field, '.')) { return object_get($this, $field); // this acts as a delimiter, which we can replace with / } else { return $this->{$field}; } }, $fields); return $fields; }
[ "public", "function", "getTitleFields", "(", "array", "$", "fields", ")", "{", "$", "fields", "=", "array_map", "(", "function", "(", "$", "field", ")", "{", "if", "(", "str_contains", "(", "$", "field", ",", "'.'", ")", ")", "{", "return", "object_get", "(", "$", "this", ",", "$", "field", ")", ";", "// this acts as a delimiter, which we can replace with /", "}", "else", "{", "return", "$", "this", "->", "{", "$", "field", "}", ";", "}", "}", ",", "$", "fields", ")", ";", "return", "$", "fields", ";", "}" ]
Because a title slug can be created from multiple sources (such as an article title, a category title.etc.), this allows us to search out those fields from related objects and return the combined values. @param array $fields @return array
[ "Because", "a", "title", "slug", "can", "be", "created", "from", "multiple", "sources", "(", "such", "as", "an", "article", "title", "a", "category", "title", ".", "etc", ".", ")", "this", "allows", "us", "to", "search", "out", "those", "fields", "from", "related", "objects", "and", "return", "the", "combined", "values", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Sluggable.php#L76-L87
kirkbushell/eloquence
src/Behaviours/Sluggable.php
Sluggable.generateSlug
public function generateSlug() { $strategy = $this->slugStrategy(); if ($strategy == 'uuid') { $this->generateIdSlug(); } elseif ($strategy != 'id') { $this->generateTitleSlug((array) $strategy); } }
php
public function generateSlug() { $strategy = $this->slugStrategy(); if ($strategy == 'uuid') { $this->generateIdSlug(); } elseif ($strategy != 'id') { $this->generateTitleSlug((array) $strategy); } }
[ "public", "function", "generateSlug", "(", ")", "{", "$", "strategy", "=", "$", "this", "->", "slugStrategy", "(", ")", ";", "if", "(", "$", "strategy", "==", "'uuid'", ")", "{", "$", "this", "->", "generateIdSlug", "(", ")", ";", "}", "elseif", "(", "$", "strategy", "!=", "'id'", ")", "{", "$", "this", "->", "generateTitleSlug", "(", "(", "array", ")", "$", "strategy", ")", ";", "}", "}" ]
Generate the slug for the model based on the model's slug strategy.
[ "Generate", "the", "slug", "for", "the", "model", "based", "on", "the", "model", "s", "slug", "strategy", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Sluggable.php#L92-L101
kirkbushell/eloquence
src/Behaviours/Uuid.php
Uuid.bootUuid
protected static function bootUuid() { /** * Attach to the 'creating' Model Event to provide a UUID * for the `id` field (provided by $model->getKeyName()) */ static::creating(function ($model) { $key = $model->getKeyName(); if (empty($model->$key)) { $model->$key = (string) $model->generateNewUuid(); } }); }
php
protected static function bootUuid() { /** * Attach to the 'creating' Model Event to provide a UUID * for the `id` field (provided by $model->getKeyName()) */ static::creating(function ($model) { $key = $model->getKeyName(); if (empty($model->$key)) { $model->$key = (string) $model->generateNewUuid(); } }); }
[ "protected", "static", "function", "bootUuid", "(", ")", "{", "/**\n * Attach to the 'creating' Model Event to provide a UUID\n * for the `id` field (provided by $model->getKeyName())\n */", "static", "::", "creating", "(", "function", "(", "$", "model", ")", "{", "$", "key", "=", "$", "model", "->", "getKeyName", "(", ")", ";", "if", "(", "empty", "(", "$", "model", "->", "$", "key", ")", ")", "{", "$", "model", "->", "$", "key", "=", "(", "string", ")", "$", "model", "->", "generateNewUuid", "(", ")", ";", "}", "}", ")", ";", "}" ]
The "booting" method of the model. @return void
[ "The", "booting", "method", "of", "the", "model", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Uuid.php#L23-L36
kirkbushell/eloquence
src/Behaviours/Cacheable.php
Cacheable.updateCacheRecord
public function updateCacheRecord(array $config, $operation, $amount, $foreignKey) { if (is_null($foreignKey)) { return; } $config = $this->processConfig($config); $sql = DB::table($config['table'])->where($config['key'], $foreignKey); /* * Increment for + operator */ if ($operation == '+') { return $sql->increment($config['field'], $amount); } /* * Decrement for - operator */ return $sql->decrement($config['field'], $amount); }
php
public function updateCacheRecord(array $config, $operation, $amount, $foreignKey) { if (is_null($foreignKey)) { return; } $config = $this->processConfig($config); $sql = DB::table($config['table'])->where($config['key'], $foreignKey); /* * Increment for + operator */ if ($operation == '+') { return $sql->increment($config['field'], $amount); } /* * Decrement for - operator */ return $sql->decrement($config['field'], $amount); }
[ "public", "function", "updateCacheRecord", "(", "array", "$", "config", ",", "$", "operation", ",", "$", "amount", ",", "$", "foreignKey", ")", "{", "if", "(", "is_null", "(", "$", "foreignKey", ")", ")", "{", "return", ";", "}", "$", "config", "=", "$", "this", "->", "processConfig", "(", "$", "config", ")", ";", "$", "sql", "=", "DB", "::", "table", "(", "$", "config", "[", "'table'", "]", ")", "->", "where", "(", "$", "config", "[", "'key'", "]", ",", "$", "foreignKey", ")", ";", "/*\n * Increment for + operator\n */", "if", "(", "$", "operation", "==", "'+'", ")", "{", "return", "$", "sql", "->", "increment", "(", "$", "config", "[", "'field'", "]", ",", "$", "amount", ")", ";", "}", "/*\n * Decrement for - operator\n */", "return", "$", "sql", "->", "decrement", "(", "$", "config", "[", "'field'", "]", ",", "$", "amount", ")", ";", "}" ]
Updates a table's record based on the query information provided in the $config variable. @param array $config @param string $operation Whether to increase or decrease a value. Valid values: +/- @param int|float|double $amount @param string $foreignKey
[ "Updates", "a", "table", "s", "record", "based", "on", "the", "query", "information", "provided", "in", "the", "$config", "variable", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Cacheable.php#L18-L39
kirkbushell/eloquence
src/Behaviours/Cacheable.php
Cacheable.rebuildCacheRecord
public function rebuildCacheRecord(array $config, Model $model, $command, $aggregateField = null) { $config = $this->processConfig($config); $table = $this->getModelTable($model); if (is_null($aggregateField)) { $aggregateField = $config['foreignKey']; } else { $aggregateField = snake_case($aggregateField); } $sql = DB::table($table)->select($config['foreignKey'])->groupBy($config['foreignKey']); if (strtolower($command) == 'count') { $aggregate = $sql->count($aggregateField); } else if (strtolower($command) == 'sum') { $aggregate = $sql->sum($aggregateField); } else if (strtolower($command) == 'avg') { $aggregate = $sql->avg($aggregateField); } else { $aggregate = null; } return DB::table($config['table']) ->update([ $config['field'] => $aggregate ]); }
php
public function rebuildCacheRecord(array $config, Model $model, $command, $aggregateField = null) { $config = $this->processConfig($config); $table = $this->getModelTable($model); if (is_null($aggregateField)) { $aggregateField = $config['foreignKey']; } else { $aggregateField = snake_case($aggregateField); } $sql = DB::table($table)->select($config['foreignKey'])->groupBy($config['foreignKey']); if (strtolower($command) == 'count') { $aggregate = $sql->count($aggregateField); } else if (strtolower($command) == 'sum') { $aggregate = $sql->sum($aggregateField); } else if (strtolower($command) == 'avg') { $aggregate = $sql->avg($aggregateField); } else { $aggregate = null; } return DB::table($config['table']) ->update([ $config['field'] => $aggregate ]); }
[ "public", "function", "rebuildCacheRecord", "(", "array", "$", "config", ",", "Model", "$", "model", ",", "$", "command", ",", "$", "aggregateField", "=", "null", ")", "{", "$", "config", "=", "$", "this", "->", "processConfig", "(", "$", "config", ")", ";", "$", "table", "=", "$", "this", "->", "getModelTable", "(", "$", "model", ")", ";", "if", "(", "is_null", "(", "$", "aggregateField", ")", ")", "{", "$", "aggregateField", "=", "$", "config", "[", "'foreignKey'", "]", ";", "}", "else", "{", "$", "aggregateField", "=", "snake_case", "(", "$", "aggregateField", ")", ";", "}", "$", "sql", "=", "DB", "::", "table", "(", "$", "table", ")", "->", "select", "(", "$", "config", "[", "'foreignKey'", "]", ")", "->", "groupBy", "(", "$", "config", "[", "'foreignKey'", "]", ")", ";", "if", "(", "strtolower", "(", "$", "command", ")", "==", "'count'", ")", "{", "$", "aggregate", "=", "$", "sql", "->", "count", "(", "$", "aggregateField", ")", ";", "}", "else", "if", "(", "strtolower", "(", "$", "command", ")", "==", "'sum'", ")", "{", "$", "aggregate", "=", "$", "sql", "->", "sum", "(", "$", "aggregateField", ")", ";", "}", "else", "if", "(", "strtolower", "(", "$", "command", ")", "==", "'avg'", ")", "{", "$", "aggregate", "=", "$", "sql", "->", "avg", "(", "$", "aggregateField", ")", ";", "}", "else", "{", "$", "aggregate", "=", "null", ";", "}", "return", "DB", "::", "table", "(", "$", "config", "[", "'table'", "]", ")", "->", "update", "(", "[", "$", "config", "[", "'field'", "]", "=>", "$", "aggregate", "]", ")", ";", "}" ]
Rebuilds the cache for the records in question. @param array $config @param Model $model @param $command @param null $aggregateField @return mixed
[ "Rebuilds", "the", "cache", "for", "the", "records", "in", "question", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Cacheable.php#L50-L77
kirkbushell/eloquence
src/Behaviours/Cacheable.php
Cacheable.processConfig
protected function processConfig(array $config) { return [ 'model' => $config['model'], 'table' => $this->getModelTable($config['model']), 'field' => snake_case($config['field']), 'key' => snake_case($this->key($config['key'])), 'foreignKey' => snake_case($this->key($config['foreignKey'])), ]; }
php
protected function processConfig(array $config) { return [ 'model' => $config['model'], 'table' => $this->getModelTable($config['model']), 'field' => snake_case($config['field']), 'key' => snake_case($this->key($config['key'])), 'foreignKey' => snake_case($this->key($config['foreignKey'])), ]; }
[ "protected", "function", "processConfig", "(", "array", "$", "config", ")", "{", "return", "[", "'model'", "=>", "$", "config", "[", "'model'", "]", ",", "'table'", "=>", "$", "this", "->", "getModelTable", "(", "$", "config", "[", "'model'", "]", ")", ",", "'field'", "=>", "snake_case", "(", "$", "config", "[", "'field'", "]", ")", ",", "'key'", "=>", "snake_case", "(", "$", "this", "->", "key", "(", "$", "config", "[", "'key'", "]", ")", ")", ",", "'foreignKey'", "=>", "snake_case", "(", "$", "this", "->", "key", "(", "$", "config", "[", "'foreignKey'", "]", ")", ")", ",", "]", ";", "}" ]
Process configuration parameters to check key names, fix snake casing, etc.. @param array $config @return array
[ "Process", "configuration", "parameters", "to", "check", "key", "names", "fix", "snake", "casing", "etc", ".." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Cacheable.php#L101-L110
kirkbushell/eloquence
src/Behaviours/Cacheable.php
Cacheable.key
protected function key($field) { if (method_exists($this->model, 'getTrueKey')) { return $this->model->getTrueKey($field); } return $field; }
php
protected function key($field) { if (method_exists($this->model, 'getTrueKey')) { return $this->model->getTrueKey($field); } return $field; }
[ "protected", "function", "key", "(", "$", "field", ")", "{", "if", "(", "method_exists", "(", "$", "this", "->", "model", ",", "'getTrueKey'", ")", ")", "{", "return", "$", "this", "->", "model", "->", "getTrueKey", "(", "$", "field", ")", ";", "}", "return", "$", "field", ";", "}" ]
Returns the true key for a given field. @param string $field @return mixed
[ "Returns", "the", "true", "key", "for", "a", "given", "field", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Cacheable.php#L118-L125
kirkbushell/eloquence
src/Behaviours/Cacheable.php
Cacheable.getModelTable
protected function getModelTable($model) { if (!is_object($model)) { $model = new $model; } return DB::getTablePrefix().$model->getTable(); }
php
protected function getModelTable($model) { if (!is_object($model)) { $model = new $model; } return DB::getTablePrefix().$model->getTable(); }
[ "protected", "function", "getModelTable", "(", "$", "model", ")", "{", "if", "(", "!", "is_object", "(", "$", "model", ")", ")", "{", "$", "model", "=", "new", "$", "model", ";", "}", "return", "DB", "::", "getTablePrefix", "(", ")", ".", "$", "model", "->", "getTable", "(", ")", ";", "}" ]
Returns the table for a given model. Model can be an Eloquent model object, or a full namespaced class string. @param string|Model $model @return mixed
[ "Returns", "the", "table", "for", "a", "given", "model", ".", "Model", "can", "be", "an", "Eloquent", "model", "object", "or", "a", "full", "namespaced", "class", "string", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/Cacheable.php#L134-L141
kirkbushell/eloquence
src/Behaviours/SumCache/SumCache.php
SumCache.rebuild
public function rebuild() { $this->apply(function($config) { $this->rebuildCacheRecord($config, $this->model, 'SUM', $config['columnToSum']); }); }
php
public function rebuild() { $this->apply(function($config) { $this->rebuildCacheRecord($config, $this->model, 'SUM', $config['columnToSum']); }); }
[ "public", "function", "rebuild", "(", ")", "{", "$", "this", "->", "apply", "(", "function", "(", "$", "config", ")", "{", "$", "this", "->", "rebuildCacheRecord", "(", "$", "config", ",", "$", "this", "->", "model", ",", "'SUM'", ",", "$", "config", "[", "'columnToSum'", "]", ")", ";", "}", ")", ";", "}" ]
Rebuild the count caches from the database
[ "Rebuild", "the", "count", "caches", "from", "the", "database" ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/SumCache/SumCache.php#L39-L44
kirkbushell/eloquence
src/Behaviours/SumCache/SumCache.php
SumCache.update
public function update() { $this->apply(function ($config) { $foreignKey = snake_case($this->key($config['foreignKey'])); $amount = $this->model->{$config['columnToSum']}; if ($this->model->getOriginal($foreignKey) && $this->model->{$foreignKey} != $this->model->getOriginal($foreignKey)) { $this->updateCacheRecord($config, '-', $amount, $this->model->getOriginal($foreignKey)); $this->updateCacheRecord($config, '+', $amount, $this->model->{$foreignKey}); } }); }
php
public function update() { $this->apply(function ($config) { $foreignKey = snake_case($this->key($config['foreignKey'])); $amount = $this->model->{$config['columnToSum']}; if ($this->model->getOriginal($foreignKey) && $this->model->{$foreignKey} != $this->model->getOriginal($foreignKey)) { $this->updateCacheRecord($config, '-', $amount, $this->model->getOriginal($foreignKey)); $this->updateCacheRecord($config, '+', $amount, $this->model->{$foreignKey}); } }); }
[ "public", "function", "update", "(", ")", "{", "$", "this", "->", "apply", "(", "function", "(", "$", "config", ")", "{", "$", "foreignKey", "=", "snake_case", "(", "$", "this", "->", "key", "(", "$", "config", "[", "'foreignKey'", "]", ")", ")", ";", "$", "amount", "=", "$", "this", "->", "model", "->", "{", "$", "config", "[", "'columnToSum'", "]", "}", ";", "if", "(", "$", "this", "->", "model", "->", "getOriginal", "(", "$", "foreignKey", ")", "&&", "$", "this", "->", "model", "->", "{", "$", "foreignKey", "}", "!=", "$", "this", "->", "model", "->", "getOriginal", "(", "$", "foreignKey", ")", ")", "{", "$", "this", "->", "updateCacheRecord", "(", "$", "config", ",", "'-'", ",", "$", "amount", ",", "$", "this", "->", "model", "->", "getOriginal", "(", "$", "foreignKey", ")", ")", ";", "$", "this", "->", "updateCacheRecord", "(", "$", "config", ",", "'+'", ",", "$", "amount", ",", "$", "this", "->", "model", "->", "{", "$", "foreignKey", "}", ")", ";", "}", "}", ")", ";", "}" ]
Update the cache for all operations.
[ "Update", "the", "cache", "for", "all", "operations", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/SumCache/SumCache.php#L49-L60
kirkbushell/eloquence
src/Behaviours/SumCache/SumCache.php
SumCache.config
protected function config($cacheKey, $cacheOptions) { $opts = []; if (is_numeric($cacheKey)) { if (is_array($cacheOptions)) { // Most explicit configuration provided $opts = $cacheOptions; $relatedModel = array_get($opts, 'model'); } else { // Smallest number of options provided, figure out the rest $relatedModel = $cacheOptions; } } else { // Semi-verbose configuration provided $relatedModel = $cacheOptions; $opts['field'] = $cacheKey; if (is_array($cacheOptions)) { if (isset($cacheOptions[3])) { $opts['key'] = $cacheOptions[3]; } if (isset($cacheOptions[2])) { $opts['foreignKey'] = $cacheOptions[2]; } if (isset($cacheOptions[1])) { $opts['columnToSum'] = $cacheOptions[1]; } if (isset($cacheOptions[0])) { $relatedModel = $cacheOptions[0]; } } } return $this->defaults($opts, $relatedModel); }
php
protected function config($cacheKey, $cacheOptions) { $opts = []; if (is_numeric($cacheKey)) { if (is_array($cacheOptions)) { // Most explicit configuration provided $opts = $cacheOptions; $relatedModel = array_get($opts, 'model'); } else { // Smallest number of options provided, figure out the rest $relatedModel = $cacheOptions; } } else { // Semi-verbose configuration provided $relatedModel = $cacheOptions; $opts['field'] = $cacheKey; if (is_array($cacheOptions)) { if (isset($cacheOptions[3])) { $opts['key'] = $cacheOptions[3]; } if (isset($cacheOptions[2])) { $opts['foreignKey'] = $cacheOptions[2]; } if (isset($cacheOptions[1])) { $opts['columnToSum'] = $cacheOptions[1]; } if (isset($cacheOptions[0])) { $relatedModel = $cacheOptions[0]; } } } return $this->defaults($opts, $relatedModel); }
[ "protected", "function", "config", "(", "$", "cacheKey", ",", "$", "cacheOptions", ")", "{", "$", "opts", "=", "[", "]", ";", "if", "(", "is_numeric", "(", "$", "cacheKey", ")", ")", "{", "if", "(", "is_array", "(", "$", "cacheOptions", ")", ")", "{", "// Most explicit configuration provided", "$", "opts", "=", "$", "cacheOptions", ";", "$", "relatedModel", "=", "array_get", "(", "$", "opts", ",", "'model'", ")", ";", "}", "else", "{", "// Smallest number of options provided, figure out the rest", "$", "relatedModel", "=", "$", "cacheOptions", ";", "}", "}", "else", "{", "// Semi-verbose configuration provided", "$", "relatedModel", "=", "$", "cacheOptions", ";", "$", "opts", "[", "'field'", "]", "=", "$", "cacheKey", ";", "if", "(", "is_array", "(", "$", "cacheOptions", ")", ")", "{", "if", "(", "isset", "(", "$", "cacheOptions", "[", "3", "]", ")", ")", "{", "$", "opts", "[", "'key'", "]", "=", "$", "cacheOptions", "[", "3", "]", ";", "}", "if", "(", "isset", "(", "$", "cacheOptions", "[", "2", "]", ")", ")", "{", "$", "opts", "[", "'foreignKey'", "]", "=", "$", "cacheOptions", "[", "2", "]", ";", "}", "if", "(", "isset", "(", "$", "cacheOptions", "[", "1", "]", ")", ")", "{", "$", "opts", "[", "'columnToSum'", "]", "=", "$", "cacheOptions", "[", "1", "]", ";", "}", "if", "(", "isset", "(", "$", "cacheOptions", "[", "0", "]", ")", ")", "{", "$", "relatedModel", "=", "$", "cacheOptions", "[", "0", "]", ";", "}", "}", "}", "return", "$", "this", "->", "defaults", "(", "$", "opts", ",", "$", "relatedModel", ")", ";", "}" ]
Takes a registered sum cache, and setups up defaults. @param string $cacheKey @param array $cacheOptions @return array
[ "Takes", "a", "registered", "sum", "cache", "and", "setups", "up", "defaults", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/SumCache/SumCache.php#L69-L104
kirkbushell/eloquence
src/Behaviours/SumCache/SumCache.php
SumCache.defaults
protected function defaults($options, $relatedModel) { $defaults = [ 'model' => $relatedModel, 'columnToSum' => 'total', 'field' => $this->field($this->model, 'total'), 'foreignKey' => $this->field($relatedModel, 'id'), 'key' => 'id' ]; return array_merge($defaults, $options); }
php
protected function defaults($options, $relatedModel) { $defaults = [ 'model' => $relatedModel, 'columnToSum' => 'total', 'field' => $this->field($this->model, 'total'), 'foreignKey' => $this->field($relatedModel, 'id'), 'key' => 'id' ]; return array_merge($defaults, $options); }
[ "protected", "function", "defaults", "(", "$", "options", ",", "$", "relatedModel", ")", "{", "$", "defaults", "=", "[", "'model'", "=>", "$", "relatedModel", ",", "'columnToSum'", "=>", "'total'", ",", "'field'", "=>", "$", "this", "->", "field", "(", "$", "this", "->", "model", ",", "'total'", ")", ",", "'foreignKey'", "=>", "$", "this", "->", "field", "(", "$", "relatedModel", ",", "'id'", ")", ",", "'key'", "=>", "'id'", "]", ";", "return", "array_merge", "(", "$", "defaults", ",", "$", "options", ")", ";", "}" ]
Returns necessary defaults, overwritten by provided options. @param array $options @param string $relatedModel @return array
[ "Returns", "necessary", "defaults", "overwritten", "by", "provided", "options", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/SumCache/SumCache.php#L113-L124
kirkbushell/eloquence
src/Behaviours/CountCache/Observer.php
Observer.update
private function update($model, $operation) { $countCache = new CountCache($model); $countCache->apply(function ($config) use ($countCache, $model, $operation) { $countCache->updateCacheRecord($config, $operation, 1, $model->{$config['foreignKey']}); }); }
php
private function update($model, $operation) { $countCache = new CountCache($model); $countCache->apply(function ($config) use ($countCache, $model, $operation) { $countCache->updateCacheRecord($config, $operation, 1, $model->{$config['foreignKey']}); }); }
[ "private", "function", "update", "(", "$", "model", ",", "$", "operation", ")", "{", "$", "countCache", "=", "new", "CountCache", "(", "$", "model", ")", ";", "$", "countCache", "->", "apply", "(", "function", "(", "$", "config", ")", "use", "(", "$", "countCache", ",", "$", "model", ",", "$", "operation", ")", "{", "$", "countCache", "->", "updateCacheRecord", "(", "$", "config", ",", "$", "operation", ",", "1", ",", "$", "model", "->", "{", "$", "config", "[", "'foreignKey'", "]", "}", ")", ";", "}", ")", ";", "}" ]
Handle most update operations of the count cache. @param $model @param string $operation + or -
[ "Handle", "most", "update", "operations", "of", "the", "count", "cache", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CountCache/Observer.php#L57-L63
kirkbushell/eloquence
src/Behaviours/CountCache/CountCache.php
CountCache.apply
public function apply(\Closure $function) { foreach ($this->model->countCaches() as $key => $cache) { $function($this->config($key, $cache)); } }
php
public function apply(\Closure $function) { foreach ($this->model->countCaches() as $key => $cache) { $function($this->config($key, $cache)); } }
[ "public", "function", "apply", "(", "\\", "Closure", "$", "function", ")", "{", "foreach", "(", "$", "this", "->", "model", "->", "countCaches", "(", ")", "as", "$", "key", "=>", "$", "cache", ")", "{", "$", "function", "(", "$", "this", "->", "config", "(", "$", "key", ",", "$", "cache", ")", ")", ";", "}", "}" ]
Applies the provided function to the count cache setup/configuration. @param \Closure $function
[ "Applies", "the", "provided", "function", "to", "the", "count", "cache", "setup", "/", "configuration", "." ]
train
https://github.com/kirkbushell/eloquence/blob/a076e2e683b19500dc934ca7d1b1aa7e76912961/src/Behaviours/CountCache/CountCache.php#L29-L34
certificationy/certificationy
src/Loaders/YamlLoader.php
YamlLoader.all
public function all() : Questions { if (is_null($this->questions)) { $this->questions = $this->load(PHP_INT_MAX, []); } return $this->questions; }
php
public function all() : Questions { if (is_null($this->questions)) { $this->questions = $this->load(PHP_INT_MAX, []); } return $this->questions; }
[ "public", "function", "all", "(", ")", ":", "Questions", "{", "if", "(", "is_null", "(", "$", "this", "->", "questions", ")", ")", "{", "$", "this", "->", "questions", "=", "$", "this", "->", "load", "(", "PHP_INT_MAX", ",", "[", "]", ")", ";", "}", "return", "$", "this", "->", "questions", ";", "}" ]
@inheritdoc @throws \ErrorException
[ "@inheritdoc" ]
train
https://github.com/certificationy/certificationy/blob/3d8239dcafefb5ff020fbe02e0041865624030db/src/Loaders/YamlLoader.php#L79-L86
certificationy/certificationy
src/Loaders/YamlLoader.php
YamlLoader.prepareFromYaml
protected function prepareFromYaml(array $categories = []) : array { $data = array(); foreach ($this->paths as $path) { $files = Finder::create()->files()->in($path)->name('*.yml'); foreach ($files as $file) { $fileData = Yaml::parse($file->getContents()); $category = $fileData['category']; if (count($categories) > 0 && !in_array($category, $categories)) { continue; } array_walk($fileData['questions'], function (&$item) use ($category) { $item['category'] = $category; }); $data = array_merge($data, $fileData['questions']); } } return $data; }
php
protected function prepareFromYaml(array $categories = []) : array { $data = array(); foreach ($this->paths as $path) { $files = Finder::create()->files()->in($path)->name('*.yml'); foreach ($files as $file) { $fileData = Yaml::parse($file->getContents()); $category = $fileData['category']; if (count($categories) > 0 && !in_array($category, $categories)) { continue; } array_walk($fileData['questions'], function (&$item) use ($category) { $item['category'] = $category; }); $data = array_merge($data, $fileData['questions']); } } return $data; }
[ "protected", "function", "prepareFromYaml", "(", "array", "$", "categories", "=", "[", "]", ")", ":", "array", "{", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "paths", "as", "$", "path", ")", "{", "$", "files", "=", "Finder", "::", "create", "(", ")", "->", "files", "(", ")", "->", "in", "(", "$", "path", ")", "->", "name", "(", "'*.yml'", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "fileData", "=", "Yaml", "::", "parse", "(", "$", "file", "->", "getContents", "(", ")", ")", ";", "$", "category", "=", "$", "fileData", "[", "'category'", "]", ";", "if", "(", "count", "(", "$", "categories", ")", ">", "0", "&&", "!", "in_array", "(", "$", "category", ",", "$", "categories", ")", ")", "{", "continue", ";", "}", "array_walk", "(", "$", "fileData", "[", "'questions'", "]", ",", "function", "(", "&", "$", "item", ")", "use", "(", "$", "category", ")", "{", "$", "item", "[", "'category'", "]", "=", "$", "category", ";", "}", ")", ";", "$", "data", "=", "array_merge", "(", "$", "data", ",", "$", "fileData", "[", "'questions'", "]", ")", ";", "}", "}", "return", "$", "data", ";", "}" ]
Prepares data from Yaml files and returns an array of questions @param array $categories : List of categories which should be included, empty array = all @return array
[ "Prepares", "data", "from", "Yaml", "files", "and", "returns", "an", "array", "of", "questions" ]
train
https://github.com/certificationy/certificationy/blob/3d8239dcafefb5ff020fbe02e0041865624030db/src/Loaders/YamlLoader.php#L110-L134