repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/ControllerHandler.php
ControllerHandler.determineControllerAndAction
private function determineControllerAndAction(&$controller, &$actionName) { $request = $this->getRequest(); $this->invokePluginsHook( 'beforeControllerSelected', array($this, $request) ); $controllerDiKey = $request->getController(); try { $controller = $this->getServiceProvider()->getServiceInstance($controllerDiKey); } catch (Exception $e) { throw new ResourceNotFoundException(sprintf( 'No such controller found "%s".', $this->getRequest()->getController() )); } $actionName = $request->getAction(); if (!method_exists($controller, $actionName)) { throw new ResourceNotFoundException(sprintf( '%s does not have method %s', $controllerDiKey, $actionName )); } $this->invokePluginsHook( 'afterControllerSelected', array($this, $request, $controller, $actionName) ); $controller->initialize($request, $this); }
php
private function determineControllerAndAction(&$controller, &$actionName) { $request = $this->getRequest(); $this->invokePluginsHook( 'beforeControllerSelected', array($this, $request) ); $controllerDiKey = $request->getController(); try { $controller = $this->getServiceProvider()->getServiceInstance($controllerDiKey); } catch (Exception $e) { throw new ResourceNotFoundException(sprintf( 'No such controller found "%s".', $this->getRequest()->getController() )); } $actionName = $request->getAction(); if (!method_exists($controller, $actionName)) { throw new ResourceNotFoundException(sprintf( '%s does not have method %s', $controllerDiKey, $actionName )); } $this->invokePluginsHook( 'afterControllerSelected', array($this, $request, $controller, $actionName) ); $controller->initialize($request, $this); }
[ "private", "function", "determineControllerAndAction", "(", "&", "$", "controller", ",", "&", "$", "actionName", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "this", "->", "invokePluginsHook", "(", "'beforeControllerSelected'", ",", "array", "(", "$", "this", ",", "$", "request", ")", ")", ";", "$", "controllerDiKey", "=", "$", "request", "->", "getController", "(", ")", ";", "try", "{", "$", "controller", "=", "$", "this", "->", "getServiceProvider", "(", ")", "->", "getServiceInstance", "(", "$", "controllerDiKey", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "ResourceNotFoundException", "(", "sprintf", "(", "'No such controller found \"%s\".'", ",", "$", "this", "->", "getRequest", "(", ")", "->", "getController", "(", ")", ")", ")", ";", "}", "$", "actionName", "=", "$", "request", "->", "getAction", "(", ")", ";", "if", "(", "!", "method_exists", "(", "$", "controller", ",", "$", "actionName", ")", ")", "{", "throw", "new", "ResourceNotFoundException", "(", "sprintf", "(", "'%s does not have method %s'", ",", "$", "controllerDiKey", ",", "$", "actionName", ")", ")", ";", "}", "$", "this", "->", "invokePluginsHook", "(", "'afterControllerSelected'", ",", "array", "(", "$", "this", ",", "$", "request", ",", "$", "controller", ",", "$", "actionName", ")", ")", ";", "$", "controller", "->", "initialize", "(", "$", "request", ",", "$", "this", ")", ";", "}" ]
Determines the exact controller instance and action name to be invoked by the request. @param mixed $controller The controller passed by reference. @param mixed $actionName The action name passed by reference.
[ "Determines", "the", "exact", "controller", "instance", "and", "action", "name", "to", "be", "invoked", "by", "the", "request", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/ControllerHandler.php#L180-L210
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/ControllerHandler.php
ControllerHandler.invokeControllerAction
protected function invokeControllerAction(AbstractController $controller, $action) { $this->invokePluginsHook( 'beforeActionInvoked', array($this, $this->getRequest(), $controller, $action) ); $response = $controller->$action($this->routeParams); if (null === $response) { // if the action returns null, we simply render the default view $response = array(); } elseif (!is_string($response)) { // if they don't return a string, try to use whatever is returned // as variables to the view renderer $response = (array)$response; } // merge the response variables with the existing view context if (is_array($response)) { $response = array_merge($controller->getViewContext(), $response); } // whatever we have as a response needs to be encapsulated in an // AbstractResponse object if (!($response instanceof AbstractResponse)) { $response = new Response($response); } $this->invokePluginsHook( 'afterActionInvoked', array($this, $this->getRequest(), $controller, $action, $response) ); return $response; }
php
protected function invokeControllerAction(AbstractController $controller, $action) { $this->invokePluginsHook( 'beforeActionInvoked', array($this, $this->getRequest(), $controller, $action) ); $response = $controller->$action($this->routeParams); if (null === $response) { // if the action returns null, we simply render the default view $response = array(); } elseif (!is_string($response)) { // if they don't return a string, try to use whatever is returned // as variables to the view renderer $response = (array)$response; } // merge the response variables with the existing view context if (is_array($response)) { $response = array_merge($controller->getViewContext(), $response); } // whatever we have as a response needs to be encapsulated in an // AbstractResponse object if (!($response instanceof AbstractResponse)) { $response = new Response($response); } $this->invokePluginsHook( 'afterActionInvoked', array($this, $this->getRequest(), $controller, $action, $response) ); return $response; }
[ "protected", "function", "invokeControllerAction", "(", "AbstractController", "$", "controller", ",", "$", "action", ")", "{", "$", "this", "->", "invokePluginsHook", "(", "'beforeActionInvoked'", ",", "array", "(", "$", "this", ",", "$", "this", "->", "getRequest", "(", ")", ",", "$", "controller", ",", "$", "action", ")", ")", ";", "$", "response", "=", "$", "controller", "->", "$", "action", "(", "$", "this", "->", "routeParams", ")", ";", "if", "(", "null", "===", "$", "response", ")", "{", "// if the action returns null, we simply render the default view", "$", "response", "=", "array", "(", ")", ";", "}", "elseif", "(", "!", "is_string", "(", "$", "response", ")", ")", "{", "// if they don't return a string, try to use whatever is returned", "// as variables to the view renderer", "$", "response", "=", "(", "array", ")", "$", "response", ";", "}", "// merge the response variables with the existing view context", "if", "(", "is_array", "(", "$", "response", ")", ")", "{", "$", "response", "=", "array_merge", "(", "$", "controller", "->", "getViewContext", "(", ")", ",", "$", "response", ")", ";", "}", "// whatever we have as a response needs to be encapsulated in an", "// AbstractResponse object", "if", "(", "!", "(", "$", "response", "instanceof", "AbstractResponse", ")", ")", "{", "$", "response", "=", "new", "Response", "(", "$", "response", ")", ";", "}", "$", "this", "->", "invokePluginsHook", "(", "'afterActionInvoked'", ",", "array", "(", "$", "this", ",", "$", "this", "->", "getRequest", "(", ")", ",", "$", "controller", ",", "$", "action", ",", "$", "response", ")", ")", ";", "return", "$", "response", ";", "}" ]
Invokes the actual controller action and returns the response. @param AbstractController $controller The controller to use. @param string $action The action to invoke. @return AbstractResponse Returns the response from the action.
[ "Invokes", "the", "actual", "controller", "action", "and", "returns", "the", "response", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/ControllerHandler.php#L218-L249
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/ControllerHandler.php
ControllerHandler.configureViewEncoder
private function configureViewEncoder($options, $controller, $action) { // configure the view encoder if they specify a view option if (isset($options[self::KEY_VIEWS])) { $this->encoder = new TwigViewEncoder( $options[self::KEY_VIEWS], sprintf('%s/%s.twig', $controller, $action) ); } else { $this->encoder = new NullEncoder(); } }
php
private function configureViewEncoder($options, $controller, $action) { // configure the view encoder if they specify a view option if (isset($options[self::KEY_VIEWS])) { $this->encoder = new TwigViewEncoder( $options[self::KEY_VIEWS], sprintf('%s/%s.twig', $controller, $action) ); } else { $this->encoder = new NullEncoder(); } }
[ "private", "function", "configureViewEncoder", "(", "$", "options", ",", "$", "controller", ",", "$", "action", ")", "{", "// configure the view encoder if they specify a view option", "if", "(", "isset", "(", "$", "options", "[", "self", "::", "KEY_VIEWS", "]", ")", ")", "{", "$", "this", "->", "encoder", "=", "new", "TwigViewEncoder", "(", "$", "options", "[", "self", "::", "KEY_VIEWS", "]", ",", "sprintf", "(", "'%s/%s.twig'", ",", "$", "controller", ",", "$", "action", ")", ")", ";", "}", "else", "{", "$", "this", "->", "encoder", "=", "new", "NullEncoder", "(", ")", ";", "}", "}" ]
Configures the view encoder based on the current options. @param array $options The current options. @param string $controller The controller to use for the default view. @param string $action The action to use for the default view.
[ "Configures", "the", "view", "encoder", "based", "on", "the", "current", "options", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/ControllerHandler.php#L257-L268
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Config/Config.php
Config.offsetSet
public function offsetSet($key, $value) { if (null === $key) { throw new \Exception('Config values must contain a key.'); } $this->config[$key] = $value; }
php
public function offsetSet($key, $value) { if (null === $key) { throw new \Exception('Config values must contain a key.'); } $this->config[$key] = $value; }
[ "public", "function", "offsetSet", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "null", "===", "$", "key", ")", "{", "throw", "new", "\\", "Exception", "(", "'Config values must contain a key.'", ")", ";", "}", "$", "this", "->", "config", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Sets the value associated with the given key. @param string $key The key to be used. @param mixed $value The value to be set. @return void
[ "Sets", "the", "value", "associated", "with", "the", "given", "key", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Config/Config.php#L78-L84
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Config/Config.php
Config.get
public function get($key, $defaultValue = null) { return $this->offsetExists($key) ? $this->offsetGet($key) : $defaultValue; }
php
public function get($key, $defaultValue = null) { return $this->offsetExists($key) ? $this->offsetGet($key) : $defaultValue; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "defaultValue", "=", "null", ")", "{", "return", "$", "this", "->", "offsetExists", "(", "$", "key", ")", "?", "$", "this", "->", "offsetGet", "(", "$", "key", ")", ":", "$", "defaultValue", ";", "}" ]
Returns the value associated with the given key. An optional default value can be provided and will be returned if no value is associated with the key. @param string $key The key to be used. @param mixed $defaultValue The default value to return if the key currently has no value associated with it. @return Returns the value associated with the key or the default value if no value is associated with the key.
[ "Returns", "the", "value", "associated", "with", "the", "given", "key", ".", "An", "optional", "default", "value", "can", "be", "provided", "and", "will", "be", "returned", "if", "no", "value", "is", "associated", "with", "the", "key", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Config/Config.php#L105-L108
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Plugin/AbstractPlugin.php
AbstractPlugin.supportsControllerAndAction
public function supportsControllerAndAction($controller, $action) { if (null === $this->blacklist) { if (null === $this->whitelist) { // plugin has global scope return true; } // we use a whitelist so ensure the controller is in the whitelist if (!isset($this->whitelist[$controller])) { return false; } // the whitelisted controller could be an array of actions or it could // be mapped to the "all" string if (is_array($this->whitelist[$controller])) { return in_array($action, $this->whitelist[$controller]); } return (self::ALL_ACTIONS === (string)$this->whitelist[$controller]); } // if the controller isn't in the blacklist at all, we're good if (!isset($this->blacklist[$controller])) { return true; } // if the controller is not an array we return false // otherwise we check if the action is listed in the array return is_array($this->blacklist[$controller]) && !in_array($action, $this->blacklist[$controller]); }
php
public function supportsControllerAndAction($controller, $action) { if (null === $this->blacklist) { if (null === $this->whitelist) { // plugin has global scope return true; } // we use a whitelist so ensure the controller is in the whitelist if (!isset($this->whitelist[$controller])) { return false; } // the whitelisted controller could be an array of actions or it could // be mapped to the "all" string if (is_array($this->whitelist[$controller])) { return in_array($action, $this->whitelist[$controller]); } return (self::ALL_ACTIONS === (string)$this->whitelist[$controller]); } // if the controller isn't in the blacklist at all, we're good if (!isset($this->blacklist[$controller])) { return true; } // if the controller is not an array we return false // otherwise we check if the action is listed in the array return is_array($this->blacklist[$controller]) && !in_array($action, $this->blacklist[$controller]); }
[ "public", "function", "supportsControllerAndAction", "(", "$", "controller", ",", "$", "action", ")", "{", "if", "(", "null", "===", "$", "this", "->", "blacklist", ")", "{", "if", "(", "null", "===", "$", "this", "->", "whitelist", ")", "{", "// plugin has global scope", "return", "true", ";", "}", "// we use a whitelist so ensure the controller is in the whitelist", "if", "(", "!", "isset", "(", "$", "this", "->", "whitelist", "[", "$", "controller", "]", ")", ")", "{", "return", "false", ";", "}", "// the whitelisted controller could be an array of actions or it could", "// be mapped to the \"all\" string", "if", "(", "is_array", "(", "$", "this", "->", "whitelist", "[", "$", "controller", "]", ")", ")", "{", "return", "in_array", "(", "$", "action", ",", "$", "this", "->", "whitelist", "[", "$", "controller", "]", ")", ";", "}", "return", "(", "self", "::", "ALL_ACTIONS", "===", "(", "string", ")", "$", "this", "->", "whitelist", "[", "$", "controller", "]", ")", ";", "}", "// if the controller isn't in the blacklist at all, we're good", "if", "(", "!", "isset", "(", "$", "this", "->", "blacklist", "[", "$", "controller", "]", ")", ")", "{", "return", "true", ";", "}", "// if the controller is not an array we return false", "// otherwise we check if the action is listed in the array", "return", "is_array", "(", "$", "this", "->", "blacklist", "[", "$", "controller", "]", ")", "&&", "!", "in_array", "(", "$", "action", ",", "$", "this", "->", "blacklist", "[", "$", "controller", "]", ")", ";", "}" ]
Returns whether or not the given controller and action requested should invoke this plugin. @param string $controller The requested controller. @param string $action The requested action. @return boolean Returns true if the given plugin is allowed to run against this controller/action and false otherwise.
[ "Returns", "whether", "or", "not", "the", "given", "controller", "and", "action", "requested", "should", "invoke", "this", "plugin", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Plugin/AbstractPlugin.php#L112-L139
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/SnappyRouter.php
SnappyRouter.handleRoute
public function handleRoute($environment = null) { if (null === $environment) { $environment = PHP_SAPI; } switch ($environment) { case 'cli': case 'phpdbg': $components = empty($_SERVER['argv']) ? array() : $_SERVER['argv']; return $this->handleCliRoute($components).PHP_EOL; default: $queryPos = strpos($_SERVER['REQUEST_URI'], '?'); $path = (false === $queryPos) ? $_SERVER['REQUEST_URI'] : substr($_SERVER['REQUEST_URI'], 0, $queryPos); return $this->handleHttpRoute( $path, $_GET, $_POST, isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' ); } }
php
public function handleRoute($environment = null) { if (null === $environment) { $environment = PHP_SAPI; } switch ($environment) { case 'cli': case 'phpdbg': $components = empty($_SERVER['argv']) ? array() : $_SERVER['argv']; return $this->handleCliRoute($components).PHP_EOL; default: $queryPos = strpos($_SERVER['REQUEST_URI'], '?'); $path = (false === $queryPos) ? $_SERVER['REQUEST_URI'] : substr($_SERVER['REQUEST_URI'], 0, $queryPos); return $this->handleHttpRoute( $path, $_GET, $_POST, isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' ); } }
[ "public", "function", "handleRoute", "(", "$", "environment", "=", "null", ")", "{", "if", "(", "null", "===", "$", "environment", ")", "{", "$", "environment", "=", "PHP_SAPI", ";", "}", "switch", "(", "$", "environment", ")", "{", "case", "'cli'", ":", "case", "'phpdbg'", ":", "$", "components", "=", "empty", "(", "$", "_SERVER", "[", "'argv'", "]", ")", "?", "array", "(", ")", ":", "$", "_SERVER", "[", "'argv'", "]", ";", "return", "$", "this", "->", "handleCliRoute", "(", "$", "components", ")", ".", "PHP_EOL", ";", "default", ":", "$", "queryPos", "=", "strpos", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ",", "'?'", ")", ";", "$", "path", "=", "(", "false", "===", "$", "queryPos", ")", "?", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ":", "substr", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ",", "0", ",", "$", "queryPos", ")", ";", "return", "$", "this", "->", "handleHttpRoute", "(", "$", "path", ",", "$", "_GET", ",", "$", "_POST", ",", "isset", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ")", "?", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ":", "'GET'", ")", ";", "}", "}" ]
Handles the standard route. Determines the execution environment and makes the appropriate call. @param string $environment (optional) An optional environment variable, if not specified, the method will fallback to php_sapi_name(). @return string Returns the encoded response string.
[ "Handles", "the", "standard", "route", ".", "Determines", "the", "execution", "environment", "and", "makes", "the", "appropriate", "call", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/SnappyRouter.php#L73-L94
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/SnappyRouter.php
SnappyRouter.handleHttpRoute
public function handleHttpRoute($path, $query, $post, $verb) { $this->logger->debug("SnappyRouter: Handling HTTP route: $path"); return $this->invokeHandler(false, array($path, $query, $post, $verb)); }
php
public function handleHttpRoute($path, $query, $post, $verb) { $this->logger->debug("SnappyRouter: Handling HTTP route: $path"); return $this->invokeHandler(false, array($path, $query, $post, $verb)); }
[ "public", "function", "handleHttpRoute", "(", "$", "path", ",", "$", "query", ",", "$", "post", ",", "$", "verb", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "\"SnappyRouter: Handling HTTP route: $path\"", ")", ";", "return", "$", "this", "->", "invokeHandler", "(", "false", ",", "array", "(", "$", "path", ",", "$", "query", ",", "$", "post", ",", "$", "verb", ")", ")", ";", "}" ]
Handles routing an HTTP request directly. @param string $path The URL path from the client. @param array $query The query parameters as an array. @param array $post The post data as an array. @param string $verb The HTTP verb used in the request. @return string Returns an encoded string to pass back to the client.
[ "Handles", "routing", "an", "HTTP", "request", "directly", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/SnappyRouter.php#L104-L108
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/SnappyRouter.php
SnappyRouter.handleCliRoute
public function handleCliRoute($pathComponents) { $this->logger->debug("SnappyRouter: Handling CLI route: " . implode("/", $pathComponents)); return $this->invokeHandler(true, array($pathComponents)); }
php
public function handleCliRoute($pathComponents) { $this->logger->debug("SnappyRouter: Handling CLI route: " . implode("/", $pathComponents)); return $this->invokeHandler(true, array($pathComponents)); }
[ "public", "function", "handleCliRoute", "(", "$", "pathComponents", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "\"SnappyRouter: Handling CLI route: \"", ".", "implode", "(", "\"/\"", ",", "$", "pathComponents", ")", ")", ";", "return", "$", "this", "->", "invokeHandler", "(", "true", ",", "array", "(", "$", "pathComponents", ")", ")", ";", "}" ]
Handles routing a CLI request directly. @param array $pathComponents The array of path components to the CLI script. @return string Returns an encoded string to be output to the CLI.
[ "Handles", "routing", "a", "CLI", "request", "directly", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/SnappyRouter.php#L115-L119
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/SnappyRouter.php
SnappyRouter.handleInvocationException
private function handleInvocationException($exception, $activeHandler, $isCli) { $this->logger->debug(sprintf( "SnappyRouter: caught exception while invoking handler: %s (%d)", $exception->getMessage(), $exception->getCode() )); // if we have a valid handler give it a chance to handle the error if (null !== $activeHandler) { $activeHandler->invokePluginsHook( 'errorOccurred', array($activeHandler, $exception) ); return $activeHandler->getEncoder()->encode( new Response($activeHandler->handleException($exception)) ); } // if not on the command line, set an HTTP response code if (!$isCli) { $responseCode = AbstractResponse::RESPONSE_SERVER_ERROR; if ($exception instanceof RouterExceptionInterface) { $responseCode = $exception->getAssociatedStatusCode(); } \Vectorface\SnappyRouter\http_response_code($responseCode); } return $exception->getMessage(); }
php
private function handleInvocationException($exception, $activeHandler, $isCli) { $this->logger->debug(sprintf( "SnappyRouter: caught exception while invoking handler: %s (%d)", $exception->getMessage(), $exception->getCode() )); // if we have a valid handler give it a chance to handle the error if (null !== $activeHandler) { $activeHandler->invokePluginsHook( 'errorOccurred', array($activeHandler, $exception) ); return $activeHandler->getEncoder()->encode( new Response($activeHandler->handleException($exception)) ); } // if not on the command line, set an HTTP response code if (!$isCli) { $responseCode = AbstractResponse::RESPONSE_SERVER_ERROR; if ($exception instanceof RouterExceptionInterface) { $responseCode = $exception->getAssociatedStatusCode(); } \Vectorface\SnappyRouter\http_response_code($responseCode); } return $exception->getMessage(); }
[ "private", "function", "handleInvocationException", "(", "$", "exception", ",", "$", "activeHandler", ",", "$", "isCli", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "sprintf", "(", "\"SnappyRouter: caught exception while invoking handler: %s (%d)\"", ",", "$", "exception", "->", "getMessage", "(", ")", ",", "$", "exception", "->", "getCode", "(", ")", ")", ")", ";", "// if we have a valid handler give it a chance to handle the error", "if", "(", "null", "!==", "$", "activeHandler", ")", "{", "$", "activeHandler", "->", "invokePluginsHook", "(", "'errorOccurred'", ",", "array", "(", "$", "activeHandler", ",", "$", "exception", ")", ")", ";", "return", "$", "activeHandler", "->", "getEncoder", "(", ")", "->", "encode", "(", "new", "Response", "(", "$", "activeHandler", "->", "handleException", "(", "$", "exception", ")", ")", ")", ";", "}", "// if not on the command line, set an HTTP response code", "if", "(", "!", "$", "isCli", ")", "{", "$", "responseCode", "=", "AbstractResponse", "::", "RESPONSE_SERVER_ERROR", ";", "if", "(", "$", "exception", "instanceof", "RouterExceptionInterface", ")", "{", "$", "responseCode", "=", "$", "exception", "->", "getAssociatedStatusCode", "(", ")", ";", "}", "\\", "Vectorface", "\\", "SnappyRouter", "\\", "http_response_code", "(", "$", "responseCode", ")", ";", "}", "return", "$", "exception", "->", "getMessage", "(", ")", ";", "}" ]
Attempts to mop up after an exception during handler invocation. @param \Exception $exception The exception that occurred during invocation. @param HandlerInterface $activeHandler The active handler, or null. @param bool $isCli True for CLI handlers, false otherwise. @return mixed Returns a handler-dependent response type, usually a string.
[ "Attempts", "to", "mop", "up", "after", "an", "exception", "during", "handler", "invocation", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/SnappyRouter.php#L160-L188
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/SnappyRouter.php
SnappyRouter.parseConfig
private function parseConfig() { // setup the DI layer $diClass = $this->config->get(Config::KEY_DI); if (class_exists($diClass)) { $di = new $diClass(); if ($di instanceof DiInterface) { Di::setDefault($di); } } Di::getDefault()->set(self::KEY_CONFIG, $this->config); $this->setupHandlers( $this->config->get(Config::KEY_HANDLERS, array()) ); }
php
private function parseConfig() { // setup the DI layer $diClass = $this->config->get(Config::KEY_DI); if (class_exists($diClass)) { $di = new $diClass(); if ($di instanceof DiInterface) { Di::setDefault($di); } } Di::getDefault()->set(self::KEY_CONFIG, $this->config); $this->setupHandlers( $this->config->get(Config::KEY_HANDLERS, array()) ); }
[ "private", "function", "parseConfig", "(", ")", "{", "// setup the DI layer", "$", "diClass", "=", "$", "this", "->", "config", "->", "get", "(", "Config", "::", "KEY_DI", ")", ";", "if", "(", "class_exists", "(", "$", "diClass", ")", ")", "{", "$", "di", "=", "new", "$", "diClass", "(", ")", ";", "if", "(", "$", "di", "instanceof", "DiInterface", ")", "{", "Di", "::", "setDefault", "(", "$", "di", ")", ";", "}", "}", "Di", "::", "getDefault", "(", ")", "->", "set", "(", "self", "::", "KEY_CONFIG", ",", "$", "this", "->", "config", ")", ";", "$", "this", "->", "setupHandlers", "(", "$", "this", "->", "config", "->", "get", "(", "Config", "::", "KEY_HANDLERS", ",", "array", "(", ")", ")", ")", ";", "}" ]
Parses the config, sets up the default DI and registers the config in the DI.
[ "Parses", "the", "config", "sets", "up", "the", "default", "DI", "and", "registers", "the", "config", "in", "the", "DI", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/SnappyRouter.php#L223-L237
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/SnappyRouter.php
SnappyRouter.setupHandlers
private function setupHandlers($handlers) { $this->handlers = array(); foreach ($handlers as $handlerClass => $handlerDetails) { $options = array(); if (isset($handlerDetails[Config::KEY_OPTIONS])) { $options = (array)$handlerDetails[Config::KEY_OPTIONS]; } if (isset($handlerDetails[Config::KEY_CLASS])) { $handlerClass = $handlerDetails[Config::KEY_CLASS]; } if (!class_exists($handlerClass)) { throw new Exception( 'Cannot instantiate instance of '.$handlerClass ); } $this->handlers[] = new $handlerClass($options); } }
php
private function setupHandlers($handlers) { $this->handlers = array(); foreach ($handlers as $handlerClass => $handlerDetails) { $options = array(); if (isset($handlerDetails[Config::KEY_OPTIONS])) { $options = (array)$handlerDetails[Config::KEY_OPTIONS]; } if (isset($handlerDetails[Config::KEY_CLASS])) { $handlerClass = $handlerDetails[Config::KEY_CLASS]; } if (!class_exists($handlerClass)) { throw new Exception( 'Cannot instantiate instance of '.$handlerClass ); } $this->handlers[] = new $handlerClass($options); } }
[ "private", "function", "setupHandlers", "(", "$", "handlers", ")", "{", "$", "this", "->", "handlers", "=", "array", "(", ")", ";", "foreach", "(", "$", "handlers", "as", "$", "handlerClass", "=>", "$", "handlerDetails", ")", "{", "$", "options", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "handlerDetails", "[", "Config", "::", "KEY_OPTIONS", "]", ")", ")", "{", "$", "options", "=", "(", "array", ")", "$", "handlerDetails", "[", "Config", "::", "KEY_OPTIONS", "]", ";", "}", "if", "(", "isset", "(", "$", "handlerDetails", "[", "Config", "::", "KEY_CLASS", "]", ")", ")", "{", "$", "handlerClass", "=", "$", "handlerDetails", "[", "Config", "::", "KEY_CLASS", "]", ";", "}", "if", "(", "!", "class_exists", "(", "$", "handlerClass", ")", ")", "{", "throw", "new", "Exception", "(", "'Cannot instantiate instance of '", ".", "$", "handlerClass", ")", ";", "}", "$", "this", "->", "handlers", "[", "]", "=", "new", "$", "handlerClass", "(", "$", "options", ")", ";", "}", "}" ]
helper to setup the array of handlers
[ "helper", "to", "setup", "the", "array", "of", "handlers" ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/SnappyRouter.php#L240-L260
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/Di.php
Di.get
public function get($element, $useCache = true) { if ($useCache && isset($this->elements[$element])) { // return the cached version return $this->elements[$element]; } if (isset($this->elementMap[$element])) { if (is_callable($this->elementMap[$element])) { // if we have callback, invoke it and cache the result $this->elements[$element] = call_user_func( $this->elementMap[$element], $this ); } else { // otherwise simply cache the result and return it $this->elements[$element] = $this->elementMap[$element]; } return $this->elements[$element]; } throw new Exception('No element registered for key: '.$element); }
php
public function get($element, $useCache = true) { if ($useCache && isset($this->elements[$element])) { // return the cached version return $this->elements[$element]; } if (isset($this->elementMap[$element])) { if (is_callable($this->elementMap[$element])) { // if we have callback, invoke it and cache the result $this->elements[$element] = call_user_func( $this->elementMap[$element], $this ); } else { // otherwise simply cache the result and return it $this->elements[$element] = $this->elementMap[$element]; } return $this->elements[$element]; } throw new Exception('No element registered for key: '.$element); }
[ "public", "function", "get", "(", "$", "element", ",", "$", "useCache", "=", "true", ")", "{", "if", "(", "$", "useCache", "&&", "isset", "(", "$", "this", "->", "elements", "[", "$", "element", "]", ")", ")", "{", "// return the cached version", "return", "$", "this", "->", "elements", "[", "$", "element", "]", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "elementMap", "[", "$", "element", "]", ")", ")", "{", "if", "(", "is_callable", "(", "$", "this", "->", "elementMap", "[", "$", "element", "]", ")", ")", "{", "// if we have callback, invoke it and cache the result", "$", "this", "->", "elements", "[", "$", "element", "]", "=", "call_user_func", "(", "$", "this", "->", "elementMap", "[", "$", "element", "]", ",", "$", "this", ")", ";", "}", "else", "{", "// otherwise simply cache the result and return it", "$", "this", "->", "elements", "[", "$", "element", "]", "=", "$", "this", "->", "elementMap", "[", "$", "element", "]", ";", "}", "return", "$", "this", "->", "elements", "[", "$", "element", "]", ";", "}", "throw", "new", "Exception", "(", "'No element registered for key: '", ".", "$", "element", ")", ";", "}" ]
Returns the element associated with the specified key. @param string $element The key for the element. @param boolean $useCache An optional flag for whether we can use the cached version of the element (defaults to true). @return Returns the associated element. @throws \Exception Throws an exception if no element is registered for the given key.
[ "Returns", "the", "element", "associated", "with", "the", "specified", "key", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/Di.php#L38-L60
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/Di.php
Di.set
public function set($key, $element) { // clear the cached element unset($this->elements[$key]); $this->elementMap[$key] = $element; return $this; }
php
public function set($key, $element) { // clear the cached element unset($this->elements[$key]); $this->elementMap[$key] = $element; return $this; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "element", ")", "{", "// clear the cached element", "unset", "(", "$", "this", "->", "elements", "[", "$", "key", "]", ")", ";", "$", "this", "->", "elementMap", "[", "$", "key", "]", "=", "$", "element", ";", "return", "$", "this", ";", "}" ]
Assigns a specific element to the given key. This method will override any previously assigned element for the given key. @param string $key The key for the specified element. @param mixed $element The specified element. This can be an instance of the element or a callback to be invoked. @return Returns $this.
[ "Assigns", "a", "specific", "element", "to", "the", "given", "key", ".", "This", "method", "will", "override", "any", "previously", "assigned", "element", "for", "the", "given", "key", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/Di.php#L70-L76
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/Di.php
Di.getDefault
public static function getDefault() { if (isset(self::$instance)) { return self::$instance; } self::$instance = new self(); return self::$instance; }
php
public static function getDefault() { if (isset(self::$instance)) { return self::$instance; } self::$instance = new self(); return self::$instance; }
[ "public", "static", "function", "getDefault", "(", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "instance", ")", ")", "{", "return", "self", "::", "$", "instance", ";", "}", "self", "::", "$", "instance", "=", "new", "self", "(", ")", ";", "return", "self", "::", "$", "instance", ";", "}" ]
Returns the current default DI instance. @return Di The current default DI instance.
[ "Returns", "the", "current", "default", "DI", "instance", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/Di.php#L101-L108
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/JsonRpcHandler.php
JsonRpcHandler.getServiceFromPath
private function getServiceFromPath($path) { /* Ensure the path is in a standard form, removing empty elements. */ $path = implode('/', array_filter(array_map('trim', explode('/', $path)), 'strlen')); /* If using the basePath option, strip the basePath. Otherwise, the path becomes the basename of the URI. */ if (isset($this->options[self::KEY_BASE_PATH])) { $basePathPosition = strpos($path, $this->options[self::KEY_BASE_PATH]); if (false !== $basePathPosition) { $path = substr($path, $basePathPosition + strlen($this->options[self::KEY_BASE_PATH])); } return trim(dirname($path), "/") . '/' . basename($path, '.php'); /* For example, x/y/z/FooService */ } else { return basename($path, '.php'); /* For example: FooService, from /x/y/z/FooService.php */ } }
php
private function getServiceFromPath($path) { /* Ensure the path is in a standard form, removing empty elements. */ $path = implode('/', array_filter(array_map('trim', explode('/', $path)), 'strlen')); /* If using the basePath option, strip the basePath. Otherwise, the path becomes the basename of the URI. */ if (isset($this->options[self::KEY_BASE_PATH])) { $basePathPosition = strpos($path, $this->options[self::KEY_BASE_PATH]); if (false !== $basePathPosition) { $path = substr($path, $basePathPosition + strlen($this->options[self::KEY_BASE_PATH])); } return trim(dirname($path), "/") . '/' . basename($path, '.php'); /* For example, x/y/z/FooService */ } else { return basename($path, '.php'); /* For example: FooService, from /x/y/z/FooService.php */ } }
[ "private", "function", "getServiceFromPath", "(", "$", "path", ")", "{", "/* Ensure the path is in a standard form, removing empty elements. */", "$", "path", "=", "implode", "(", "'/'", ",", "array_filter", "(", "array_map", "(", "'trim'", ",", "explode", "(", "'/'", ",", "$", "path", ")", ")", ",", "'strlen'", ")", ")", ";", "/* If using the basePath option, strip the basePath. Otherwise, the path becomes the basename of the URI. */", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "self", "::", "KEY_BASE_PATH", "]", ")", ")", "{", "$", "basePathPosition", "=", "strpos", "(", "$", "path", ",", "$", "this", "->", "options", "[", "self", "::", "KEY_BASE_PATH", "]", ")", ";", "if", "(", "false", "!==", "$", "basePathPosition", ")", "{", "$", "path", "=", "substr", "(", "$", "path", ",", "$", "basePathPosition", "+", "strlen", "(", "$", "this", "->", "options", "[", "self", "::", "KEY_BASE_PATH", "]", ")", ")", ";", "}", "return", "trim", "(", "dirname", "(", "$", "path", ")", ",", "\"/\"", ")", ".", "'/'", ".", "basename", "(", "$", "path", ",", "'.php'", ")", ";", "/* For example, x/y/z/FooService */", "}", "else", "{", "return", "basename", "(", "$", "path", ",", "'.php'", ")", ";", "/* For example: FooService, from /x/y/z/FooService.php */", "}", "}" ]
Determine the service to load via the ServiceProvider based on path @param string $path The raw path (URI) used to determine the service. @return string The name of the service that we should attempt to load.
[ "Determine", "the", "service", "to", "load", "via", "the", "ServiceProvider", "based", "on", "path" ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/JsonRpcHandler.php#L100-L116
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/JsonRpcHandler.php
JsonRpcHandler.processPayload
private function processPayload($service, $verb, $post) { $this->batch = is_array($post); if (false === $this->batch) { $post = array($post); } $this->requests = array_map(function ($payload) use ($service, $verb) { return new JsonRpcRequest($service, $payload, $verb); }, $post); }
php
private function processPayload($service, $verb, $post) { $this->batch = is_array($post); if (false === $this->batch) { $post = array($post); } $this->requests = array_map(function ($payload) use ($service, $verb) { return new JsonRpcRequest($service, $payload, $verb); }, $post); }
[ "private", "function", "processPayload", "(", "$", "service", ",", "$", "verb", ",", "$", "post", ")", "{", "$", "this", "->", "batch", "=", "is_array", "(", "$", "post", ")", ";", "if", "(", "false", "===", "$", "this", "->", "batch", ")", "{", "$", "post", "=", "array", "(", "$", "post", ")", ";", "}", "$", "this", "->", "requests", "=", "array_map", "(", "function", "(", "$", "payload", ")", "use", "(", "$", "service", ",", "$", "verb", ")", "{", "return", "new", "JsonRpcRequest", "(", "$", "service", ",", "$", "payload", ",", "$", "verb", ")", ";", "}", ",", "$", "post", ")", ";", "}" ]
Processes the payload POST data and sets up the array of requests. @param string $service The service being requested. @param string $verb The HTTP verb being used. @param array|object $post The raw POST data.
[ "Processes", "the", "payload", "POST", "data", "and", "sets", "up", "the", "array", "of", "requests", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/JsonRpcHandler.php#L124-L133
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/JsonRpcHandler.php
JsonRpcHandler.invokeMethod
private function invokeMethod($service, JsonRpcRequest $request) { if (false === $request->isValid()) { /* Note: Method isn't known, so invocation hooks aren't called. */ return new JsonRpcResponse( null, new Exception( 'The JSON sent is not a valid Request object', self::ERR_INVALID_REQUEST ) ); } $action = $request->getAction(); $this->invokePluginsHook( 'afterServiceSelected', array($this, $request, $service, $action) ); $this->invokePluginsHook( 'beforeMethodInvoked', array($this, $request, $service, $action) ); try { $response = new JsonRpcResponse( call_user_func_array(array($service, $action), $request->getParameters()), null, $request ); } catch (Exception $e) { $error = new Exception($e->getMessage(), self::ERR_INTERNAL_ERROR); $response = new JsonRpcResponse(null, $error, $request); } $this->invokePluginsHook( 'afterMethodInvoked', array($this, $request, $service, $action, $response) ); return $response; }
php
private function invokeMethod($service, JsonRpcRequest $request) { if (false === $request->isValid()) { /* Note: Method isn't known, so invocation hooks aren't called. */ return new JsonRpcResponse( null, new Exception( 'The JSON sent is not a valid Request object', self::ERR_INVALID_REQUEST ) ); } $action = $request->getAction(); $this->invokePluginsHook( 'afterServiceSelected', array($this, $request, $service, $action) ); $this->invokePluginsHook( 'beforeMethodInvoked', array($this, $request, $service, $action) ); try { $response = new JsonRpcResponse( call_user_func_array(array($service, $action), $request->getParameters()), null, $request ); } catch (Exception $e) { $error = new Exception($e->getMessage(), self::ERR_INTERNAL_ERROR); $response = new JsonRpcResponse(null, $error, $request); } $this->invokePluginsHook( 'afterMethodInvoked', array($this, $request, $service, $action, $response) ); return $response; }
[ "private", "function", "invokeMethod", "(", "$", "service", ",", "JsonRpcRequest", "$", "request", ")", "{", "if", "(", "false", "===", "$", "request", "->", "isValid", "(", ")", ")", "{", "/* Note: Method isn't known, so invocation hooks aren't called. */", "return", "new", "JsonRpcResponse", "(", "null", ",", "new", "Exception", "(", "'The JSON sent is not a valid Request object'", ",", "self", "::", "ERR_INVALID_REQUEST", ")", ")", ";", "}", "$", "action", "=", "$", "request", "->", "getAction", "(", ")", ";", "$", "this", "->", "invokePluginsHook", "(", "'afterServiceSelected'", ",", "array", "(", "$", "this", ",", "$", "request", ",", "$", "service", ",", "$", "action", ")", ")", ";", "$", "this", "->", "invokePluginsHook", "(", "'beforeMethodInvoked'", ",", "array", "(", "$", "this", ",", "$", "request", ",", "$", "service", ",", "$", "action", ")", ")", ";", "try", "{", "$", "response", "=", "new", "JsonRpcResponse", "(", "call_user_func_array", "(", "array", "(", "$", "service", ",", "$", "action", ")", ",", "$", "request", "->", "getParameters", "(", ")", ")", ",", "null", ",", "$", "request", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "error", "=", "new", "Exception", "(", "$", "e", "->", "getMessage", "(", ")", ",", "self", "::", "ERR_INTERNAL_ERROR", ")", ";", "$", "response", "=", "new", "JsonRpcResponse", "(", "null", ",", "$", "error", ",", "$", "request", ")", ";", "}", "$", "this", "->", "invokePluginsHook", "(", "'afterMethodInvoked'", ",", "array", "(", "$", "this", ",", "$", "request", ",", "$", "service", ",", "$", "action", ",", "$", "response", ")", ")", ";", "return", "$", "response", ";", "}" ]
Invokes a method on a service class, based on the raw JSON-RPC request. @param mixed $service The service being invoked. @param Vectorface\SnappyRouter\Request\JsonRpcRequest $request The request to invoke. @return JsonRpcResponse A response based on the result of the procedure call.
[ "Invokes", "a", "method", "on", "a", "service", "class", "based", "on", "the", "raw", "JSON", "-", "RPC", "request", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/JsonRpcHandler.php#L207-L248
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Response/Response.php
Response.setStatusCode
public function setStatusCode($statusCode) { $statusCode = intval($statusCode); $this->statusCode = ($statusCode > 0) ? $statusCode : self::RESPONSE_OK; return $this; }
php
public function setStatusCode($statusCode) { $statusCode = intval($statusCode); $this->statusCode = ($statusCode > 0) ? $statusCode : self::RESPONSE_OK; return $this; }
[ "public", "function", "setStatusCode", "(", "$", "statusCode", ")", "{", "$", "statusCode", "=", "intval", "(", "$", "statusCode", ")", ";", "$", "this", "->", "statusCode", "=", "(", "$", "statusCode", ">", "0", ")", "?", "$", "statusCode", ":", "self", "::", "RESPONSE_OK", ";", "return", "$", "this", ";", "}" ]
Sets the HTTP status code associated with this response. @param int $statusCode The HTTP status code associated with this response. @return ResponseInterface Returns $this.
[ "Sets", "the", "HTTP", "status", "code", "associated", "with", "this", "response", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Response/Response.php#L50-L55
train
bigcommerce/net-http
src/Net/Http/Request.php
Net_Http_Request.setBody
public function setBody($content, $mime) { $this->parameters = $content; $this->setMime($mime); return $this; }
php
public function setBody($content, $mime) { $this->parameters = $content; $this->setMime($mime); return $this; }
[ "public", "function", "setBody", "(", "$", "content", ",", "$", "mime", ")", "{", "$", "this", "->", "parameters", "=", "$", "content", ";", "$", "this", "->", "setMime", "(", "$", "mime", ")", ";", "return", "$", "this", ";", "}" ]
Set the entire body of a POST or PUT request. The provided MIME type must reflect the content format of the string.
[ "Set", "the", "entire", "body", "of", "a", "POST", "or", "PUT", "request", ".", "The", "provided", "MIME", "type", "must", "reflect", "the", "content", "format", "of", "the", "string", "." ]
aba27bdaa13e478bcf31b2ec1686577994efbd96
https://github.com/bigcommerce/net-http/blob/aba27bdaa13e478bcf31b2ec1686577994efbd96/src/Net/Http/Request.php#L137-L142
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/AbstractHandler.php
AbstractHandler.setPlugins
public function setPlugins($plugins) { $this->plugins = array(); foreach ($plugins as $key => $plugin) { $pluginClass = $plugin; if (is_array($plugin)) { if (!isset($plugin[Config::KEY_CLASS])) { throw new PluginException('Invalid or missing class for plugin '.$key); } elseif (!class_exists($plugin[Config::KEY_CLASS])) { throw new PluginException('Invalid or missing class for plugin '.$key); } $pluginClass = $plugin[Config::KEY_CLASS]; } $options = array(); if (isset($plugin[Config::KEY_OPTIONS])) { $options = (array)$plugin[Config::KEY_OPTIONS]; } $this->plugins[] = new $pluginClass($options); } $this->plugins = $this->sortPlugins($this->plugins); return $this; }
php
public function setPlugins($plugins) { $this->plugins = array(); foreach ($plugins as $key => $plugin) { $pluginClass = $plugin; if (is_array($plugin)) { if (!isset($plugin[Config::KEY_CLASS])) { throw new PluginException('Invalid or missing class for plugin '.$key); } elseif (!class_exists($plugin[Config::KEY_CLASS])) { throw new PluginException('Invalid or missing class for plugin '.$key); } $pluginClass = $plugin[Config::KEY_CLASS]; } $options = array(); if (isset($plugin[Config::KEY_OPTIONS])) { $options = (array)$plugin[Config::KEY_OPTIONS]; } $this->plugins[] = new $pluginClass($options); } $this->plugins = $this->sortPlugins($this->plugins); return $this; }
[ "public", "function", "setPlugins", "(", "$", "plugins", ")", "{", "$", "this", "->", "plugins", "=", "array", "(", ")", ";", "foreach", "(", "$", "plugins", "as", "$", "key", "=>", "$", "plugin", ")", "{", "$", "pluginClass", "=", "$", "plugin", ";", "if", "(", "is_array", "(", "$", "plugin", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "plugin", "[", "Config", "::", "KEY_CLASS", "]", ")", ")", "{", "throw", "new", "PluginException", "(", "'Invalid or missing class for plugin '", ".", "$", "key", ")", ";", "}", "elseif", "(", "!", "class_exists", "(", "$", "plugin", "[", "Config", "::", "KEY_CLASS", "]", ")", ")", "{", "throw", "new", "PluginException", "(", "'Invalid or missing class for plugin '", ".", "$", "key", ")", ";", "}", "$", "pluginClass", "=", "$", "plugin", "[", "Config", "::", "KEY_CLASS", "]", ";", "}", "$", "options", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "plugin", "[", "Config", "::", "KEY_OPTIONS", "]", ")", ")", "{", "$", "options", "=", "(", "array", ")", "$", "plugin", "[", "Config", "::", "KEY_OPTIONS", "]", ";", "}", "$", "this", "->", "plugins", "[", "]", "=", "new", "$", "pluginClass", "(", "$", "options", ")", ";", "}", "$", "this", "->", "plugins", "=", "$", "this", "->", "sortPlugins", "(", "$", "this", "->", "plugins", ")", ";", "return", "$", "this", ";", "}" ]
Sets the current list of plugins. @param array $plugins The array of plugins. @return AbstractHandler Returns $this.
[ "Sets", "the", "current", "list", "of", "plugins", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/AbstractHandler.php#L106-L127
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/AbstractHandler.php
AbstractHandler.sortPlugins
private function sortPlugins($plugins) { usort($plugins, function ($a, $b) { return $a->getExecutionOrder() - $b->getExecutionOrder(); }); return $plugins; }
php
private function sortPlugins($plugins) { usort($plugins, function ($a, $b) { return $a->getExecutionOrder() - $b->getExecutionOrder(); }); return $plugins; }
[ "private", "function", "sortPlugins", "(", "$", "plugins", ")", "{", "usort", "(", "$", "plugins", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "$", "a", "->", "getExecutionOrder", "(", ")", "-", "$", "b", "->", "getExecutionOrder", "(", ")", ";", "}", ")", ";", "return", "$", "plugins", ";", "}" ]
sorts the list of plugins according to their execution order
[ "sorts", "the", "list", "of", "plugins", "according", "to", "their", "execution", "order" ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/AbstractHandler.php#L130-L136
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Handler/AbstractHandler.php
AbstractHandler.invokePluginsHook
public function invokePluginsHook($hook, $args) { foreach ($this->getPlugins() as $plugin) { if (method_exists($plugin, $hook)) { call_user_func_array(array($plugin, $hook), $args); } } }
php
public function invokePluginsHook($hook, $args) { foreach ($this->getPlugins() as $plugin) { if (method_exists($plugin, $hook)) { call_user_func_array(array($plugin, $hook), $args); } } }
[ "public", "function", "invokePluginsHook", "(", "$", "hook", ",", "$", "args", ")", "{", "foreach", "(", "$", "this", "->", "getPlugins", "(", ")", "as", "$", "plugin", ")", "{", "if", "(", "method_exists", "(", "$", "plugin", ",", "$", "hook", ")", ")", "{", "call_user_func_array", "(", "array", "(", "$", "plugin", ",", "$", "hook", ")", ",", "$", "args", ")", ";", "}", "}", "}" ]
Invokes the plugin hook against all the listed plugins. @param string $hook The hook to invoke. @param array $args The arguments to pass to the call.
[ "Invokes", "the", "plugin", "hook", "against", "all", "the", "listed", "plugins", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/AbstractHandler.php#L143-L150
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/ServiceProvider.php
ServiceProvider.setService
public function setService($key, $service) { $this->set($key, $service); unset($this->instanceCache[$key]); return $this; }
php
public function setService($key, $service) { $this->set($key, $service); unset($this->instanceCache[$key]); return $this; }
[ "public", "function", "setService", "(", "$", "key", ",", "$", "service", ")", "{", "$", "this", "->", "set", "(", "$", "key", ",", "$", "service", ")", ";", "unset", "(", "$", "this", "->", "instanceCache", "[", "$", "key", "]", ")", ";", "return", "$", "this", ";", "}" ]
Specifies the mapping between the given key and service. @param string $key The key to assign. @param mixed $service The service to be assigned to the key. @return Returns $this.
[ "Specifies", "the", "mapping", "between", "the", "given", "key", "and", "service", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/ServiceProvider.php#L63-L68
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/ServiceProvider.php
ServiceProvider.getServiceInstance
public function getServiceInstance($key, $useCache = true) { // retrieve the service from the instance cache if it exists if ($useCache && isset($this->instanceCache[$key])) { return $this->instanceCache[$key]; } // retrieve the given controller from the key using the proper // provisioning mode switch ($this->provisioningMode) { case self::PROVISIONING_MODE_NAMESPACES: $this->instanceCache[$key] = $this->getServiceFromNamespaces($key); break; case self::PROVISIONING_MODE_FOLDERS: $this->instanceCache[$key] = $this->getServiceFromFolder($key); break; default: $this->instanceCache[$key] = $this->getServiceFromServiceList($key); } return $this->instanceCache[$key]; }
php
public function getServiceInstance($key, $useCache = true) { // retrieve the service from the instance cache if it exists if ($useCache && isset($this->instanceCache[$key])) { return $this->instanceCache[$key]; } // retrieve the given controller from the key using the proper // provisioning mode switch ($this->provisioningMode) { case self::PROVISIONING_MODE_NAMESPACES: $this->instanceCache[$key] = $this->getServiceFromNamespaces($key); break; case self::PROVISIONING_MODE_FOLDERS: $this->instanceCache[$key] = $this->getServiceFromFolder($key); break; default: $this->instanceCache[$key] = $this->getServiceFromServiceList($key); } return $this->instanceCache[$key]; }
[ "public", "function", "getServiceInstance", "(", "$", "key", ",", "$", "useCache", "=", "true", ")", "{", "// retrieve the service from the instance cache if it exists", "if", "(", "$", "useCache", "&&", "isset", "(", "$", "this", "->", "instanceCache", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "instanceCache", "[", "$", "key", "]", ";", "}", "// retrieve the given controller from the key using the proper", "// provisioning mode", "switch", "(", "$", "this", "->", "provisioningMode", ")", "{", "case", "self", "::", "PROVISIONING_MODE_NAMESPACES", ":", "$", "this", "->", "instanceCache", "[", "$", "key", "]", "=", "$", "this", "->", "getServiceFromNamespaces", "(", "$", "key", ")", ";", "break", ";", "case", "self", "::", "PROVISIONING_MODE_FOLDERS", ":", "$", "this", "->", "instanceCache", "[", "$", "key", "]", "=", "$", "this", "->", "getServiceFromFolder", "(", "$", "key", ")", ";", "break", ";", "default", ":", "$", "this", "->", "instanceCache", "[", "$", "key", "]", "=", "$", "this", "->", "getServiceFromServiceList", "(", "$", "key", ")", ";", "}", "return", "$", "this", "->", "instanceCache", "[", "$", "key", "]", ";", "}" ]
Returns an instance of the specified service. @param string $key The key to lookup. @param boolean $useCache An optional flag indicating whether we should use the cache. True by default. @return AbstractController Returns an instance of the specified service. @throws ServiceNotFoundForKeyException Throws this exception if the key isn't associated with any registered service.
[ "Returns", "an", "instance", "of", "the", "specified", "service", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/ServiceProvider.php#L79-L99
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/ServiceProvider.php
ServiceProvider.setNamespaces
public function setNamespaces($namespaces) { $this->set(self::KEY_NAMESPACES, $namespaces); $this->provisioningMode = self::PROVISIONING_MODE_NAMESPACES; return $this; }
php
public function setNamespaces($namespaces) { $this->set(self::KEY_NAMESPACES, $namespaces); $this->provisioningMode = self::PROVISIONING_MODE_NAMESPACES; return $this; }
[ "public", "function", "setNamespaces", "(", "$", "namespaces", ")", "{", "$", "this", "->", "set", "(", "self", "::", "KEY_NAMESPACES", ",", "$", "namespaces", ")", ";", "$", "this", "->", "provisioningMode", "=", "self", "::", "PROVISIONING_MODE_NAMESPACES", ";", "return", "$", "this", ";", "}" ]
Sets the list of namespaces and switches to namespace provisioning mode. @param array $namespaces An array of namespaces. @return ServiceProvider Returns $this.
[ "Sets", "the", "list", "of", "namespaces", "and", "switches", "to", "namespace", "provisioning", "mode", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/ServiceProvider.php#L106-L111
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/ServiceProvider.php
ServiceProvider.setFolders
public function setFolders($folders) { $this->set(self::KEY_FOLDERS, $folders); $this->provisioningMode = self::PROVISIONING_MODE_FOLDERS; return $this; }
php
public function setFolders($folders) { $this->set(self::KEY_FOLDERS, $folders); $this->provisioningMode = self::PROVISIONING_MODE_FOLDERS; return $this; }
[ "public", "function", "setFolders", "(", "$", "folders", ")", "{", "$", "this", "->", "set", "(", "self", "::", "KEY_FOLDERS", ",", "$", "folders", ")", ";", "$", "this", "->", "provisioningMode", "=", "self", "::", "PROVISIONING_MODE_FOLDERS", ";", "return", "$", "this", ";", "}" ]
Sets the list of folders and switches to folder provisioning mode. @param array $folders An array of folders. @return ServiceProvider Returns $this.
[ "Sets", "the", "list", "of", "folders", "and", "switches", "to", "folder", "provisioning", "mode", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/ServiceProvider.php#L118-L123
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/ServiceProvider.php
ServiceProvider.getServiceFromServiceList
private function getServiceFromServiceList($controllerClass) { // default provisioning mode uses a hardcoded list of services $serviceClass = $this->get($controllerClass); if (is_string($serviceClass) && !class_exists($serviceClass)) { require_once $serviceClass; $serviceClass = $controllerClass; } elseif (is_array($serviceClass)) { if (isset($serviceClass[Config::KEY_FILE])) { require_once $serviceClass[Config::KEY_FILE]; } if (isset($serviceClass[Config::KEY_CLASS])) { $serviceClass = $serviceClass[Config::KEY_CLASS]; } } return new $serviceClass(); }
php
private function getServiceFromServiceList($controllerClass) { // default provisioning mode uses a hardcoded list of services $serviceClass = $this->get($controllerClass); if (is_string($serviceClass) && !class_exists($serviceClass)) { require_once $serviceClass; $serviceClass = $controllerClass; } elseif (is_array($serviceClass)) { if (isset($serviceClass[Config::KEY_FILE])) { require_once $serviceClass[Config::KEY_FILE]; } if (isset($serviceClass[Config::KEY_CLASS])) { $serviceClass = $serviceClass[Config::KEY_CLASS]; } } return new $serviceClass(); }
[ "private", "function", "getServiceFromServiceList", "(", "$", "controllerClass", ")", "{", "// default provisioning mode uses a hardcoded list of services", "$", "serviceClass", "=", "$", "this", "->", "get", "(", "$", "controllerClass", ")", ";", "if", "(", "is_string", "(", "$", "serviceClass", ")", "&&", "!", "class_exists", "(", "$", "serviceClass", ")", ")", "{", "require_once", "$", "serviceClass", ";", "$", "serviceClass", "=", "$", "controllerClass", ";", "}", "elseif", "(", "is_array", "(", "$", "serviceClass", ")", ")", "{", "if", "(", "isset", "(", "$", "serviceClass", "[", "Config", "::", "KEY_FILE", "]", ")", ")", "{", "require_once", "$", "serviceClass", "[", "Config", "::", "KEY_FILE", "]", ";", "}", "if", "(", "isset", "(", "$", "serviceClass", "[", "Config", "::", "KEY_CLASS", "]", ")", ")", "{", "$", "serviceClass", "=", "$", "serviceClass", "[", "Config", "::", "KEY_CLASS", "]", ";", "}", "}", "return", "new", "$", "serviceClass", "(", ")", ";", "}" ]
Returns an instance of the specified controller using the existing the explicitly specified services list. @param string $controllerClass The controller class we are resolving. @return AbstractController Returns an instance of the controller.
[ "Returns", "an", "instance", "of", "the", "specified", "controller", "using", "the", "existing", "the", "explicitly", "specified", "services", "list", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/ServiceProvider.php#L164-L180
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Di/ServiceProvider.php
ServiceProvider.findFileInFolderRecursively
private function findFileInFolderRecursively($file, $folder) { $dir = dir($folder); while (false !== ($item = $dir->read())) { if ('.' === $item || '..' === $item) { continue; } $fullPath = $folder.DIRECTORY_SEPARATOR.$item; if (0 === strcasecmp($item, $file)) { return $fullPath; } elseif (is_dir($fullPath)) { $fullPath = $this->findFileInFolderRecursively($file, $fullPath); if (false !== $fullPath) { return $fullPath; } } } return false; }
php
private function findFileInFolderRecursively($file, $folder) { $dir = dir($folder); while (false !== ($item = $dir->read())) { if ('.' === $item || '..' === $item) { continue; } $fullPath = $folder.DIRECTORY_SEPARATOR.$item; if (0 === strcasecmp($item, $file)) { return $fullPath; } elseif (is_dir($fullPath)) { $fullPath = $this->findFileInFolderRecursively($file, $fullPath); if (false !== $fullPath) { return $fullPath; } } } return false; }
[ "private", "function", "findFileInFolderRecursively", "(", "$", "file", ",", "$", "folder", ")", "{", "$", "dir", "=", "dir", "(", "$", "folder", ")", ";", "while", "(", "false", "!==", "(", "$", "item", "=", "$", "dir", "->", "read", "(", ")", ")", ")", "{", "if", "(", "'.'", "===", "$", "item", "||", "'..'", "===", "$", "item", ")", "{", "continue", ";", "}", "$", "fullPath", "=", "$", "folder", ".", "DIRECTORY_SEPARATOR", ".", "$", "item", ";", "if", "(", "0", "===", "strcasecmp", "(", "$", "item", ",", "$", "file", ")", ")", "{", "return", "$", "fullPath", ";", "}", "elseif", "(", "is_dir", "(", "$", "fullPath", ")", ")", "{", "$", "fullPath", "=", "$", "this", "->", "findFileInFolderRecursively", "(", "$", "file", ",", "$", "fullPath", ")", ";", "if", "(", "false", "!==", "$", "fullPath", ")", "{", "return", "$", "fullPath", ";", "}", "}", "}", "return", "false", ";", "}" ]
Scan for the specific file recursively. @param string $file The file to search for. @param string $folder The folder to search inside. @return mixed Returns either the full path string to the file or false if the file was not found.
[ "Scan", "for", "the", "specific", "file", "recursively", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Di/ServiceProvider.php#L189-L207
train
Vectorface/SnappyRouter
src/Vectorface/SnappyRouter/Request/JsonRpcRequest.php
JsonRpcRequest.getParameters
public function getParameters() { if (isset($this->payload->params)) { /* JSON-RPC 2 can pass named params. For PHP's sake, turn that into a single object param. */ return is_array($this->payload->params) ? $this->payload->params : array($this->payload->params); } return array(); }
php
public function getParameters() { if (isset($this->payload->params)) { /* JSON-RPC 2 can pass named params. For PHP's sake, turn that into a single object param. */ return is_array($this->payload->params) ? $this->payload->params : array($this->payload->params); } return array(); }
[ "public", "function", "getParameters", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "payload", "->", "params", ")", ")", "{", "/* JSON-RPC 2 can pass named params. For PHP's sake, turn that into a single object param. */", "return", "is_array", "(", "$", "this", "->", "payload", "->", "params", ")", "?", "$", "this", "->", "payload", "->", "params", ":", "array", "(", "$", "this", "->", "payload", "->", "params", ")", ";", "}", "return", "array", "(", ")", ";", "}" ]
Get request parameters. Note: Since PHP does not support named params, named params are turned into a single request object parameter. @return array An array of request paramters
[ "Get", "request", "parameters", "." ]
795c8377e808933f228835c9aa4d2071136931fc
https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/JsonRpcRequest.php#L92-L99
train
glpi-project/tools
src/Tools/RoboFile.php
RoboFile.minifyCSS
public function minifyCSS() { $css_dir = './css'; if (is_dir($css_dir)) { foreach (glob("$css_dir/*.css") as $css_file) { if (!$this->endsWith($css_file, 'min.css')) { $this->taskMinify($css_file) ->to(str_replace('.css', '.min.css', $css_file)) ->type('css') ->run(); } } } return $this; }
php
public function minifyCSS() { $css_dir = './css'; if (is_dir($css_dir)) { foreach (glob("$css_dir/*.css") as $css_file) { if (!$this->endsWith($css_file, 'min.css')) { $this->taskMinify($css_file) ->to(str_replace('.css', '.min.css', $css_file)) ->type('css') ->run(); } } } return $this; }
[ "public", "function", "minifyCSS", "(", ")", "{", "$", "css_dir", "=", "'./css'", ";", "if", "(", "is_dir", "(", "$", "css_dir", ")", ")", "{", "foreach", "(", "glob", "(", "\"$css_dir/*.css\"", ")", "as", "$", "css_file", ")", "{", "if", "(", "!", "$", "this", "->", "endsWith", "(", "$", "css_file", ",", "'min.css'", ")", ")", "{", "$", "this", "->", "taskMinify", "(", "$", "css_file", ")", "->", "to", "(", "str_replace", "(", "'.css'", ",", "'.min.css'", ",", "$", "css_file", ")", ")", "->", "type", "(", "'css'", ")", "->", "run", "(", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Minify CSS stylesheets @return void
[ "Minify", "CSS", "stylesheets" ]
7f46bd479801f9530f0e70400739c75b535245a9
https://github.com/glpi-project/tools/blob/7f46bd479801f9530f0e70400739c75b535245a9/src/Tools/RoboFile.php#L30-L43
train
glpi-project/tools
src/Tools/RoboFile.php
RoboFile.minifyJS
public function minifyJS() { $js_dir = './js'; if (is_dir($js_dir)) { foreach (glob("$js_dir/*.js") as $js_file) { if (!$this->endsWith($js_file, 'min.js')) { $this->taskMinify($js_file) ->to(str_replace('.js', '.min.js', $js_file)) ->type('js') ->run(); } } } return $this; }
php
public function minifyJS() { $js_dir = './js'; if (is_dir($js_dir)) { foreach (glob("$js_dir/*.js") as $js_file) { if (!$this->endsWith($js_file, 'min.js')) { $this->taskMinify($js_file) ->to(str_replace('.js', '.min.js', $js_file)) ->type('js') ->run(); } } } return $this; }
[ "public", "function", "minifyJS", "(", ")", "{", "$", "js_dir", "=", "'./js'", ";", "if", "(", "is_dir", "(", "$", "js_dir", ")", ")", "{", "foreach", "(", "glob", "(", "\"$js_dir/*.js\"", ")", "as", "$", "js_file", ")", "{", "if", "(", "!", "$", "this", "->", "endsWith", "(", "$", "js_file", ",", "'min.js'", ")", ")", "{", "$", "this", "->", "taskMinify", "(", "$", "js_file", ")", "->", "to", "(", "str_replace", "(", "'.js'", ",", "'.min.js'", ",", "$", "js_file", ")", ")", "->", "type", "(", "'js'", ")", "->", "run", "(", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Minify JavaScript files stylesheets @return void
[ "Minify", "JavaScript", "files", "stylesheets" ]
7f46bd479801f9530f0e70400739c75b535245a9
https://github.com/glpi-project/tools/blob/7f46bd479801f9530f0e70400739c75b535245a9/src/Tools/RoboFile.php#L50-L63
train
glpi-project/tools
src/Tools/RoboFile.php
RoboFile.codeCs
public function codeCs( $file = null, $options = [ 'autofix' => false, 'strict' => false, ] ) { if ($file === null) { $file = implode(' ', $this->csfiles); } $csignore = ''; if (count($this->csignore)) { $csignore .= '--ignore='; $csignore .= implode(',', $this->csignore); } $strict = $options['strict'] ? '' : '-n'; $result = $this->taskExec("./vendor/bin/phpcs $csignore --standard=vendor/glpi-project/coding-standard/GlpiStandard/ {$strict} {$file}")->run(); if (!$result->wasSuccessful()) { if (!$options['autofix'] && !$options['no-interaction']) { $options['autofix'] = $this->confirm('Would you like to run phpcbf to fix the reported errors?'); } if ($options['autofix']) { $result = $this->taskExec("./vendor/bin/phpcbf $csignore --standard=vendor/glpi-project/coding-standard/GlpiStandard/ {$file}")->run(); } } return $result; }
php
public function codeCs( $file = null, $options = [ 'autofix' => false, 'strict' => false, ] ) { if ($file === null) { $file = implode(' ', $this->csfiles); } $csignore = ''; if (count($this->csignore)) { $csignore .= '--ignore='; $csignore .= implode(',', $this->csignore); } $strict = $options['strict'] ? '' : '-n'; $result = $this->taskExec("./vendor/bin/phpcs $csignore --standard=vendor/glpi-project/coding-standard/GlpiStandard/ {$strict} {$file}")->run(); if (!$result->wasSuccessful()) { if (!$options['autofix'] && !$options['no-interaction']) { $options['autofix'] = $this->confirm('Would you like to run phpcbf to fix the reported errors?'); } if ($options['autofix']) { $result = $this->taskExec("./vendor/bin/phpcbf $csignore --standard=vendor/glpi-project/coding-standard/GlpiStandard/ {$file}")->run(); } } return $result; }
[ "public", "function", "codeCs", "(", "$", "file", "=", "null", ",", "$", "options", "=", "[", "'autofix'", "=>", "false", ",", "'strict'", "=>", "false", ",", "]", ")", "{", "if", "(", "$", "file", "===", "null", ")", "{", "$", "file", "=", "implode", "(", "' '", ",", "$", "this", "->", "csfiles", ")", ";", "}", "$", "csignore", "=", "''", ";", "if", "(", "count", "(", "$", "this", "->", "csignore", ")", ")", "{", "$", "csignore", ".=", "'--ignore='", ";", "$", "csignore", ".=", "implode", "(", "','", ",", "$", "this", "->", "csignore", ")", ";", "}", "$", "strict", "=", "$", "options", "[", "'strict'", "]", "?", "''", ":", "'-n'", ";", "$", "result", "=", "$", "this", "->", "taskExec", "(", "\"./vendor/bin/phpcs $csignore --standard=vendor/glpi-project/coding-standard/GlpiStandard/ {$strict} {$file}\"", ")", "->", "run", "(", ")", ";", "if", "(", "!", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "if", "(", "!", "$", "options", "[", "'autofix'", "]", "&&", "!", "$", "options", "[", "'no-interaction'", "]", ")", "{", "$", "options", "[", "'autofix'", "]", "=", "$", "this", "->", "confirm", "(", "'Would you like to run phpcbf to fix the reported errors?'", ")", ";", "}", "if", "(", "$", "options", "[", "'autofix'", "]", ")", "{", "$", "result", "=", "$", "this", "->", "taskExec", "(", "\"./vendor/bin/phpcbf $csignore --standard=vendor/glpi-project/coding-standard/GlpiStandard/ {$file}\"", ")", "->", "run", "(", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Code sniffer. Run the PHP Codesniffer on a file or directory. @param string $file A file or directory to analyze. @param array $options Options: @option $autofix Whether to run the automatic fixer or not. @option $strict Show warnings as well as errors. Default is to show only errors. @return void
[ "Code", "sniffer", "." ]
7f46bd479801f9530f0e70400739c75b535245a9
https://github.com/glpi-project/tools/blob/7f46bd479801f9530f0e70400739c75b535245a9/src/Tools/RoboFile.php#L144-L175
train
bringyourownideas/silverstripe-maintenance
src/Util/ApiLoader.php
ApiLoader.doRequest
public function doRequest($endpoint, callable $callback) { // Check for a cached value and return if one is available if ($result = $this->getFromCache()) { return $result; } // Otherwise go and request data from the API $request = new Request('GET', $endpoint); $failureMessage = 'Could not obtain information about module. '; try { /** @var Response $response */ $response = $this->getGuzzleClient()->send($request, $this->getClientOptions()); } catch (GuzzleException $exception) { throw new RuntimeException($failureMessage); } if ($response->getStatusCode() !== 200) { throw new RuntimeException($failureMessage . 'Error code ' . $response->getStatusCode()); } if (!in_array('application/json', $response->getHeader('Content-Type'))) { throw new RuntimeException($failureMessage . 'Response is not JSON'); } $responseBody = Convert::json2array($response->getBody()->getContents()); if (empty($responseBody)) { throw new RuntimeException($failureMessage . 'Response could not be parsed'); } if (!isset($responseBody['success']) || !$responseBody['success']) { throw new RuntimeException($failureMessage . 'Response returned unsuccessfully'); } // Allow callback to handle processing of the response body $result = $callback($responseBody); // Setting the value to the cache for subsequent requests $this->handleCacheFromResponse($response, $result); return $result; }
php
public function doRequest($endpoint, callable $callback) { // Check for a cached value and return if one is available if ($result = $this->getFromCache()) { return $result; } // Otherwise go and request data from the API $request = new Request('GET', $endpoint); $failureMessage = 'Could not obtain information about module. '; try { /** @var Response $response */ $response = $this->getGuzzleClient()->send($request, $this->getClientOptions()); } catch (GuzzleException $exception) { throw new RuntimeException($failureMessage); } if ($response->getStatusCode() !== 200) { throw new RuntimeException($failureMessage . 'Error code ' . $response->getStatusCode()); } if (!in_array('application/json', $response->getHeader('Content-Type'))) { throw new RuntimeException($failureMessage . 'Response is not JSON'); } $responseBody = Convert::json2array($response->getBody()->getContents()); if (empty($responseBody)) { throw new RuntimeException($failureMessage . 'Response could not be parsed'); } if (!isset($responseBody['success']) || !$responseBody['success']) { throw new RuntimeException($failureMessage . 'Response returned unsuccessfully'); } // Allow callback to handle processing of the response body $result = $callback($responseBody); // Setting the value to the cache for subsequent requests $this->handleCacheFromResponse($response, $result); return $result; }
[ "public", "function", "doRequest", "(", "$", "endpoint", ",", "callable", "$", "callback", ")", "{", "// Check for a cached value and return if one is available", "if", "(", "$", "result", "=", "$", "this", "->", "getFromCache", "(", ")", ")", "{", "return", "$", "result", ";", "}", "// Otherwise go and request data from the API", "$", "request", "=", "new", "Request", "(", "'GET'", ",", "$", "endpoint", ")", ";", "$", "failureMessage", "=", "'Could not obtain information about module. '", ";", "try", "{", "/** @var Response $response */", "$", "response", "=", "$", "this", "->", "getGuzzleClient", "(", ")", "->", "send", "(", "$", "request", ",", "$", "this", "->", "getClientOptions", "(", ")", ")", ";", "}", "catch", "(", "GuzzleException", "$", "exception", ")", "{", "throw", "new", "RuntimeException", "(", "$", "failureMessage", ")", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", ")", "{", "throw", "new", "RuntimeException", "(", "$", "failureMessage", ".", "'Error code '", ".", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}", "if", "(", "!", "in_array", "(", "'application/json'", ",", "$", "response", "->", "getHeader", "(", "'Content-Type'", ")", ")", ")", "{", "throw", "new", "RuntimeException", "(", "$", "failureMessage", ".", "'Response is not JSON'", ")", ";", "}", "$", "responseBody", "=", "Convert", "::", "json2array", "(", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "responseBody", ")", ")", "{", "throw", "new", "RuntimeException", "(", "$", "failureMessage", ".", "'Response could not be parsed'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "responseBody", "[", "'success'", "]", ")", "||", "!", "$", "responseBody", "[", "'success'", "]", ")", "{", "throw", "new", "RuntimeException", "(", "$", "failureMessage", ".", "'Response returned unsuccessfully'", ")", ";", "}", "// Allow callback to handle processing of the response body", "$", "result", "=", "$", "callback", "(", "$", "responseBody", ")", ";", "// Setting the value to the cache for subsequent requests", "$", "this", "->", "handleCacheFromResponse", "(", "$", "response", ",", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Perform an HTTP request for module health information @param string $endpoint API endpoint to check for results @param callable $callback Function to return the result of after loading the API data @return array @throws RuntimeException When the API responds with something that's not module health information
[ "Perform", "an", "HTTP", "request", "for", "module", "health", "information" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ApiLoader.php#L52-L95
train
bringyourownideas/silverstripe-maintenance
src/Util/ApiLoader.php
ApiLoader.getFromCache
protected function getFromCache() { $cacheKey = $this->getCacheKey(); $result = $this->getCache()->get($cacheKey, false); if ($result === false) { return false; } // Deserialize JSON object and return as an array return Convert::json2array($result); }
php
protected function getFromCache() { $cacheKey = $this->getCacheKey(); $result = $this->getCache()->get($cacheKey, false); if ($result === false) { return false; } // Deserialize JSON object and return as an array return Convert::json2array($result); }
[ "protected", "function", "getFromCache", "(", ")", "{", "$", "cacheKey", "=", "$", "this", "->", "getCacheKey", "(", ")", ";", "$", "result", "=", "$", "this", "->", "getCache", "(", ")", "->", "get", "(", "$", "cacheKey", ",", "false", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "return", "false", ";", "}", "// Deserialize JSON object and return as an array", "return", "Convert", "::", "json2array", "(", "$", "result", ")", ";", "}" ]
Attempts to load something from the cache and deserializes from JSON if successful @return array|bool @throws \Psr\SimpleCache\InvalidArgumentException
[ "Attempts", "to", "load", "something", "from", "the", "cache", "and", "deserializes", "from", "JSON", "if", "successful" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ApiLoader.php#L135-L145
train
bringyourownideas/silverstripe-maintenance
src/Util/ApiLoader.php
ApiLoader.setToCache
protected function setToCache($cacheKey, $value, $ttl = null) { // Seralize as JSON to ensure array etc can be stored $value = Convert::raw2json($value); return $this->getCache()->set($cacheKey, $value, $ttl); }
php
protected function setToCache($cacheKey, $value, $ttl = null) { // Seralize as JSON to ensure array etc can be stored $value = Convert::raw2json($value); return $this->getCache()->set($cacheKey, $value, $ttl); }
[ "protected", "function", "setToCache", "(", "$", "cacheKey", ",", "$", "value", ",", "$", "ttl", "=", "null", ")", "{", "// Seralize as JSON to ensure array etc can be stored", "$", "value", "=", "Convert", "::", "raw2json", "(", "$", "value", ")", ";", "return", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "cacheKey", ",", "$", "value", ",", "$", "ttl", ")", ";", "}" ]
Given a value, set it to the cache with the given key after serializing the value as JSON @param string $cacheKey @param mixed $value @param int $ttl @return bool @throws \Psr\SimpleCache\InvalidArgumentException
[ "Given", "a", "value", "set", "it", "to", "the", "cache", "with", "the", "given", "key", "after", "serializing", "the", "value", "as", "JSON" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ApiLoader.php#L156-L162
train
bringyourownideas/silverstripe-maintenance
src/Util/ApiLoader.php
ApiLoader.handleCacheFromResponse
protected function handleCacheFromResponse(Response $response, $result) { // Handle caching if requested if ($cacheControl = $response->getHeader('Cache-Control')) { // Combine separate header rows $cacheControl = implode(', ', $cacheControl); if (strpos($cacheControl, 'no-store') === false && preg_match('/(?:max-age=)(\d+)/i', $cacheControl, $matches) ) { $duration = (int) $matches[1]; $cacheKey = $this->getCacheKey(); $this->setToCache($cacheKey, $result, $duration); } } }
php
protected function handleCacheFromResponse(Response $response, $result) { // Handle caching if requested if ($cacheControl = $response->getHeader('Cache-Control')) { // Combine separate header rows $cacheControl = implode(', ', $cacheControl); if (strpos($cacheControl, 'no-store') === false && preg_match('/(?:max-age=)(\d+)/i', $cacheControl, $matches) ) { $duration = (int) $matches[1]; $cacheKey = $this->getCacheKey(); $this->setToCache($cacheKey, $result, $duration); } } }
[ "protected", "function", "handleCacheFromResponse", "(", "Response", "$", "response", ",", "$", "result", ")", "{", "// Handle caching if requested", "if", "(", "$", "cacheControl", "=", "$", "response", "->", "getHeader", "(", "'Cache-Control'", ")", ")", "{", "// Combine separate header rows", "$", "cacheControl", "=", "implode", "(", "', '", ",", "$", "cacheControl", ")", ";", "if", "(", "strpos", "(", "$", "cacheControl", ",", "'no-store'", ")", "===", "false", "&&", "preg_match", "(", "'/(?:max-age=)(\\d+)/i'", ",", "$", "cacheControl", ",", "$", "matches", ")", ")", "{", "$", "duration", "=", "(", "int", ")", "$", "matches", "[", "1", "]", ";", "$", "cacheKey", "=", "$", "this", "->", "getCacheKey", "(", ")", ";", "$", "this", "->", "setToCache", "(", "$", "cacheKey", ",", "$", "result", ",", "$", "duration", ")", ";", "}", "}", "}" ]
Check the API response for cache control headers and respect them internally in the SilverStripe cache if found @param Response $response @param array|string $result @throws \Psr\SimpleCache\InvalidArgumentException
[ "Check", "the", "API", "response", "for", "cache", "control", "headers", "and", "respect", "them", "internally", "in", "the", "SilverStripe", "cache", "if", "found" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ApiLoader.php#L172-L188
train
bringyourownideas/silverstripe-maintenance
src/Util/ApiLoader.php
ApiLoader.createRequest
protected function createRequest($uri, $method = 'GET') { $headers = []; $version = $this->resolveVersion(); if (!empty($version)) { $headers['Silverstripe-Framework-Version'] = $version; } return new Request($method, $uri, $headers); }
php
protected function createRequest($uri, $method = 'GET') { $headers = []; $version = $this->resolveVersion(); if (!empty($version)) { $headers['Silverstripe-Framework-Version'] = $version; } return new Request($method, $uri, $headers); }
[ "protected", "function", "createRequest", "(", "$", "uri", ",", "$", "method", "=", "'GET'", ")", "{", "$", "headers", "=", "[", "]", ";", "$", "version", "=", "$", "this", "->", "resolveVersion", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "version", ")", ")", "{", "$", "headers", "[", "'Silverstripe-Framework-Version'", "]", "=", "$", "version", ";", "}", "return", "new", "Request", "(", "$", "method", ",", "$", "uri", ",", "$", "headers", ")", ";", "}" ]
Create a request with some standard headers @param string $uri @param string $method @return Request
[ "Create", "a", "request", "with", "some", "standard", "headers" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ApiLoader.php#L219-L228
train
bringyourownideas/silverstripe-maintenance
src/Util/ModuleHealthLoader.php
ModuleHealthLoader.getModuleHealthInfo
public function getModuleHealthInfo() { $addons = $this->getModuleNames(); $endpoint = 'addons.silverstripe.org/api/ratings?addons=' . implode(',', $addons); return $this->doRequest($endpoint, function ($responseBody) { return isset($responseBody) ? $responseBody['ratings'] : []; }); }
php
public function getModuleHealthInfo() { $addons = $this->getModuleNames(); $endpoint = 'addons.silverstripe.org/api/ratings?addons=' . implode(',', $addons); return $this->doRequest($endpoint, function ($responseBody) { return isset($responseBody) ? $responseBody['ratings'] : []; }); }
[ "public", "function", "getModuleHealthInfo", "(", ")", "{", "$", "addons", "=", "$", "this", "->", "getModuleNames", "(", ")", ";", "$", "endpoint", "=", "'addons.silverstripe.org/api/ratings?addons='", ".", "implode", "(", "','", ",", "$", "addons", ")", ";", "return", "$", "this", "->", "doRequest", "(", "$", "endpoint", ",", "function", "(", "$", "responseBody", ")", "{", "return", "isset", "(", "$", "responseBody", ")", "?", "$", "responseBody", "[", "'ratings'", "]", ":", "[", "]", ";", "}", ")", ";", "}" ]
Return the list of supported addons as provided by addons.silverstripe.org @return array
[ "Return", "the", "list", "of", "supported", "addons", "as", "provided", "by", "addons", ".", "silverstripe", ".", "org" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ModuleHealthLoader.php#L20-L27
train
bringyourownideas/silverstripe-maintenance
src/Jobs/CheckForUpdatesJob.php
CheckForUpdatesJob.process
public function process() { // Run the UpdatePackageInfo task $updateTask = Injector::inst()->create(UpdatePackageInfoTask::class); $updateTask->run(null); // mark job as completed $this->isComplete = true; }
php
public function process() { // Run the UpdatePackageInfo task $updateTask = Injector::inst()->create(UpdatePackageInfoTask::class); $updateTask->run(null); // mark job as completed $this->isComplete = true; }
[ "public", "function", "process", "(", ")", "{", "// Run the UpdatePackageInfo task", "$", "updateTask", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "UpdatePackageInfoTask", "::", "class", ")", ";", "$", "updateTask", "->", "run", "(", "null", ")", ";", "// mark job as completed", "$", "this", "->", "isComplete", "=", "true", ";", "}" ]
Processes the task as a job
[ "Processes", "the", "task", "as", "a", "job" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Jobs/CheckForUpdatesJob.php#L58-L66
train
esbenp/architect
src/Architect.php
Architect.parseData
public function parseData($data, array $modes, $key = null) { $return = []; uksort($modes, function ($a, $b) { return substr_count($b, '.')-substr_count($a, '.'); }); if (Utility::isCollection($data)) { $parsed = $this->parseCollection($modes, $data, $return); } else { $parsed = $this->parseResource($modes, $data, $return); } if ($key !== null) { $return[$key] = $parsed; } else { if (in_array('sideload', $modes)) { throw new InvalidArgumentException('$key cannot be null when ' . 'resources are transformed using sideload.'); } $return = $parsed; } return $return; }
php
public function parseData($data, array $modes, $key = null) { $return = []; uksort($modes, function ($a, $b) { return substr_count($b, '.')-substr_count($a, '.'); }); if (Utility::isCollection($data)) { $parsed = $this->parseCollection($modes, $data, $return); } else { $parsed = $this->parseResource($modes, $data, $return); } if ($key !== null) { $return[$key] = $parsed; } else { if (in_array('sideload', $modes)) { throw new InvalidArgumentException('$key cannot be null when ' . 'resources are transformed using sideload.'); } $return = $parsed; } return $return; }
[ "public", "function", "parseData", "(", "$", "data", ",", "array", "$", "modes", ",", "$", "key", "=", "null", ")", "{", "$", "return", "=", "[", "]", ";", "uksort", "(", "$", "modes", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "substr_count", "(", "$", "b", ",", "'.'", ")", "-", "substr_count", "(", "$", "a", ",", "'.'", ")", ";", "}", ")", ";", "if", "(", "Utility", "::", "isCollection", "(", "$", "data", ")", ")", "{", "$", "parsed", "=", "$", "this", "->", "parseCollection", "(", "$", "modes", ",", "$", "data", ",", "$", "return", ")", ";", "}", "else", "{", "$", "parsed", "=", "$", "this", "->", "parseResource", "(", "$", "modes", ",", "$", "data", ",", "$", "return", ")", ";", "}", "if", "(", "$", "key", "!==", "null", ")", "{", "$", "return", "[", "$", "key", "]", "=", "$", "parsed", ";", "}", "else", "{", "if", "(", "in_array", "(", "'sideload'", ",", "$", "modes", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'$key cannot be null when '", ".", "'resources are transformed using sideload.'", ")", ";", "}", "$", "return", "=", "$", "parsed", ";", "}", "return", "$", "return", ";", "}" ]
Parse a collection using given modes. @param mixed $data The collection to be parsed @param array $modes The modes to be used, format is ['relation' => 'mode'] @param string $key A key to hoist the collection into the root array @return array
[ "Parse", "a", "collection", "using", "given", "modes", "." ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/Architect.php#L19-L45
train
esbenp/architect
src/Architect.php
Architect.parseCollection
private function parseCollection(array $modes, $collection, &$root, $fullPropertyPath = '') { if (is_array($collection)) { foreach ($collection as $i => $resource) { $collection[$i] = $this->parseResource($modes, $resource, $root, $fullPropertyPath); } } elseif ($collection instanceof Collection) { $collection = $collection->map(function ($resource) use ($modes, &$root, $fullPropertyPath) { return $this->parseResource($modes, $resource, $root, $fullPropertyPath); }); } return $collection; }
php
private function parseCollection(array $modes, $collection, &$root, $fullPropertyPath = '') { if (is_array($collection)) { foreach ($collection as $i => $resource) { $collection[$i] = $this->parseResource($modes, $resource, $root, $fullPropertyPath); } } elseif ($collection instanceof Collection) { $collection = $collection->map(function ($resource) use ($modes, &$root, $fullPropertyPath) { return $this->parseResource($modes, $resource, $root, $fullPropertyPath); }); } return $collection; }
[ "private", "function", "parseCollection", "(", "array", "$", "modes", ",", "$", "collection", ",", "&", "$", "root", ",", "$", "fullPropertyPath", "=", "''", ")", "{", "if", "(", "is_array", "(", "$", "collection", ")", ")", "{", "foreach", "(", "$", "collection", "as", "$", "i", "=>", "$", "resource", ")", "{", "$", "collection", "[", "$", "i", "]", "=", "$", "this", "->", "parseResource", "(", "$", "modes", ",", "$", "resource", ",", "$", "root", ",", "$", "fullPropertyPath", ")", ";", "}", "}", "elseif", "(", "$", "collection", "instanceof", "Collection", ")", "{", "$", "collection", "=", "$", "collection", "->", "map", "(", "function", "(", "$", "resource", ")", "use", "(", "$", "modes", ",", "&", "$", "root", ",", "$", "fullPropertyPath", ")", "{", "return", "$", "this", "->", "parseResource", "(", "$", "modes", ",", "$", "resource", ",", "$", "root", ",", "$", "fullPropertyPath", ")", ";", "}", ")", ";", "}", "return", "$", "collection", ";", "}" ]
Parse a collection using given modes @param array $modes @param mixed $collection @param array $root @param string $fullPropertyPath @return mixed
[ "Parse", "a", "collection", "using", "given", "modes" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/Architect.php#L55-L68
train
esbenp/architect
src/Architect.php
Architect.parseResource
private function parseResource(array $modes, &$resource, &$root, $fullPropertyPath = '') { foreach ($modes as $relation => $mode) { $modeResolver = $this->resolveMode($mode); $steps = explode('.', $relation); // Get the first resource in the relation // TODO: Refactor $property = array_shift($steps); if (is_array($resource)) { if ($resource[$property] === null) { continue; } $object = &$resource[$property]; } else { if ($resource->{$property} === null) { continue; } $object = &$resource->{$property}; } if (empty($steps)) { // This is the deepest level. Resolve it. $fullPropertyPath .= $relation; $object = $this->modeResolvers[$mode]->resolve($relation, $object, $root, $fullPropertyPath); } else { // More levels exist in this relation. // We want a drill down and resolve the deepest level first. $path = implode('.', $steps); $modes = [ $path => $mode ]; // Add the previous levels to the full path so it can be used // to populate the root level properly. $fullPropertyPath .= $property . '.'; if (Utility::isCollection($object)) { $object = $this->parseCollection($modes, $object, $root, $fullPropertyPath); } else { $object = $this->parseResource($modes, $object, $root, $fullPropertyPath); } } // Reset the full property path after running a full relation $fullPropertyPath = ''; Utility::setProperty($resource, $property, $object); } return $resource; }
php
private function parseResource(array $modes, &$resource, &$root, $fullPropertyPath = '') { foreach ($modes as $relation => $mode) { $modeResolver = $this->resolveMode($mode); $steps = explode('.', $relation); // Get the first resource in the relation // TODO: Refactor $property = array_shift($steps); if (is_array($resource)) { if ($resource[$property] === null) { continue; } $object = &$resource[$property]; } else { if ($resource->{$property} === null) { continue; } $object = &$resource->{$property}; } if (empty($steps)) { // This is the deepest level. Resolve it. $fullPropertyPath .= $relation; $object = $this->modeResolvers[$mode]->resolve($relation, $object, $root, $fullPropertyPath); } else { // More levels exist in this relation. // We want a drill down and resolve the deepest level first. $path = implode('.', $steps); $modes = [ $path => $mode ]; // Add the previous levels to the full path so it can be used // to populate the root level properly. $fullPropertyPath .= $property . '.'; if (Utility::isCollection($object)) { $object = $this->parseCollection($modes, $object, $root, $fullPropertyPath); } else { $object = $this->parseResource($modes, $object, $root, $fullPropertyPath); } } // Reset the full property path after running a full relation $fullPropertyPath = ''; Utility::setProperty($resource, $property, $object); } return $resource; }
[ "private", "function", "parseResource", "(", "array", "$", "modes", ",", "&", "$", "resource", ",", "&", "$", "root", ",", "$", "fullPropertyPath", "=", "''", ")", "{", "foreach", "(", "$", "modes", "as", "$", "relation", "=>", "$", "mode", ")", "{", "$", "modeResolver", "=", "$", "this", "->", "resolveMode", "(", "$", "mode", ")", ";", "$", "steps", "=", "explode", "(", "'.'", ",", "$", "relation", ")", ";", "// Get the first resource in the relation", "// TODO: Refactor", "$", "property", "=", "array_shift", "(", "$", "steps", ")", ";", "if", "(", "is_array", "(", "$", "resource", ")", ")", "{", "if", "(", "$", "resource", "[", "$", "property", "]", "===", "null", ")", "{", "continue", ";", "}", "$", "object", "=", "&", "$", "resource", "[", "$", "property", "]", ";", "}", "else", "{", "if", "(", "$", "resource", "->", "{", "$", "property", "}", "===", "null", ")", "{", "continue", ";", "}", "$", "object", "=", "&", "$", "resource", "->", "{", "$", "property", "}", ";", "}", "if", "(", "empty", "(", "$", "steps", ")", ")", "{", "// This is the deepest level. Resolve it.", "$", "fullPropertyPath", ".=", "$", "relation", ";", "$", "object", "=", "$", "this", "->", "modeResolvers", "[", "$", "mode", "]", "->", "resolve", "(", "$", "relation", ",", "$", "object", ",", "$", "root", ",", "$", "fullPropertyPath", ")", ";", "}", "else", "{", "// More levels exist in this relation.", "// We want a drill down and resolve the deepest level first.", "$", "path", "=", "implode", "(", "'.'", ",", "$", "steps", ")", ";", "$", "modes", "=", "[", "$", "path", "=>", "$", "mode", "]", ";", "// Add the previous levels to the full path so it can be used", "// to populate the root level properly.", "$", "fullPropertyPath", ".=", "$", "property", ".", "'.'", ";", "if", "(", "Utility", "::", "isCollection", "(", "$", "object", ")", ")", "{", "$", "object", "=", "$", "this", "->", "parseCollection", "(", "$", "modes", ",", "$", "object", ",", "$", "root", ",", "$", "fullPropertyPath", ")", ";", "}", "else", "{", "$", "object", "=", "$", "this", "->", "parseResource", "(", "$", "modes", ",", "$", "object", ",", "$", "root", ",", "$", "fullPropertyPath", ")", ";", "}", "}", "// Reset the full property path after running a full relation", "$", "fullPropertyPath", "=", "''", ";", "Utility", "::", "setProperty", "(", "$", "resource", ",", "$", "property", ",", "$", "object", ")", ";", "}", "return", "$", "resource", ";", "}" ]
Parse a single resource using given modes @param array $modes @param mixed $resource @param array $root @param string $fullPropertyPath @return mixed
[ "Parse", "a", "single", "resource", "using", "given", "modes" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/Architect.php#L78-L132
train
esbenp/architect
src/Architect.php
Architect.resolveMode
private function resolveMode($mode) { if (!isset($this->modeResolers[$mode])) { $this->modeResolvers[$mode] = $this->createModeResolver($mode); } return $this->modeResolvers[$mode]; }
php
private function resolveMode($mode) { if (!isset($this->modeResolers[$mode])) { $this->modeResolvers[$mode] = $this->createModeResolver($mode); } return $this->modeResolvers[$mode]; }
[ "private", "function", "resolveMode", "(", "$", "mode", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "modeResolers", "[", "$", "mode", "]", ")", ")", "{", "$", "this", "->", "modeResolvers", "[", "$", "mode", "]", "=", "$", "this", "->", "createModeResolver", "(", "$", "mode", ")", ";", "}", "return", "$", "this", "->", "modeResolvers", "[", "$", "mode", "]", ";", "}" ]
Resolve a mode resolver class if it has not been resolved before @param string $mode The mode to be resolved @return Optimus\Architect\ModeResolver\ModeResolverInterface
[ "Resolve", "a", "mode", "resolver", "class", "if", "it", "has", "not", "been", "resolved", "before" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/Architect.php#L139-L146
train
bringyourownideas/silverstripe-maintenance
src/Forms/GridFieldRefreshButton.php
GridFieldRefreshButton.handleAction
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if ($actionName == 'refresh') { return $this->handleRefresh($gridField); } }
php
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if ($actionName == 'refresh') { return $this->handleRefresh($gridField); } }
[ "public", "function", "handleAction", "(", "GridField", "$", "gridField", ",", "$", "actionName", ",", "$", "arguments", ",", "$", "data", ")", "{", "if", "(", "$", "actionName", "==", "'refresh'", ")", "{", "return", "$", "this", "->", "handleRefresh", "(", "$", "gridField", ")", ";", "}", "}" ]
Handle the refresh action. @param GridField $gridField @param string $actionName @param array $arguments @param array $data @return null
[ "Handle", "the", "refresh", "action", "." ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Forms/GridFieldRefreshButton.php#L116-L121
train
bringyourownideas/silverstripe-maintenance
src/Forms/GridFieldRefreshButton.php
GridFieldRefreshButton.handleRefresh
public function handleRefresh() { if ($this->hasPendingJob()) { return; } // Queue the job in the immediate queue $job = Injector::inst()->create(CheckForUpdatesJob::class); $jobDescriptorId = $this->getQueuedJobService()->queueJob($job, null, null, QueuedJob::IMMEDIATE); // Check the job descriptor on the queue $jobDescriptor = QueuedJobDescriptor::get()->filter('ID', $jobDescriptorId)->first(); // If the job is not immediate, change it to immediate and reschedule it to occur immediately if ($jobDescriptor->JobType !== QueuedJob::IMMEDIATE) { $jobDescriptor->JobType = QueuedJob::IMMEDIATE; $jobDescriptor->StartAfter = null; $jobDescriptor->write(); } }
php
public function handleRefresh() { if ($this->hasPendingJob()) { return; } // Queue the job in the immediate queue $job = Injector::inst()->create(CheckForUpdatesJob::class); $jobDescriptorId = $this->getQueuedJobService()->queueJob($job, null, null, QueuedJob::IMMEDIATE); // Check the job descriptor on the queue $jobDescriptor = QueuedJobDescriptor::get()->filter('ID', $jobDescriptorId)->first(); // If the job is not immediate, change it to immediate and reschedule it to occur immediately if ($jobDescriptor->JobType !== QueuedJob::IMMEDIATE) { $jobDescriptor->JobType = QueuedJob::IMMEDIATE; $jobDescriptor->StartAfter = null; $jobDescriptor->write(); } }
[ "public", "function", "handleRefresh", "(", ")", "{", "if", "(", "$", "this", "->", "hasPendingJob", "(", ")", ")", "{", "return", ";", "}", "// Queue the job in the immediate queue", "$", "job", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "CheckForUpdatesJob", "::", "class", ")", ";", "$", "jobDescriptorId", "=", "$", "this", "->", "getQueuedJobService", "(", ")", "->", "queueJob", "(", "$", "job", ",", "null", ",", "null", ",", "QueuedJob", "::", "IMMEDIATE", ")", ";", "// Check the job descriptor on the queue", "$", "jobDescriptor", "=", "QueuedJobDescriptor", "::", "get", "(", ")", "->", "filter", "(", "'ID'", ",", "$", "jobDescriptorId", ")", "->", "first", "(", ")", ";", "// If the job is not immediate, change it to immediate and reschedule it to occur immediately", "if", "(", "$", "jobDescriptor", "->", "JobType", "!==", "QueuedJob", "::", "IMMEDIATE", ")", "{", "$", "jobDescriptor", "->", "JobType", "=", "QueuedJob", "::", "IMMEDIATE", ";", "$", "jobDescriptor", "->", "StartAfter", "=", "null", ";", "$", "jobDescriptor", "->", "write", "(", ")", ";", "}", "}" ]
Handle the refresh, for both the action button and the URL
[ "Handle", "the", "refresh", "for", "both", "the", "action", "button", "and", "the", "URL" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Forms/GridFieldRefreshButton.php#L182-L201
train
bringyourownideas/silverstripe-maintenance
src/Tasks/UpdatePackageInfoTask.php
UpdatePackageInfoTask.run
public function run($request) { // Loading packages and all their updates can be quite memory intensive. $memoryLimit = $this->config()->get('memory_limit'); if ($memoryLimit) { if (Environment::getMemoryLimitMax() < Convert::memstring2bytes($memoryLimit)) { Environment::setMemoryLimitMax($memoryLimit); } Environment::increaseMemoryLimitTo($memoryLimit); } $composerLock = $this->getComposerLoader()->getLock(); $rawPackages = array_merge($composerLock->packages, (array) $composerLock->{'packages-dev'}); $packages = $this->getPackageInfo($rawPackages); // Get "name" from $packages and put into an array $moduleNames = array_column($packages, 'Name'); $supportedPackages = $this->getSupportedPackages(); $moduleHealthInfo = $this->getHealthIndicator($moduleNames); // Extensions to the process that add data may rely on external services. // There may be a communication issue between the site and the external service, // so if there are 'none' we should assume this is untrue and _not_ proceed // to remove everything. Stale information is better than no information. if ($packages) { // There is no onBeforeDelete for Package $table = DataObjectSchema::create()->tableName(Package::class); SQLDelete::create("\"$table\"")->execute(); foreach ($packages as $package) { $packageName = $package['Name']; if (is_array($supportedPackages)) { $package['Supported'] = in_array($packageName, $supportedPackages); } if (is_array($moduleHealthInfo) && isset($moduleHealthInfo[$packageName])) { $package['Rating'] = $moduleHealthInfo[$packageName]; } Package::create()->update($package)->write(); } } }
php
public function run($request) { // Loading packages and all their updates can be quite memory intensive. $memoryLimit = $this->config()->get('memory_limit'); if ($memoryLimit) { if (Environment::getMemoryLimitMax() < Convert::memstring2bytes($memoryLimit)) { Environment::setMemoryLimitMax($memoryLimit); } Environment::increaseMemoryLimitTo($memoryLimit); } $composerLock = $this->getComposerLoader()->getLock(); $rawPackages = array_merge($composerLock->packages, (array) $composerLock->{'packages-dev'}); $packages = $this->getPackageInfo($rawPackages); // Get "name" from $packages and put into an array $moduleNames = array_column($packages, 'Name'); $supportedPackages = $this->getSupportedPackages(); $moduleHealthInfo = $this->getHealthIndicator($moduleNames); // Extensions to the process that add data may rely on external services. // There may be a communication issue between the site and the external service, // so if there are 'none' we should assume this is untrue and _not_ proceed // to remove everything. Stale information is better than no information. if ($packages) { // There is no onBeforeDelete for Package $table = DataObjectSchema::create()->tableName(Package::class); SQLDelete::create("\"$table\"")->execute(); foreach ($packages as $package) { $packageName = $package['Name']; if (is_array($supportedPackages)) { $package['Supported'] = in_array($packageName, $supportedPackages); } if (is_array($moduleHealthInfo) && isset($moduleHealthInfo[$packageName])) { $package['Rating'] = $moduleHealthInfo[$packageName]; } Package::create()->update($package)->write(); } } }
[ "public", "function", "run", "(", "$", "request", ")", "{", "// Loading packages and all their updates can be quite memory intensive.", "$", "memoryLimit", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'memory_limit'", ")", ";", "if", "(", "$", "memoryLimit", ")", "{", "if", "(", "Environment", "::", "getMemoryLimitMax", "(", ")", "<", "Convert", "::", "memstring2bytes", "(", "$", "memoryLimit", ")", ")", "{", "Environment", "::", "setMemoryLimitMax", "(", "$", "memoryLimit", ")", ";", "}", "Environment", "::", "increaseMemoryLimitTo", "(", "$", "memoryLimit", ")", ";", "}", "$", "composerLock", "=", "$", "this", "->", "getComposerLoader", "(", ")", "->", "getLock", "(", ")", ";", "$", "rawPackages", "=", "array_merge", "(", "$", "composerLock", "->", "packages", ",", "(", "array", ")", "$", "composerLock", "->", "{", "'packages-dev'", "}", ")", ";", "$", "packages", "=", "$", "this", "->", "getPackageInfo", "(", "$", "rawPackages", ")", ";", "// Get \"name\" from $packages and put into an array", "$", "moduleNames", "=", "array_column", "(", "$", "packages", ",", "'Name'", ")", ";", "$", "supportedPackages", "=", "$", "this", "->", "getSupportedPackages", "(", ")", ";", "$", "moduleHealthInfo", "=", "$", "this", "->", "getHealthIndicator", "(", "$", "moduleNames", ")", ";", "// Extensions to the process that add data may rely on external services.", "// There may be a communication issue between the site and the external service,", "// so if there are 'none' we should assume this is untrue and _not_ proceed", "// to remove everything. Stale information is better than no information.", "if", "(", "$", "packages", ")", "{", "// There is no onBeforeDelete for Package", "$", "table", "=", "DataObjectSchema", "::", "create", "(", ")", "->", "tableName", "(", "Package", "::", "class", ")", ";", "SQLDelete", "::", "create", "(", "\"\\\"$table\\\"\"", ")", "->", "execute", "(", ")", ";", "foreach", "(", "$", "packages", "as", "$", "package", ")", "{", "$", "packageName", "=", "$", "package", "[", "'Name'", "]", ";", "if", "(", "is_array", "(", "$", "supportedPackages", ")", ")", "{", "$", "package", "[", "'Supported'", "]", "=", "in_array", "(", "$", "packageName", ",", "$", "supportedPackages", ")", ";", "}", "if", "(", "is_array", "(", "$", "moduleHealthInfo", ")", "&&", "isset", "(", "$", "moduleHealthInfo", "[", "$", "packageName", "]", ")", ")", "{", "$", "package", "[", "'Rating'", "]", "=", "$", "moduleHealthInfo", "[", "$", "packageName", "]", ";", "}", "Package", "::", "create", "(", ")", "->", "update", "(", "$", "package", ")", "->", "write", "(", ")", ";", "}", "}", "}" ]
Update database cached information about this site. @param HTTPRequest $request unused, can be null (must match signature of parent function).
[ "Update", "database", "cached", "information", "about", "this", "site", "." ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Tasks/UpdatePackageInfoTask.php#L150-L190
train
bringyourownideas/silverstripe-maintenance
src/Tasks/UpdatePackageInfoTask.php
UpdatePackageInfoTask.getPackageInfo
public function getPackageInfo($packageList) { $formatInfo = function ($package) { // Convert object to array, with Capitalised keys $package = get_object_vars($package); return array_combine( array_map('ucfirst', array_keys($package)), $package ); }; $packageList = array_map($formatInfo, $packageList); $this->extend('updatePackageInfo', $packageList); return $packageList; }
php
public function getPackageInfo($packageList) { $formatInfo = function ($package) { // Convert object to array, with Capitalised keys $package = get_object_vars($package); return array_combine( array_map('ucfirst', array_keys($package)), $package ); }; $packageList = array_map($formatInfo, $packageList); $this->extend('updatePackageInfo', $packageList); return $packageList; }
[ "public", "function", "getPackageInfo", "(", "$", "packageList", ")", "{", "$", "formatInfo", "=", "function", "(", "$", "package", ")", "{", "// Convert object to array, with Capitalised keys", "$", "package", "=", "get_object_vars", "(", "$", "package", ")", ";", "return", "array_combine", "(", "array_map", "(", "'ucfirst'", ",", "array_keys", "(", "$", "package", ")", ")", ",", "$", "package", ")", ";", "}", ";", "$", "packageList", "=", "array_map", "(", "$", "formatInfo", ",", "$", "packageList", ")", ";", "$", "this", "->", "extend", "(", "'updatePackageInfo'", ",", "$", "packageList", ")", ";", "return", "$", "packageList", ";", "}" ]
Fetch information about the installed packages. @param array $packageList list of packages as objects, formatted as one finds in a composer.lock @return array indexed array of package information, represented as associative arrays.
[ "Fetch", "information", "about", "the", "installed", "packages", "." ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Tasks/UpdatePackageInfoTask.php#L199-L213
train
bringyourownideas/silverstripe-maintenance
src/Tasks/UpdatePackageInfoTask.php
UpdatePackageInfoTask.getSupportedPackages
public function getSupportedPackages() { try { return $this->getSupportedAddonsLoader()->getAddonNames() ?: []; } catch (RuntimeException $exception) { echo $exception->getMessage() . PHP_EOL; } return null; }
php
public function getSupportedPackages() { try { return $this->getSupportedAddonsLoader()->getAddonNames() ?: []; } catch (RuntimeException $exception) { echo $exception->getMessage() . PHP_EOL; } return null; }
[ "public", "function", "getSupportedPackages", "(", ")", "{", "try", "{", "return", "$", "this", "->", "getSupportedAddonsLoader", "(", ")", "->", "getAddonNames", "(", ")", "?", ":", "[", "]", ";", "}", "catch", "(", "RuntimeException", "$", "exception", ")", "{", "echo", "$", "exception", "->", "getMessage", "(", ")", ".", "PHP_EOL", ";", "}", "return", "null", ";", "}" ]
Return an array of supported modules as fetched from addons.silverstripe.org. Outputs a message and returns null if an error occurs @return null|array
[ "Return", "an", "array", "of", "supported", "modules", "as", "fetched", "from", "addons", ".", "silverstripe", ".", "org", ".", "Outputs", "a", "message", "and", "returns", "null", "if", "an", "error", "occurs" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Tasks/UpdatePackageInfoTask.php#L221-L230
train
bringyourownideas/silverstripe-maintenance
src/Tasks/UpdatePackageInfoTask.php
UpdatePackageInfoTask.getHealthIndicator
public function getHealthIndicator(array $moduleNames) { try { return $this->getModuleHealthLoader()->setModuleNames($moduleNames)->getModuleHealthInfo() ?: []; } catch (RuntimeException $exception) { echo $exception->getMessage() . PHP_EOL; } return null; }
php
public function getHealthIndicator(array $moduleNames) { try { return $this->getModuleHealthLoader()->setModuleNames($moduleNames)->getModuleHealthInfo() ?: []; } catch (RuntimeException $exception) { echo $exception->getMessage() . PHP_EOL; } return null; }
[ "public", "function", "getHealthIndicator", "(", "array", "$", "moduleNames", ")", "{", "try", "{", "return", "$", "this", "->", "getModuleHealthLoader", "(", ")", "->", "setModuleNames", "(", "$", "moduleNames", ")", "->", "getModuleHealthInfo", "(", ")", "?", ":", "[", "]", ";", "}", "catch", "(", "RuntimeException", "$", "exception", ")", "{", "echo", "$", "exception", "->", "getMessage", "(", ")", ".", "PHP_EOL", ";", "}", "return", "null", ";", "}" ]
Return an array of module health information as fetched from addons.silverstripe.org. Outputs a message and returns null if an error occurs @param string[] $moduleNames @return null|array
[ "Return", "an", "array", "of", "module", "health", "information", "as", "fetched", "from", "addons", ".", "silverstripe", ".", "org", ".", "Outputs", "a", "message", "and", "returns", "null", "if", "an", "error", "occurs" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Tasks/UpdatePackageInfoTask.php#L239-L248
train
barbushin/dater
src/Dater/Dater.php
Dater.initDatetimeObject
public function initDatetimeObject($datetimeOrTimestamp = null, $inputTimezone = null, $outputTimezone = null) { if(!$inputTimezone) { $inputTimezone = $this->serverTimezone; } if(!$outputTimezone) { $outputTimezone = $this->clientTimezone; } if(strlen($datetimeOrTimestamp) == 10) { $isTimeStamp = is_numeric($datetimeOrTimestamp); $isDate = !$isTimeStamp; } else { $isTimeStamp = false; $isDate = false; } if($isTimeStamp) { $datetime = new \DateTime(); $datetime->setTimestamp($datetimeOrTimestamp); } else { $datetime = new \DateTime($datetimeOrTimestamp, $inputTimezone ? $this->getTimezoneObject($inputTimezone) : null); } if(!$isDate && $outputTimezone && $outputTimezone != $inputTimezone) { $datetime->setTimezone($this->getTimezoneObject($outputTimezone)); } return $datetime; }
php
public function initDatetimeObject($datetimeOrTimestamp = null, $inputTimezone = null, $outputTimezone = null) { if(!$inputTimezone) { $inputTimezone = $this->serverTimezone; } if(!$outputTimezone) { $outputTimezone = $this->clientTimezone; } if(strlen($datetimeOrTimestamp) == 10) { $isTimeStamp = is_numeric($datetimeOrTimestamp); $isDate = !$isTimeStamp; } else { $isTimeStamp = false; $isDate = false; } if($isTimeStamp) { $datetime = new \DateTime(); $datetime->setTimestamp($datetimeOrTimestamp); } else { $datetime = new \DateTime($datetimeOrTimestamp, $inputTimezone ? $this->getTimezoneObject($inputTimezone) : null); } if(!$isDate && $outputTimezone && $outputTimezone != $inputTimezone) { $datetime->setTimezone($this->getTimezoneObject($outputTimezone)); } return $datetime; }
[ "public", "function", "initDatetimeObject", "(", "$", "datetimeOrTimestamp", "=", "null", ",", "$", "inputTimezone", "=", "null", ",", "$", "outputTimezone", "=", "null", ")", "{", "if", "(", "!", "$", "inputTimezone", ")", "{", "$", "inputTimezone", "=", "$", "this", "->", "serverTimezone", ";", "}", "if", "(", "!", "$", "outputTimezone", ")", "{", "$", "outputTimezone", "=", "$", "this", "->", "clientTimezone", ";", "}", "if", "(", "strlen", "(", "$", "datetimeOrTimestamp", ")", "==", "10", ")", "{", "$", "isTimeStamp", "=", "is_numeric", "(", "$", "datetimeOrTimestamp", ")", ";", "$", "isDate", "=", "!", "$", "isTimeStamp", ";", "}", "else", "{", "$", "isTimeStamp", "=", "false", ";", "$", "isDate", "=", "false", ";", "}", "if", "(", "$", "isTimeStamp", ")", "{", "$", "datetime", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "datetime", "->", "setTimestamp", "(", "$", "datetimeOrTimestamp", ")", ";", "}", "else", "{", "$", "datetime", "=", "new", "\\", "DateTime", "(", "$", "datetimeOrTimestamp", ",", "$", "inputTimezone", "?", "$", "this", "->", "getTimezoneObject", "(", "$", "inputTimezone", ")", ":", "null", ")", ";", "}", "if", "(", "!", "$", "isDate", "&&", "$", "outputTimezone", "&&", "$", "outputTimezone", "!=", "$", "inputTimezone", ")", "{", "$", "datetime", "->", "setTimezone", "(", "$", "this", "->", "getTimezoneObject", "(", "$", "outputTimezone", ")", ")", ";", "}", "return", "$", "datetime", ";", "}" ]
Init standard \DateTime object configured to outputTimezone corresponding to inputTimezone @param null $datetimeOrTimestamp @param null $inputTimezone @param null $outputTimezone @return \DateTime
[ "Init", "standard", "\\", "DateTime", "object", "configured", "to", "outputTimezone", "corresponding", "to", "inputTimezone" ]
423f64587b0ff87ee3b46314f26b4c16e4f8f845
https://github.com/barbushin/dater/blob/423f64587b0ff87ee3b46314f26b4c16e4f8f845/src/Dater/Dater.php#L169-L198
train
barbushin/dater
src/Dater/Dater.php
Dater.serverDate
public function serverDate($serverDatetimeOrTimestamp = null) { return $this->format($serverDatetimeOrTimestamp, self::ISO_DATE_FORMAT, $this->serverTimezone); }
php
public function serverDate($serverDatetimeOrTimestamp = null) { return $this->format($serverDatetimeOrTimestamp, self::ISO_DATE_FORMAT, $this->serverTimezone); }
[ "public", "function", "serverDate", "(", "$", "serverDatetimeOrTimestamp", "=", "null", ")", "{", "return", "$", "this", "->", "format", "(", "$", "serverDatetimeOrTimestamp", ",", "self", "::", "ISO_DATE_FORMAT", ",", "$", "this", "->", "serverTimezone", ")", ";", "}" ]
Get date in YYYY-MM-DD format, in server timezone @param string|int|null $serverDatetimeOrTimestamp @return string
[ "Get", "date", "in", "YYYY", "-", "MM", "-", "DD", "format", "in", "server", "timezone" ]
423f64587b0ff87ee3b46314f26b4c16e4f8f845
https://github.com/barbushin/dater/blob/423f64587b0ff87ee3b46314f26b4c16e4f8f845/src/Dater/Dater.php#L252-L254
train
barbushin/dater
src/Dater/Dater.php
Dater.serverTime
public function serverTime($serverDatetimeOrTimestamp = null) { return $this->format($serverDatetimeOrTimestamp, self::ISO_TIME_FORMAT, $this->serverTimezone); }
php
public function serverTime($serverDatetimeOrTimestamp = null) { return $this->format($serverDatetimeOrTimestamp, self::ISO_TIME_FORMAT, $this->serverTimezone); }
[ "public", "function", "serverTime", "(", "$", "serverDatetimeOrTimestamp", "=", "null", ")", "{", "return", "$", "this", "->", "format", "(", "$", "serverDatetimeOrTimestamp", ",", "self", "::", "ISO_TIME_FORMAT", ",", "$", "this", "->", "serverTimezone", ")", ";", "}" ]
Get date in HH-II-SS format, in server timezone @param string|int|null $serverDatetimeOrTimestamp @return string
[ "Get", "date", "in", "HH", "-", "II", "-", "SS", "format", "in", "server", "timezone" ]
423f64587b0ff87ee3b46314f26b4c16e4f8f845
https://github.com/barbushin/dater/blob/423f64587b0ff87ee3b46314f26b4c16e4f8f845/src/Dater/Dater.php#L261-L263
train
barbushin/dater
src/Dater/Dater.php
Dater.getTimezoneObject
protected function getTimezoneObject($timezone) { if(!isset($this->timezonesObjects[$timezone])) { $this->timezonesObjects[$timezone] = new \DateTimezone($timezone); } return $this->timezonesObjects[$timezone]; }
php
protected function getTimezoneObject($timezone) { if(!isset($this->timezonesObjects[$timezone])) { $this->timezonesObjects[$timezone] = new \DateTimezone($timezone); } return $this->timezonesObjects[$timezone]; }
[ "protected", "function", "getTimezoneObject", "(", "$", "timezone", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "timezonesObjects", "[", "$", "timezone", "]", ")", ")", "{", "$", "this", "->", "timezonesObjects", "[", "$", "timezone", "]", "=", "new", "\\", "DateTimezone", "(", "$", "timezone", ")", ";", "}", "return", "$", "this", "->", "timezonesObjects", "[", "$", "timezone", "]", ";", "}" ]
Get Datetimezone object by timezone name @param $timezone @return \DateTimezone
[ "Get", "Datetimezone", "object", "by", "timezone", "name" ]
423f64587b0ff87ee3b46314f26b4c16e4f8f845
https://github.com/barbushin/dater/blob/423f64587b0ff87ee3b46314f26b4c16e4f8f845/src/Dater/Dater.php#L300-L305
train
bringyourownideas/silverstripe-maintenance
src/Util/ComposerLoader.php
ComposerLoader.build
public function build() { $basePath = $this->getBasePath(); $composerJson = file_get_contents($basePath . '/composer.json'); $composerLock = file_get_contents($basePath . '/composer.lock'); if (!$composerJson || !$composerLock) { throw new Exception('composer.json or composer.lock could not be found!'); } $this->setJson(json_decode($composerJson)); $this->setLock(json_decode($composerLock)); $this->extend('onAfterBuild'); }
php
public function build() { $basePath = $this->getBasePath(); $composerJson = file_get_contents($basePath . '/composer.json'); $composerLock = file_get_contents($basePath . '/composer.lock'); if (!$composerJson || !$composerLock) { throw new Exception('composer.json or composer.lock could not be found!'); } $this->setJson(json_decode($composerJson)); $this->setLock(json_decode($composerLock)); $this->extend('onAfterBuild'); }
[ "public", "function", "build", "(", ")", "{", "$", "basePath", "=", "$", "this", "->", "getBasePath", "(", ")", ";", "$", "composerJson", "=", "file_get_contents", "(", "$", "basePath", ".", "'/composer.json'", ")", ";", "$", "composerLock", "=", "file_get_contents", "(", "$", "basePath", ".", "'/composer.lock'", ")", ";", "if", "(", "!", "$", "composerJson", "||", "!", "$", "composerLock", ")", "{", "throw", "new", "Exception", "(", "'composer.json or composer.lock could not be found!'", ")", ";", "}", "$", "this", "->", "setJson", "(", "json_decode", "(", "$", "composerJson", ")", ")", ";", "$", "this", "->", "setLock", "(", "json_decode", "(", "$", "composerLock", ")", ")", ";", "$", "this", "->", "extend", "(", "'onAfterBuild'", ")", ";", "}" ]
Load and build the composer.json and composer.lock files @return $this @throws Exception If either file could not be loaded
[ "Load", "and", "build", "the", "composer", ".", "json", "and", "composer", ".", "lock", "files" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Util/ComposerLoader.php#L52-L66
train
bringyourownideas/silverstripe-maintenance
src/Forms/GridFieldDropdownFilter.php
GridFieldDropdownFilter.removeFilterOption
public function removeFilterOption($name) { $this->filterOptions->remove($this->filterOptions->find('name', $name)); return $this; }
php
public function removeFilterOption($name) { $this->filterOptions->remove($this->filterOptions->find('name', $name)); return $this; }
[ "public", "function", "removeFilterOption", "(", "$", "name", ")", "{", "$", "this", "->", "filterOptions", "->", "remove", "(", "$", "this", "->", "filterOptions", "->", "find", "(", "'name'", ",", "$", "name", ")", ")", ";", "return", "$", "this", ";", "}" ]
Remove a filter option with the given name @param string $name @return $this
[ "Remove", "a", "filter", "option", "with", "the", "given", "name" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Forms/GridFieldDropdownFilter.php#L85-L89
train
esbenp/architect
src/Utility.php
Utility.setProperty
public static function setProperty(&$objectOrArray, $property, $value) { // Eloquent models are also instances of ArrayAccess, and therefore // we check for that first if ($objectOrArray instanceof EloquentModel) { // Does relation exist? // If so, only set the relation if not primitive. Keeping a attribute // as a relation will allow for it to be converted to arrays during // serialization if ($property) { if ($objectOrArray->relationLoaded($property) && !Utility::isPrimitive($value)) { $objectOrArray->setRelation($property, $value); // If attribute is not a relation we just set it on // the model directly. If it is a primitive relation (a relation // converted to IDs) we unset the relation and set it as an attribute } else { unset($objectOrArray[$property]); $objectOrArray->setAttribute($property, $value); } } } elseif (is_array($objectOrArray)) { $objectOrArray[$property] = $value; } else { $objectOrArray->{$property} = $value; } }
php
public static function setProperty(&$objectOrArray, $property, $value) { // Eloquent models are also instances of ArrayAccess, and therefore // we check for that first if ($objectOrArray instanceof EloquentModel) { // Does relation exist? // If so, only set the relation if not primitive. Keeping a attribute // as a relation will allow for it to be converted to arrays during // serialization if ($property) { if ($objectOrArray->relationLoaded($property) && !Utility::isPrimitive($value)) { $objectOrArray->setRelation($property, $value); // If attribute is not a relation we just set it on // the model directly. If it is a primitive relation (a relation // converted to IDs) we unset the relation and set it as an attribute } else { unset($objectOrArray[$property]); $objectOrArray->setAttribute($property, $value); } } } elseif (is_array($objectOrArray)) { $objectOrArray[$property] = $value; } else { $objectOrArray->{$property} = $value; } }
[ "public", "static", "function", "setProperty", "(", "&", "$", "objectOrArray", ",", "$", "property", ",", "$", "value", ")", "{", "// Eloquent models are also instances of ArrayAccess, and therefore", "// we check for that first", "if", "(", "$", "objectOrArray", "instanceof", "EloquentModel", ")", "{", "// Does relation exist?", "// If so, only set the relation if not primitive. Keeping a attribute", "// as a relation will allow for it to be converted to arrays during", "// serialization", "if", "(", "$", "property", ")", "{", "if", "(", "$", "objectOrArray", "->", "relationLoaded", "(", "$", "property", ")", "&&", "!", "Utility", "::", "isPrimitive", "(", "$", "value", ")", ")", "{", "$", "objectOrArray", "->", "setRelation", "(", "$", "property", ",", "$", "value", ")", ";", "// If attribute is not a relation we just set it on", "// the model directly. If it is a primitive relation (a relation", "// converted to IDs) we unset the relation and set it as an attribute", "}", "else", "{", "unset", "(", "$", "objectOrArray", "[", "$", "property", "]", ")", ";", "$", "objectOrArray", "->", "setAttribute", "(", "$", "property", ",", "$", "value", ")", ";", "}", "}", "}", "elseif", "(", "is_array", "(", "$", "objectOrArray", ")", ")", "{", "$", "objectOrArray", "[", "$", "property", "]", "=", "$", "value", ";", "}", "else", "{", "$", "objectOrArray", "->", "{", "$", "property", "}", "=", "$", "value", ";", "}", "}" ]
Set a property of an Eloquent model, normal object or array @param mixed $objectOrArray model, object or array @param string $property @param void
[ "Set", "a", "property", "of", "an", "Eloquent", "model", "normal", "object", "or", "array" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/Utility.php#L31-L57
train
esbenp/architect
src/ModeResolver/IdsModeResolver.php
IdsModeResolver.resolve
public function resolve($property, &$object, &$root, $fullPropertyPath) { if (is_array($object)) { // We need to determine if this is a singular relationship or // a collection of models $arrayCopy = $object; $firstElement = array_shift($arrayCopy); // The object was not a collection, and was rather a single // model, because the first item returned was a property // We therefore just return the single ID if (Utility::isPrimitive($firstElement)) { return (int) Utility::getProperty($object, 'id'); } return array_map(function ($entry) { return (int) Utility::getProperty($entry, 'id'); }, $object); } elseif ($object instanceof Collection) { return $object->map(function ($entry) { return (int) Utility::getProperty($entry, 'id'); }); // The relation is not a collection, but rather // a singular relation } elseif ($object instanceof Model) { return $object->id; } }
php
public function resolve($property, &$object, &$root, $fullPropertyPath) { if (is_array($object)) { // We need to determine if this is a singular relationship or // a collection of models $arrayCopy = $object; $firstElement = array_shift($arrayCopy); // The object was not a collection, and was rather a single // model, because the first item returned was a property // We therefore just return the single ID if (Utility::isPrimitive($firstElement)) { return (int) Utility::getProperty($object, 'id'); } return array_map(function ($entry) { return (int) Utility::getProperty($entry, 'id'); }, $object); } elseif ($object instanceof Collection) { return $object->map(function ($entry) { return (int) Utility::getProperty($entry, 'id'); }); // The relation is not a collection, but rather // a singular relation } elseif ($object instanceof Model) { return $object->id; } }
[ "public", "function", "resolve", "(", "$", "property", ",", "&", "$", "object", ",", "&", "$", "root", ",", "$", "fullPropertyPath", ")", "{", "if", "(", "is_array", "(", "$", "object", ")", ")", "{", "// We need to determine if this is a singular relationship or", "// a collection of models", "$", "arrayCopy", "=", "$", "object", ";", "$", "firstElement", "=", "array_shift", "(", "$", "arrayCopy", ")", ";", "// The object was not a collection, and was rather a single", "// model, because the first item returned was a property", "// We therefore just return the single ID", "if", "(", "Utility", "::", "isPrimitive", "(", "$", "firstElement", ")", ")", "{", "return", "(", "int", ")", "Utility", "::", "getProperty", "(", "$", "object", ",", "'id'", ")", ";", "}", "return", "array_map", "(", "function", "(", "$", "entry", ")", "{", "return", "(", "int", ")", "Utility", "::", "getProperty", "(", "$", "entry", ",", "'id'", ")", ";", "}", ",", "$", "object", ")", ";", "}", "elseif", "(", "$", "object", "instanceof", "Collection", ")", "{", "return", "$", "object", "->", "map", "(", "function", "(", "$", "entry", ")", "{", "return", "(", "int", ")", "Utility", "::", "getProperty", "(", "$", "entry", ",", "'id'", ")", ";", "}", ")", ";", "// The relation is not a collection, but rather", "// a singular relation", "}", "elseif", "(", "$", "object", "instanceof", "Model", ")", "{", "return", "$", "object", "->", "id", ";", "}", "}" ]
Map through the collection and convert it to a collection of ids @param string $property @param object $object @param array $root @param string $fullPropertyPath @return mixed
[ "Map", "through", "the", "collection", "and", "convert", "it", "to", "a", "collection", "of", "ids" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/ModeResolver/IdsModeResolver.php#L21-L48
train
bringyourownideas/silverstripe-maintenance
src/Reports/SiteSummary.php
SiteSummary.getReportField
public function getReportField() { Requirements::css('bringyourownideas/silverstripe-maintenance: client/dist/styles/bundle.css'); Requirements::javascript('bringyourownideas/silverstripe-maintenance: client/dist/js/bundle.js'); /** @var GridField $grid */ $grid = parent::getReportField(); /** @var GridFieldConfig $config */ $config = $grid->getConfig(); $grid->addExtraClass('site-summary'); $summaryFields = Package::create()->summaryFields(); /** @var GridFieldExportButton $exportButton */ $exportButton = $config->getComponentByType(GridFieldExportButton::class); $exportButton->setExportColumns($summaryFields); /** @var GridFieldPrintButton $printButton */ $printButton = $config->getComponentByType(GridFieldPrintButton::class); $printButton->setPrintColumns($summaryFields); $versionHtml = ArrayData::create([ 'Title' => _t(__CLASS__ . '.VERSION', 'Version'), 'Version' => $this->resolveCmsVersion(), 'LastUpdated' => $this->getLastUpdated(), ])->renderWith(__CLASS__ . '/VersionHeader'); $config->addComponents( Injector::inst()->create(GridFieldRefreshButton::class, 'buttons-before-left'), Injector::inst()->create( GridFieldLinkButton::class, 'https://addons.silverstripe.org', _t(__CLASS__ . '.LINK_TO_ADDONS', 'Explore Addons'), 'buttons-before-left' ), $this->getDropdownFilter(), $this->getInfoLink(), Injector::inst()->create(GridFieldHtmlFragment::class, 'header', $versionHtml) ); // Re-order the paginator to ensure it counts correctly, and reorder the buttons $paginator = $config->getComponentByType(GridFieldPaginator::class); $config->removeComponent($paginator)->addComponent($paginator); $exportButton = $config->getComponentByType(GridFieldExportButton::class); $config->removeComponent($exportButton)->addComponent($exportButton); $printButton = $config->getComponentByType(GridFieldPrintButton::class); $config->removeComponentsByType($printButton)->addComponent($printButton); return $grid; }
php
public function getReportField() { Requirements::css('bringyourownideas/silverstripe-maintenance: client/dist/styles/bundle.css'); Requirements::javascript('bringyourownideas/silverstripe-maintenance: client/dist/js/bundle.js'); /** @var GridField $grid */ $grid = parent::getReportField(); /** @var GridFieldConfig $config */ $config = $grid->getConfig(); $grid->addExtraClass('site-summary'); $summaryFields = Package::create()->summaryFields(); /** @var GridFieldExportButton $exportButton */ $exportButton = $config->getComponentByType(GridFieldExportButton::class); $exportButton->setExportColumns($summaryFields); /** @var GridFieldPrintButton $printButton */ $printButton = $config->getComponentByType(GridFieldPrintButton::class); $printButton->setPrintColumns($summaryFields); $versionHtml = ArrayData::create([ 'Title' => _t(__CLASS__ . '.VERSION', 'Version'), 'Version' => $this->resolveCmsVersion(), 'LastUpdated' => $this->getLastUpdated(), ])->renderWith(__CLASS__ . '/VersionHeader'); $config->addComponents( Injector::inst()->create(GridFieldRefreshButton::class, 'buttons-before-left'), Injector::inst()->create( GridFieldLinkButton::class, 'https://addons.silverstripe.org', _t(__CLASS__ . '.LINK_TO_ADDONS', 'Explore Addons'), 'buttons-before-left' ), $this->getDropdownFilter(), $this->getInfoLink(), Injector::inst()->create(GridFieldHtmlFragment::class, 'header', $versionHtml) ); // Re-order the paginator to ensure it counts correctly, and reorder the buttons $paginator = $config->getComponentByType(GridFieldPaginator::class); $config->removeComponent($paginator)->addComponent($paginator); $exportButton = $config->getComponentByType(GridFieldExportButton::class); $config->removeComponent($exportButton)->addComponent($exportButton); $printButton = $config->getComponentByType(GridFieldPrintButton::class); $config->removeComponentsByType($printButton)->addComponent($printButton); return $grid; }
[ "public", "function", "getReportField", "(", ")", "{", "Requirements", "::", "css", "(", "'bringyourownideas/silverstripe-maintenance: client/dist/styles/bundle.css'", ")", ";", "Requirements", "::", "javascript", "(", "'bringyourownideas/silverstripe-maintenance: client/dist/js/bundle.js'", ")", ";", "/** @var GridField $grid */", "$", "grid", "=", "parent", "::", "getReportField", "(", ")", ";", "/** @var GridFieldConfig $config */", "$", "config", "=", "$", "grid", "->", "getConfig", "(", ")", ";", "$", "grid", "->", "addExtraClass", "(", "'site-summary'", ")", ";", "$", "summaryFields", "=", "Package", "::", "create", "(", ")", "->", "summaryFields", "(", ")", ";", "/** @var GridFieldExportButton $exportButton */", "$", "exportButton", "=", "$", "config", "->", "getComponentByType", "(", "GridFieldExportButton", "::", "class", ")", ";", "$", "exportButton", "->", "setExportColumns", "(", "$", "summaryFields", ")", ";", "/** @var GridFieldPrintButton $printButton */", "$", "printButton", "=", "$", "config", "->", "getComponentByType", "(", "GridFieldPrintButton", "::", "class", ")", ";", "$", "printButton", "->", "setPrintColumns", "(", "$", "summaryFields", ")", ";", "$", "versionHtml", "=", "ArrayData", "::", "create", "(", "[", "'Title'", "=>", "_t", "(", "__CLASS__", ".", "'.VERSION'", ",", "'Version'", ")", ",", "'Version'", "=>", "$", "this", "->", "resolveCmsVersion", "(", ")", ",", "'LastUpdated'", "=>", "$", "this", "->", "getLastUpdated", "(", ")", ",", "]", ")", "->", "renderWith", "(", "__CLASS__", ".", "'/VersionHeader'", ")", ";", "$", "config", "->", "addComponents", "(", "Injector", "::", "inst", "(", ")", "->", "create", "(", "GridFieldRefreshButton", "::", "class", ",", "'buttons-before-left'", ")", ",", "Injector", "::", "inst", "(", ")", "->", "create", "(", "GridFieldLinkButton", "::", "class", ",", "'https://addons.silverstripe.org'", ",", "_t", "(", "__CLASS__", ".", "'.LINK_TO_ADDONS'", ",", "'Explore Addons'", ")", ",", "'buttons-before-left'", ")", ",", "$", "this", "->", "getDropdownFilter", "(", ")", ",", "$", "this", "->", "getInfoLink", "(", ")", ",", "Injector", "::", "inst", "(", ")", "->", "create", "(", "GridFieldHtmlFragment", "::", "class", ",", "'header'", ",", "$", "versionHtml", ")", ")", ";", "// Re-order the paginator to ensure it counts correctly, and reorder the buttons", "$", "paginator", "=", "$", "config", "->", "getComponentByType", "(", "GridFieldPaginator", "::", "class", ")", ";", "$", "config", "->", "removeComponent", "(", "$", "paginator", ")", "->", "addComponent", "(", "$", "paginator", ")", ";", "$", "exportButton", "=", "$", "config", "->", "getComponentByType", "(", "GridFieldExportButton", "::", "class", ")", ";", "$", "config", "->", "removeComponent", "(", "$", "exportButton", ")", "->", "addComponent", "(", "$", "exportButton", ")", ";", "$", "printButton", "=", "$", "config", "->", "getComponentByType", "(", "GridFieldPrintButton", "::", "class", ")", ";", "$", "config", "->", "removeComponentsByType", "(", "$", "printButton", ")", "->", "addComponent", "(", "$", "printButton", ")", ";", "return", "$", "grid", ";", "}" ]
Add a button row, including link out to the SilverStripe addons repository, and export button {@inheritdoc}
[ "Add", "a", "button", "row", "including", "link", "out", "to", "the", "SilverStripe", "addons", "repository", "and", "export", "button" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Reports/SiteSummary.php#L74-L125
train
bringyourownideas/silverstripe-maintenance
src/Reports/SiteSummary.php
SiteSummary.getDropdownFilter
protected function getDropdownFilter() { /** @var GridFieldDropdownFilter $dropdownFilter */ $dropdownFilter = Injector::inst()->create( GridFieldDropdownFilter::class, 'addonFilter', 'buttons-before-right', _t(__CLASS__ . '.ShowAllModules', 'Show all modules') ); $dropdownFilter->addFilterOption( 'supported', _t(__CLASS__ . '.FilterSupported', 'Supported modules'), ['Supported' => true] ); $dropdownFilter->addFilterOption( 'unsupported', _t(__CLASS__ . '.FilterUnsupported', 'Unsupported modules'), ['Supported' => false] ); $this->extend('updateDropdownFilterOptions', $dropdownFilter); return $dropdownFilter; }
php
protected function getDropdownFilter() { /** @var GridFieldDropdownFilter $dropdownFilter */ $dropdownFilter = Injector::inst()->create( GridFieldDropdownFilter::class, 'addonFilter', 'buttons-before-right', _t(__CLASS__ . '.ShowAllModules', 'Show all modules') ); $dropdownFilter->addFilterOption( 'supported', _t(__CLASS__ . '.FilterSupported', 'Supported modules'), ['Supported' => true] ); $dropdownFilter->addFilterOption( 'unsupported', _t(__CLASS__ . '.FilterUnsupported', 'Unsupported modules'), ['Supported' => false] ); $this->extend('updateDropdownFilterOptions', $dropdownFilter); return $dropdownFilter; }
[ "protected", "function", "getDropdownFilter", "(", ")", "{", "/** @var GridFieldDropdownFilter $dropdownFilter */", "$", "dropdownFilter", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "GridFieldDropdownFilter", "::", "class", ",", "'addonFilter'", ",", "'buttons-before-right'", ",", "_t", "(", "__CLASS__", ".", "'.ShowAllModules'", ",", "'Show all modules'", ")", ")", ";", "$", "dropdownFilter", "->", "addFilterOption", "(", "'supported'", ",", "_t", "(", "__CLASS__", ".", "'.FilterSupported'", ",", "'Supported modules'", ")", ",", "[", "'Supported'", "=>", "true", "]", ")", ";", "$", "dropdownFilter", "->", "addFilterOption", "(", "'unsupported'", ",", "_t", "(", "__CLASS__", ".", "'.FilterUnsupported'", ",", "'Unsupported modules'", ")", ",", "[", "'Supported'", "=>", "false", "]", ")", ";", "$", "this", "->", "extend", "(", "'updateDropdownFilterOptions'", ",", "$", "dropdownFilter", ")", ";", "return", "$", "dropdownFilter", ";", "}" ]
Returns a dropdown filter with user configurable options in it @return GridFieldDropdownFilter
[ "Returns", "a", "dropdown", "filter", "with", "user", "configurable", "options", "in", "it" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Reports/SiteSummary.php#L132-L156
train
bringyourownideas/silverstripe-maintenance
src/Reports/SiteSummary.php
SiteSummary.getInfoLink
protected function getInfoLink() { return Injector::inst()->create( GridFieldHtmlFragment::class, 'buttons-before-right', DBField::create_field('HTMLFragment', ArrayData::create([ 'Link' => 'https://addons.silverstripe.org/add-ons/bringyourownideas/silverstripe-maintenance', 'Label' => _t(__CLASS__ . '.MORE_INFORMATION', 'More information'), ])->renderWith(__CLASS__ . '/MoreInformationLink')) ); }
php
protected function getInfoLink() { return Injector::inst()->create( GridFieldHtmlFragment::class, 'buttons-before-right', DBField::create_field('HTMLFragment', ArrayData::create([ 'Link' => 'https://addons.silverstripe.org/add-ons/bringyourownideas/silverstripe-maintenance', 'Label' => _t(__CLASS__ . '.MORE_INFORMATION', 'More information'), ])->renderWith(__CLASS__ . '/MoreInformationLink')) ); }
[ "protected", "function", "getInfoLink", "(", ")", "{", "return", "Injector", "::", "inst", "(", ")", "->", "create", "(", "GridFieldHtmlFragment", "::", "class", ",", "'buttons-before-right'", ",", "DBField", "::", "create_field", "(", "'HTMLFragment'", ",", "ArrayData", "::", "create", "(", "[", "'Link'", "=>", "'https://addons.silverstripe.org/add-ons/bringyourownideas/silverstripe-maintenance'", ",", "'Label'", "=>", "_t", "(", "__CLASS__", ".", "'.MORE_INFORMATION'", ",", "'More information'", ")", ",", "]", ")", "->", "renderWith", "(", "__CLASS__", ".", "'/MoreInformationLink'", ")", ")", ")", ";", "}" ]
Returns a link to more information on this module on the addons site @return GridFieldHtmlFragment
[ "Returns", "a", "link", "to", "more", "information", "on", "this", "module", "on", "the", "addons", "site" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Reports/SiteSummary.php#L163-L173
train
bringyourownideas/silverstripe-maintenance
src/Reports/SiteSummary.php
SiteSummary.resolveCmsVersion
protected function resolveCmsVersion() { $versionModules = [ 'silverstripe/framework' => 'Framework', 'silverstripe/cms' => 'CMS', ]; $this->extend('updateVersionModules', $versionModules); $records = $this->sourceRecords()->filter('Name', array_keys($versionModules)); $versionParts = []; foreach ($versionModules as $name => $label) { $record = $records->find('Name', $name); if (!$record) { $version = _t(__CLASS__.'.VersionUnknown', 'Unknown'); } else { $version = $record->Version; } $versionParts[] = "$label $version"; } return implode(', ', $versionParts); }
php
protected function resolveCmsVersion() { $versionModules = [ 'silverstripe/framework' => 'Framework', 'silverstripe/cms' => 'CMS', ]; $this->extend('updateVersionModules', $versionModules); $records = $this->sourceRecords()->filter('Name', array_keys($versionModules)); $versionParts = []; foreach ($versionModules as $name => $label) { $record = $records->find('Name', $name); if (!$record) { $version = _t(__CLASS__.'.VersionUnknown', 'Unknown'); } else { $version = $record->Version; } $versionParts[] = "$label $version"; } return implode(', ', $versionParts); }
[ "protected", "function", "resolveCmsVersion", "(", ")", "{", "$", "versionModules", "=", "[", "'silverstripe/framework'", "=>", "'Framework'", ",", "'silverstripe/cms'", "=>", "'CMS'", ",", "]", ";", "$", "this", "->", "extend", "(", "'updateVersionModules'", ",", "$", "versionModules", ")", ";", "$", "records", "=", "$", "this", "->", "sourceRecords", "(", ")", "->", "filter", "(", "'Name'", ",", "array_keys", "(", "$", "versionModules", ")", ")", ";", "$", "versionParts", "=", "[", "]", ";", "foreach", "(", "$", "versionModules", "as", "$", "name", "=>", "$", "label", ")", "{", "$", "record", "=", "$", "records", "->", "find", "(", "'Name'", ",", "$", "name", ")", ";", "if", "(", "!", "$", "record", ")", "{", "$", "version", "=", "_t", "(", "__CLASS__", ".", "'.VersionUnknown'", ",", "'Unknown'", ")", ";", "}", "else", "{", "$", "version", "=", "$", "record", "->", "Version", ";", "}", "$", "versionParts", "[", "]", "=", "\"$label $version\"", ";", "}", "return", "implode", "(", "', '", ",", "$", "versionParts", ")", ";", "}" ]
Extract CMS and Framework version details from the records in the report @return string
[ "Extract", "CMS", "and", "Framework", "version", "details", "from", "the", "records", "in", "the", "report" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Reports/SiteSummary.php#L204-L227
train
bringyourownideas/silverstripe-maintenance
src/Reports/SiteSummary.php
SiteSummary.getLastUpdated
public function getLastUpdated() { $packages = Package::get()->limit(1); if (!$packages->count()) { return ''; } /** @var DBDatetime $datetime */ $datetime = $packages->first()->dbObject('LastEdited'); return $datetime->Date() . ' ' . $datetime->Time12(); }
php
public function getLastUpdated() { $packages = Package::get()->limit(1); if (!$packages->count()) { return ''; } /** @var DBDatetime $datetime */ $datetime = $packages->first()->dbObject('LastEdited'); return $datetime->Date() . ' ' . $datetime->Time12(); }
[ "public", "function", "getLastUpdated", "(", ")", "{", "$", "packages", "=", "Package", "::", "get", "(", ")", "->", "limit", "(", "1", ")", ";", "if", "(", "!", "$", "packages", "->", "count", "(", ")", ")", "{", "return", "''", ";", "}", "/** @var DBDatetime $datetime */", "$", "datetime", "=", "$", "packages", "->", "first", "(", ")", "->", "dbObject", "(", "'LastEdited'", ")", ";", "return", "$", "datetime", "->", "Date", "(", ")", ".", "' '", ".", "$", "datetime", "->", "Time12", "(", ")", ";", "}" ]
Get the "last updated" date for the report. This is based on the modified date of any of the records, since they are regenerated when the report is generated. @return string
[ "Get", "the", "last", "updated", "date", "for", "the", "report", ".", "This", "is", "based", "on", "the", "modified", "date", "of", "any", "of", "the", "records", "since", "they", "are", "regenerated", "when", "the", "report", "is", "generated", "." ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Reports/SiteSummary.php#L235-L244
train
esbenp/architect
src/ModeResolver/SideloadModeResolver.php
SideloadModeResolver.resolve
public function resolve($property, &$object, &$root, $fullPropertyPath) { $this->addCollectionToRoot($root, $object, $fullPropertyPath); return $this->idsResolver->resolve($property, $object, $root, $fullPropertyPath); }
php
public function resolve($property, &$object, &$root, $fullPropertyPath) { $this->addCollectionToRoot($root, $object, $fullPropertyPath); return $this->idsResolver->resolve($property, $object, $root, $fullPropertyPath); }
[ "public", "function", "resolve", "(", "$", "property", ",", "&", "$", "object", ",", "&", "$", "root", ",", "$", "fullPropertyPath", ")", "{", "$", "this", "->", "addCollectionToRoot", "(", "$", "root", ",", "$", "object", ",", "$", "fullPropertyPath", ")", ";", "return", "$", "this", "->", "idsResolver", "->", "resolve", "(", "$", "property", ",", "$", "object", ",", "$", "root", ",", "$", "fullPropertyPath", ")", ";", "}" ]
Move all relational resources to the root element and use idsResolver to replace them with a collection of identifiers @param string $property The property to resolve @param object $object The object which has the property @param array $root The root array which will contain the object @param string $fullPropertyPath The full dotnotation path to this property @return mixed
[ "Move", "all", "relational", "resources", "to", "the", "root", "element", "and", "use", "idsResolver", "to", "replace", "them", "with", "a", "collection", "of", "identifiers" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/ModeResolver/SideloadModeResolver.php#L29-L34
train
esbenp/architect
src/ModeResolver/SideloadModeResolver.php
SideloadModeResolver.addCollectionToRoot
private function addCollectionToRoot(&$root, &$object, $fullPropertyPath) { // First determine if the $object is a resource or a // collection of resources $isResource = false; if (is_array($object)) { $copy = $object; $values = array_values($copy); $firstPropertyOrResource = array_shift($values); if (Utility::isPrimitive($firstPropertyOrResource)) { $isResource = true; } } elseif ($object instanceof EloquentModel) { $isResource = true; } $newCollection = $isResource ? [$object] : $object; // Does existing collections use arrays or Collections $copy = $root; $values = array_values($copy); $existingRootCollection = array_shift($values); $newCollection = $existingRootCollection instanceof Collection ? new Collection($newCollection) : $newCollection; if (!array_key_exists($fullPropertyPath, $root)) { $root[$fullPropertyPath] = $newCollection; } else { $this->mergeRootCollection($root[$fullPropertyPath], $newCollection); } }
php
private function addCollectionToRoot(&$root, &$object, $fullPropertyPath) { // First determine if the $object is a resource or a // collection of resources $isResource = false; if (is_array($object)) { $copy = $object; $values = array_values($copy); $firstPropertyOrResource = array_shift($values); if (Utility::isPrimitive($firstPropertyOrResource)) { $isResource = true; } } elseif ($object instanceof EloquentModel) { $isResource = true; } $newCollection = $isResource ? [$object] : $object; // Does existing collections use arrays or Collections $copy = $root; $values = array_values($copy); $existingRootCollection = array_shift($values); $newCollection = $existingRootCollection instanceof Collection ? new Collection($newCollection) : $newCollection; if (!array_key_exists($fullPropertyPath, $root)) { $root[$fullPropertyPath] = $newCollection; } else { $this->mergeRootCollection($root[$fullPropertyPath], $newCollection); } }
[ "private", "function", "addCollectionToRoot", "(", "&", "$", "root", ",", "&", "$", "object", ",", "$", "fullPropertyPath", ")", "{", "// First determine if the $object is a resource or a", "// collection of resources", "$", "isResource", "=", "false", ";", "if", "(", "is_array", "(", "$", "object", ")", ")", "{", "$", "copy", "=", "$", "object", ";", "$", "values", "=", "array_values", "(", "$", "copy", ")", ";", "$", "firstPropertyOrResource", "=", "array_shift", "(", "$", "values", ")", ";", "if", "(", "Utility", "::", "isPrimitive", "(", "$", "firstPropertyOrResource", ")", ")", "{", "$", "isResource", "=", "true", ";", "}", "}", "elseif", "(", "$", "object", "instanceof", "EloquentModel", ")", "{", "$", "isResource", "=", "true", ";", "}", "$", "newCollection", "=", "$", "isResource", "?", "[", "$", "object", "]", ":", "$", "object", ";", "// Does existing collections use arrays or Collections", "$", "copy", "=", "$", "root", ";", "$", "values", "=", "array_values", "(", "$", "copy", ")", ";", "$", "existingRootCollection", "=", "array_shift", "(", "$", "values", ")", ";", "$", "newCollection", "=", "$", "existingRootCollection", "instanceof", "Collection", "?", "new", "Collection", "(", "$", "newCollection", ")", ":", "$", "newCollection", ";", "if", "(", "!", "array_key_exists", "(", "$", "fullPropertyPath", ",", "$", "root", ")", ")", "{", "$", "root", "[", "$", "fullPropertyPath", "]", "=", "$", "newCollection", ";", "}", "else", "{", "$", "this", "->", "mergeRootCollection", "(", "$", "root", "[", "$", "fullPropertyPath", "]", ",", "$", "newCollection", ")", ";", "}", "}" ]
Add the collection to the root array @param array $root @param object $object @param string $fullPropertyPath @return void
[ "Add", "the", "collection", "to", "the", "root", "array" ]
1719a25ca2f8cde1520bdb898c317f695b84e7b8
https://github.com/esbenp/architect/blob/1719a25ca2f8cde1520bdb898c317f695b84e7b8/src/ModeResolver/SideloadModeResolver.php#L43-L75
train
bringyourownideas/silverstripe-maintenance
src/Model/Package.php
Package.getDataSchema
public function getDataSchema() { $schema = [ 'description' => $this->Description, 'link' => 'https://addons.silverstripe.org/add-ons/' . $this->Name, 'linkTitle' => _t( __CLASS__ . '.ADDONS_LINK_TITLE', 'View {package} on addons.silverstripe.org', ['package' => $this->Title] ), 'rating'=> (int) $this->Rating ]; $this->extend('updateDataSchema', $schema); return $schema; }
php
public function getDataSchema() { $schema = [ 'description' => $this->Description, 'link' => 'https://addons.silverstripe.org/add-ons/' . $this->Name, 'linkTitle' => _t( __CLASS__ . '.ADDONS_LINK_TITLE', 'View {package} on addons.silverstripe.org', ['package' => $this->Title] ), 'rating'=> (int) $this->Rating ]; $this->extend('updateDataSchema', $schema); return $schema; }
[ "public", "function", "getDataSchema", "(", ")", "{", "$", "schema", "=", "[", "'description'", "=>", "$", "this", "->", "Description", ",", "'link'", "=>", "'https://addons.silverstripe.org/add-ons/'", ".", "$", "this", "->", "Name", ",", "'linkTitle'", "=>", "_t", "(", "__CLASS__", ".", "'.ADDONS_LINK_TITLE'", ",", "'View {package} on addons.silverstripe.org'", ",", "[", "'package'", "=>", "$", "this", "->", "Title", "]", ")", ",", "'rating'", "=>", "(", "int", ")", "$", "this", "->", "Rating", "]", ";", "$", "this", "->", "extend", "(", "'updateDataSchema'", ",", "$", "schema", ")", ";", "return", "$", "schema", ";", "}" ]
Returns a JSON data schema for the frontend React components to use @return array
[ "Returns", "a", "JSON", "data", "schema", "for", "the", "frontend", "React", "components", "to", "use" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Model/Package.php#L119-L135
train
bringyourownideas/silverstripe-maintenance
src/Model/Package.php
Package.requireDefaultRecords
public function requireDefaultRecords() { parent::requireDefaultRecords(); $pendingJobs = QueuedJobDescriptor::get()->filter([ 'Implementation' => CheckForUpdatesJob::class, 'JobStatus' => [ QueuedJob::STATUS_NEW, QueuedJob::STATUS_INIT, QueuedJob::STATUS_RUN, ], ]); if ($pendingJobs->count()) { return; } /** @var QueuedJobService $jobService */ $jobService = QueuedJobService::singleton(); $jobService->queueJob(Injector::inst()->create(CheckForUpdatesJob::class)); }
php
public function requireDefaultRecords() { parent::requireDefaultRecords(); $pendingJobs = QueuedJobDescriptor::get()->filter([ 'Implementation' => CheckForUpdatesJob::class, 'JobStatus' => [ QueuedJob::STATUS_NEW, QueuedJob::STATUS_INIT, QueuedJob::STATUS_RUN, ], ]); if ($pendingJobs->count()) { return; } /** @var QueuedJobService $jobService */ $jobService = QueuedJobService::singleton(); $jobService->queueJob(Injector::inst()->create(CheckForUpdatesJob::class)); }
[ "public", "function", "requireDefaultRecords", "(", ")", "{", "parent", "::", "requireDefaultRecords", "(", ")", ";", "$", "pendingJobs", "=", "QueuedJobDescriptor", "::", "get", "(", ")", "->", "filter", "(", "[", "'Implementation'", "=>", "CheckForUpdatesJob", "::", "class", ",", "'JobStatus'", "=>", "[", "QueuedJob", "::", "STATUS_NEW", ",", "QueuedJob", "::", "STATUS_INIT", ",", "QueuedJob", "::", "STATUS_RUN", ",", "]", ",", "]", ")", ";", "if", "(", "$", "pendingJobs", "->", "count", "(", ")", ")", "{", "return", ";", "}", "/** @var QueuedJobService $jobService */", "$", "jobService", "=", "QueuedJobService", "::", "singleton", "(", ")", ";", "$", "jobService", "->", "queueJob", "(", "Injector", "::", "inst", "(", ")", "->", "create", "(", "CheckForUpdatesJob", "::", "class", ")", ")", ";", "}" ]
Queue up a job to check for updates to packages if there isn't a pending job in the queue already
[ "Queue", "up", "a", "job", "to", "check", "for", "updates", "to", "packages", "if", "there", "isn", "t", "a", "pending", "job", "in", "the", "queue", "already" ]
47f6eb9a01fb48d779fcac2157ea066a07c09e8e
https://github.com/bringyourownideas/silverstripe-maintenance/blob/47f6eb9a01fb48d779fcac2157ea066a07c09e8e/src/Model/Package.php#L140-L159
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.getBundeled
public function getBundeled() : array { $directory = MODULARITY_PATH . 'source/php/Module/'; $bundeled = array(); foreach (@glob($directory . "*", GLOB_ONLYDIR) as $folder) { $bundeled[$folder] = basename($folder); } return $bundeled; }
php
public function getBundeled() : array { $directory = MODULARITY_PATH . 'source/php/Module/'; $bundeled = array(); foreach (@glob($directory . "*", GLOB_ONLYDIR) as $folder) { $bundeled[$folder] = basename($folder); } return $bundeled; }
[ "public", "function", "getBundeled", "(", ")", ":", "array", "{", "$", "directory", "=", "MODULARITY_PATH", ".", "'source/php/Module/'", ";", "$", "bundeled", "=", "array", "(", ")", ";", "foreach", "(", "@", "glob", "(", "$", "directory", ".", "\"*\"", ",", "GLOB_ONLYDIR", ")", "as", "$", "folder", ")", "{", "$", "bundeled", "[", "$", "folder", "]", "=", "basename", "(", "$", "folder", ")", ";", "}", "return", "$", "bundeled", ";", "}" ]
Gets bundeled modules @return array
[ "Gets", "bundeled", "modules" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L115-L125
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.prefixSlug
public static function prefixSlug(string $slug) : string { if (substr($slug, 0, strlen(self::MODULE_PREFIX)) !== self::MODULE_PREFIX) { $slug = self::MODULE_PREFIX . $slug; } if (strlen($slug) > 20) { $slug = substr($slug, 0, 20); } $slug = strtolower($slug); return $slug; }
php
public static function prefixSlug(string $slug) : string { if (substr($slug, 0, strlen(self::MODULE_PREFIX)) !== self::MODULE_PREFIX) { $slug = self::MODULE_PREFIX . $slug; } if (strlen($slug) > 20) { $slug = substr($slug, 0, 20); } $slug = strtolower($slug); return $slug; }
[ "public", "static", "function", "prefixSlug", "(", "string", "$", "slug", ")", ":", "string", "{", "if", "(", "substr", "(", "$", "slug", ",", "0", ",", "strlen", "(", "self", "::", "MODULE_PREFIX", ")", ")", "!==", "self", "::", "MODULE_PREFIX", ")", "{", "$", "slug", "=", "self", "::", "MODULE_PREFIX", ".", "$", "slug", ";", "}", "if", "(", "strlen", "(", "$", "slug", ")", ">", "20", ")", "{", "$", "slug", "=", "substr", "(", "$", "slug", ",", "0", ",", "20", ")", ";", "}", "$", "slug", "=", "strtolower", "(", "$", "slug", ")", ";", "return", "$", "slug", ";", "}" ]
Prefixes module post type slug if needed @param string $slug @return string
[ "Prefixes", "module", "post", "type", "slug", "if", "needed" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L295-L308
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.getIcon
public function getIcon(string $path, $class) : string { if (file_exists($path . '/assets/icon.svg')) { return file_get_contents($path . '/assets/icon.svg'); } // If fail to load (may happen on some systems) TODO: Make this more fancy if (file_exists($path . preg_replace('/\s+/', '', ucwords($class->nameSingular)). '/assets/icon.svg')) { return file_get_contents($path . preg_replace('/\s+/', '', ucwords($class->nameSingular)). '/assets/icon.svg'); } return ''; }
php
public function getIcon(string $path, $class) : string { if (file_exists($path . '/assets/icon.svg')) { return file_get_contents($path . '/assets/icon.svg'); } // If fail to load (may happen on some systems) TODO: Make this more fancy if (file_exists($path . preg_replace('/\s+/', '', ucwords($class->nameSingular)). '/assets/icon.svg')) { return file_get_contents($path . preg_replace('/\s+/', '', ucwords($class->nameSingular)). '/assets/icon.svg'); } return ''; }
[ "public", "function", "getIcon", "(", "string", "$", "path", ",", "$", "class", ")", ":", "string", "{", "if", "(", "file_exists", "(", "$", "path", ".", "'/assets/icon.svg'", ")", ")", "{", "return", "file_get_contents", "(", "$", "path", ".", "'/assets/icon.svg'", ")", ";", "}", "// If fail to load (may happen on some systems) TODO: Make this more fancy", "if", "(", "file_exists", "(", "$", "path", ".", "preg_replace", "(", "'/\\s+/'", ",", "''", ",", "ucwords", "(", "$", "class", "->", "nameSingular", ")", ")", ".", "'/assets/icon.svg'", ")", ")", "{", "return", "file_get_contents", "(", "$", "path", ".", "preg_replace", "(", "'/\\s+/'", ",", "''", ",", "ucwords", "(", "$", "class", "->", "nameSingular", ")", ")", ".", "'/assets/icon.svg'", ")", ";", "}", "return", "''", ";", "}" ]
Get bundeled icon @param string $path Path to module folder @return string
[ "Get", "bundeled", "icon" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L315-L327
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.hideTitleCheckbox
public function hideTitleCheckbox() { global $post; if (substr($post->post_type, 0, 4) != 'mod-') { return; } $current = self::$moduleSettings[$post->post_type]['hide_title']; if (strlen(get_post_meta($post->ID, 'modularity-module-hide-title', true)) > 0) { $current = boolval(get_post_meta($post->ID, 'modularity-module-hide-title', true)); } $checked = checked(true, $current, false); echo '<div> <label style="cursor:pointer;"> <input type="checkbox" name="modularity-module-hide-title" value="1" ' . $checked . '> ' . __('Hide title', 'modularity') . ' </label> </div>'; }
php
public function hideTitleCheckbox() { global $post; if (substr($post->post_type, 0, 4) != 'mod-') { return; } $current = self::$moduleSettings[$post->post_type]['hide_title']; if (strlen(get_post_meta($post->ID, 'modularity-module-hide-title', true)) > 0) { $current = boolval(get_post_meta($post->ID, 'modularity-module-hide-title', true)); } $checked = checked(true, $current, false); echo '<div> <label style="cursor:pointer;"> <input type="checkbox" name="modularity-module-hide-title" value="1" ' . $checked . '> ' . __('Hide title', 'modularity') . ' </label> </div>'; }
[ "public", "function", "hideTitleCheckbox", "(", ")", "{", "global", "$", "post", ";", "if", "(", "substr", "(", "$", "post", "->", "post_type", ",", "0", ",", "4", ")", "!=", "'mod-'", ")", "{", "return", ";", "}", "$", "current", "=", "self", "::", "$", "moduleSettings", "[", "$", "post", "->", "post_type", "]", "[", "'hide_title'", "]", ";", "if", "(", "strlen", "(", "get_post_meta", "(", "$", "post", "->", "ID", ",", "'modularity-module-hide-title'", ",", "true", ")", ")", ">", "0", ")", "{", "$", "current", "=", "boolval", "(", "get_post_meta", "(", "$", "post", "->", "ID", ",", "'modularity-module-hide-title'", ",", "true", ")", ")", ";", "}", "$", "checked", "=", "checked", "(", "true", ",", "$", "current", ",", "false", ")", ";", "echo", "'<div>\n <label style=\"cursor:pointer;\">\n <input type=\"checkbox\" name=\"modularity-module-hide-title\" value=\"1\" '", ".", "$", "checked", ".", "'>\n '", ".", "__", "(", "'Hide title'", ",", "'modularity'", ")", ".", "'\n </label>\n </div>'", ";", "}" ]
Adds checkbox to post edit page to hide title @return void
[ "Adds", "checkbox", "to", "post", "edit", "page", "to", "hide", "title" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L348-L370
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.saveHideTitleCheckbox
public function saveHideTitleCheckbox($postId, $post) { if (substr($post->post_type, 0, 4) != 'mod-') { return; } if (!isset($_POST['modularity-module-hide-title'])) { update_post_meta($post->ID, 'modularity-module-hide-title', 0); return; } update_post_meta($post->ID, 'modularity-module-hide-title', 1); return; }
php
public function saveHideTitleCheckbox($postId, $post) { if (substr($post->post_type, 0, 4) != 'mod-') { return; } if (!isset($_POST['modularity-module-hide-title'])) { update_post_meta($post->ID, 'modularity-module-hide-title', 0); return; } update_post_meta($post->ID, 'modularity-module-hide-title', 1); return; }
[ "public", "function", "saveHideTitleCheckbox", "(", "$", "postId", ",", "$", "post", ")", "{", "if", "(", "substr", "(", "$", "post", "->", "post_type", ",", "0", ",", "4", ")", "!=", "'mod-'", ")", "{", "return", ";", "}", "if", "(", "!", "isset", "(", "$", "_POST", "[", "'modularity-module-hide-title'", "]", ")", ")", "{", "update_post_meta", "(", "$", "post", "->", "ID", ",", "'modularity-module-hide-title'", ",", "0", ")", ";", "return", ";", "}", "update_post_meta", "(", "$", "post", "->", "ID", ",", "'modularity-module-hide-title'", ",", "1", ")", ";", "return", ";", "}" ]
Saves the hide title checkboc @param int $postId @param WP_Post $post @return void
[ "Saves", "the", "hide", "title", "checkboc" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L378-L391
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.whereUsedMetaBox
public function whereUsedMetaBox() { if (empty(self::$enabled)) { return; } global $post; $module = $this; if (is_null($post)) { return; } $usage = self::getModuleUsage($post->ID); add_meta_box('modularity-usage', 'Module usage', function () use ($module, $usage) { if (count($usage) == 0) { echo '<p>' . __('This modules is not used yet.', 'modularity') . '</p>'; return; } echo '<p>' . __('This module is used on the following places:', 'modularity') . '</p><p><ul class="modularity-usage-list">'; foreach ($usage as $page) { echo '<li><a href="' . get_permalink($page->post_id) . '">' . $page->post_title . '</a></li>'; } echo '</ul></p>'; }, self::$enabled, 'side', 'default'); }
php
public function whereUsedMetaBox() { if (empty(self::$enabled)) { return; } global $post; $module = $this; if (is_null($post)) { return; } $usage = self::getModuleUsage($post->ID); add_meta_box('modularity-usage', 'Module usage', function () use ($module, $usage) { if (count($usage) == 0) { echo '<p>' . __('This modules is not used yet.', 'modularity') . '</p>'; return; } echo '<p>' . __('This module is used on the following places:', 'modularity') . '</p><p><ul class="modularity-usage-list">'; foreach ($usage as $page) { echo '<li><a href="' . get_permalink($page->post_id) . '">' . $page->post_title . '</a></li>'; } echo '</ul></p>'; }, self::$enabled, 'side', 'default'); }
[ "public", "function", "whereUsedMetaBox", "(", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "enabled", ")", ")", "{", "return", ";", "}", "global", "$", "post", ";", "$", "module", "=", "$", "this", ";", "if", "(", "is_null", "(", "$", "post", ")", ")", "{", "return", ";", "}", "$", "usage", "=", "self", "::", "getModuleUsage", "(", "$", "post", "->", "ID", ")", ";", "add_meta_box", "(", "'modularity-usage'", ",", "'Module usage'", ",", "function", "(", ")", "use", "(", "$", "module", ",", "$", "usage", ")", "{", "if", "(", "count", "(", "$", "usage", ")", "==", "0", ")", "{", "echo", "'<p>'", ".", "__", "(", "'This modules is not used yet.'", ",", "'modularity'", ")", ".", "'</p>'", ";", "return", ";", "}", "echo", "'<p>'", ".", "__", "(", "'This module is used on the following places:'", ",", "'modularity'", ")", ".", "'</p><p><ul class=\"modularity-usage-list\">'", ";", "foreach", "(", "$", "usage", "as", "$", "page", ")", "{", "echo", "'<li><a href=\"'", ".", "get_permalink", "(", "$", "page", "->", "post_id", ")", ".", "'\">'", ".", "$", "page", "->", "post_title", ".", "'</a></li>'", ";", "}", "echo", "'</ul></p>'", ";", "}", ",", "self", "::", "$", "enabled", ",", "'side'", ",", "'default'", ")", ";", "}" ]
Metabox that shows where the module is used @return void
[ "Metabox", "that", "shows", "where", "the", "module", "is", "used" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L432-L461
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.getModuleUsage
public static function getModuleUsage($id, $limit = false) { global $wpdb; // Normal modules $query = " SELECT {$wpdb->postmeta}.post_id, {$wpdb->posts}.post_title, {$wpdb->posts}.post_type FROM {$wpdb->postmeta} LEFT JOIN {$wpdb->posts} ON ({$wpdb->postmeta}.post_id = {$wpdb->posts}.ID) WHERE {$wpdb->postmeta}.meta_key = 'modularity-modules' AND ({$wpdb->postmeta}.meta_value REGEXP '.*\"postid\";s:[0-9]+:\"{$id}\".*') AND {$wpdb->posts}.post_type != 'revision' ORDER BY {$wpdb->posts}.post_title ASC "; $modules = $wpdb->get_results($query, OBJECT); // Shortcode modules $query = " SELECT {$wpdb->posts}.ID AS post_id, {$wpdb->posts}.post_title, {$wpdb->posts}.post_type FROM {$wpdb->posts} WHERE ({$wpdb->posts}.post_content REGEXP '([\[]modularity.*id=\"{$id}\".*[\]])') AND {$wpdb->posts}.post_type != 'revision' ORDER BY {$wpdb->posts}.post_title ASC "; $shortcodes = $wpdb->get_results($query, OBJECT); $result = array_merge($modules, $shortcodes); if (is_numeric($limit)) { if (count($result) > $limit) { $sliced = array_slice($result, $limit); } else { $sliced = $result; } return (object) array( 'data' => $sliced, 'more' => (count($result) > 0 && count($sliced) > 0) ? count($result) - count($sliced) : 0 ); } return $result; }
php
public static function getModuleUsage($id, $limit = false) { global $wpdb; // Normal modules $query = " SELECT {$wpdb->postmeta}.post_id, {$wpdb->posts}.post_title, {$wpdb->posts}.post_type FROM {$wpdb->postmeta} LEFT JOIN {$wpdb->posts} ON ({$wpdb->postmeta}.post_id = {$wpdb->posts}.ID) WHERE {$wpdb->postmeta}.meta_key = 'modularity-modules' AND ({$wpdb->postmeta}.meta_value REGEXP '.*\"postid\";s:[0-9]+:\"{$id}\".*') AND {$wpdb->posts}.post_type != 'revision' ORDER BY {$wpdb->posts}.post_title ASC "; $modules = $wpdb->get_results($query, OBJECT); // Shortcode modules $query = " SELECT {$wpdb->posts}.ID AS post_id, {$wpdb->posts}.post_title, {$wpdb->posts}.post_type FROM {$wpdb->posts} WHERE ({$wpdb->posts}.post_content REGEXP '([\[]modularity.*id=\"{$id}\".*[\]])') AND {$wpdb->posts}.post_type != 'revision' ORDER BY {$wpdb->posts}.post_title ASC "; $shortcodes = $wpdb->get_results($query, OBJECT); $result = array_merge($modules, $shortcodes); if (is_numeric($limit)) { if (count($result) > $limit) { $sliced = array_slice($result, $limit); } else { $sliced = $result; } return (object) array( 'data' => $sliced, 'more' => (count($result) > 0 && count($sliced) > 0) ? count($result) - count($sliced) : 0 ); } return $result; }
[ "public", "static", "function", "getModuleUsage", "(", "$", "id", ",", "$", "limit", "=", "false", ")", "{", "global", "$", "wpdb", ";", "// Normal modules", "$", "query", "=", "\"\n SELECT\n {$wpdb->postmeta}.post_id,\n {$wpdb->posts}.post_title,\n {$wpdb->posts}.post_type\n FROM {$wpdb->postmeta}\n LEFT JOIN\n {$wpdb->posts} ON ({$wpdb->postmeta}.post_id = {$wpdb->posts}.ID)\n WHERE\n {$wpdb->postmeta}.meta_key = 'modularity-modules'\n AND ({$wpdb->postmeta}.meta_value REGEXP '.*\\\"postid\\\";s:[0-9]+:\\\"{$id}\\\".*')\n AND {$wpdb->posts}.post_type != 'revision'\n ORDER BY {$wpdb->posts}.post_title ASC\n \"", ";", "$", "modules", "=", "$", "wpdb", "->", "get_results", "(", "$", "query", ",", "OBJECT", ")", ";", "// Shortcode modules", "$", "query", "=", "\"\n SELECT\n {$wpdb->posts}.ID AS post_id,\n {$wpdb->posts}.post_title,\n {$wpdb->posts}.post_type\n FROM {$wpdb->posts}\n WHERE\n ({$wpdb->posts}.post_content REGEXP '([\\[]modularity.*id=\\\"{$id}\\\".*[\\]])')\n AND {$wpdb->posts}.post_type != 'revision'\n ORDER BY {$wpdb->posts}.post_title ASC\n \"", ";", "$", "shortcodes", "=", "$", "wpdb", "->", "get_results", "(", "$", "query", ",", "OBJECT", ")", ";", "$", "result", "=", "array_merge", "(", "$", "modules", ",", "$", "shortcodes", ")", ";", "if", "(", "is_numeric", "(", "$", "limit", ")", ")", "{", "if", "(", "count", "(", "$", "result", ")", ">", "$", "limit", ")", "{", "$", "sliced", "=", "array_slice", "(", "$", "result", ",", "$", "limit", ")", ";", "}", "else", "{", "$", "sliced", "=", "$", "result", ";", "}", "return", "(", "object", ")", "array", "(", "'data'", "=>", "$", "sliced", ",", "'more'", "=>", "(", "count", "(", "$", "result", ")", ">", "0", "&&", "count", "(", "$", "sliced", ")", ">", "0", ")", "?", "count", "(", "$", "result", ")", "-", "count", "(", "$", "sliced", ")", ":", "0", ")", ";", "}", "return", "$", "result", ";", "}" ]
Search database for where the module is used @param integer $id Module id @return array List of pages where the module is used
[ "Search", "database", "for", "where", "the", "module", "is", "used" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L468-L521
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.descriptionMetabox
public function descriptionMetabox() { if (empty(self::$enabled)) { return; } add_meta_box( 'modularity-description', __('Module description', 'modularity'), function () { $description = get_post_meta(get_the_id(), 'module-description', true); include MODULARITY_TEMPLATE_PATH . 'editor/modularity-module-description.php'; }, self::$enabled, 'normal', 'high' ); }
php
public function descriptionMetabox() { if (empty(self::$enabled)) { return; } add_meta_box( 'modularity-description', __('Module description', 'modularity'), function () { $description = get_post_meta(get_the_id(), 'module-description', true); include MODULARITY_TEMPLATE_PATH . 'editor/modularity-module-description.php'; }, self::$enabled, 'normal', 'high' ); }
[ "public", "function", "descriptionMetabox", "(", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "enabled", ")", ")", "{", "return", ";", "}", "add_meta_box", "(", "'modularity-description'", ",", "__", "(", "'Module description'", ",", "'modularity'", ")", ",", "function", "(", ")", "{", "$", "description", "=", "get_post_meta", "(", "get_the_id", "(", ")", ",", "'module-description'", ",", "true", ")", ";", "include", "MODULARITY_TEMPLATE_PATH", ".", "'editor/modularity-module-description.php'", ";", "}", ",", "self", "::", "$", "enabled", ",", "'normal'", ",", "'high'", ")", ";", "}" ]
Description metabox content @return void
[ "Description", "metabox", "content" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L527-L544
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.setupListTableField
public function setupListTableField($slug) { add_filter('manage_edit-' . $slug . '_columns', array($this, 'listTableColumns')); add_action('manage_' . $slug . '_posts_custom_column', array($this, 'listTableColumnContent'), 10, 2); add_filter('manage_edit-' . $slug . '_sortable_columns', array($this, 'listTableColumnSorting')); }
php
public function setupListTableField($slug) { add_filter('manage_edit-' . $slug . '_columns', array($this, 'listTableColumns')); add_action('manage_' . $slug . '_posts_custom_column', array($this, 'listTableColumnContent'), 10, 2); add_filter('manage_edit-' . $slug . '_sortable_columns', array($this, 'listTableColumnSorting')); }
[ "public", "function", "setupListTableField", "(", "$", "slug", ")", "{", "add_filter", "(", "'manage_edit-'", ".", "$", "slug", ".", "'_columns'", ",", "array", "(", "$", "this", ",", "'listTableColumns'", ")", ")", ";", "add_action", "(", "'manage_'", ".", "$", "slug", ".", "'_posts_custom_column'", ",", "array", "(", "$", "this", ",", "'listTableColumnContent'", ")", ",", "10", ",", "2", ")", ";", "add_filter", "(", "'manage_edit-'", ".", "$", "slug", ".", "'_sortable_columns'", ",", "array", "(", "$", "this", ",", "'listTableColumnSorting'", ")", ")", ";", "}" ]
Setup list table fields @return void
[ "Setup", "list", "table", "fields" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L563-L568
train
helsingborg-stad/Modularity
source/php/ModuleManager.php
ModuleManager.listTableColumnContent
public function listTableColumnContent($column, $postId) { switch ($column) { case 'description': $description = get_post_meta($postId, 'module-description', true); echo !empty($description) ? $description : ''; break; case 'usage': $usage = self::getModuleUsage($postId, 3); if (count($usage->data) == 0) { echo __('Not used', 'modularity'); break; } $i = 0; foreach ($usage->data as $item) { $i++; if ($i > 1) { echo ', '; } echo '<a href="' . get_permalink($item->post_id) . '">' . $item->post_title . '</a>'; } if ($usage->more > 0) { echo ' (' . $usage->more . ' ' . __('more', 'modularity') . ')'; } break; } }
php
public function listTableColumnContent($column, $postId) { switch ($column) { case 'description': $description = get_post_meta($postId, 'module-description', true); echo !empty($description) ? $description : ''; break; case 'usage': $usage = self::getModuleUsage($postId, 3); if (count($usage->data) == 0) { echo __('Not used', 'modularity'); break; } $i = 0; foreach ($usage->data as $item) { $i++; if ($i > 1) { echo ', '; } echo '<a href="' . get_permalink($item->post_id) . '">' . $item->post_title . '</a>'; } if ($usage->more > 0) { echo ' (' . $usage->more . ' ' . __('more', 'modularity') . ')'; } break; } }
[ "public", "function", "listTableColumnContent", "(", "$", "column", ",", "$", "postId", ")", "{", "switch", "(", "$", "column", ")", "{", "case", "'description'", ":", "$", "description", "=", "get_post_meta", "(", "$", "postId", ",", "'module-description'", ",", "true", ")", ";", "echo", "!", "empty", "(", "$", "description", ")", "?", "$", "description", ":", "''", ";", "break", ";", "case", "'usage'", ":", "$", "usage", "=", "self", "::", "getModuleUsage", "(", "$", "postId", ",", "3", ")", ";", "if", "(", "count", "(", "$", "usage", "->", "data", ")", "==", "0", ")", "{", "echo", "__", "(", "'Not used'", ",", "'modularity'", ")", ";", "break", ";", "}", "$", "i", "=", "0", ";", "foreach", "(", "$", "usage", "->", "data", "as", "$", "item", ")", "{", "$", "i", "++", ";", "if", "(", "$", "i", ">", "1", ")", "{", "echo", "', '", ";", "}", "echo", "'<a href=\"'", ".", "get_permalink", "(", "$", "item", "->", "post_id", ")", ".", "'\">'", ".", "$", "item", "->", "post_title", ".", "'</a>'", ";", "}", "if", "(", "$", "usage", "->", "more", ">", "0", ")", "{", "echo", "' ('", ".", "$", "usage", "->", "more", ".", "' '", ".", "__", "(", "'more'", ",", "'modularity'", ")", ".", "')'", ";", "}", "break", ";", "}", "}" ]
List table column content @param string $column Column @param integer $postId Post id @return void
[ "List", "table", "column", "content" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/ModuleManager.php#L594-L628
train
helsingborg-stad/Modularity
source/php/Module/Rss/Rss.php
Rss.getFeedContents
public function getFeedContents($rss, $items = 10, $order = '') : array { $entries = array(); if (! empty($rss)) { $rss = fetch_feed($rss); } else { $entries['error'] = __('RSS feed URL is missing', 'modularity'); return $entries; } if (is_wp_error($rss)) { if (is_admin() || current_user_can('manage_options')) { $entries['error'] = __('RSS Error:', 'modularity') . ' ' . $rss->get_error_message(); } return $entries; } if (!$rss->get_item_quantity()) { $entries['error'] = __( 'An error has occurred, which probably means the feed is down. Try again later.', 'modularity'); $rss->__destruct(); unset($rss); return $entries; } $items = ($items <= 0) ? 0 : (int) $items; $entries = $rss->get_items(0, $items); if ($order == 'asc') { $entries = array_reverse($entries); } $rss->__destruct(); unset($rss); return $entries; }
php
public function getFeedContents($rss, $items = 10, $order = '') : array { $entries = array(); if (! empty($rss)) { $rss = fetch_feed($rss); } else { $entries['error'] = __('RSS feed URL is missing', 'modularity'); return $entries; } if (is_wp_error($rss)) { if (is_admin() || current_user_can('manage_options')) { $entries['error'] = __('RSS Error:', 'modularity') . ' ' . $rss->get_error_message(); } return $entries; } if (!$rss->get_item_quantity()) { $entries['error'] = __( 'An error has occurred, which probably means the feed is down. Try again later.', 'modularity'); $rss->__destruct(); unset($rss); return $entries; } $items = ($items <= 0) ? 0 : (int) $items; $entries = $rss->get_items(0, $items); if ($order == 'asc') { $entries = array_reverse($entries); } $rss->__destruct(); unset($rss); return $entries; }
[ "public", "function", "getFeedContents", "(", "$", "rss", ",", "$", "items", "=", "10", ",", "$", "order", "=", "''", ")", ":", "array", "{", "$", "entries", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "rss", ")", ")", "{", "$", "rss", "=", "fetch_feed", "(", "$", "rss", ")", ";", "}", "else", "{", "$", "entries", "[", "'error'", "]", "=", "__", "(", "'RSS feed URL is missing'", ",", "'modularity'", ")", ";", "return", "$", "entries", ";", "}", "if", "(", "is_wp_error", "(", "$", "rss", ")", ")", "{", "if", "(", "is_admin", "(", ")", "||", "current_user_can", "(", "'manage_options'", ")", ")", "{", "$", "entries", "[", "'error'", "]", "=", "__", "(", "'RSS Error:'", ",", "'modularity'", ")", ".", "' '", ".", "$", "rss", "->", "get_error_message", "(", ")", ";", "}", "return", "$", "entries", ";", "}", "if", "(", "!", "$", "rss", "->", "get_item_quantity", "(", ")", ")", "{", "$", "entries", "[", "'error'", "]", "=", "__", "(", "'An error has occurred, which probably means the feed is down. Try again later.'", ",", "'modularity'", ")", ";", "$", "rss", "->", "__destruct", "(", ")", ";", "unset", "(", "$", "rss", ")", ";", "return", "$", "entries", ";", "}", "$", "items", "=", "(", "$", "items", "<=", "0", ")", "?", "0", ":", "(", "int", ")", "$", "items", ";", "$", "entries", "=", "$", "rss", "->", "get_items", "(", "0", ",", "$", "items", ")", ";", "if", "(", "$", "order", "==", "'asc'", ")", "{", "$", "entries", "=", "array_reverse", "(", "$", "entries", ")", ";", "}", "$", "rss", "->", "__destruct", "(", ")", ";", "unset", "(", "$", "rss", ")", ";", "return", "$", "entries", ";", "}" ]
Returns the RSS entries @param string $rss RSS feed URL @param integer $items Number of items to return @param string $order Sorting order, asc or desc @return array List of RSS entries
[ "Returns", "the", "RSS", "entries" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Module/Rss/Rss.php#L36-L70
train
helsingborg-stad/Modularity
source/php/Module/Rss/Rss.php
Rss.getRssAuthor
public static function getRssAuthor($author) { if (is_object($author)) { $author = $author->get_name(); $author = esc_html(strip_tags($author)); } else { $author = ''; } return $author; }
php
public static function getRssAuthor($author) { if (is_object($author)) { $author = $author->get_name(); $author = esc_html(strip_tags($author)); } else { $author = ''; } return $author; }
[ "public", "static", "function", "getRssAuthor", "(", "$", "author", ")", "{", "if", "(", "is_object", "(", "$", "author", ")", ")", "{", "$", "author", "=", "$", "author", "->", "get_name", "(", ")", ";", "$", "author", "=", "esc_html", "(", "strip_tags", "(", "$", "author", ")", ")", ";", "}", "else", "{", "$", "author", "=", "''", ";", "}", "return", "$", "author", ";", "}" ]
Sanitize author name @param object $author object with author data @return string sanitized author name
[ "Sanitize", "author", "name" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Module/Rss/Rss.php#L105-L115
train
helsingborg-stad/Modularity
source/php/Module/Rss/Rss.php
Rss.getRssSummary
public static function getRssSummary($summary = '') { $summary = @html_entity_decode($summary, ENT_QUOTES, get_option('blog_charset')); $summary = esc_attr(wp_trim_words($summary, 50, ' [&hellip;]')); // Change existing [...] to [&hellip;]. if ('[...]' == substr($summary, -5)) { $summary = substr($summary, 0, -5) . '[&hellip;]'; } $summary = esc_html($summary); return $summary; }
php
public static function getRssSummary($summary = '') { $summary = @html_entity_decode($summary, ENT_QUOTES, get_option('blog_charset')); $summary = esc_attr(wp_trim_words($summary, 50, ' [&hellip;]')); // Change existing [...] to [&hellip;]. if ('[...]' == substr($summary, -5)) { $summary = substr($summary, 0, -5) . '[&hellip;]'; } $summary = esc_html($summary); return $summary; }
[ "public", "static", "function", "getRssSummary", "(", "$", "summary", "=", "''", ")", "{", "$", "summary", "=", "@", "html_entity_decode", "(", "$", "summary", ",", "ENT_QUOTES", ",", "get_option", "(", "'blog_charset'", ")", ")", ";", "$", "summary", "=", "esc_attr", "(", "wp_trim_words", "(", "$", "summary", ",", "50", ",", "' [&hellip;]'", ")", ")", ";", "// Change existing [...] to [&hellip;].", "if", "(", "'[...]'", "==", "substr", "(", "$", "summary", ",", "-", "5", ")", ")", "{", "$", "summary", "=", "substr", "(", "$", "summary", ",", "0", ",", "-", "5", ")", ".", "'[&hellip;]'", ";", "}", "$", "summary", "=", "esc_html", "(", "$", "summary", ")", ";", "return", "$", "summary", ";", "}" ]
Sanitize and trim summary @param string $summary default RSS entry summary @return string sanitized entry
[ "Sanitize", "and", "trim", "summary" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Module/Rss/Rss.php#L122-L135
train
helsingborg-stad/Modularity
source/php/Helper/Wp.php
Wp.getTemplate
public static function getTemplate($prefix = '', $slug = '', $error = true) { $paths = apply_filters('Modularity/Module/TemplatePath', array( get_stylesheet_directory() . '/templates/', get_template_directory() . '/templates/', MODULARITY_PATH . 'templates/', )); $slug = apply_filters('Modularity/TemplatePathSlug', $slug ? $slug . '/' : '', $prefix); $prefix = $prefix ? '-'.$prefix : ''; foreach ($paths as $path) { $file = $path . $slug . 'modularity' . $prefix.'.php'; if (file_exists($file)) { return $file; } } if (defined('WP_DEBUG') && WP_DEBUG === true) { error_log('Modularity: Template ' . $slug . 'modularity' . $prefix . '.php' . ' not found in any of the paths: ' . var_export($paths, true)); if ($error) { trigger_error('Modularity: Template ' . $slug . 'modularity' . $prefix . '.php' . ' not found in any of the paths: ' . var_export($paths, true), E_USER_WARNING); } } }
php
public static function getTemplate($prefix = '', $slug = '', $error = true) { $paths = apply_filters('Modularity/Module/TemplatePath', array( get_stylesheet_directory() . '/templates/', get_template_directory() . '/templates/', MODULARITY_PATH . 'templates/', )); $slug = apply_filters('Modularity/TemplatePathSlug', $slug ? $slug . '/' : '', $prefix); $prefix = $prefix ? '-'.$prefix : ''; foreach ($paths as $path) { $file = $path . $slug . 'modularity' . $prefix.'.php'; if (file_exists($file)) { return $file; } } if (defined('WP_DEBUG') && WP_DEBUG === true) { error_log('Modularity: Template ' . $slug . 'modularity' . $prefix . '.php' . ' not found in any of the paths: ' . var_export($paths, true)); if ($error) { trigger_error('Modularity: Template ' . $slug . 'modularity' . $prefix . '.php' . ' not found in any of the paths: ' . var_export($paths, true), E_USER_WARNING); } } }
[ "public", "static", "function", "getTemplate", "(", "$", "prefix", "=", "''", ",", "$", "slug", "=", "''", ",", "$", "error", "=", "true", ")", "{", "$", "paths", "=", "apply_filters", "(", "'Modularity/Module/TemplatePath'", ",", "array", "(", "get_stylesheet_directory", "(", ")", ".", "'/templates/'", ",", "get_template_directory", "(", ")", ".", "'/templates/'", ",", "MODULARITY_PATH", ".", "'templates/'", ",", ")", ")", ";", "$", "slug", "=", "apply_filters", "(", "'Modularity/TemplatePathSlug'", ",", "$", "slug", "?", "$", "slug", ".", "'/'", ":", "''", ",", "$", "prefix", ")", ";", "$", "prefix", "=", "$", "prefix", "?", "'-'", ".", "$", "prefix", ":", "''", ";", "foreach", "(", "$", "paths", "as", "$", "path", ")", "{", "$", "file", "=", "$", "path", ".", "$", "slug", ".", "'modularity'", ".", "$", "prefix", ".", "'.php'", ";", "if", "(", "file_exists", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "}", "if", "(", "defined", "(", "'WP_DEBUG'", ")", "&&", "WP_DEBUG", "===", "true", ")", "{", "error_log", "(", "'Modularity: Template '", ".", "$", "slug", ".", "'modularity'", ".", "$", "prefix", ".", "'.php'", ".", "' not found in any of the paths: '", ".", "var_export", "(", "$", "paths", ",", "true", ")", ")", ";", "if", "(", "$", "error", ")", "{", "trigger_error", "(", "'Modularity: Template '", ".", "$", "slug", ".", "'modularity'", ".", "$", "prefix", ".", "'.php'", ".", "' not found in any of the paths: '", ".", "var_export", "(", "$", "paths", ",", "true", ")", ",", "E_USER_WARNING", ")", ";", "}", "}", "}" ]
Tries to get the template path Checks the plugin's template folder, the parent theme's templates folder and the current theme's template folder @param string $prefix The filename without prefix @param string $slug The directory @param boolean $error Show errors or not @return string The path to the template to use
[ "Tries", "to", "get", "the", "template", "path", "Checks", "the", "plugin", "s", "template", "folder", "the", "parent", "theme", "s", "templates", "folder", "and", "the", "current", "theme", "s", "template", "folder" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Helper/Wp.php#L122-L147
train
helsingborg-stad/Modularity
source/php/Helper/Wp.php
Wp.isThickBox
public static function isThickBox() { $referer = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : null; if ((isset($_GET['is_thickbox']) && $_GET['is_thickbox'] == 'true') || strpos($referer, 'is_thickbox=true') > -1) { return true; } else { return false; } }
php
public static function isThickBox() { $referer = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : null; if ((isset($_GET['is_thickbox']) && $_GET['is_thickbox'] == 'true') || strpos($referer, 'is_thickbox=true') > -1) { return true; } else { return false; } }
[ "public", "static", "function", "isThickBox", "(", ")", "{", "$", "referer", "=", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_REFERER'", "]", ")", ")", "?", "$", "_SERVER", "[", "'HTTP_REFERER'", "]", ":", "null", ";", "if", "(", "(", "isset", "(", "$", "_GET", "[", "'is_thickbox'", "]", ")", "&&", "$", "_GET", "[", "'is_thickbox'", "]", "==", "'true'", ")", "||", "strpos", "(", "$", "referer", ",", "'is_thickbox=true'", ")", ">", "-", "1", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Check if the add question form is opened in thickbox iframe @return boolean
[ "Check", "if", "the", "add", "question", "form", "is", "opened", "in", "thickbox", "iframe" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Helper/Wp.php#L167-L177
train
helsingborg-stad/Modularity
source/php/Helper/Wp.php
Wp.getArchiveSlug
public static function getArchiveSlug() { global $wp_query; if ($wp_query && !is_tax() && (is_post_type_archive() || is_archive() || is_home() || is_search() || is_404())) { $postType = get_post_type(); if (isset($wp_query->query_vars['post_type']) && !empty($wp_query->query_vars['post_type'])) { $postType = $wp_query->query_vars['post_type']; } if (is_home()) { $archiveSlug = 'archive-post'; } elseif (is_post_type_archive() && is_search()) { $archiveSlug = 'archive-' . get_post_type_object($postType)->name; } elseif (is_search()) { $archiveSlug = 'search'; } elseif (is_404()) { $archiveSlug = 'e404'; } elseif (is_author()) { $archiveSlug = 'author'; } else { $archiveSlug = 'archive-' . get_post_type_object($postType)->name; } return $archiveSlug; } return false; }
php
public static function getArchiveSlug() { global $wp_query; if ($wp_query && !is_tax() && (is_post_type_archive() || is_archive() || is_home() || is_search() || is_404())) { $postType = get_post_type(); if (isset($wp_query->query_vars['post_type']) && !empty($wp_query->query_vars['post_type'])) { $postType = $wp_query->query_vars['post_type']; } if (is_home()) { $archiveSlug = 'archive-post'; } elseif (is_post_type_archive() && is_search()) { $archiveSlug = 'archive-' . get_post_type_object($postType)->name; } elseif (is_search()) { $archiveSlug = 'search'; } elseif (is_404()) { $archiveSlug = 'e404'; } elseif (is_author()) { $archiveSlug = 'author'; } else { $archiveSlug = 'archive-' . get_post_type_object($postType)->name; } return $archiveSlug; } return false; }
[ "public", "static", "function", "getArchiveSlug", "(", ")", "{", "global", "$", "wp_query", ";", "if", "(", "$", "wp_query", "&&", "!", "is_tax", "(", ")", "&&", "(", "is_post_type_archive", "(", ")", "||", "is_archive", "(", ")", "||", "is_home", "(", ")", "||", "is_search", "(", ")", "||", "is_404", "(", ")", ")", ")", "{", "$", "postType", "=", "get_post_type", "(", ")", ";", "if", "(", "isset", "(", "$", "wp_query", "->", "query_vars", "[", "'post_type'", "]", ")", "&&", "!", "empty", "(", "$", "wp_query", "->", "query_vars", "[", "'post_type'", "]", ")", ")", "{", "$", "postType", "=", "$", "wp_query", "->", "query_vars", "[", "'post_type'", "]", ";", "}", "if", "(", "is_home", "(", ")", ")", "{", "$", "archiveSlug", "=", "'archive-post'", ";", "}", "elseif", "(", "is_post_type_archive", "(", ")", "&&", "is_search", "(", ")", ")", "{", "$", "archiveSlug", "=", "'archive-'", ".", "get_post_type_object", "(", "$", "postType", ")", "->", "name", ";", "}", "elseif", "(", "is_search", "(", ")", ")", "{", "$", "archiveSlug", "=", "'search'", ";", "}", "elseif", "(", "is_404", "(", ")", ")", "{", "$", "archiveSlug", "=", "'e404'", ";", "}", "elseif", "(", "is_author", "(", ")", ")", "{", "$", "archiveSlug", "=", "'author'", ";", "}", "else", "{", "$", "archiveSlug", "=", "'archive-'", ".", "get_post_type_object", "(", "$", "postType", ")", "->", "name", ";", "}", "return", "$", "archiveSlug", ";", "}", "return", "false", ";", "}" ]
Fetches current archive slug @return mixed (string, boolean) False if not archive else archive slug
[ "Fetches", "current", "archive", "slug" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Helper/Wp.php#L192-L221
train
helsingborg-stad/Modularity
App.php
App.isModularityPage
public function isModularityPage() { global $current_screen; $result = true; if (strpos($current_screen->id, 'modularity') === false && strpos($current_screen->id, 'mod-') === false && ($current_screen->action != 'add' && ( isset($_GET['action']) && $_GET['action'] != 'edit') ) && $current_screen->base != 'post' && $current_screen->base != 'widgets') { $result = false; } return $result; }
php
public function isModularityPage() { global $current_screen; $result = true; if (strpos($current_screen->id, 'modularity') === false && strpos($current_screen->id, 'mod-') === false && ($current_screen->action != 'add' && ( isset($_GET['action']) && $_GET['action'] != 'edit') ) && $current_screen->base != 'post' && $current_screen->base != 'widgets') { $result = false; } return $result; }
[ "public", "function", "isModularityPage", "(", ")", "{", "global", "$", "current_screen", ";", "$", "result", "=", "true", ";", "if", "(", "strpos", "(", "$", "current_screen", "->", "id", ",", "'modularity'", ")", "===", "false", "&&", "strpos", "(", "$", "current_screen", "->", "id", ",", "'mod-'", ")", "===", "false", "&&", "(", "$", "current_screen", "->", "action", "!=", "'add'", "&&", "(", "isset", "(", "$", "_GET", "[", "'action'", "]", ")", "&&", "$", "_GET", "[", "'action'", "]", "!=", "'edit'", ")", ")", "&&", "$", "current_screen", "->", "base", "!=", "'post'", "&&", "$", "current_screen", "->", "base", "!=", "'widgets'", ")", "{", "$", "result", "=", "false", ";", "}", "return", "$", "result", ";", "}" ]
Check if current page is a modularity page @return boolean
[ "Check", "if", "current", "page", "is", "a", "modularity", "page" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/App.php#L248-L267
train
helsingborg-stad/Modularity
source/php/Module/InlayList/InlayList.php
InlayList.acfLocationSelect
public function acfLocationSelect($title, $post, $field, $post_id) { $address = get_permalink($post->ID, false); if (! empty($address)) { $title .= '<br/><span class="inlay-list-url-helper"> ( ' . str_replace(home_url(),"", $address) . ' ) </span>'; } return $title; }
php
public function acfLocationSelect($title, $post, $field, $post_id) { $address = get_permalink($post->ID, false); if (! empty($address)) { $title .= '<br/><span class="inlay-list-url-helper"> ( ' . str_replace(home_url(),"", $address) . ' ) </span>'; } return $title; }
[ "public", "function", "acfLocationSelect", "(", "$", "title", ",", "$", "post", ",", "$", "field", ",", "$", "post_id", ")", "{", "$", "address", "=", "get_permalink", "(", "$", "post", "->", "ID", ",", "false", ")", ";", "if", "(", "!", "empty", "(", "$", "address", ")", ")", "{", "$", "title", ".=", "'<br/><span class=\"inlay-list-url-helper\"> ( '", ".", "str_replace", "(", "home_url", "(", ")", ",", "\"\"", ",", "$", "address", ")", ".", "' ) </span>'", ";", "}", "return", "$", "title", ";", "}" ]
Adding address to Location select box @param string $title the text displayed for this post object @param object $post the post object @param array $field the field array containing all attributes & settings @param int $post_id the current post ID being edited @return string updated title
[ "Adding", "address", "to", "Location", "select", "box" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Module/InlayList/InlayList.php#L35-L44
train
helsingborg-stad/Modularity
source/php/Editor/Tabs.php
Tabs.output
public function output() { if (!$this->shouldOutput()) { return false; } echo '<h2 class="modularity-nav-tab-wrapper" id="modularity-tabs">'; $requestUri = str_replace('&message=1', '', $_SERVER['REQUEST_URI']); foreach ($this->tabs as $tab => $url) { if (strpos($url, $requestUri) !== false || (strpos($url, 'post.php') !== false && strpos($requestUri, 'post-new.php') !== false)) { echo '<a href="' . $url . '" class="nav-tab nav-tab-active">' . $tab . '</a>'; } else { echo '<a href="' . $url . '" class="nav-tab">' . $tab . '</a>'; } } echo '<div class="modularity-clearfix"></div></h2>'; }
php
public function output() { if (!$this->shouldOutput()) { return false; } echo '<h2 class="modularity-nav-tab-wrapper" id="modularity-tabs">'; $requestUri = str_replace('&message=1', '', $_SERVER['REQUEST_URI']); foreach ($this->tabs as $tab => $url) { if (strpos($url, $requestUri) !== false || (strpos($url, 'post.php') !== false && strpos($requestUri, 'post-new.php') !== false)) { echo '<a href="' . $url . '" class="nav-tab nav-tab-active">' . $tab . '</a>'; } else { echo '<a href="' . $url . '" class="nav-tab">' . $tab . '</a>'; } } echo '<div class="modularity-clearfix"></div></h2>'; }
[ "public", "function", "output", "(", ")", "{", "if", "(", "!", "$", "this", "->", "shouldOutput", "(", ")", ")", "{", "return", "false", ";", "}", "echo", "'<h2 class=\"modularity-nav-tab-wrapper\" id=\"modularity-tabs\">'", ";", "$", "requestUri", "=", "str_replace", "(", "'&message=1'", ",", "''", ",", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ";", "foreach", "(", "$", "this", "->", "tabs", "as", "$", "tab", "=>", "$", "url", ")", "{", "if", "(", "strpos", "(", "$", "url", ",", "$", "requestUri", ")", "!==", "false", "||", "(", "strpos", "(", "$", "url", ",", "'post.php'", ")", "!==", "false", "&&", "strpos", "(", "$", "requestUri", ",", "'post-new.php'", ")", "!==", "false", ")", ")", "{", "echo", "'<a href=\"'", ".", "$", "url", ".", "'\" class=\"nav-tab nav-tab-active\">'", ".", "$", "tab", ".", "'</a>'", ";", "}", "else", "{", "echo", "'<a href=\"'", ".", "$", "url", ".", "'\" class=\"nav-tab\">'", ".", "$", "tab", ".", "'</a>'", ";", "}", "}", "echo", "'<div class=\"modularity-clearfix\"></div></h2>'", ";", "}" ]
Outputs the tabbar html @param integer $activeIndex Current active tab index @return void
[ "Outputs", "the", "tabbar", "html" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor/Tabs.php#L19-L38
train
helsingborg-stad/Modularity
source/php/Editor/Tabs.php
Tabs.shouldOutput
protected function shouldOutput() { global $current_screen; $options = get_option('modularity-options'); $enabled = isset($options['enabled-post-types']) && is_array($options['enabled-post-types']) ? $options['enabled-post-types'] : array(); $validPostType = in_array($current_screen->id, $enabled); $action = $current_screen->action; if (empty($action)) { $action = (isset($_GET['action']) && !empty($_GET['action'])) ? $_GET['action'] : null; } $validAction = in_array($action, array( 'add', 'edit' )); return ($validPostType && $validAction) || $current_screen->id == 'admin_page_modularity-editor'; }
php
protected function shouldOutput() { global $current_screen; $options = get_option('modularity-options'); $enabled = isset($options['enabled-post-types']) && is_array($options['enabled-post-types']) ? $options['enabled-post-types'] : array(); $validPostType = in_array($current_screen->id, $enabled); $action = $current_screen->action; if (empty($action)) { $action = (isset($_GET['action']) && !empty($_GET['action'])) ? $_GET['action'] : null; } $validAction = in_array($action, array( 'add', 'edit' )); return ($validPostType && $validAction) || $current_screen->id == 'admin_page_modularity-editor'; }
[ "protected", "function", "shouldOutput", "(", ")", "{", "global", "$", "current_screen", ";", "$", "options", "=", "get_option", "(", "'modularity-options'", ")", ";", "$", "enabled", "=", "isset", "(", "$", "options", "[", "'enabled-post-types'", "]", ")", "&&", "is_array", "(", "$", "options", "[", "'enabled-post-types'", "]", ")", "?", "$", "options", "[", "'enabled-post-types'", "]", ":", "array", "(", ")", ";", "$", "validPostType", "=", "in_array", "(", "$", "current_screen", "->", "id", ",", "$", "enabled", ")", ";", "$", "action", "=", "$", "current_screen", "->", "action", ";", "if", "(", "empty", "(", "$", "action", ")", ")", "{", "$", "action", "=", "(", "isset", "(", "$", "_GET", "[", "'action'", "]", ")", "&&", "!", "empty", "(", "$", "_GET", "[", "'action'", "]", ")", ")", "?", "$", "_GET", "[", "'action'", "]", ":", "null", ";", "}", "$", "validAction", "=", "in_array", "(", "$", "action", ",", "array", "(", "'add'", ",", "'edit'", ")", ")", ";", "return", "(", "$", "validPostType", "&&", "$", "validAction", ")", "||", "$", "current_screen", "->", "id", "==", "'admin_page_modularity-editor'", ";", "}" ]
Check if tabs should be outputted @return boolean
[ "Check", "if", "tabs", "should", "be", "outputted" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor/Tabs.php#L55-L75
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.avoidDuplicatePostName
public function avoidDuplicatePostName($data, $postarr) { if (!isset($data['post_type']) || (isset($data['post_type']) && substr($data['post_type'], 0, 4) != 'mod-')) { return $data; } $data['post_name'] = $data['post_type'] . '_' . uniqid() . '_' . sanitize_title($data['post_title']); return $data; }
php
public function avoidDuplicatePostName($data, $postarr) { if (!isset($data['post_type']) || (isset($data['post_type']) && substr($data['post_type'], 0, 4) != 'mod-')) { return $data; } $data['post_name'] = $data['post_type'] . '_' . uniqid() . '_' . sanitize_title($data['post_title']); return $data; }
[ "public", "function", "avoidDuplicatePostName", "(", "$", "data", ",", "$", "postarr", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'post_type'", "]", ")", "||", "(", "isset", "(", "$", "data", "[", "'post_type'", "]", ")", "&&", "substr", "(", "$", "data", "[", "'post_type'", "]", ",", "0", ",", "4", ")", "!=", "'mod-'", ")", ")", "{", "return", "$", "data", ";", "}", "$", "data", "[", "'post_name'", "]", "=", "$", "data", "[", "'post_type'", "]", ".", "'_'", ".", "uniqid", "(", ")", ".", "'_'", ".", "sanitize_title", "(", "$", "data", "[", "'post_title'", "]", ")", ";", "return", "$", "data", ";", "}" ]
Avoid duplicate post_name in db @param array $data Post data @param array $postarr Postarr @return array Post data to save
[ "Avoid", "duplicate", "post_name", "in", "db" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L32-L41
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.adminBar
public function adminBar() { if (isset($_GET['id'])) { if (is_numeric($_GET['id']) && $_GET['id'] > 0) { $post = get_post($_GET['id']); if (!$post) { return; } setup_postdata($post); add_action('admin_bar_menu', function () use ($post) { global $wp_admin_bar; $wp_admin_bar->add_node(array( 'id' => 'view_page', 'title' => __('View Page'), 'href' => get_permalink($post->ID), 'meta' => array( 'target' => '_blank' ) )); }, 1050); self::$isEditing = array( 'id' => $post->ID, 'title' => $post->post_title ); wp_reset_postdata(); } else { global $archive; $archive = $_GET['id']; self::$isEditing = array( 'id' => null, 'title' => $archive ); } self::$isEditing = apply_filters('Modularity/is_editing', self::$isEditing); add_action('Modularity/options_page_title_suffix', function () { echo ': ' . self::$isEditing['title']; }); } }
php
public function adminBar() { if (isset($_GET['id'])) { if (is_numeric($_GET['id']) && $_GET['id'] > 0) { $post = get_post($_GET['id']); if (!$post) { return; } setup_postdata($post); add_action('admin_bar_menu', function () use ($post) { global $wp_admin_bar; $wp_admin_bar->add_node(array( 'id' => 'view_page', 'title' => __('View Page'), 'href' => get_permalink($post->ID), 'meta' => array( 'target' => '_blank' ) )); }, 1050); self::$isEditing = array( 'id' => $post->ID, 'title' => $post->post_title ); wp_reset_postdata(); } else { global $archive; $archive = $_GET['id']; self::$isEditing = array( 'id' => null, 'title' => $archive ); } self::$isEditing = apply_filters('Modularity/is_editing', self::$isEditing); add_action('Modularity/options_page_title_suffix', function () { echo ': ' . self::$isEditing['title']; }); } }
[ "public", "function", "adminBar", "(", ")", "{", "if", "(", "isset", "(", "$", "_GET", "[", "'id'", "]", ")", ")", "{", "if", "(", "is_numeric", "(", "$", "_GET", "[", "'id'", "]", ")", "&&", "$", "_GET", "[", "'id'", "]", ">", "0", ")", "{", "$", "post", "=", "get_post", "(", "$", "_GET", "[", "'id'", "]", ")", ";", "if", "(", "!", "$", "post", ")", "{", "return", ";", "}", "setup_postdata", "(", "$", "post", ")", ";", "add_action", "(", "'admin_bar_menu'", ",", "function", "(", ")", "use", "(", "$", "post", ")", "{", "global", "$", "wp_admin_bar", ";", "$", "wp_admin_bar", "->", "add_node", "(", "array", "(", "'id'", "=>", "'view_page'", ",", "'title'", "=>", "__", "(", "'View Page'", ")", ",", "'href'", "=>", "get_permalink", "(", "$", "post", "->", "ID", ")", ",", "'meta'", "=>", "array", "(", "'target'", "=>", "'_blank'", ")", ")", ")", ";", "}", ",", "1050", ")", ";", "self", "::", "$", "isEditing", "=", "array", "(", "'id'", "=>", "$", "post", "->", "ID", ",", "'title'", "=>", "$", "post", "->", "post_title", ")", ";", "wp_reset_postdata", "(", ")", ";", "}", "else", "{", "global", "$", "archive", ";", "$", "archive", "=", "$", "_GET", "[", "'id'", "]", ";", "self", "::", "$", "isEditing", "=", "array", "(", "'id'", "=>", "null", ",", "'title'", "=>", "$", "archive", ")", ";", "}", "self", "::", "$", "isEditing", "=", "apply_filters", "(", "'Modularity/is_editing'", ",", "self", "::", "$", "isEditing", ")", ";", "add_action", "(", "'Modularity/options_page_title_suffix'", ",", "function", "(", ")", "{", "echo", "': '", ".", "self", "::", "$", "isEditing", "[", "'title'", "]", ";", "}", ")", ";", "}", "}" ]
Handle admin bar stuff @return void
[ "Handle", "admin", "bar", "stuff" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L47-L93
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.registerTabs
public function registerTabs() { global $post; if (!$post && !isset($_GET['page_for'])) { return; } if (!$post && isset($_GET['page_for']) && !empty($_GET['page_for'])) { $post = get_post($_GET['page_for']); } $modulesEditorId = false; if ($post) { $modulesEditorId = $post->ID; $thePostId = $post->ID; } if ($postType = self::isPageForPostType($post->ID)) { $modulesEditorId = 'archive-' . $postType . '&page_for=' . $post->ID; } $tabs = new \Modularity\Editor\Tabs(); $tabs->add(__('Content', 'modularity'), admin_url('post.php?post=' . $thePostId . '&action=edit')); $tabs->add(__('Modules', 'modularity'), admin_url('options.php?page=modularity-editor&id=' . $modulesEditorId)); }
php
public function registerTabs() { global $post; if (!$post && !isset($_GET['page_for'])) { return; } if (!$post && isset($_GET['page_for']) && !empty($_GET['page_for'])) { $post = get_post($_GET['page_for']); } $modulesEditorId = false; if ($post) { $modulesEditorId = $post->ID; $thePostId = $post->ID; } if ($postType = self::isPageForPostType($post->ID)) { $modulesEditorId = 'archive-' . $postType . '&page_for=' . $post->ID; } $tabs = new \Modularity\Editor\Tabs(); $tabs->add(__('Content', 'modularity'), admin_url('post.php?post=' . $thePostId . '&action=edit')); $tabs->add(__('Modules', 'modularity'), admin_url('options.php?page=modularity-editor&id=' . $modulesEditorId)); }
[ "public", "function", "registerTabs", "(", ")", "{", "global", "$", "post", ";", "if", "(", "!", "$", "post", "&&", "!", "isset", "(", "$", "_GET", "[", "'page_for'", "]", ")", ")", "{", "return", ";", "}", "if", "(", "!", "$", "post", "&&", "isset", "(", "$", "_GET", "[", "'page_for'", "]", ")", "&&", "!", "empty", "(", "$", "_GET", "[", "'page_for'", "]", ")", ")", "{", "$", "post", "=", "get_post", "(", "$", "_GET", "[", "'page_for'", "]", ")", ";", "}", "$", "modulesEditorId", "=", "false", ";", "if", "(", "$", "post", ")", "{", "$", "modulesEditorId", "=", "$", "post", "->", "ID", ";", "$", "thePostId", "=", "$", "post", "->", "ID", ";", "}", "if", "(", "$", "postType", "=", "self", "::", "isPageForPostType", "(", "$", "post", "->", "ID", ")", ")", "{", "$", "modulesEditorId", "=", "'archive-'", ".", "$", "postType", ".", "'&page_for='", ".", "$", "post", "->", "ID", ";", "}", "$", "tabs", "=", "new", "\\", "Modularity", "\\", "Editor", "\\", "Tabs", "(", ")", ";", "$", "tabs", "->", "add", "(", "__", "(", "'Content'", ",", "'modularity'", ")", ",", "admin_url", "(", "'post.php?post='", ".", "$", "thePostId", ".", "'&action=edit'", ")", ")", ";", "$", "tabs", "->", "add", "(", "__", "(", "'Modules'", ",", "'modularity'", ")", ",", "admin_url", "(", "'options.php?page=modularity-editor&id='", ".", "$", "modulesEditorId", ")", ")", ";", "}" ]
Registers navigation tabs @return void
[ "Registers", "navigation", "tabs" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L99-L125
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.registerEditorPage
public function registerEditorPage() { $this->register( $pageTitle = __('Modularity editor'), $menuTitle = __('Editor'), $capability = 'edit_posts', $menuSlug = 'modularity-editor', $iconUrl = null, $position = 1, $parent = 'options.php' ); }
php
public function registerEditorPage() { $this->register( $pageTitle = __('Modularity editor'), $menuTitle = __('Editor'), $capability = 'edit_posts', $menuSlug = 'modularity-editor', $iconUrl = null, $position = 1, $parent = 'options.php' ); }
[ "public", "function", "registerEditorPage", "(", ")", "{", "$", "this", "->", "register", "(", "$", "pageTitle", "=", "__", "(", "'Modularity editor'", ")", ",", "$", "menuTitle", "=", "__", "(", "'Editor'", ")", ",", "$", "capability", "=", "'edit_posts'", ",", "$", "menuSlug", "=", "'modularity-editor'", ",", "$", "iconUrl", "=", "null", ",", "$", "position", "=", "1", ",", "$", "parent", "=", "'options.php'", ")", ";", "}" ]
Register an option page for the editor @return void
[ "Register", "an", "option", "page", "for", "the", "editor" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L149-L160
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.addMetaBoxes
public function addMetaBoxes() { // Publish add_meta_box( 'modularity-mb-editor-publish', __('Save modules', 'modularity'), function () { include MODULARITY_TEMPLATE_PATH . 'editor/modularity-publish.php'; }, $this->screenHook, 'side' ); // Modules add_meta_box( 'modularity-mb-modules', __('Enabled modules', 'modularity'), function () { $enabled = \Modularity\ModuleManager::$enabled; $available = \Modularity\ModuleManager::$available; $deprecated = \Modularity\ModuleManager::$deprecated; $modules = array(); if (is_array($enabled) && !empty($enabled)) { foreach ($enabled as $module) { if (isset($available[$module]) && !in_array($module, $deprecated)) { $modules[$module] = apply_filters('Modularity/Editor/SidebarIncompability', $available[$module], $module); } } } uasort($modules, function ($a, $b) { return $a['labels']['name'] > $b['labels']['name']; }); include MODULARITY_TEMPLATE_PATH . 'editor/modularity-enabled-modules.php'; }, $this->screenHook, 'side' ); $this->addSidebarsMetaBoxes(); }
php
public function addMetaBoxes() { // Publish add_meta_box( 'modularity-mb-editor-publish', __('Save modules', 'modularity'), function () { include MODULARITY_TEMPLATE_PATH . 'editor/modularity-publish.php'; }, $this->screenHook, 'side' ); // Modules add_meta_box( 'modularity-mb-modules', __('Enabled modules', 'modularity'), function () { $enabled = \Modularity\ModuleManager::$enabled; $available = \Modularity\ModuleManager::$available; $deprecated = \Modularity\ModuleManager::$deprecated; $modules = array(); if (is_array($enabled) && !empty($enabled)) { foreach ($enabled as $module) { if (isset($available[$module]) && !in_array($module, $deprecated)) { $modules[$module] = apply_filters('Modularity/Editor/SidebarIncompability', $available[$module], $module); } } } uasort($modules, function ($a, $b) { return $a['labels']['name'] > $b['labels']['name']; }); include MODULARITY_TEMPLATE_PATH . 'editor/modularity-enabled-modules.php'; }, $this->screenHook, 'side' ); $this->addSidebarsMetaBoxes(); }
[ "public", "function", "addMetaBoxes", "(", ")", "{", "// Publish", "add_meta_box", "(", "'modularity-mb-editor-publish'", ",", "__", "(", "'Save modules'", ",", "'modularity'", ")", ",", "function", "(", ")", "{", "include", "MODULARITY_TEMPLATE_PATH", ".", "'editor/modularity-publish.php'", ";", "}", ",", "$", "this", "->", "screenHook", ",", "'side'", ")", ";", "// Modules", "add_meta_box", "(", "'modularity-mb-modules'", ",", "__", "(", "'Enabled modules'", ",", "'modularity'", ")", ",", "function", "(", ")", "{", "$", "enabled", "=", "\\", "Modularity", "\\", "ModuleManager", "::", "$", "enabled", ";", "$", "available", "=", "\\", "Modularity", "\\", "ModuleManager", "::", "$", "available", ";", "$", "deprecated", "=", "\\", "Modularity", "\\", "ModuleManager", "::", "$", "deprecated", ";", "$", "modules", "=", "array", "(", ")", ";", "if", "(", "is_array", "(", "$", "enabled", ")", "&&", "!", "empty", "(", "$", "enabled", ")", ")", "{", "foreach", "(", "$", "enabled", "as", "$", "module", ")", "{", "if", "(", "isset", "(", "$", "available", "[", "$", "module", "]", ")", "&&", "!", "in_array", "(", "$", "module", ",", "$", "deprecated", ")", ")", "{", "$", "modules", "[", "$", "module", "]", "=", "apply_filters", "(", "'Modularity/Editor/SidebarIncompability'", ",", "$", "available", "[", "$", "module", "]", ",", "$", "module", ")", ";", "}", "}", "}", "uasort", "(", "$", "modules", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "$", "a", "[", "'labels'", "]", "[", "'name'", "]", ">", "$", "b", "[", "'labels'", "]", "[", "'name'", "]", ";", "}", ")", ";", "include", "MODULARITY_TEMPLATE_PATH", ".", "'editor/modularity-enabled-modules.php'", ";", "}", ",", "$", "this", "->", "screenHook", ",", "'side'", ")", ";", "$", "this", "->", "addSidebarsMetaBoxes", "(", ")", ";", "}" ]
Adds meta boxes to the options page @return void
[ "Adds", "meta", "boxes", "to", "the", "options", "page" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L166-L208
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.addSidebarsMetaBoxes
public function addSidebarsMetaBoxes() { global $wp_registered_sidebars; $template = \Modularity\Helper\Post::getPostTemplate(); $sidebars = null; $activeAreas = $this->getActiveAreas($template); // Add no active sidebars message if no active sidebars exists if (is_array($activeAreas) && count($activeAreas) === 0) { add_meta_box( 'no-sidebars', __('No active sidebar areas', 'modularity'), function () { echo '<p>' . __('There\'s no active sidebars. Please activate sidebar areas in the Modularity Options to add modules.', 'modularity') . '</p>'; }, $this->screenHook, 'normal', 'low', null ); return; } if (is_array($activeAreas) && !empty($activeAreas)) { foreach ($activeAreas as $area) { if (isset($wp_registered_sidebars[$area])) { $sidebars[$area] = $wp_registered_sidebars[$area]; } } if (is_array($sidebars)) { foreach ($sidebars as $sidebar) { $this->sidebarMetaBox($sidebar); } } } }
php
public function addSidebarsMetaBoxes() { global $wp_registered_sidebars; $template = \Modularity\Helper\Post::getPostTemplate(); $sidebars = null; $activeAreas = $this->getActiveAreas($template); // Add no active sidebars message if no active sidebars exists if (is_array($activeAreas) && count($activeAreas) === 0) { add_meta_box( 'no-sidebars', __('No active sidebar areas', 'modularity'), function () { echo '<p>' . __('There\'s no active sidebars. Please activate sidebar areas in the Modularity Options to add modules.', 'modularity') . '</p>'; }, $this->screenHook, 'normal', 'low', null ); return; } if (is_array($activeAreas) && !empty($activeAreas)) { foreach ($activeAreas as $area) { if (isset($wp_registered_sidebars[$area])) { $sidebars[$area] = $wp_registered_sidebars[$area]; } } if (is_array($sidebars)) { foreach ($sidebars as $sidebar) { $this->sidebarMetaBox($sidebar); } } } }
[ "public", "function", "addSidebarsMetaBoxes", "(", ")", "{", "global", "$", "wp_registered_sidebars", ";", "$", "template", "=", "\\", "Modularity", "\\", "Helper", "\\", "Post", "::", "getPostTemplate", "(", ")", ";", "$", "sidebars", "=", "null", ";", "$", "activeAreas", "=", "$", "this", "->", "getActiveAreas", "(", "$", "template", ")", ";", "// Add no active sidebars message if no active sidebars exists", "if", "(", "is_array", "(", "$", "activeAreas", ")", "&&", "count", "(", "$", "activeAreas", ")", "===", "0", ")", "{", "add_meta_box", "(", "'no-sidebars'", ",", "__", "(", "'No active sidebar areas'", ",", "'modularity'", ")", ",", "function", "(", ")", "{", "echo", "'<p>'", ".", "__", "(", "'There\\'s no active sidebars. Please activate sidebar areas in the Modularity Options to add modules.'", ",", "'modularity'", ")", ".", "'</p>'", ";", "}", ",", "$", "this", "->", "screenHook", ",", "'normal'", ",", "'low'", ",", "null", ")", ";", "return", ";", "}", "if", "(", "is_array", "(", "$", "activeAreas", ")", "&&", "!", "empty", "(", "$", "activeAreas", ")", ")", "{", "foreach", "(", "$", "activeAreas", "as", "$", "area", ")", "{", "if", "(", "isset", "(", "$", "wp_registered_sidebars", "[", "$", "area", "]", ")", ")", "{", "$", "sidebars", "[", "$", "area", "]", "=", "$", "wp_registered_sidebars", "[", "$", "area", "]", ";", "}", "}", "if", "(", "is_array", "(", "$", "sidebars", ")", ")", "{", "foreach", "(", "$", "sidebars", "as", "$", "sidebar", ")", "{", "$", "this", "->", "sidebarMetaBox", "(", "$", "sidebar", ")", ";", "}", "}", "}", "}" ]
Loops registered sidebars and creates metaboxes for them @return void
[ "Loops", "registered", "sidebars", "and", "creates", "metaboxes", "for", "them" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L214-L254
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.metaBoxSidebar
public function metaBoxSidebar($post, $args) { global $post; $options = null; if (\Modularity\Helper\Post::isArchive()) { global $archive; $options = get_option('modularity_' . $archive . '_sidebar-options'); } else { if ($post) { $options = get_post_meta($post->ID, 'modularity-sidebar-options', true); } else { if (!isset($_GET['id']) || empty($_GET['id'])) { throw new \Error('Get paramter ID is empty.'); } $options = get_post_meta($_GET['id'], 'modularity-sidebar-options', true); } } if (isset($options[$args['args']['sidebar']['id']])) { $options = $options[$args['args']['sidebar']['id']]; } else { $options = null; } include MODULARITY_TEMPLATE_PATH . 'editor/modularity-sidebar-drop-area.php'; }
php
public function metaBoxSidebar($post, $args) { global $post; $options = null; if (\Modularity\Helper\Post::isArchive()) { global $archive; $options = get_option('modularity_' . $archive . '_sidebar-options'); } else { if ($post) { $options = get_post_meta($post->ID, 'modularity-sidebar-options', true); } else { if (!isset($_GET['id']) || empty($_GET['id'])) { throw new \Error('Get paramter ID is empty.'); } $options = get_post_meta($_GET['id'], 'modularity-sidebar-options', true); } } if (isset($options[$args['args']['sidebar']['id']])) { $options = $options[$args['args']['sidebar']['id']]; } else { $options = null; } include MODULARITY_TEMPLATE_PATH . 'editor/modularity-sidebar-drop-area.php'; }
[ "public", "function", "metaBoxSidebar", "(", "$", "post", ",", "$", "args", ")", "{", "global", "$", "post", ";", "$", "options", "=", "null", ";", "if", "(", "\\", "Modularity", "\\", "Helper", "\\", "Post", "::", "isArchive", "(", ")", ")", "{", "global", "$", "archive", ";", "$", "options", "=", "get_option", "(", "'modularity_'", ".", "$", "archive", ".", "'_sidebar-options'", ")", ";", "}", "else", "{", "if", "(", "$", "post", ")", "{", "$", "options", "=", "get_post_meta", "(", "$", "post", "->", "ID", ",", "'modularity-sidebar-options'", ",", "true", ")", ";", "}", "else", "{", "if", "(", "!", "isset", "(", "$", "_GET", "[", "'id'", "]", ")", "||", "empty", "(", "$", "_GET", "[", "'id'", "]", ")", ")", "{", "throw", "new", "\\", "Error", "(", "'Get paramter ID is empty.'", ")", ";", "}", "$", "options", "=", "get_post_meta", "(", "$", "_GET", "[", "'id'", "]", ",", "'modularity-sidebar-options'", ",", "true", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "options", "[", "$", "args", "[", "'args'", "]", "[", "'sidebar'", "]", "[", "'id'", "]", "]", ")", ")", "{", "$", "options", "=", "$", "options", "[", "$", "args", "[", "'args'", "]", "[", "'sidebar'", "]", "[", "'id'", "]", "]", ";", "}", "else", "{", "$", "options", "=", "null", ";", "}", "include", "MODULARITY_TEMPLATE_PATH", ".", "'editor/modularity-sidebar-drop-area.php'", ";", "}" ]
The content for sidebar metabox @param array $post @param array $args The metabox args @return void
[ "The", "content", "for", "sidebar", "metabox" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L323-L351
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.getPostModules
public static function getPostModules($postId) { //Declarations $modules = array(); $retModules = array(); //Get current post id $postId = self::pageForPostTypeTranscribe($postId); // Get enabled modules $available = \Modularity\ModuleManager::$available; $enabled = \Modularity\ModuleManager::$enabled; // Get modules structure $moduleIds = array(); $moduleSidebars = null; if (is_numeric($postId)) { $moduleSidebars = get_post_meta($postId, 'modularity-modules', true); } else { $moduleSidebars = get_option('modularity_' . $postId . '_modules'); } //Create array of visible modules if (!empty($moduleSidebars)) { foreach ($moduleSidebars as $sidebar) { foreach ($sidebar as $module) { if (!isset($module['postid'])) { continue; } $moduleIds[] = $module['postid']; } } } //Get allowed post statuses $postStatuses = array('publish'); if (is_user_logged_in()) { $postStatuses[] = 'private'; } // Get module posts $modulesPosts = get_posts(array( 'posts_per_page' => -1, 'post_type' => $enabled, 'include' => $moduleIds, 'post_status' => $postStatuses )); // Add module id's as keys in the array if (!empty($modulesPosts)) { foreach ($modulesPosts as $module) { $modules[$module->ID] = $module; } } // Create an strucural correct array with module post data if (!empty($moduleSidebars)) { foreach ($moduleSidebars as $key => $sidebar) { $retModules[$key] = array( 'modules' => array(), // Todo: This will duplicate for every sidebar, move it to top level of array(?) // Alternatively only fetch options for the current sidebar (not all like now) 'options' => get_post_meta($postId, 'modularity-sidebar-options', true) ); $arrayIndex = 0; foreach ($sidebar as $moduleUid => $module) { if (!isset($module['postid'])) { continue; } $moduleId = $module['postid']; if (!isset($modules[$moduleId])) { continue; } $moduleObject = self::getModule($moduleId, $module); if (!$moduleObject) { continue; } $retModules[$key]['modules'][$arrayIndex] = $moduleObject; $arrayIndex++; } } } return $retModules; }
php
public static function getPostModules($postId) { //Declarations $modules = array(); $retModules = array(); //Get current post id $postId = self::pageForPostTypeTranscribe($postId); // Get enabled modules $available = \Modularity\ModuleManager::$available; $enabled = \Modularity\ModuleManager::$enabled; // Get modules structure $moduleIds = array(); $moduleSidebars = null; if (is_numeric($postId)) { $moduleSidebars = get_post_meta($postId, 'modularity-modules', true); } else { $moduleSidebars = get_option('modularity_' . $postId . '_modules'); } //Create array of visible modules if (!empty($moduleSidebars)) { foreach ($moduleSidebars as $sidebar) { foreach ($sidebar as $module) { if (!isset($module['postid'])) { continue; } $moduleIds[] = $module['postid']; } } } //Get allowed post statuses $postStatuses = array('publish'); if (is_user_logged_in()) { $postStatuses[] = 'private'; } // Get module posts $modulesPosts = get_posts(array( 'posts_per_page' => -1, 'post_type' => $enabled, 'include' => $moduleIds, 'post_status' => $postStatuses )); // Add module id's as keys in the array if (!empty($modulesPosts)) { foreach ($modulesPosts as $module) { $modules[$module->ID] = $module; } } // Create an strucural correct array with module post data if (!empty($moduleSidebars)) { foreach ($moduleSidebars as $key => $sidebar) { $retModules[$key] = array( 'modules' => array(), // Todo: This will duplicate for every sidebar, move it to top level of array(?) // Alternatively only fetch options for the current sidebar (not all like now) 'options' => get_post_meta($postId, 'modularity-sidebar-options', true) ); $arrayIndex = 0; foreach ($sidebar as $moduleUid => $module) { if (!isset($module['postid'])) { continue; } $moduleId = $module['postid']; if (!isset($modules[$moduleId])) { continue; } $moduleObject = self::getModule($moduleId, $module); if (!$moduleObject) { continue; } $retModules[$key]['modules'][$arrayIndex] = $moduleObject; $arrayIndex++; } } } return $retModules; }
[ "public", "static", "function", "getPostModules", "(", "$", "postId", ")", "{", "//Declarations", "$", "modules", "=", "array", "(", ")", ";", "$", "retModules", "=", "array", "(", ")", ";", "//Get current post id", "$", "postId", "=", "self", "::", "pageForPostTypeTranscribe", "(", "$", "postId", ")", ";", "// Get enabled modules", "$", "available", "=", "\\", "Modularity", "\\", "ModuleManager", "::", "$", "available", ";", "$", "enabled", "=", "\\", "Modularity", "\\", "ModuleManager", "::", "$", "enabled", ";", "// Get modules structure", "$", "moduleIds", "=", "array", "(", ")", ";", "$", "moduleSidebars", "=", "null", ";", "if", "(", "is_numeric", "(", "$", "postId", ")", ")", "{", "$", "moduleSidebars", "=", "get_post_meta", "(", "$", "postId", ",", "'modularity-modules'", ",", "true", ")", ";", "}", "else", "{", "$", "moduleSidebars", "=", "get_option", "(", "'modularity_'", ".", "$", "postId", ".", "'_modules'", ")", ";", "}", "//Create array of visible modules", "if", "(", "!", "empty", "(", "$", "moduleSidebars", ")", ")", "{", "foreach", "(", "$", "moduleSidebars", "as", "$", "sidebar", ")", "{", "foreach", "(", "$", "sidebar", "as", "$", "module", ")", "{", "if", "(", "!", "isset", "(", "$", "module", "[", "'postid'", "]", ")", ")", "{", "continue", ";", "}", "$", "moduleIds", "[", "]", "=", "$", "module", "[", "'postid'", "]", ";", "}", "}", "}", "//Get allowed post statuses", "$", "postStatuses", "=", "array", "(", "'publish'", ")", ";", "if", "(", "is_user_logged_in", "(", ")", ")", "{", "$", "postStatuses", "[", "]", "=", "'private'", ";", "}", "// Get module posts", "$", "modulesPosts", "=", "get_posts", "(", "array", "(", "'posts_per_page'", "=>", "-", "1", ",", "'post_type'", "=>", "$", "enabled", ",", "'include'", "=>", "$", "moduleIds", ",", "'post_status'", "=>", "$", "postStatuses", ")", ")", ";", "// Add module id's as keys in the array", "if", "(", "!", "empty", "(", "$", "modulesPosts", ")", ")", "{", "foreach", "(", "$", "modulesPosts", "as", "$", "module", ")", "{", "$", "modules", "[", "$", "module", "->", "ID", "]", "=", "$", "module", ";", "}", "}", "// Create an strucural correct array with module post data", "if", "(", "!", "empty", "(", "$", "moduleSidebars", ")", ")", "{", "foreach", "(", "$", "moduleSidebars", "as", "$", "key", "=>", "$", "sidebar", ")", "{", "$", "retModules", "[", "$", "key", "]", "=", "array", "(", "'modules'", "=>", "array", "(", ")", ",", "// Todo: This will duplicate for every sidebar, move it to top level of array(?)", "// Alternatively only fetch options for the current sidebar (not all like now)", "'options'", "=>", "get_post_meta", "(", "$", "postId", ",", "'modularity-sidebar-options'", ",", "true", ")", ")", ";", "$", "arrayIndex", "=", "0", ";", "foreach", "(", "$", "sidebar", "as", "$", "moduleUid", "=>", "$", "module", ")", "{", "if", "(", "!", "isset", "(", "$", "module", "[", "'postid'", "]", ")", ")", "{", "continue", ";", "}", "$", "moduleId", "=", "$", "module", "[", "'postid'", "]", ";", "if", "(", "!", "isset", "(", "$", "modules", "[", "$", "moduleId", "]", ")", ")", "{", "continue", ";", "}", "$", "moduleObject", "=", "self", "::", "getModule", "(", "$", "moduleId", ",", "$", "module", ")", ";", "if", "(", "!", "$", "moduleObject", ")", "{", "continue", ";", "}", "$", "retModules", "[", "$", "key", "]", "[", "'modules'", "]", "[", "$", "arrayIndex", "]", "=", "$", "moduleObject", ";", "$", "arrayIndex", "++", ";", "}", "}", "}", "return", "$", "retModules", ";", "}" ]
Get modules added to a specific post @param integer $postId The post id @return array The modules on the post
[ "Get", "modules", "added", "to", "a", "specific", "post" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L377-L471
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.save
public function save() { if (!$this->isValidPostSave()) { return; } // Check if post id is valid if (!isset($_REQUEST['id']) || empty($_REQUEST['id'])) { return trigger_error('Invalid post id. Please contact system administrator.'); } $this->savePost(); // If this is an ajax post, return "success" as plain text if (defined('DOING_AJAX') && DOING_AJAX) { echo "success"; wp_die(); } $this->notice(__('Modules saved', 'modularity'), ['updated']); }
php
public function save() { if (!$this->isValidPostSave()) { return; } // Check if post id is valid if (!isset($_REQUEST['id']) || empty($_REQUEST['id'])) { return trigger_error('Invalid post id. Please contact system administrator.'); } $this->savePost(); // If this is an ajax post, return "success" as plain text if (defined('DOING_AJAX') && DOING_AJAX) { echo "success"; wp_die(); } $this->notice(__('Modules saved', 'modularity'), ['updated']); }
[ "public", "function", "save", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isValidPostSave", "(", ")", ")", "{", "return", ";", "}", "// Check if post id is valid", "if", "(", "!", "isset", "(", "$", "_REQUEST", "[", "'id'", "]", ")", "||", "empty", "(", "$", "_REQUEST", "[", "'id'", "]", ")", ")", "{", "return", "trigger_error", "(", "'Invalid post id. Please contact system administrator.'", ")", ";", "}", "$", "this", "->", "savePost", "(", ")", ";", "// If this is an ajax post, return \"success\" as plain text", "if", "(", "defined", "(", "'DOING_AJAX'", ")", "&&", "DOING_AJAX", ")", "{", "echo", "\"success\"", ";", "wp_die", "(", ")", ";", "}", "$", "this", "->", "notice", "(", "__", "(", "'Modules saved'", ",", "'modularity'", ")", ",", "[", "'updated'", "]", ")", ";", "}" ]
Saves the selected modules @return void
[ "Saves", "the", "selected", "modules" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L521-L541
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.savePost
public function savePost() { $key = $_REQUEST['id']; if (is_numeric($key)) { return $this->saveAsPostMeta($key); } if (\Modularity\Helper\Post::isArchive()) { global $archive; $key = $archive; } return $this->saveAsOption($key); }
php
public function savePost() { $key = $_REQUEST['id']; if (is_numeric($key)) { return $this->saveAsPostMeta($key); } if (\Modularity\Helper\Post::isArchive()) { global $archive; $key = $archive; } return $this->saveAsOption($key); }
[ "public", "function", "savePost", "(", ")", "{", "$", "key", "=", "$", "_REQUEST", "[", "'id'", "]", ";", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "saveAsPostMeta", "(", "$", "key", ")", ";", "}", "if", "(", "\\", "Modularity", "\\", "Helper", "\\", "Post", "::", "isArchive", "(", ")", ")", "{", "global", "$", "archive", ";", "$", "key", "=", "$", "archive", ";", "}", "return", "$", "this", "->", "saveAsOption", "(", "$", "key", ")", ";", "}" ]
Saves post modules @return boolean
[ "Saves", "post", "modules" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L547-L561
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.saveAsOption
public function saveAsOption($key) { $key = 'modularity_' . $key; $optionName = $key . '_modules'; if (isset($_POST['modularity_modules'])) { $data = $this->sanitizeModuleData($_POST['modularity_modules']); if (get_option($optionName)) { update_option($optionName, $data); } else { add_option($optionName, $data, '', 'no'); } } else { delete_option($optionName); } // Save/remove sidebar options $optionName = $key . '_sidebar-options'; if (isset($_POST['modularity_sidebar_options'])) { if (get_option($optionName)) { update_option($optionName, $_POST['modularity_sidebar_options']); } else { add_option($optionName, $_POST['modularity_sidebar_options'], '', 'no'); } } else { delete_option($optionName); } return true; }
php
public function saveAsOption($key) { $key = 'modularity_' . $key; $optionName = $key . '_modules'; if (isset($_POST['modularity_modules'])) { $data = $this->sanitizeModuleData($_POST['modularity_modules']); if (get_option($optionName)) { update_option($optionName, $data); } else { add_option($optionName, $data, '', 'no'); } } else { delete_option($optionName); } // Save/remove sidebar options $optionName = $key . '_sidebar-options'; if (isset($_POST['modularity_sidebar_options'])) { if (get_option($optionName)) { update_option($optionName, $_POST['modularity_sidebar_options']); } else { add_option($optionName, $_POST['modularity_sidebar_options'], '', 'no'); } } else { delete_option($optionName); } return true; }
[ "public", "function", "saveAsOption", "(", "$", "key", ")", "{", "$", "key", "=", "'modularity_'", ".", "$", "key", ";", "$", "optionName", "=", "$", "key", ".", "'_modules'", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'modularity_modules'", "]", ")", ")", "{", "$", "data", "=", "$", "this", "->", "sanitizeModuleData", "(", "$", "_POST", "[", "'modularity_modules'", "]", ")", ";", "if", "(", "get_option", "(", "$", "optionName", ")", ")", "{", "update_option", "(", "$", "optionName", ",", "$", "data", ")", ";", "}", "else", "{", "add_option", "(", "$", "optionName", ",", "$", "data", ",", "''", ",", "'no'", ")", ";", "}", "}", "else", "{", "delete_option", "(", "$", "optionName", ")", ";", "}", "// Save/remove sidebar options", "$", "optionName", "=", "$", "key", ".", "'_sidebar-options'", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'modularity_sidebar_options'", "]", ")", ")", "{", "if", "(", "get_option", "(", "$", "optionName", ")", ")", "{", "update_option", "(", "$", "optionName", ",", "$", "_POST", "[", "'modularity_sidebar_options'", "]", ")", ";", "}", "else", "{", "add_option", "(", "$", "optionName", ",", "$", "_POST", "[", "'modularity_sidebar_options'", "]", ",", "''", ",", "'no'", ")", ";", "}", "}", "else", "{", "delete_option", "(", "$", "optionName", ")", ";", "}", "return", "true", ";", "}" ]
Saves archive modules @return boolean
[ "Saves", "archive", "modules" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L587-L617
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.getWidthOptions
public function getWidthOptions() { $markup = '<option value="">' . __('Inherit', 'modularity') . '</option>' . "\n"; foreach (self::widthOptions() as $key => $value) { $markup .= '<option value="' . $key . '">' . $value . '</option>' . "\n"; } return $markup; }
php
public function getWidthOptions() { $markup = '<option value="">' . __('Inherit', 'modularity') . '</option>' . "\n"; foreach (self::widthOptions() as $key => $value) { $markup .= '<option value="' . $key . '">' . $value . '</option>' . "\n"; } return $markup; }
[ "public", "function", "getWidthOptions", "(", ")", "{", "$", "markup", "=", "'<option value=\"\">'", ".", "__", "(", "'Inherit'", ",", "'modularity'", ")", ".", "'</option>'", ".", "\"\\n\"", ";", "foreach", "(", "self", "::", "widthOptions", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "markup", ".=", "'<option value=\"'", ".", "$", "key", ".", "'\">'", ".", "$", "value", ".", "'</option>'", ".", "\"\\n\"", ";", "}", "return", "$", "markup", ";", "}" ]
Get column width options @return string Options markup
[ "Get", "column", "width", "options" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L623-L632
train
helsingborg-stad/Modularity
source/php/Editor.php
Editor.registerScopeMetaBox
public function registerScopeMetaBox($postType, $choises) { if (!is_string($postType)) { return WP_Error("Post type variable must be of the type string."); } if (!is_array($choises)) { return WP_Error("Choises variable must be of the type assoc array."); } if (!function_exists('acf_add_local_field_group')) { return WP_Error("Could not find required ACF function acf_add_local_field_group."); } acf_add_local_field_group(array( 'key' => 'group_' . substr(md5($postType . '_scope'), 0, 13), 'title' => __('Scope styling', 'modularity'), 'fields' => array( array( 'key' => 'field_' . substr(md5($postType . '_scope'), 0, 13), 'label' => __('Select an apperance for this instance of module', 'modularity'), 'name' => 'module_css_scope', 'type' => 'select', 'instructions' => __('By selecting a scope for this class, they will appear in a different way than the standard layout.', 'modularity'), 'required' => 0, 'conditional_logic' => 0, 'wrapper' => array( 'width' => '', 'class' => '', 'id' => '', ), 'choices' => $choises, 'default_value' => array( ), 'allow_null' => 1, 'multiple' => 0, 'ui' => 0, 'ajax' => 0, 'return_format' => 'value', 'placeholder' => '', ), ), 'location' => array( array( array( 'param' => 'post_type', 'operator' => '==', 'value' => $postType, ), ), ), 'menu_order' => 0, 'position' => 'side', 'style' => 'default', 'label_placement' => 'top', 'instruction_placement' => 'label', 'hide_on_screen' => '', 'active' => 1, 'description' => '', )); return true; }
php
public function registerScopeMetaBox($postType, $choises) { if (!is_string($postType)) { return WP_Error("Post type variable must be of the type string."); } if (!is_array($choises)) { return WP_Error("Choises variable must be of the type assoc array."); } if (!function_exists('acf_add_local_field_group')) { return WP_Error("Could not find required ACF function acf_add_local_field_group."); } acf_add_local_field_group(array( 'key' => 'group_' . substr(md5($postType . '_scope'), 0, 13), 'title' => __('Scope styling', 'modularity'), 'fields' => array( array( 'key' => 'field_' . substr(md5($postType . '_scope'), 0, 13), 'label' => __('Select an apperance for this instance of module', 'modularity'), 'name' => 'module_css_scope', 'type' => 'select', 'instructions' => __('By selecting a scope for this class, they will appear in a different way than the standard layout.', 'modularity'), 'required' => 0, 'conditional_logic' => 0, 'wrapper' => array( 'width' => '', 'class' => '', 'id' => '', ), 'choices' => $choises, 'default_value' => array( ), 'allow_null' => 1, 'multiple' => 0, 'ui' => 0, 'ajax' => 0, 'return_format' => 'value', 'placeholder' => '', ), ), 'location' => array( array( array( 'param' => 'post_type', 'operator' => '==', 'value' => $postType, ), ), ), 'menu_order' => 0, 'position' => 'side', 'style' => 'default', 'label_placement' => 'top', 'instruction_placement' => 'label', 'hide_on_screen' => '', 'active' => 1, 'description' => '', )); return true; }
[ "public", "function", "registerScopeMetaBox", "(", "$", "postType", ",", "$", "choises", ")", "{", "if", "(", "!", "is_string", "(", "$", "postType", ")", ")", "{", "return", "WP_Error", "(", "\"Post type variable must be of the type string.\"", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "choises", ")", ")", "{", "return", "WP_Error", "(", "\"Choises variable must be of the type assoc array.\"", ")", ";", "}", "if", "(", "!", "function_exists", "(", "'acf_add_local_field_group'", ")", ")", "{", "return", "WP_Error", "(", "\"Could not find required ACF function acf_add_local_field_group.\"", ")", ";", "}", "acf_add_local_field_group", "(", "array", "(", "'key'", "=>", "'group_'", ".", "substr", "(", "md5", "(", "$", "postType", ".", "'_scope'", ")", ",", "0", ",", "13", ")", ",", "'title'", "=>", "__", "(", "'Scope styling'", ",", "'modularity'", ")", ",", "'fields'", "=>", "array", "(", "array", "(", "'key'", "=>", "'field_'", ".", "substr", "(", "md5", "(", "$", "postType", ".", "'_scope'", ")", ",", "0", ",", "13", ")", ",", "'label'", "=>", "__", "(", "'Select an apperance for this instance of module'", ",", "'modularity'", ")", ",", "'name'", "=>", "'module_css_scope'", ",", "'type'", "=>", "'select'", ",", "'instructions'", "=>", "__", "(", "'By selecting a scope for this class, they will appear in a different way than the standard layout.'", ",", "'modularity'", ")", ",", "'required'", "=>", "0", ",", "'conditional_logic'", "=>", "0", ",", "'wrapper'", "=>", "array", "(", "'width'", "=>", "''", ",", "'class'", "=>", "''", ",", "'id'", "=>", "''", ",", ")", ",", "'choices'", "=>", "$", "choises", ",", "'default_value'", "=>", "array", "(", ")", ",", "'allow_null'", "=>", "1", ",", "'multiple'", "=>", "0", ",", "'ui'", "=>", "0", ",", "'ajax'", "=>", "0", ",", "'return_format'", "=>", "'value'", ",", "'placeholder'", "=>", "''", ",", ")", ",", ")", ",", "'location'", "=>", "array", "(", "array", "(", "array", "(", "'param'", "=>", "'post_type'", ",", "'operator'", "=>", "'=='", ",", "'value'", "=>", "$", "postType", ",", ")", ",", ")", ",", ")", ",", "'menu_order'", "=>", "0", ",", "'position'", "=>", "'side'", ",", "'style'", "=>", "'default'", ",", "'label_placement'", "=>", "'top'", ",", "'instruction_placement'", "=>", "'label'", ",", "'hide_on_screen'", "=>", "''", ",", "'active'", "=>", "1", ",", "'description'", "=>", "''", ",", ")", ")", ";", "return", "true", ";", "}" ]
Registers a scope metabox @return WP_Error, true
[ "Registers", "a", "scope", "metabox" ]
db4fcde30ba5db4fac9c8b3c3475c8229b50271d
https://github.com/helsingborg-stad/Modularity/blob/db4fcde30ba5db4fac9c8b3c3475c8229b50271d/source/php/Editor.php#L670-L732
train