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
silverstripe/silverstripe-framework
src/Core/Extensible.php
Extensible.add_extension
public static function add_extension($classOrExtension, $extension = null) { if ($extension) { $class = $classOrExtension; } else { $class = get_called_class(); $extension = $classOrExtension; } if (!preg_match('/^([^(]*)/', $extension, $matches)) { return false; } $extensionClass = $matches[1]; if (!class_exists($extensionClass)) { user_error( sprintf('Object::add_extension() - Can\'t find extension class for "%s"', $extensionClass), E_USER_ERROR ); } if (!is_subclass_of($extensionClass, 'SilverStripe\\Core\\Extension')) { user_error( sprintf('Object::add_extension() - Extension "%s" is not a subclass of Extension', $extensionClass), E_USER_ERROR ); } // unset some caches $subclasses = ClassInfo::subclassesFor($class); $subclasses[] = $class; if ($subclasses) { foreach ($subclasses as $subclass) { unset(self::$extra_methods[$subclass]); } } Config::modify() ->merge($class, 'extensions', array( $extension )); Injector::inst()->unregisterNamedObject($class); return true; }
php
public static function add_extension($classOrExtension, $extension = null) { if ($extension) { $class = $classOrExtension; } else { $class = get_called_class(); $extension = $classOrExtension; } if (!preg_match('/^([^(]*)/', $extension, $matches)) { return false; } $extensionClass = $matches[1]; if (!class_exists($extensionClass)) { user_error( sprintf('Object::add_extension() - Can\'t find extension class for "%s"', $extensionClass), E_USER_ERROR ); } if (!is_subclass_of($extensionClass, 'SilverStripe\\Core\\Extension')) { user_error( sprintf('Object::add_extension() - Extension "%s" is not a subclass of Extension', $extensionClass), E_USER_ERROR ); } // unset some caches $subclasses = ClassInfo::subclassesFor($class); $subclasses[] = $class; if ($subclasses) { foreach ($subclasses as $subclass) { unset(self::$extra_methods[$subclass]); } } Config::modify() ->merge($class, 'extensions', array( $extension )); Injector::inst()->unregisterNamedObject($class); return true; }
[ "public", "static", "function", "add_extension", "(", "$", "classOrExtension", ",", "$", "extension", "=", "null", ")", "{", "if", "(", "$", "extension", ")", "{", "$", "class", "=", "$", "classOrExtension", ";", "}", "else", "{", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "extension", "=", "$", "classOrExtension", ";", "}", "if", "(", "!", "preg_match", "(", "'/^([^(]*)/'", ",", "$", "extension", ",", "$", "matches", ")", ")", "{", "return", "false", ";", "}", "$", "extensionClass", "=", "$", "matches", "[", "1", "]", ";", "if", "(", "!", "class_exists", "(", "$", "extensionClass", ")", ")", "{", "user_error", "(", "sprintf", "(", "'Object::add_extension() - Can\\'t find extension class for \"%s\"'", ",", "$", "extensionClass", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "!", "is_subclass_of", "(", "$", "extensionClass", ",", "'SilverStripe\\\\Core\\\\Extension'", ")", ")", "{", "user_error", "(", "sprintf", "(", "'Object::add_extension() - Extension \"%s\" is not a subclass of Extension'", ",", "$", "extensionClass", ")", ",", "E_USER_ERROR", ")", ";", "}", "// unset some caches", "$", "subclasses", "=", "ClassInfo", "::", "subclassesFor", "(", "$", "class", ")", ";", "$", "subclasses", "[", "]", "=", "$", "class", ";", "if", "(", "$", "subclasses", ")", "{", "foreach", "(", "$", "subclasses", "as", "$", "subclass", ")", "{", "unset", "(", "self", "::", "$", "extra_methods", "[", "$", "subclass", "]", ")", ";", "}", "}", "Config", "::", "modify", "(", ")", "->", "merge", "(", "$", "class", ",", "'extensions'", ",", "array", "(", "$", "extension", ")", ")", ";", "Injector", "::", "inst", "(", ")", "->", "unregisterNamedObject", "(", "$", "class", ")", ";", "return", "true", ";", "}" ]
Add an extension to a specific class. The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations. As an alternative, extensions can be added to a specific class directly in the {@link Object::$extensions} array. See {@link SiteTree::$extensions} for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through {@link singleton()}). @see http://doc.silverstripe.org/framework/en/trunk/reference/dataextension @param string $classOrExtension Class that should be extended - has to be a subclass of {@link Object} @param string $extension Subclass of {@link Extension} with optional parameters as a string, e.g. "Versioned" or "Translatable('Param')" @return bool Flag if the extension was added
[ "Add", "an", "extension", "to", "a", "specific", "class", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Extensible.php#L172-L216
train
silverstripe/silverstripe-framework
src/Core/Extensible.php
Extensible.get_extra_config_sources
public static function get_extra_config_sources($class = null) { if (!$class) { $class = get_called_class(); } // If this class is unextendable, NOP if (in_array($class, self::$unextendable_classes)) { return null; } // Variable to hold sources in $sources = null; // Get a list of extensions $extensions = Config::inst()->get($class, 'extensions', Config::EXCLUDE_EXTRA_SOURCES | Config::UNINHERITED); if (!$extensions) { return null; } // Build a list of all sources; $sources = array(); foreach ($extensions as $extension) { list($extensionClass, $extensionArgs) = ClassInfo::parse_class_spec($extension); // Strip service name specifier $extensionClass = strtok($extensionClass, '.'); $sources[] = $extensionClass; if (!class_exists($extensionClass)) { throw new InvalidArgumentException("$class references nonexistent $extensionClass in \$extensions"); } call_user_func(array($extensionClass, 'add_to_class'), $class, $extensionClass, $extensionArgs); foreach (array_reverse(ClassInfo::ancestry($extensionClass)) as $extensionClassParent) { if (ClassInfo::has_method_from($extensionClassParent, 'get_extra_config', $extensionClassParent)) { $extras = $extensionClassParent::get_extra_config($class, $extensionClass, $extensionArgs); if ($extras) { $sources[] = $extras; } } } } return $sources; }
php
public static function get_extra_config_sources($class = null) { if (!$class) { $class = get_called_class(); } // If this class is unextendable, NOP if (in_array($class, self::$unextendable_classes)) { return null; } // Variable to hold sources in $sources = null; // Get a list of extensions $extensions = Config::inst()->get($class, 'extensions', Config::EXCLUDE_EXTRA_SOURCES | Config::UNINHERITED); if (!$extensions) { return null; } // Build a list of all sources; $sources = array(); foreach ($extensions as $extension) { list($extensionClass, $extensionArgs) = ClassInfo::parse_class_spec($extension); // Strip service name specifier $extensionClass = strtok($extensionClass, '.'); $sources[] = $extensionClass; if (!class_exists($extensionClass)) { throw new InvalidArgumentException("$class references nonexistent $extensionClass in \$extensions"); } call_user_func(array($extensionClass, 'add_to_class'), $class, $extensionClass, $extensionArgs); foreach (array_reverse(ClassInfo::ancestry($extensionClass)) as $extensionClassParent) { if (ClassInfo::has_method_from($extensionClassParent, 'get_extra_config', $extensionClassParent)) { $extras = $extensionClassParent::get_extra_config($class, $extensionClass, $extensionArgs); if ($extras) { $sources[] = $extras; } } } } return $sources; }
[ "public", "static", "function", "get_extra_config_sources", "(", "$", "class", "=", "null", ")", "{", "if", "(", "!", "$", "class", ")", "{", "$", "class", "=", "get_called_class", "(", ")", ";", "}", "// If this class is unextendable, NOP", "if", "(", "in_array", "(", "$", "class", ",", "self", "::", "$", "unextendable_classes", ")", ")", "{", "return", "null", ";", "}", "// Variable to hold sources in", "$", "sources", "=", "null", ";", "// Get a list of extensions", "$", "extensions", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'extensions'", ",", "Config", "::", "EXCLUDE_EXTRA_SOURCES", "|", "Config", "::", "UNINHERITED", ")", ";", "if", "(", "!", "$", "extensions", ")", "{", "return", "null", ";", "}", "// Build a list of all sources;", "$", "sources", "=", "array", "(", ")", ";", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "list", "(", "$", "extensionClass", ",", "$", "extensionArgs", ")", "=", "ClassInfo", "::", "parse_class_spec", "(", "$", "extension", ")", ";", "// Strip service name specifier", "$", "extensionClass", "=", "strtok", "(", "$", "extensionClass", ",", "'.'", ")", ";", "$", "sources", "[", "]", "=", "$", "extensionClass", ";", "if", "(", "!", "class_exists", "(", "$", "extensionClass", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"$class references nonexistent $extensionClass in \\$extensions\"", ")", ";", "}", "call_user_func", "(", "array", "(", "$", "extensionClass", ",", "'add_to_class'", ")", ",", "$", "class", ",", "$", "extensionClass", ",", "$", "extensionArgs", ")", ";", "foreach", "(", "array_reverse", "(", "ClassInfo", "::", "ancestry", "(", "$", "extensionClass", ")", ")", "as", "$", "extensionClassParent", ")", "{", "if", "(", "ClassInfo", "::", "has_method_from", "(", "$", "extensionClassParent", ",", "'get_extra_config'", ",", "$", "extensionClassParent", ")", ")", "{", "$", "extras", "=", "$", "extensionClassParent", "::", "get_extra_config", "(", "$", "class", ",", "$", "extensionClass", ",", "$", "extensionArgs", ")", ";", "if", "(", "$", "extras", ")", "{", "$", "sources", "[", "]", "=", "$", "extras", ";", "}", "}", "}", "}", "return", "$", "sources", ";", "}" ]
Get extra config sources for this class @param string $class Name of class. If left null will return for the current class @return array|null
[ "Get", "extra", "config", "sources", "for", "this", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Extensible.php#L312-L359
train
silverstripe/silverstripe-framework
src/Core/Extensible.php
Extensible.extend
public function extend($method, &$a1 = null, &$a2 = null, &$a3 = null, &$a4 = null, &$a5 = null, &$a6 = null, &$a7 = null) { $values = array(); if (!empty($this->beforeExtendCallbacks[$method])) { foreach (array_reverse($this->beforeExtendCallbacks[$method]) as $callback) { $value = call_user_func_array($callback, array(&$a1, &$a2, &$a3, &$a4, &$a5, &$a6, &$a7)); if ($value !== null) { $values[] = $value; } } $this->beforeExtendCallbacks[$method] = array(); } foreach ($this->getExtensionInstances() as $instance) { if (method_exists($instance, $method)) { try { $instance->setOwner($this); $value = $instance->$method($a1, $a2, $a3, $a4, $a5, $a6, $a7); } finally { $instance->clearOwner(); } if ($value !== null) { $values[] = $value; } } } if (!empty($this->afterExtendCallbacks[$method])) { foreach (array_reverse($this->afterExtendCallbacks[$method]) as $callback) { $value = call_user_func_array($callback, array(&$a1, &$a2, &$a3, &$a4, &$a5, &$a6, &$a7)); if ($value !== null) { $values[] = $value; } } $this->afterExtendCallbacks[$method] = array(); } return $values; }
php
public function extend($method, &$a1 = null, &$a2 = null, &$a3 = null, &$a4 = null, &$a5 = null, &$a6 = null, &$a7 = null) { $values = array(); if (!empty($this->beforeExtendCallbacks[$method])) { foreach (array_reverse($this->beforeExtendCallbacks[$method]) as $callback) { $value = call_user_func_array($callback, array(&$a1, &$a2, &$a3, &$a4, &$a5, &$a6, &$a7)); if ($value !== null) { $values[] = $value; } } $this->beforeExtendCallbacks[$method] = array(); } foreach ($this->getExtensionInstances() as $instance) { if (method_exists($instance, $method)) { try { $instance->setOwner($this); $value = $instance->$method($a1, $a2, $a3, $a4, $a5, $a6, $a7); } finally { $instance->clearOwner(); } if ($value !== null) { $values[] = $value; } } } if (!empty($this->afterExtendCallbacks[$method])) { foreach (array_reverse($this->afterExtendCallbacks[$method]) as $callback) { $value = call_user_func_array($callback, array(&$a1, &$a2, &$a3, &$a4, &$a5, &$a6, &$a7)); if ($value !== null) { $values[] = $value; } } $this->afterExtendCallbacks[$method] = array(); } return $values; }
[ "public", "function", "extend", "(", "$", "method", ",", "&", "$", "a1", "=", "null", ",", "&", "$", "a2", "=", "null", ",", "&", "$", "a3", "=", "null", ",", "&", "$", "a4", "=", "null", ",", "&", "$", "a5", "=", "null", ",", "&", "$", "a6", "=", "null", ",", "&", "$", "a7", "=", "null", ")", "{", "$", "values", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "beforeExtendCallbacks", "[", "$", "method", "]", ")", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "beforeExtendCallbacks", "[", "$", "method", "]", ")", "as", "$", "callback", ")", "{", "$", "value", "=", "call_user_func_array", "(", "$", "callback", ",", "array", "(", "&", "$", "a1", ",", "&", "$", "a2", ",", "&", "$", "a3", ",", "&", "$", "a4", ",", "&", "$", "a5", ",", "&", "$", "a6", ",", "&", "$", "a7", ")", ")", ";", "if", "(", "$", "value", "!==", "null", ")", "{", "$", "values", "[", "]", "=", "$", "value", ";", "}", "}", "$", "this", "->", "beforeExtendCallbacks", "[", "$", "method", "]", "=", "array", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "getExtensionInstances", "(", ")", "as", "$", "instance", ")", "{", "if", "(", "method_exists", "(", "$", "instance", ",", "$", "method", ")", ")", "{", "try", "{", "$", "instance", "->", "setOwner", "(", "$", "this", ")", ";", "$", "value", "=", "$", "instance", "->", "$", "method", "(", "$", "a1", ",", "$", "a2", ",", "$", "a3", ",", "$", "a4", ",", "$", "a5", ",", "$", "a6", ",", "$", "a7", ")", ";", "}", "finally", "{", "$", "instance", "->", "clearOwner", "(", ")", ";", "}", "if", "(", "$", "value", "!==", "null", ")", "{", "$", "values", "[", "]", "=", "$", "value", ";", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "afterExtendCallbacks", "[", "$", "method", "]", ")", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "afterExtendCallbacks", "[", "$", "method", "]", ")", "as", "$", "callback", ")", "{", "$", "value", "=", "call_user_func_array", "(", "$", "callback", ",", "array", "(", "&", "$", "a1", ",", "&", "$", "a2", ",", "&", "$", "a3", ",", "&", "$", "a4", ",", "&", "$", "a5", ",", "&", "$", "a6", ",", "&", "$", "a7", ")", ")", ";", "if", "(", "$", "value", "!==", "null", ")", "{", "$", "values", "[", "]", "=", "$", "value", ";", "}", "}", "$", "this", "->", "afterExtendCallbacks", "[", "$", "method", "]", "=", "array", "(", ")", ";", "}", "return", "$", "values", ";", "}" ]
Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks. The extension methods are defined during {@link __construct()} in {@link defineMethods()}. @param string $method the name of the method to call on each extension @param mixed $a1 @param mixed $a2 @param mixed $a3 @param mixed $a4 @param mixed $a5 @param mixed $a6 @param mixed $a7 @return array
[ "Run", "the", "given", "function", "on", "all", "of", "this", "object", "s", "extensions", ".", "Note", "that", "this", "method", "originally", "returned", "void", "so", "if", "you", "wanted", "to", "return", "results", "you", "re", "hosed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Extensible.php#L450-L489
train
silverstripe/silverstripe-framework
src/Core/Extensible.php
Extensible.getExtensionInstance
public function getExtensionInstance($extension) { $instances = $this->getExtensionInstances(); if (array_key_exists($extension, $instances)) { return $instances[$extension]; } // in case Injector has been used to replace an extension foreach ($instances as $instance) { if (is_a($instance, $extension)) { return $instance; } } return null; }
php
public function getExtensionInstance($extension) { $instances = $this->getExtensionInstances(); if (array_key_exists($extension, $instances)) { return $instances[$extension]; } // in case Injector has been used to replace an extension foreach ($instances as $instance) { if (is_a($instance, $extension)) { return $instance; } } return null; }
[ "public", "function", "getExtensionInstance", "(", "$", "extension", ")", "{", "$", "instances", "=", "$", "this", "->", "getExtensionInstances", "(", ")", ";", "if", "(", "array_key_exists", "(", "$", "extension", ",", "$", "instances", ")", ")", "{", "return", "$", "instances", "[", "$", "extension", "]", ";", "}", "// in case Injector has been used to replace an extension", "foreach", "(", "$", "instances", "as", "$", "instance", ")", "{", "if", "(", "is_a", "(", "$", "instance", ",", "$", "extension", ")", ")", "{", "return", "$", "instance", ";", "}", "}", "return", "null", ";", "}" ]
Get an extension instance attached to this object by name. @param string $extension @return Extension|null
[ "Get", "an", "extension", "instance", "attached", "to", "this", "object", "by", "name", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Extensible.php#L497-L510
train
silverstripe/silverstripe-framework
src/Security/LogoutForm.php
LogoutForm.getFormFields
protected function getFormFields() { $fields = FieldList::create(); $controller = $this->getController(); $backURL = $controller->getBackURL() ?: $controller->getReturnReferer(); // Protect against infinite redirection back to the logout URL after logging out if (!$backURL || Director::makeRelative($backURL) === $controller->getRequest()->getURL()) { $backURL = Director::baseURL(); } $fields->push(HiddenField::create('BackURL', 'BackURL', $backURL)); return $fields; }
php
protected function getFormFields() { $fields = FieldList::create(); $controller = $this->getController(); $backURL = $controller->getBackURL() ?: $controller->getReturnReferer(); // Protect against infinite redirection back to the logout URL after logging out if (!$backURL || Director::makeRelative($backURL) === $controller->getRequest()->getURL()) { $backURL = Director::baseURL(); } $fields->push(HiddenField::create('BackURL', 'BackURL', $backURL)); return $fields; }
[ "protected", "function", "getFormFields", "(", ")", "{", "$", "fields", "=", "FieldList", "::", "create", "(", ")", ";", "$", "controller", "=", "$", "this", "->", "getController", "(", ")", ";", "$", "backURL", "=", "$", "controller", "->", "getBackURL", "(", ")", "?", ":", "$", "controller", "->", "getReturnReferer", "(", ")", ";", "// Protect against infinite redirection back to the logout URL after logging out", "if", "(", "!", "$", "backURL", "||", "Director", "::", "makeRelative", "(", "$", "backURL", ")", "===", "$", "controller", "->", "getRequest", "(", ")", "->", "getURL", "(", ")", ")", "{", "$", "backURL", "=", "Director", "::", "baseURL", "(", ")", ";", "}", "$", "fields", "->", "push", "(", "HiddenField", "::", "create", "(", "'BackURL'", ",", "'BackURL'", ",", "$", "backURL", ")", ")", ";", "return", "$", "fields", ";", "}" ]
Build the FieldList for the logout form @return FieldList
[ "Build", "the", "FieldList", "for", "the", "logout", "form" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/LogoutForm.php#L50-L66
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.filename2url
public static function filename2url($filename) { $filename = realpath($filename); if (!$filename) { return null; } // Filter files outside of the webroot $base = realpath(BASE_PATH); $baseLength = strlen($base); if (substr($filename, 0, $baseLength) !== $base) { return null; } $relativePath = ltrim(substr($filename, $baseLength), '/\\'); return Director::absoluteURL($relativePath); }
php
public static function filename2url($filename) { $filename = realpath($filename); if (!$filename) { return null; } // Filter files outside of the webroot $base = realpath(BASE_PATH); $baseLength = strlen($base); if (substr($filename, 0, $baseLength) !== $base) { return null; } $relativePath = ltrim(substr($filename, $baseLength), '/\\'); return Director::absoluteURL($relativePath); }
[ "public", "static", "function", "filename2url", "(", "$", "filename", ")", "{", "$", "filename", "=", "realpath", "(", "$", "filename", ")", ";", "if", "(", "!", "$", "filename", ")", "{", "return", "null", ";", "}", "// Filter files outside of the webroot", "$", "base", "=", "realpath", "(", "BASE_PATH", ")", ";", "$", "baseLength", "=", "strlen", "(", "$", "base", ")", ";", "if", "(", "substr", "(", "$", "filename", ",", "0", ",", "$", "baseLength", ")", "!==", "$", "base", ")", "{", "return", "null", ";", "}", "$", "relativePath", "=", "ltrim", "(", "substr", "(", "$", "filename", ",", "$", "baseLength", ")", ",", "'/\\\\'", ")", ";", "return", "Director", "::", "absoluteURL", "(", "$", "relativePath", ")", ";", "}" ]
Turns a local system filename into a URL by comparing it to the script filename. @param string $filename @return string
[ "Turns", "a", "local", "system", "filename", "into", "a", "URL", "by", "comparing", "it", "to", "the", "script", "filename", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L96-L112
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.absoluteURLs
public static function absoluteURLs($html) { $html = str_replace('$CurrentPageURL', Controller::curr()->getRequest()->getURL(), $html); return HTTP::urlRewriter($html, function ($url) { //no need to rewrite, if uri has a protocol (determined here by existence of reserved URI character ":") if (preg_match('/^\w+:/', $url)) { return $url; } return Director::absoluteURL($url, true); }); }
php
public static function absoluteURLs($html) { $html = str_replace('$CurrentPageURL', Controller::curr()->getRequest()->getURL(), $html); return HTTP::urlRewriter($html, function ($url) { //no need to rewrite, if uri has a protocol (determined here by existence of reserved URI character ":") if (preg_match('/^\w+:/', $url)) { return $url; } return Director::absoluteURL($url, true); }); }
[ "public", "static", "function", "absoluteURLs", "(", "$", "html", ")", "{", "$", "html", "=", "str_replace", "(", "'$CurrentPageURL'", ",", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", "->", "getURL", "(", ")", ",", "$", "html", ")", ";", "return", "HTTP", "::", "urlRewriter", "(", "$", "html", ",", "function", "(", "$", "url", ")", "{", "//no need to rewrite, if uri has a protocol (determined here by existence of reserved URI character \":\")", "if", "(", "preg_match", "(", "'/^\\w+:/'", ",", "$", "url", ")", ")", "{", "return", "$", "url", ";", "}", "return", "Director", "::", "absoluteURL", "(", "$", "url", ",", "true", ")", ";", "}", ")", ";", "}" ]
Turn all relative URLs in the content to absolute URLs. @param string $html @return string
[ "Turn", "all", "relative", "URLs", "in", "the", "content", "to", "absolute", "URLs", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L121-L131
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.urlRewriter
public static function urlRewriter($content, $code) { if (!is_callable($code)) { throw new InvalidArgumentException( 'HTTP::urlRewriter expects a callable as the second parameter' ); } // Replace attributes $attribs = ["src", "background", "a" => "href", "link" => "href", "base" => "href"]; $regExps = []; foreach ($attribs as $tag => $attrib) { if (!is_numeric($tag)) { $tagPrefix = "$tag "; } else { $tagPrefix = ""; } $regExps[] = "/(<{$tagPrefix}[^>]*$attrib *= *\")([^\"]*)(\")/i"; $regExps[] = "/(<{$tagPrefix}[^>]*$attrib *= *')([^']*)(')/i"; $regExps[] = "/(<{$tagPrefix}[^>]*$attrib *= *)([^\"' ]*)( )/i"; } // Replace css styles // @todo - http://www.css3.info/preview/multiple-backgrounds/ $styles = ['background-image', 'background', 'list-style-image', 'list-style', 'content']; foreach ($styles as $style) { $regExps[] = "/($style:[^;]*url *\\(\")([^\"]+)(\"\\))/i"; $regExps[] = "/($style:[^;]*url *\\(')([^']+)('\\))/i"; $regExps[] = "/($style:[^;]*url *\\()([^\"\\)')]+)(\\))/i"; } // Callback for regexp replacement $callback = function ($matches) use ($code) { // Decode HTML attribute $URL = Convert::xml2raw($matches[2]); $rewritten = $code($URL); return $matches[1] . Convert::raw2xml($rewritten) . $matches[3]; }; // Execute each expression foreach ($regExps as $regExp) { $content = preg_replace_callback($regExp, $callback, $content); } return $content; }
php
public static function urlRewriter($content, $code) { if (!is_callable($code)) { throw new InvalidArgumentException( 'HTTP::urlRewriter expects a callable as the second parameter' ); } // Replace attributes $attribs = ["src", "background", "a" => "href", "link" => "href", "base" => "href"]; $regExps = []; foreach ($attribs as $tag => $attrib) { if (!is_numeric($tag)) { $tagPrefix = "$tag "; } else { $tagPrefix = ""; } $regExps[] = "/(<{$tagPrefix}[^>]*$attrib *= *\")([^\"]*)(\")/i"; $regExps[] = "/(<{$tagPrefix}[^>]*$attrib *= *')([^']*)(')/i"; $regExps[] = "/(<{$tagPrefix}[^>]*$attrib *= *)([^\"' ]*)( )/i"; } // Replace css styles // @todo - http://www.css3.info/preview/multiple-backgrounds/ $styles = ['background-image', 'background', 'list-style-image', 'list-style', 'content']; foreach ($styles as $style) { $regExps[] = "/($style:[^;]*url *\\(\")([^\"]+)(\"\\))/i"; $regExps[] = "/($style:[^;]*url *\\(')([^']+)('\\))/i"; $regExps[] = "/($style:[^;]*url *\\()([^\"\\)')]+)(\\))/i"; } // Callback for regexp replacement $callback = function ($matches) use ($code) { // Decode HTML attribute $URL = Convert::xml2raw($matches[2]); $rewritten = $code($URL); return $matches[1] . Convert::raw2xml($rewritten) . $matches[3]; }; // Execute each expression foreach ($regExps as $regExp) { $content = preg_replace_callback($regExp, $callback, $content); } return $content; }
[ "public", "static", "function", "urlRewriter", "(", "$", "content", ",", "$", "code", ")", "{", "if", "(", "!", "is_callable", "(", "$", "code", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'HTTP::urlRewriter expects a callable as the second parameter'", ")", ";", "}", "// Replace attributes", "$", "attribs", "=", "[", "\"src\"", ",", "\"background\"", ",", "\"a\"", "=>", "\"href\"", ",", "\"link\"", "=>", "\"href\"", ",", "\"base\"", "=>", "\"href\"", "]", ";", "$", "regExps", "=", "[", "]", ";", "foreach", "(", "$", "attribs", "as", "$", "tag", "=>", "$", "attrib", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "tag", ")", ")", "{", "$", "tagPrefix", "=", "\"$tag \"", ";", "}", "else", "{", "$", "tagPrefix", "=", "\"\"", ";", "}", "$", "regExps", "[", "]", "=", "\"/(<{$tagPrefix}[^>]*$attrib *= *\\\")([^\\\"]*)(\\\")/i\"", ";", "$", "regExps", "[", "]", "=", "\"/(<{$tagPrefix}[^>]*$attrib *= *')([^']*)(')/i\"", ";", "$", "regExps", "[", "]", "=", "\"/(<{$tagPrefix}[^>]*$attrib *= *)([^\\\"' ]*)( )/i\"", ";", "}", "// Replace css styles", "// @todo - http://www.css3.info/preview/multiple-backgrounds/", "$", "styles", "=", "[", "'background-image'", ",", "'background'", ",", "'list-style-image'", ",", "'list-style'", ",", "'content'", "]", ";", "foreach", "(", "$", "styles", "as", "$", "style", ")", "{", "$", "regExps", "[", "]", "=", "\"/($style:[^;]*url *\\\\(\\\")([^\\\"]+)(\\\"\\\\))/i\"", ";", "$", "regExps", "[", "]", "=", "\"/($style:[^;]*url *\\\\(')([^']+)('\\\\))/i\"", ";", "$", "regExps", "[", "]", "=", "\"/($style:[^;]*url *\\\\()([^\\\"\\\\)')]+)(\\\\))/i\"", ";", "}", "// Callback for regexp replacement", "$", "callback", "=", "function", "(", "$", "matches", ")", "use", "(", "$", "code", ")", "{", "// Decode HTML attribute", "$", "URL", "=", "Convert", "::", "xml2raw", "(", "$", "matches", "[", "2", "]", ")", ";", "$", "rewritten", "=", "$", "code", "(", "$", "URL", ")", ";", "return", "$", "matches", "[", "1", "]", ".", "Convert", "::", "raw2xml", "(", "$", "rewritten", ")", ".", "$", "matches", "[", "3", "]", ";", "}", ";", "// Execute each expression", "foreach", "(", "$", "regExps", "as", "$", "regExp", ")", "{", "$", "content", "=", "preg_replace_callback", "(", "$", "regExp", ",", "$", "callback", ",", "$", "content", ")", ";", "}", "return", "$", "content", ";", "}" ]
Rewrite all the URLs in the given content, evaluating the given string as PHP code. Put $URL where you want the URL to appear, however, you can't embed $URL in strings, for example: <ul> <li><code>'"../../" . $URL'</code></li> <li><code>'myRewriter($URL)'</code></li> <li><code>'(substr($URL, 0, 1)=="/") ? "../" . substr($URL, 1) : $URL'</code></li> </ul> As of 3.2 $code should be a callable which takes a single parameter and returns the rewritten, for example: <code> function($url) { return Director::absoluteURL($url, true); } </code> @param string $content The HTML to search for links to rewrite. @param callable $code Either a string that can evaluate to an expression to rewrite links (depreciated), or a callable that takes a single parameter and returns the rewritten URL. @return string The content with all links rewritten as per the logic specified in $code.
[ "Rewrite", "all", "the", "URLs", "in", "the", "given", "content", "evaluating", "the", "given", "string", "as", "PHP", "code", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L157-L202
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.findByTagAndAttribute
public static function findByTagAndAttribute($content, $attributes) { $regexes = []; foreach ($attributes as $tag => $attribute) { $regexes[] = "/<{$tag} [^>]*$attribute *= *([\"'])(.*?)\\1[^>]*>/i"; $regexes[] = "/<{$tag} [^>]*$attribute *= *([^ \"'>]+)/i"; } $result = []; if ($regexes) { foreach ($regexes as $regex) { if (preg_match_all($regex, $content, $matches)) { $result = array_merge_recursive($result, (isset($matches[2]) ? $matches[2] : $matches[1])); } } } return count($result) ? $result : null; }
php
public static function findByTagAndAttribute($content, $attributes) { $regexes = []; foreach ($attributes as $tag => $attribute) { $regexes[] = "/<{$tag} [^>]*$attribute *= *([\"'])(.*?)\\1[^>]*>/i"; $regexes[] = "/<{$tag} [^>]*$attribute *= *([^ \"'>]+)/i"; } $result = []; if ($regexes) { foreach ($regexes as $regex) { if (preg_match_all($regex, $content, $matches)) { $result = array_merge_recursive($result, (isset($matches[2]) ? $matches[2] : $matches[1])); } } } return count($result) ? $result : null; }
[ "public", "static", "function", "findByTagAndAttribute", "(", "$", "content", ",", "$", "attributes", ")", "{", "$", "regexes", "=", "[", "]", ";", "foreach", "(", "$", "attributes", "as", "$", "tag", "=>", "$", "attribute", ")", "{", "$", "regexes", "[", "]", "=", "\"/<{$tag} [^>]*$attribute *= *([\\\"'])(.*?)\\\\1[^>]*>/i\"", ";", "$", "regexes", "[", "]", "=", "\"/<{$tag} [^>]*$attribute *= *([^ \\\"'>]+)/i\"", ";", "}", "$", "result", "=", "[", "]", ";", "if", "(", "$", "regexes", ")", "{", "foreach", "(", "$", "regexes", "as", "$", "regex", ")", "{", "if", "(", "preg_match_all", "(", "$", "regex", ",", "$", "content", ",", "$", "matches", ")", ")", "{", "$", "result", "=", "array_merge_recursive", "(", "$", "result", ",", "(", "isset", "(", "$", "matches", "[", "2", "]", ")", "?", "$", "matches", "[", "2", "]", ":", "$", "matches", "[", "1", "]", ")", ")", ";", "}", "}", "}", "return", "count", "(", "$", "result", ")", "?", "$", "result", ":", "null", ";", "}" ]
Search for all tags with a specific attribute, then return the value of that attribute in a flat array. @param string $content @param array $attributes An array of tags to attributes, for example "[a] => 'href', [div] => 'id'" @return array
[ "Search", "for", "all", "tags", "with", "a", "specific", "attribute", "then", "return", "the", "value", "of", "that", "attribute", "in", "a", "flat", "array", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L299-L319
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.get_mime_type
public static function get_mime_type($filename) { // If the finfo module is compiled into PHP, use it. $path = BASE_PATH . DIRECTORY_SEPARATOR . $filename; if (class_exists('finfo') && file_exists($path)) { $finfo = new finfo(FILEINFO_MIME_TYPE); return $finfo->file($path); } // Fallback to use the list from the HTTP.yml configuration and rely on the file extension // to get the file mime-type $ext = strtolower(File::get_file_extension($filename)); // Get the mime-types $mimeTypes = HTTP::config()->uninherited('MimeTypes'); // The mime type doesn't exist if (!isset($mimeTypes[$ext])) { return 'application/unknown'; } return $mimeTypes[$ext]; }
php
public static function get_mime_type($filename) { // If the finfo module is compiled into PHP, use it. $path = BASE_PATH . DIRECTORY_SEPARATOR . $filename; if (class_exists('finfo') && file_exists($path)) { $finfo = new finfo(FILEINFO_MIME_TYPE); return $finfo->file($path); } // Fallback to use the list from the HTTP.yml configuration and rely on the file extension // to get the file mime-type $ext = strtolower(File::get_file_extension($filename)); // Get the mime-types $mimeTypes = HTTP::config()->uninherited('MimeTypes'); // The mime type doesn't exist if (!isset($mimeTypes[$ext])) { return 'application/unknown'; } return $mimeTypes[$ext]; }
[ "public", "static", "function", "get_mime_type", "(", "$", "filename", ")", "{", "// If the finfo module is compiled into PHP, use it.", "$", "path", "=", "BASE_PATH", ".", "DIRECTORY_SEPARATOR", ".", "$", "filename", ";", "if", "(", "class_exists", "(", "'finfo'", ")", "&&", "file_exists", "(", "$", "path", ")", ")", "{", "$", "finfo", "=", "new", "finfo", "(", "FILEINFO_MIME_TYPE", ")", ";", "return", "$", "finfo", "->", "file", "(", "$", "path", ")", ";", "}", "// Fallback to use the list from the HTTP.yml configuration and rely on the file extension", "// to get the file mime-type", "$", "ext", "=", "strtolower", "(", "File", "::", "get_file_extension", "(", "$", "filename", ")", ")", ";", "// Get the mime-types", "$", "mimeTypes", "=", "HTTP", "::", "config", "(", ")", "->", "uninherited", "(", "'MimeTypes'", ")", ";", "// The mime type doesn't exist", "if", "(", "!", "isset", "(", "$", "mimeTypes", "[", "$", "ext", "]", ")", ")", "{", "return", "'application/unknown'", ";", "}", "return", "$", "mimeTypes", "[", "$", "ext", "]", ";", "}" ]
Get the MIME type based on a file's extension. If the finfo class exists in PHP, and the file exists relative to the project root, then use that extension, otherwise fallback to a list of commonly known MIME types. @param string $filename @return string
[ "Get", "the", "MIME", "type", "based", "on", "a", "file", "s", "extension", ".", "If", "the", "finfo", "class", "exists", "in", "PHP", "and", "the", "file", "exists", "relative", "to", "the", "project", "root", "then", "use", "that", "extension", "otherwise", "fallback", "to", "a", "list", "of", "commonly", "known", "MIME", "types", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L349-L370
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.set_cache_age
public static function set_cache_age($age) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware::singleton()->setMaxAge($age) instead'); self::$cache_age = $age; HTTPCacheControlMiddleware::singleton()->setMaxAge($age); }
php
public static function set_cache_age($age) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware::singleton()->setMaxAge($age) instead'); self::$cache_age = $age; HTTPCacheControlMiddleware::singleton()->setMaxAge($age); }
[ "public", "static", "function", "set_cache_age", "(", "$", "age", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use HTTPCacheControlMiddleware::singleton()->setMaxAge($age) instead'", ")", ";", "self", "::", "$", "cache_age", "=", "$", "age", ";", "HTTPCacheControlMiddleware", "::", "singleton", "(", ")", "->", "setMaxAge", "(", "$", "age", ")", ";", "}" ]
Set the maximum age of this page in web caches, in seconds. @deprecated 4.2.0:5.0.0 Use HTTPCacheControlMiddleware::singleton()->setMaxAge($age) instead @param int $age
[ "Set", "the", "maximum", "age", "of", "this", "page", "in", "web", "caches", "in", "seconds", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L378-L383
train
silverstripe/silverstripe-framework
src/Control/HTTP.php
HTTP.augmentState
public static function augmentState(HTTPRequest $request, HTTPResponse $response) { // Skip if deprecated API is disabled $config = Config::forClass(HTTP::class); if ($config->get('ignoreDeprecatedCaching')) { return; } $cacheControlMiddleware = HTTPCacheControlMiddleware::singleton(); // if http caching is disabled by config, disable it - used on dev environments due to frequently changing // templates and other data. will be overridden by forced publicCache(true) or privateCache(true) calls if ($config->get('disable_http_cache')) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultState/.defaultForcingLevel instead'); $cacheControlMiddleware->disableCache(); } // if no caching ajax requests, disable ajax if is ajax request if (!$config->get('cache_ajax_requests') && Director::is_ajax()) { Deprecation::notice( '5.0', 'HTTP.cache_ajax_requests config is deprecated. Use HTTPCacheControlMiddleware::disableCache() instead' ); $cacheControlMiddleware->disableCache(); } // Pass vary to middleware $configVary = $config->get('vary'); if ($configVary) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultVary instead'); $cacheControlMiddleware->addVary($configVary); } // Pass cache_control to middleware $configCacheControl = $config->get('cache_control'); if ($configCacheControl) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware API instead'); $supportedDirectives = ['max-age', 'no-cache', 'no-store', 'must-revalidate']; if ($foundUnsupported = array_diff(array_keys($configCacheControl), $supportedDirectives)) { throw new \LogicException( 'Found unsupported legacy directives in HTTP.cache_control: ' . implode(', ', $foundUnsupported) . '. Please use HTTPCacheControlMiddleware API instead' ); } if (isset($configCacheControl['max-age'])) { $cacheControlMiddleware->setMaxAge($configCacheControl['max-age']); } if (isset($configCacheControl['no-cache'])) { $cacheControlMiddleware->setNoCache((bool)$configCacheControl['no-cache']); } if (isset($configCacheControl['no-store'])) { $cacheControlMiddleware->setNoStore((bool)$configCacheControl['no-store']); } if (isset($configCacheControl['must-revalidate'])) { $cacheControlMiddleware->setMustRevalidate((bool)$configCacheControl['must-revalidate']); } } // Set modification date if (self::$modification_date) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware::registerModificationDate() instead'); $cacheControlMiddleware->registerModificationDate(self::$modification_date); } // Ensure deprecated $etag property is assigned if (self::$etag && !$cacheControlMiddleware->hasDirective('no-store') && !$response->getHeader('ETag')) { Deprecation::notice('5.0', 'Etag should not be set explicitly'); $response->addHeader('ETag', self::$etag); } }
php
public static function augmentState(HTTPRequest $request, HTTPResponse $response) { // Skip if deprecated API is disabled $config = Config::forClass(HTTP::class); if ($config->get('ignoreDeprecatedCaching')) { return; } $cacheControlMiddleware = HTTPCacheControlMiddleware::singleton(); // if http caching is disabled by config, disable it - used on dev environments due to frequently changing // templates and other data. will be overridden by forced publicCache(true) or privateCache(true) calls if ($config->get('disable_http_cache')) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultState/.defaultForcingLevel instead'); $cacheControlMiddleware->disableCache(); } // if no caching ajax requests, disable ajax if is ajax request if (!$config->get('cache_ajax_requests') && Director::is_ajax()) { Deprecation::notice( '5.0', 'HTTP.cache_ajax_requests config is deprecated. Use HTTPCacheControlMiddleware::disableCache() instead' ); $cacheControlMiddleware->disableCache(); } // Pass vary to middleware $configVary = $config->get('vary'); if ($configVary) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultVary instead'); $cacheControlMiddleware->addVary($configVary); } // Pass cache_control to middleware $configCacheControl = $config->get('cache_control'); if ($configCacheControl) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware API instead'); $supportedDirectives = ['max-age', 'no-cache', 'no-store', 'must-revalidate']; if ($foundUnsupported = array_diff(array_keys($configCacheControl), $supportedDirectives)) { throw new \LogicException( 'Found unsupported legacy directives in HTTP.cache_control: ' . implode(', ', $foundUnsupported) . '. Please use HTTPCacheControlMiddleware API instead' ); } if (isset($configCacheControl['max-age'])) { $cacheControlMiddleware->setMaxAge($configCacheControl['max-age']); } if (isset($configCacheControl['no-cache'])) { $cacheControlMiddleware->setNoCache((bool)$configCacheControl['no-cache']); } if (isset($configCacheControl['no-store'])) { $cacheControlMiddleware->setNoStore((bool)$configCacheControl['no-store']); } if (isset($configCacheControl['must-revalidate'])) { $cacheControlMiddleware->setMustRevalidate((bool)$configCacheControl['must-revalidate']); } } // Set modification date if (self::$modification_date) { Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware::registerModificationDate() instead'); $cacheControlMiddleware->registerModificationDate(self::$modification_date); } // Ensure deprecated $etag property is assigned if (self::$etag && !$cacheControlMiddleware->hasDirective('no-store') && !$response->getHeader('ETag')) { Deprecation::notice('5.0', 'Etag should not be set explicitly'); $response->addHeader('ETag', self::$etag); } }
[ "public", "static", "function", "augmentState", "(", "HTTPRequest", "$", "request", ",", "HTTPResponse", "$", "response", ")", "{", "// Skip if deprecated API is disabled", "$", "config", "=", "Config", "::", "forClass", "(", "HTTP", "::", "class", ")", ";", "if", "(", "$", "config", "->", "get", "(", "'ignoreDeprecatedCaching'", ")", ")", "{", "return", ";", "}", "$", "cacheControlMiddleware", "=", "HTTPCacheControlMiddleware", "::", "singleton", "(", ")", ";", "// if http caching is disabled by config, disable it - used on dev environments due to frequently changing", "// templates and other data. will be overridden by forced publicCache(true) or privateCache(true) calls", "if", "(", "$", "config", "->", "get", "(", "'disable_http_cache'", ")", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use HTTPCacheControlMiddleware.defaultState/.defaultForcingLevel instead'", ")", ";", "$", "cacheControlMiddleware", "->", "disableCache", "(", ")", ";", "}", "// if no caching ajax requests, disable ajax if is ajax request", "if", "(", "!", "$", "config", "->", "get", "(", "'cache_ajax_requests'", ")", "&&", "Director", "::", "is_ajax", "(", ")", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'HTTP.cache_ajax_requests config is deprecated. Use HTTPCacheControlMiddleware::disableCache() instead'", ")", ";", "$", "cacheControlMiddleware", "->", "disableCache", "(", ")", ";", "}", "// Pass vary to middleware", "$", "configVary", "=", "$", "config", "->", "get", "(", "'vary'", ")", ";", "if", "(", "$", "configVary", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use HTTPCacheControlMiddleware.defaultVary instead'", ")", ";", "$", "cacheControlMiddleware", "->", "addVary", "(", "$", "configVary", ")", ";", "}", "// Pass cache_control to middleware", "$", "configCacheControl", "=", "$", "config", "->", "get", "(", "'cache_control'", ")", ";", "if", "(", "$", "configCacheControl", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use HTTPCacheControlMiddleware API instead'", ")", ";", "$", "supportedDirectives", "=", "[", "'max-age'", ",", "'no-cache'", ",", "'no-store'", ",", "'must-revalidate'", "]", ";", "if", "(", "$", "foundUnsupported", "=", "array_diff", "(", "array_keys", "(", "$", "configCacheControl", ")", ",", "$", "supportedDirectives", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Found unsupported legacy directives in HTTP.cache_control: '", ".", "implode", "(", "', '", ",", "$", "foundUnsupported", ")", ".", "'. Please use HTTPCacheControlMiddleware API instead'", ")", ";", "}", "if", "(", "isset", "(", "$", "configCacheControl", "[", "'max-age'", "]", ")", ")", "{", "$", "cacheControlMiddleware", "->", "setMaxAge", "(", "$", "configCacheControl", "[", "'max-age'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "configCacheControl", "[", "'no-cache'", "]", ")", ")", "{", "$", "cacheControlMiddleware", "->", "setNoCache", "(", "(", "bool", ")", "$", "configCacheControl", "[", "'no-cache'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "configCacheControl", "[", "'no-store'", "]", ")", ")", "{", "$", "cacheControlMiddleware", "->", "setNoStore", "(", "(", "bool", ")", "$", "configCacheControl", "[", "'no-store'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "configCacheControl", "[", "'must-revalidate'", "]", ")", ")", "{", "$", "cacheControlMiddleware", "->", "setMustRevalidate", "(", "(", "bool", ")", "$", "configCacheControl", "[", "'must-revalidate'", "]", ")", ";", "}", "}", "// Set modification date", "if", "(", "self", "::", "$", "modification_date", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use HTTPCacheControlMiddleware::registerModificationDate() instead'", ")", ";", "$", "cacheControlMiddleware", "->", "registerModificationDate", "(", "self", "::", "$", "modification_date", ")", ";", "}", "// Ensure deprecated $etag property is assigned", "if", "(", "self", "::", "$", "etag", "&&", "!", "$", "cacheControlMiddleware", "->", "hasDirective", "(", "'no-store'", ")", "&&", "!", "$", "response", "->", "getHeader", "(", "'ETag'", ")", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Etag should not be set explicitly'", ")", ";", "$", "response", "->", "addHeader", "(", "'ETag'", ",", "self", "::", "$", "etag", ")", ";", "}", "}" ]
Ensure that all deprecated HTTP cache settings are respected @deprecated 4.2.0:5.0.0 Use HTTPCacheControlMiddleware instead @throws \LogicException @param HTTPRequest $request @param HTTPResponse $response
[ "Ensure", "that", "all", "deprecated", "HTTP", "cache", "settings", "are", "respected" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTP.php#L481-L556
train
silverstripe/silverstripe-framework
src/ORM/Filters/ComparisonFilter.php
ComparisonFilter.applyOne
protected function applyOne(DataQuery $query) { $this->model = $query->applyRelation($this->relation); $predicate = sprintf("%s %s ?", $this->getDbName(), $this->getOperator()); $clause = [$predicate => $this->getDbFormattedValue()]; return $this->aggregate ? $this->applyAggregate($query, $clause) : $query->where($clause); }
php
protected function applyOne(DataQuery $query) { $this->model = $query->applyRelation($this->relation); $predicate = sprintf("%s %s ?", $this->getDbName(), $this->getOperator()); $clause = [$predicate => $this->getDbFormattedValue()]; return $this->aggregate ? $this->applyAggregate($query, $clause) : $query->where($clause); }
[ "protected", "function", "applyOne", "(", "DataQuery", "$", "query", ")", "{", "$", "this", "->", "model", "=", "$", "query", "->", "applyRelation", "(", "$", "this", "->", "relation", ")", ";", "$", "predicate", "=", "sprintf", "(", "\"%s %s ?\"", ",", "$", "this", "->", "getDbName", "(", ")", ",", "$", "this", "->", "getOperator", "(", ")", ")", ";", "$", "clause", "=", "[", "$", "predicate", "=>", "$", "this", "->", "getDbFormattedValue", "(", ")", "]", ";", "return", "$", "this", "->", "aggregate", "?", "$", "this", "->", "applyAggregate", "(", "$", "query", ",", "$", "clause", ")", ":", "$", "query", "->", "where", "(", "$", "clause", ")", ";", "}" ]
Applies a comparison filter to the query Handles SQL escaping for both numeric and string values @param DataQuery $query @return DataQuery
[ "Applies", "a", "comparison", "filter", "to", "the", "query", "Handles", "SQL", "escaping", "for", "both", "numeric", "and", "string", "values" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/ComparisonFilter.php#L42-L52
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.dataClass
public function dataClass() { if ($this->dataClass) { return $this->dataClass; } if (count($this->items) > 0) { return get_class($this->items[0]); } return null; }
php
public function dataClass() { if ($this->dataClass) { return $this->dataClass; } if (count($this->items) > 0) { return get_class($this->items[0]); } return null; }
[ "public", "function", "dataClass", "(", ")", "{", "if", "(", "$", "this", "->", "dataClass", ")", "{", "return", "$", "this", "->", "dataClass", ";", "}", "if", "(", "count", "(", "$", "this", "->", "items", ")", ">", "0", ")", "{", "return", "get_class", "(", "$", "this", "->", "items", "[", "0", "]", ")", ";", "}", "return", "null", ";", "}" ]
Return the class of items in this list, by looking at the first item inside it. @return string
[ "Return", "the", "class", "of", "items", "in", "this", "list", "by", "looking", "at", "the", "first", "item", "inside", "it", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L59-L68
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.toNestedArray
public function toNestedArray() { $result = []; foreach ($this->items as $item) { if (is_object($item)) { if (method_exists($item, 'toMap')) { $result[] = $item->toMap(); } else { $result[] = (array) $item; } } else { $result[] = $item; } } return $result; }
php
public function toNestedArray() { $result = []; foreach ($this->items as $item) { if (is_object($item)) { if (method_exists($item, 'toMap')) { $result[] = $item->toMap(); } else { $result[] = (array) $item; } } else { $result[] = $item; } } return $result; }
[ "public", "function", "toNestedArray", "(", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "if", "(", "is_object", "(", "$", "item", ")", ")", "{", "if", "(", "method_exists", "(", "$", "item", ",", "'toMap'", ")", ")", "{", "$", "result", "[", "]", "=", "$", "item", "->", "toMap", "(", ")", ";", "}", "else", "{", "$", "result", "[", "]", "=", "(", "array", ")", "$", "item", ";", "}", "}", "else", "{", "$", "result", "[", "]", "=", "$", "item", ";", "}", "}", "return", "$", "result", ";", "}" ]
Return this list as an array and every object it as an sub array as well @return array
[ "Return", "this", "list", "as", "an", "array", "and", "every", "object", "it", "as", "an", "sub", "array", "as", "well" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L158-L175
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.limit
public function limit($length, $offset = 0) { // Type checking: designed for consistency with DataList::limit() if (!is_numeric($length) || !is_numeric($offset)) { Deprecation::notice( '4.3', 'Arguments to ArrayList::limit() should be numeric' ); } if ($length < 0 || $offset < 0) { Deprecation::notice( '4.3', 'Arguments to ArrayList::limit() should be positive' ); } if (!$length) { if ($length === 0) { Deprecation::notice( '4.3', "limit(0) is deprecated in SS4. In SS5 a limit of 0 will instead return no records." ); } $length = count($this->items); } $list = clone $this; $list->items = array_slice($this->items, $offset, $length); return $list; }
php
public function limit($length, $offset = 0) { // Type checking: designed for consistency with DataList::limit() if (!is_numeric($length) || !is_numeric($offset)) { Deprecation::notice( '4.3', 'Arguments to ArrayList::limit() should be numeric' ); } if ($length < 0 || $offset < 0) { Deprecation::notice( '4.3', 'Arguments to ArrayList::limit() should be positive' ); } if (!$length) { if ($length === 0) { Deprecation::notice( '4.3', "limit(0) is deprecated in SS4. In SS5 a limit of 0 will instead return no records." ); } $length = count($this->items); } $list = clone $this; $list->items = array_slice($this->items, $offset, $length); return $list; }
[ "public", "function", "limit", "(", "$", "length", ",", "$", "offset", "=", "0", ")", "{", "// Type checking: designed for consistency with DataList::limit()", "if", "(", "!", "is_numeric", "(", "$", "length", ")", "||", "!", "is_numeric", "(", "$", "offset", ")", ")", "{", "Deprecation", "::", "notice", "(", "'4.3'", ",", "'Arguments to ArrayList::limit() should be numeric'", ")", ";", "}", "if", "(", "$", "length", "<", "0", "||", "$", "offset", "<", "0", ")", "{", "Deprecation", "::", "notice", "(", "'4.3'", ",", "'Arguments to ArrayList::limit() should be positive'", ")", ";", "}", "if", "(", "!", "$", "length", ")", "{", "if", "(", "$", "length", "===", "0", ")", "{", "Deprecation", "::", "notice", "(", "'4.3'", ",", "\"limit(0) is deprecated in SS4. In SS5 a limit of 0 will instead return no records.\"", ")", ";", "}", "$", "length", "=", "count", "(", "$", "this", "->", "items", ")", ";", "}", "$", "list", "=", "clone", "$", "this", ";", "$", "list", "->", "items", "=", "array_slice", "(", "$", "this", "->", "items", ",", "$", "offset", ",", "$", "length", ")", ";", "return", "$", "list", ";", "}" ]
Get a sub-range of this dataobjectset as an array @param int $length @param int $offset @return static
[ "Get", "a", "sub", "-", "range", "of", "this", "dataobjectset", "as", "an", "array" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L184-L216
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.remove
public function remove($item) { $renumberKeys = false; foreach ($this->items as $key => $value) { if ($item === $value) { $renumberKeys = true; unset($this->items[$key]); } } if ($renumberKeys) { $this->items = array_values($this->items); } }
php
public function remove($item) { $renumberKeys = false; foreach ($this->items as $key => $value) { if ($item === $value) { $renumberKeys = true; unset($this->items[$key]); } } if ($renumberKeys) { $this->items = array_values($this->items); } }
[ "public", "function", "remove", "(", "$", "item", ")", "{", "$", "renumberKeys", "=", "false", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "item", "===", "$", "value", ")", "{", "$", "renumberKeys", "=", "true", ";", "unset", "(", "$", "this", "->", "items", "[", "$", "key", "]", ")", ";", "}", "}", "if", "(", "$", "renumberKeys", ")", "{", "$", "this", "->", "items", "=", "array_values", "(", "$", "this", "->", "items", ")", ";", "}", "}" ]
Remove this item from this list @param mixed $item
[ "Remove", "this", "item", "from", "this", "list" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L233-L245
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.replace
public function replace($item, $with) { foreach ($this->items as $key => $candidate) { if ($candidate === $item) { $this->items[$key] = $with; return; } } }
php
public function replace($item, $with) { foreach ($this->items as $key => $candidate) { if ($candidate === $item) { $this->items[$key] = $with; return; } } }
[ "public", "function", "replace", "(", "$", "item", ",", "$", "with", ")", "{", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "candidate", ")", "{", "if", "(", "$", "candidate", "===", "$", "item", ")", "{", "$", "this", "->", "items", "[", "$", "key", "]", "=", "$", "with", ";", "return", ";", "}", "}", "}" ]
Replaces an item in this list with another item. @param array|object $item @param array|object $with @return void;
[ "Replaces", "an", "item", "in", "this", "list", "with", "another", "item", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L254-L262
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.removeDuplicates
public function removeDuplicates($field = 'ID') { $seen = []; $renumberKeys = false; foreach ($this->items as $key => $item) { $value = $this->extractValue($item, $field); if (array_key_exists($value, $seen)) { $renumberKeys = true; unset($this->items[$key]); } $seen[$value] = true; } if ($renumberKeys) { $this->items = array_values($this->items); } return $this; }
php
public function removeDuplicates($field = 'ID') { $seen = []; $renumberKeys = false; foreach ($this->items as $key => $item) { $value = $this->extractValue($item, $field); if (array_key_exists($value, $seen)) { $renumberKeys = true; unset($this->items[$key]); } $seen[$value] = true; } if ($renumberKeys) { $this->items = array_values($this->items); } return $this; }
[ "public", "function", "removeDuplicates", "(", "$", "field", "=", "'ID'", ")", "{", "$", "seen", "=", "[", "]", ";", "$", "renumberKeys", "=", "false", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "$", "value", "=", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "field", ")", ";", "if", "(", "array_key_exists", "(", "$", "value", ",", "$", "seen", ")", ")", "{", "$", "renumberKeys", "=", "true", ";", "unset", "(", "$", "this", "->", "items", "[", "$", "key", "]", ")", ";", "}", "$", "seen", "[", "$", "value", "]", "=", "true", ";", "}", "if", "(", "$", "renumberKeys", ")", "{", "$", "this", "->", "items", "=", "array_values", "(", "$", "this", "->", "items", ")", ";", "}", "return", "$", "this", ";", "}" ]
Removes items from this list which have a duplicate value for a certain field. This is especially useful when combining lists. @param string $field @return $this
[ "Removes", "items", "from", "this", "list", "which", "have", "a", "duplicate", "value", "for", "a", "certain", "field", ".", "This", "is", "especially", "useful", "when", "combining", "lists", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L284-L305
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.find
public function find($key, $value) { foreach ($this->items as $item) { if ($this->extractValue($item, $key) == $value) { return $item; } } return null; }
php
public function find($key, $value) { foreach ($this->items as $item) { if ($this->extractValue($item, $key) == $value) { return $item; } } return null; }
[ "public", "function", "find", "(", "$", "key", ",", "$", "value", ")", "{", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "if", "(", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "key", ")", "==", "$", "value", ")", "{", "return", "$", "item", ";", "}", "}", "return", "null", ";", "}" ]
Find the first item of this list where the given key = value @param string $key @param string $value @return mixed
[ "Find", "the", "first", "item", "of", "this", "list", "where", "the", "given", "key", "=", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L395-L403
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.column
public function column($colName = 'ID') { $result = []; foreach ($this->items as $item) { $result[] = $this->extractValue($item, $colName); } return $result; }
php
public function column($colName = 'ID') { $result = []; foreach ($this->items as $item) { $result[] = $this->extractValue($item, $colName); } return $result; }
[ "public", "function", "column", "(", "$", "colName", "=", "'ID'", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "result", "[", "]", "=", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "colName", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns an array of a single field value for all items in the list. @param string $colName @return array
[ "Returns", "an", "array", "of", "a", "single", "field", "value", "for", "all", "items", "in", "the", "list", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L411-L420
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.sort
public function sort() { $args = func_get_args(); if (count($args)==0) { return $this; } if (count($args)>2) { throw new InvalidArgumentException('This method takes zero, one or two arguments'); } $columnsToSort = []; // One argument and it's a string if (count($args)==1 && is_string($args[0])) { list($column, $direction) = $this->parseSortColumn($args[0]); $columnsToSort[$column] = $direction; } elseif (count($args)==2) { list($column, $direction) = $this->parseSortColumn($args[0], $args[1]); $columnsToSort[$column] = $direction; } elseif (is_array($args[0])) { foreach ($args[0] as $key => $value) { list($column, $direction) = $this->parseSortColumn($key, $value); $columnsToSort[$column] = $direction; } } else { throw new InvalidArgumentException("Bad arguments passed to sort()"); } // Store the original keys of the items as a sort fallback, so we can preserve the original order in the event // that array_multisort is unable to work out a sort order for them. This also prevents array_multisort trying // to inspect object properties which can result in errors with circular dependencies $originalKeys = array_keys($this->items); // This the main sorting algorithm that supports infinite sorting params $multisortArgs = []; $values = []; $firstRun = true; foreach ($columnsToSort as $column => $direction) { // The reason these are added to columns is of the references, otherwise when the foreach // is done, all $values and $direction look the same $values[$column] = []; $sortDirection[$column] = $direction; // We need to subtract every value into a temporary array for sorting foreach ($this->items as $index => $item) { $values[$column][] = strtolower($this->extractValue($item, $column)); } // PHP 5.3 requires below arguments to be reference when using array_multisort together // with call_user_func_array // First argument is the 'value' array to be sorted $multisortArgs[] = &$values[$column]; // First argument is the direction to be sorted, $multisortArgs[] = &$sortDirection[$column]; if ($firstRun) { $multisortArgs[] = SORT_REGULAR; } $firstRun = false; } $multisortArgs[] = &$originalKeys; $list = clone $this; // As the last argument we pass in a reference to the items that all the sorting will be applied upon $multisortArgs[] = &$list->items; call_user_func_array('array_multisort', $multisortArgs); return $list; }
php
public function sort() { $args = func_get_args(); if (count($args)==0) { return $this; } if (count($args)>2) { throw new InvalidArgumentException('This method takes zero, one or two arguments'); } $columnsToSort = []; // One argument and it's a string if (count($args)==1 && is_string($args[0])) { list($column, $direction) = $this->parseSortColumn($args[0]); $columnsToSort[$column] = $direction; } elseif (count($args)==2) { list($column, $direction) = $this->parseSortColumn($args[0], $args[1]); $columnsToSort[$column] = $direction; } elseif (is_array($args[0])) { foreach ($args[0] as $key => $value) { list($column, $direction) = $this->parseSortColumn($key, $value); $columnsToSort[$column] = $direction; } } else { throw new InvalidArgumentException("Bad arguments passed to sort()"); } // Store the original keys of the items as a sort fallback, so we can preserve the original order in the event // that array_multisort is unable to work out a sort order for them. This also prevents array_multisort trying // to inspect object properties which can result in errors with circular dependencies $originalKeys = array_keys($this->items); // This the main sorting algorithm that supports infinite sorting params $multisortArgs = []; $values = []; $firstRun = true; foreach ($columnsToSort as $column => $direction) { // The reason these are added to columns is of the references, otherwise when the foreach // is done, all $values and $direction look the same $values[$column] = []; $sortDirection[$column] = $direction; // We need to subtract every value into a temporary array for sorting foreach ($this->items as $index => $item) { $values[$column][] = strtolower($this->extractValue($item, $column)); } // PHP 5.3 requires below arguments to be reference when using array_multisort together // with call_user_func_array // First argument is the 'value' array to be sorted $multisortArgs[] = &$values[$column]; // First argument is the direction to be sorted, $multisortArgs[] = &$sortDirection[$column]; if ($firstRun) { $multisortArgs[] = SORT_REGULAR; } $firstRun = false; } $multisortArgs[] = &$originalKeys; $list = clone $this; // As the last argument we pass in a reference to the items that all the sorting will be applied upon $multisortArgs[] = &$list->items; call_user_func_array('array_multisort', $multisortArgs); return $list; }
[ "public", "function", "sort", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "if", "(", "count", "(", "$", "args", ")", "==", "0", ")", "{", "return", "$", "this", ";", "}", "if", "(", "count", "(", "$", "args", ")", ">", "2", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This method takes zero, one or two arguments'", ")", ";", "}", "$", "columnsToSort", "=", "[", "]", ";", "// One argument and it's a string", "if", "(", "count", "(", "$", "args", ")", "==", "1", "&&", "is_string", "(", "$", "args", "[", "0", "]", ")", ")", "{", "list", "(", "$", "column", ",", "$", "direction", ")", "=", "$", "this", "->", "parseSortColumn", "(", "$", "args", "[", "0", "]", ")", ";", "$", "columnsToSort", "[", "$", "column", "]", "=", "$", "direction", ";", "}", "elseif", "(", "count", "(", "$", "args", ")", "==", "2", ")", "{", "list", "(", "$", "column", ",", "$", "direction", ")", "=", "$", "this", "->", "parseSortColumn", "(", "$", "args", "[", "0", "]", ",", "$", "args", "[", "1", "]", ")", ";", "$", "columnsToSort", "[", "$", "column", "]", "=", "$", "direction", ";", "}", "elseif", "(", "is_array", "(", "$", "args", "[", "0", "]", ")", ")", "{", "foreach", "(", "$", "args", "[", "0", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "list", "(", "$", "column", ",", "$", "direction", ")", "=", "$", "this", "->", "parseSortColumn", "(", "$", "key", ",", "$", "value", ")", ";", "$", "columnsToSort", "[", "$", "column", "]", "=", "$", "direction", ";", "}", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "\"Bad arguments passed to sort()\"", ")", ";", "}", "// Store the original keys of the items as a sort fallback, so we can preserve the original order in the event", "// that array_multisort is unable to work out a sort order for them. This also prevents array_multisort trying", "// to inspect object properties which can result in errors with circular dependencies", "$", "originalKeys", "=", "array_keys", "(", "$", "this", "->", "items", ")", ";", "// This the main sorting algorithm that supports infinite sorting params", "$", "multisortArgs", "=", "[", "]", ";", "$", "values", "=", "[", "]", ";", "$", "firstRun", "=", "true", ";", "foreach", "(", "$", "columnsToSort", "as", "$", "column", "=>", "$", "direction", ")", "{", "// The reason these are added to columns is of the references, otherwise when the foreach", "// is done, all $values and $direction look the same", "$", "values", "[", "$", "column", "]", "=", "[", "]", ";", "$", "sortDirection", "[", "$", "column", "]", "=", "$", "direction", ";", "// We need to subtract every value into a temporary array for sorting", "foreach", "(", "$", "this", "->", "items", "as", "$", "index", "=>", "$", "item", ")", "{", "$", "values", "[", "$", "column", "]", "[", "]", "=", "strtolower", "(", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "column", ")", ")", ";", "}", "// PHP 5.3 requires below arguments to be reference when using array_multisort together", "// with call_user_func_array", "// First argument is the 'value' array to be sorted", "$", "multisortArgs", "[", "]", "=", "&", "$", "values", "[", "$", "column", "]", ";", "// First argument is the direction to be sorted,", "$", "multisortArgs", "[", "]", "=", "&", "$", "sortDirection", "[", "$", "column", "]", ";", "if", "(", "$", "firstRun", ")", "{", "$", "multisortArgs", "[", "]", "=", "SORT_REGULAR", ";", "}", "$", "firstRun", "=", "false", ";", "}", "$", "multisortArgs", "[", "]", "=", "&", "$", "originalKeys", ";", "$", "list", "=", "clone", "$", "this", ";", "// As the last argument we pass in a reference to the items that all the sorting will be applied upon", "$", "multisortArgs", "[", "]", "=", "&", "$", "list", "->", "items", ";", "call_user_func_array", "(", "'array_multisort'", ",", "$", "multisortArgs", ")", ";", "return", "$", "list", ";", "}" ]
Sorts this list by one or more fields. You can either pass in a single field name and direction, or a map of field names to sort directions. Note that columns may be double quoted as per ANSI sql standard @return static @see SS_List::sort() @example $list->sort('Name'); // default ASC sorting @example $list->sort('Name DESC'); // DESC sorting @example $list->sort('Name', 'ASC'); @example $list->sort(array('Name'=>'ASC,'Age'=>'DESC'));
[ "Sorts", "this", "list", "by", "one", "or", "more", "fields", ".", "You", "can", "either", "pass", "in", "a", "single", "field", "name", "and", "direction", "or", "a", "map", "of", "field", "names", "to", "sort", "directions", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L508-L573
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.canFilterBy
public function canFilterBy($by) { if (empty($this->items)) { return false; } $firstRecord = $this->first(); return array_key_exists($by, $firstRecord); }
php
public function canFilterBy($by) { if (empty($this->items)) { return false; } $firstRecord = $this->first(); return array_key_exists($by, $firstRecord); }
[ "public", "function", "canFilterBy", "(", "$", "by", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "items", ")", ")", "{", "return", "false", ";", "}", "$", "firstRecord", "=", "$", "this", "->", "first", "(", ")", ";", "return", "array_key_exists", "(", "$", "by", ",", "$", "firstRecord", ")", ";", "}" ]
Returns true if the given column can be used to filter the records. It works by checking the fields available in the first record of the list. @param string $by @return bool
[ "Returns", "true", "if", "the", "given", "column", "can", "be", "used", "to", "filter", "the", "records", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L583-L592
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.filter
public function filter() { $keepUs = call_user_func_array([$this, 'normaliseFilterArgs'], func_get_args()); $itemsToKeep = []; foreach ($this->items as $item) { $keepItem = true; foreach ($keepUs as $column => $value) { if ((is_array($value) && !in_array($this->extractValue($item, $column), $value)) || (!is_array($value) && $this->extractValue($item, $column) != $value) ) { $keepItem = false; break; } } if ($keepItem) { $itemsToKeep[] = $item; } } $list = clone $this; $list->items = $itemsToKeep; return $list; }
php
public function filter() { $keepUs = call_user_func_array([$this, 'normaliseFilterArgs'], func_get_args()); $itemsToKeep = []; foreach ($this->items as $item) { $keepItem = true; foreach ($keepUs as $column => $value) { if ((is_array($value) && !in_array($this->extractValue($item, $column), $value)) || (!is_array($value) && $this->extractValue($item, $column) != $value) ) { $keepItem = false; break; } } if ($keepItem) { $itemsToKeep[] = $item; } } $list = clone $this; $list->items = $itemsToKeep; return $list; }
[ "public", "function", "filter", "(", ")", "{", "$", "keepUs", "=", "call_user_func_array", "(", "[", "$", "this", ",", "'normaliseFilterArgs'", "]", ",", "func_get_args", "(", ")", ")", ";", "$", "itemsToKeep", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "keepItem", "=", "true", ";", "foreach", "(", "$", "keepUs", "as", "$", "column", "=>", "$", "value", ")", "{", "if", "(", "(", "is_array", "(", "$", "value", ")", "&&", "!", "in_array", "(", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "column", ")", ",", "$", "value", ")", ")", "||", "(", "!", "is_array", "(", "$", "value", ")", "&&", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "column", ")", "!=", "$", "value", ")", ")", "{", "$", "keepItem", "=", "false", ";", "break", ";", "}", "}", "if", "(", "$", "keepItem", ")", "{", "$", "itemsToKeep", "[", "]", "=", "$", "item", ";", "}", "}", "$", "list", "=", "clone", "$", "this", ";", "$", "list", "->", "items", "=", "$", "itemsToKeep", ";", "return", "$", "list", ";", "}" ]
Filter the list to include items with these charactaristics @return ArrayList @see SS_List::filter() @example $list->filter('Name', 'bob'); // only bob in the list @example $list->filter('Name', array('aziz', 'bob'); // aziz and bob in list @example $list->filter(array('Name'=>'bob, 'Age'=>21)); // bob with the Age 21 in list @example $list->filter(array('Name'=>'bob, 'Age'=>array(21, 43))); // bob with the Age 21 or 43 @example $list->filter(array('Name'=>array('aziz','bob'), 'Age'=>array(21, 43))); // aziz with the age 21 or 43 and bob with the Age 21 or 43
[ "Filter", "the", "list", "to", "include", "items", "with", "these", "charactaristics" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L606-L630
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.filterAny
public function filterAny() { $keepUs = $this->normaliseFilterArgs(...func_get_args()); $itemsToKeep = []; foreach ($this->items as $item) { foreach ($keepUs as $column => $value) { $extractedValue = $this->extractValue($item, $column); $matches = is_array($value) ? in_array($extractedValue, $value) : $extractedValue == $value; if ($matches) { $itemsToKeep[] = $item; break; } } } $list = clone $this; $list->items = array_unique($itemsToKeep, SORT_REGULAR); return $list; }
php
public function filterAny() { $keepUs = $this->normaliseFilterArgs(...func_get_args()); $itemsToKeep = []; foreach ($this->items as $item) { foreach ($keepUs as $column => $value) { $extractedValue = $this->extractValue($item, $column); $matches = is_array($value) ? in_array($extractedValue, $value) : $extractedValue == $value; if ($matches) { $itemsToKeep[] = $item; break; } } } $list = clone $this; $list->items = array_unique($itemsToKeep, SORT_REGULAR); return $list; }
[ "public", "function", "filterAny", "(", ")", "{", "$", "keepUs", "=", "$", "this", "->", "normaliseFilterArgs", "(", "...", "func_get_args", "(", ")", ")", ";", "$", "itemsToKeep", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "foreach", "(", "$", "keepUs", "as", "$", "column", "=>", "$", "value", ")", "{", "$", "extractedValue", "=", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "column", ")", ";", "$", "matches", "=", "is_array", "(", "$", "value", ")", "?", "in_array", "(", "$", "extractedValue", ",", "$", "value", ")", ":", "$", "extractedValue", "==", "$", "value", ";", "if", "(", "$", "matches", ")", "{", "$", "itemsToKeep", "[", "]", "=", "$", "item", ";", "break", ";", "}", "}", "}", "$", "list", "=", "clone", "$", "this", ";", "$", "list", "->", "items", "=", "array_unique", "(", "$", "itemsToKeep", ",", "SORT_REGULAR", ")", ";", "return", "$", "list", ";", "}" ]
Return a copy of this list which contains items matching any of these charactaristics. @example // only bob in the list $list = $list->filterAny('Name', 'bob'); @example // azis or bob in the list $list = $list->filterAny('Name', array('aziz', 'bob'); @example // bob or anyone aged 21 in the list $list = $list->filterAny(array('Name'=>'bob, 'Age'=>21)); @example // bob or anyone aged 21 or 43 in the list $list = $list->filterAny(array('Name'=>'bob, 'Age'=>array(21, 43))); @example // all bobs, phils or anyone aged 21 or 43 in the list $list = $list->filterAny(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43))); @param string|array See {@link filter()} @return static
[ "Return", "a", "copy", "of", "this", "list", "which", "contains", "items", "matching", "any", "of", "these", "charactaristics", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L649-L669
train
silverstripe/silverstripe-framework
src/ORM/ArrayList.php
ArrayList.exclude
public function exclude() { $removeUs = $this->normaliseFilterArgs(...func_get_args()); $hitsRequiredToRemove = count($removeUs); $matches = []; foreach ($removeUs as $column => $excludeValue) { foreach ($this->items as $key => $item) { if (!is_array($excludeValue) && $this->extractValue($item, $column) == $excludeValue) { $matches[$key] = isset($matches[$key]) ? $matches[$key] + 1 : 1; } elseif (is_array($excludeValue) && in_array($this->extractValue($item, $column), $excludeValue)) { $matches[$key] = isset($matches[$key]) ? $matches[$key] + 1 : 1; } } } $keysToRemove = array_keys($matches, $hitsRequiredToRemove); $itemsToKeep = []; foreach ($this->items as $key => $value) { if (!in_array($key, $keysToRemove)) { $itemsToKeep[] = $value; } } $list = clone $this; $list->items = $itemsToKeep; return $list; }
php
public function exclude() { $removeUs = $this->normaliseFilterArgs(...func_get_args()); $hitsRequiredToRemove = count($removeUs); $matches = []; foreach ($removeUs as $column => $excludeValue) { foreach ($this->items as $key => $item) { if (!is_array($excludeValue) && $this->extractValue($item, $column) == $excludeValue) { $matches[$key] = isset($matches[$key]) ? $matches[$key] + 1 : 1; } elseif (is_array($excludeValue) && in_array($this->extractValue($item, $column), $excludeValue)) { $matches[$key] = isset($matches[$key]) ? $matches[$key] + 1 : 1; } } } $keysToRemove = array_keys($matches, $hitsRequiredToRemove); $itemsToKeep = []; foreach ($this->items as $key => $value) { if (!in_array($key, $keysToRemove)) { $itemsToKeep[] = $value; } } $list = clone $this; $list->items = $itemsToKeep; return $list; }
[ "public", "function", "exclude", "(", ")", "{", "$", "removeUs", "=", "$", "this", "->", "normaliseFilterArgs", "(", "...", "func_get_args", "(", ")", ")", ";", "$", "hitsRequiredToRemove", "=", "count", "(", "$", "removeUs", ")", ";", "$", "matches", "=", "[", "]", ";", "foreach", "(", "$", "removeUs", "as", "$", "column", "=>", "$", "excludeValue", ")", "{", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "if", "(", "!", "is_array", "(", "$", "excludeValue", ")", "&&", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "column", ")", "==", "$", "excludeValue", ")", "{", "$", "matches", "[", "$", "key", "]", "=", "isset", "(", "$", "matches", "[", "$", "key", "]", ")", "?", "$", "matches", "[", "$", "key", "]", "+", "1", ":", "1", ";", "}", "elseif", "(", "is_array", "(", "$", "excludeValue", ")", "&&", "in_array", "(", "$", "this", "->", "extractValue", "(", "$", "item", ",", "$", "column", ")", ",", "$", "excludeValue", ")", ")", "{", "$", "matches", "[", "$", "key", "]", "=", "isset", "(", "$", "matches", "[", "$", "key", "]", ")", "?", "$", "matches", "[", "$", "key", "]", "+", "1", ":", "1", ";", "}", "}", "}", "$", "keysToRemove", "=", "array_keys", "(", "$", "matches", ",", "$", "hitsRequiredToRemove", ")", ";", "$", "itemsToKeep", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "keysToRemove", ")", ")", "{", "$", "itemsToKeep", "[", "]", "=", "$", "value", ";", "}", "}", "$", "list", "=", "clone", "$", "this", ";", "$", "list", "->", "items", "=", "$", "itemsToKeep", ";", "return", "$", "list", ";", "}" ]
Exclude the list to not contain items with these charactaristics @return ArrayList @see SS_List::exclude() @example $list->exclude('Name', 'bob'); // exclude bob from list @example $list->exclude('Name', array('aziz', 'bob'); // exclude aziz and bob from list @example $list->exclude(array('Name'=>'bob, 'Age'=>21)); // exclude bob that has Age 21 @example $list->exclude(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob with Age 21 or 43 @example $list->exclude(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43))); // bob age 21 or 43, phil age 21 or 43 would be excluded
[ "Exclude", "the", "list", "to", "not", "contain", "items", "with", "these", "charactaristics" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ArrayList.php#L767-L795
train
silverstripe/silverstripe-framework
src/ORM/UnsavedRelationList.php
UnsavedRelationList.changeToList
public function changeToList(RelationList $list) { foreach ($this->items as $key => $item) { $list->add($item, $this->extraFields[$key]); } }
php
public function changeToList(RelationList $list) { foreach ($this->items as $key => $item) { $list->add($item, $this->extraFields[$key]); } }
[ "public", "function", "changeToList", "(", "RelationList", "$", "list", ")", "{", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "$", "list", "->", "add", "(", "$", "item", ",", "$", "this", "->", "extraFields", "[", "$", "key", "]", ")", ";", "}", "}" ]
Save all the items in this list into the RelationList @param RelationList $list
[ "Save", "all", "the", "items", "in", "this", "list", "into", "the", "RelationList" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/UnsavedRelationList.php#L82-L87
train
silverstripe/silverstripe-framework
src/ORM/UnsavedRelationList.php
UnsavedRelationList.push
public function push($item, $extraFields = null) { if ((is_object($item) && !$item instanceof $this->dataClass) || (!is_object($item) && !is_numeric($item))) { throw new InvalidArgumentException( "UnsavedRelationList::add() expecting a $this->dataClass object, or ID value", E_USER_ERROR ); } if (is_object($item) && $item->ID) { $item = $item->ID; } $this->extraFields[] = $extraFields; parent::push($item); }
php
public function push($item, $extraFields = null) { if ((is_object($item) && !$item instanceof $this->dataClass) || (!is_object($item) && !is_numeric($item))) { throw new InvalidArgumentException( "UnsavedRelationList::add() expecting a $this->dataClass object, or ID value", E_USER_ERROR ); } if (is_object($item) && $item->ID) { $item = $item->ID; } $this->extraFields[] = $extraFields; parent::push($item); }
[ "public", "function", "push", "(", "$", "item", ",", "$", "extraFields", "=", "null", ")", "{", "if", "(", "(", "is_object", "(", "$", "item", ")", "&&", "!", "$", "item", "instanceof", "$", "this", "->", "dataClass", ")", "||", "(", "!", "is_object", "(", "$", "item", ")", "&&", "!", "is_numeric", "(", "$", "item", ")", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"UnsavedRelationList::add() expecting a $this->dataClass object, or ID value\"", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "is_object", "(", "$", "item", ")", "&&", "$", "item", "->", "ID", ")", "{", "$", "item", "=", "$", "item", "->", "ID", ";", "}", "$", "this", "->", "extraFields", "[", "]", "=", "$", "extraFields", ";", "parent", "::", "push", "(", "$", "item", ")", ";", "}" ]
Pushes an item onto the end of this list. @param array|object $item @param array $extraFields
[ "Pushes", "an", "item", "onto", "the", "end", "of", "this", "list", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/UnsavedRelationList.php#L95-L109
train
silverstripe/silverstripe-framework
src/ORM/UnsavedRelationList.php
UnsavedRelationList.toArray
public function toArray() { $items = array(); foreach ($this->items as $key => $item) { if (is_numeric($item)) { $item = DataObject::get_by_id($this->dataClass, $item); } if (!empty($this->extraFields[$key])) { $item->update($this->extraFields[$key]); } $items[] = $item; } return $items; }
php
public function toArray() { $items = array(); foreach ($this->items as $key => $item) { if (is_numeric($item)) { $item = DataObject::get_by_id($this->dataClass, $item); } if (!empty($this->extraFields[$key])) { $item->update($this->extraFields[$key]); } $items[] = $item; } return $items; }
[ "public", "function", "toArray", "(", ")", "{", "$", "items", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "if", "(", "is_numeric", "(", "$", "item", ")", ")", "{", "$", "item", "=", "DataObject", "::", "get_by_id", "(", "$", "this", "->", "dataClass", ",", "$", "item", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "extraFields", "[", "$", "key", "]", ")", ")", "{", "$", "item", "->", "update", "(", "$", "this", "->", "extraFields", "[", "$", "key", "]", ")", ";", "}", "$", "items", "[", "]", "=", "$", "item", ";", "}", "return", "$", "items", ";", "}" ]
Return an array of the actual items that this relation contains at this stage. This is when the query is actually executed. @return array
[ "Return", "an", "array", "of", "the", "actual", "items", "that", "this", "relation", "contains", "at", "this", "stage", ".", "This", "is", "when", "the", "query", "is", "actually", "executed", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/UnsavedRelationList.php#L137-L150
train
silverstripe/silverstripe-framework
src/ORM/UnsavedRelationList.php
UnsavedRelationList.first
public function first() { $item = reset($this->items); if (is_numeric($item)) { $item = DataObject::get_by_id($this->dataClass, $item); } if (!empty($this->extraFields[key($this->items)])) { $item->update($this->extraFields[key($this->items)]); } return $item; }
php
public function first() { $item = reset($this->items); if (is_numeric($item)) { $item = DataObject::get_by_id($this->dataClass, $item); } if (!empty($this->extraFields[key($this->items)])) { $item->update($this->extraFields[key($this->items)]); } return $item; }
[ "public", "function", "first", "(", ")", "{", "$", "item", "=", "reset", "(", "$", "this", "->", "items", ")", ";", "if", "(", "is_numeric", "(", "$", "item", ")", ")", "{", "$", "item", "=", "DataObject", "::", "get_by_id", "(", "$", "this", "->", "dataClass", ",", "$", "item", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "extraFields", "[", "key", "(", "$", "this", "->", "items", ")", "]", ")", ")", "{", "$", "item", "->", "update", "(", "$", "this", "->", "extraFields", "[", "key", "(", "$", "this", "->", "items", ")", "]", ")", ";", "}", "return", "$", "item", ";", "}" ]
Returns the first item in the list @return mixed
[ "Returns", "the", "first", "item", "in", "the", "list" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/UnsavedRelationList.php#L240-L250
train
silverstripe/silverstripe-framework
src/ORM/UnsavedRelationList.php
UnsavedRelationList.last
public function last() { $item = end($this->items); if (!empty($this->extraFields[key($this->items)])) { $item->update($this->extraFields[key($this->items)]); } return $item; }
php
public function last() { $item = end($this->items); if (!empty($this->extraFields[key($this->items)])) { $item->update($this->extraFields[key($this->items)]); } return $item; }
[ "public", "function", "last", "(", ")", "{", "$", "item", "=", "end", "(", "$", "this", "->", "items", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "extraFields", "[", "key", "(", "$", "this", "->", "items", ")", "]", ")", ")", "{", "$", "item", "->", "update", "(", "$", "this", "->", "extraFields", "[", "key", "(", "$", "this", "->", "items", ")", "]", ")", ";", "}", "return", "$", "item", ";", "}" ]
Returns the last item in the list @return mixed
[ "Returns", "the", "last", "item", "in", "the", "list" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/UnsavedRelationList.php#L257-L264
train
silverstripe/silverstripe-framework
src/ORM/UnsavedRelationList.php
UnsavedRelationList.forForeignID
public function forForeignID($id) { $singleton = DataObject::singleton($this->baseClass); /** @var Relation $relation */ $relation = $singleton->{$this->relationName}($id); return $relation; }
php
public function forForeignID($id) { $singleton = DataObject::singleton($this->baseClass); /** @var Relation $relation */ $relation = $singleton->{$this->relationName}($id); return $relation; }
[ "public", "function", "forForeignID", "(", "$", "id", ")", "{", "$", "singleton", "=", "DataObject", "::", "singleton", "(", "$", "this", "->", "baseClass", ")", ";", "/** @var Relation $relation */", "$", "relation", "=", "$", "singleton", "->", "{", "$", "this", "->", "relationName", "}", "(", "$", "id", ")", ";", "return", "$", "relation", ";", "}" ]
Returns a copy of this list with the relationship linked to the given foreign ID. @param int|array $id An ID or an array of IDs. @return Relation
[ "Returns", "a", "copy", "of", "this", "list", "with", "the", "relationship", "linked", "to", "the", "given", "foreign", "ID", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/UnsavedRelationList.php#L295-L301
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPageCount.php
GridFieldPageCount.getPaginator
protected function getPaginator($gridField) { /** @var GridFieldPaginator $paginator */ $paginator = $gridField->getConfig()->getComponentByType(GridFieldPaginator::class); if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) { throw new LogicException( static::class . " relies on a GridFieldPaginator to be added " . "to the same GridField, but none are present." ); } return $paginator; }
php
protected function getPaginator($gridField) { /** @var GridFieldPaginator $paginator */ $paginator = $gridField->getConfig()->getComponentByType(GridFieldPaginator::class); if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) { throw new LogicException( static::class . " relies on a GridFieldPaginator to be added " . "to the same GridField, but none are present." ); } return $paginator; }
[ "protected", "function", "getPaginator", "(", "$", "gridField", ")", "{", "/** @var GridFieldPaginator $paginator */", "$", "paginator", "=", "$", "gridField", "->", "getConfig", "(", ")", "->", "getComponentByType", "(", "GridFieldPaginator", "::", "class", ")", ";", "if", "(", "!", "$", "paginator", "&&", "GridFieldPageCount", "::", "config", "(", ")", "->", "uninherited", "(", "'require_paginator'", ")", ")", "{", "throw", "new", "LogicException", "(", "static", "::", "class", ".", "\" relies on a GridFieldPaginator to be added \"", ".", "\"to the same GridField, but none are present.\"", ")", ";", "}", "return", "$", "paginator", ";", "}" ]
Retrieves an instance of a GridFieldPaginator attached to the same control @param GridField $gridField The parent gridfield @return GridFieldPaginator The attached GridFieldPaginator, if found. @throws LogicException
[ "Retrieves", "an", "instance", "of", "a", "GridFieldPaginator", "attached", "to", "the", "same", "control" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldPageCount.php#L47-L59
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBClassName.php
DBClassName.getBaseClass
public function getBaseClass() { // Use explicit base class if ($this->baseClass) { return $this->baseClass; } // Default to the basename of the record $schema = DataObject::getSchema(); if ($this->record) { return $schema->baseDataClass($this->record); } // During dev/build only the table is assigned $tableClass = $schema->tableClass($this->getTable()); if ($tableClass && ($baseClass = $schema->baseDataClass($tableClass))) { return $baseClass; } // Fallback to global default return DataObject::class; }
php
public function getBaseClass() { // Use explicit base class if ($this->baseClass) { return $this->baseClass; } // Default to the basename of the record $schema = DataObject::getSchema(); if ($this->record) { return $schema->baseDataClass($this->record); } // During dev/build only the table is assigned $tableClass = $schema->tableClass($this->getTable()); if ($tableClass && ($baseClass = $schema->baseDataClass($tableClass))) { return $baseClass; } // Fallback to global default return DataObject::class; }
[ "public", "function", "getBaseClass", "(", ")", "{", "// Use explicit base class", "if", "(", "$", "this", "->", "baseClass", ")", "{", "return", "$", "this", "->", "baseClass", ";", "}", "// Default to the basename of the record", "$", "schema", "=", "DataObject", "::", "getSchema", "(", ")", ";", "if", "(", "$", "this", "->", "record", ")", "{", "return", "$", "schema", "->", "baseDataClass", "(", "$", "this", "->", "record", ")", ";", "}", "// During dev/build only the table is assigned", "$", "tableClass", "=", "$", "schema", "->", "tableClass", "(", "$", "this", "->", "getTable", "(", ")", ")", ";", "if", "(", "$", "tableClass", "&&", "(", "$", "baseClass", "=", "$", "schema", "->", "baseDataClass", "(", "$", "tableClass", ")", ")", ")", "{", "return", "$", "baseClass", ";", "}", "// Fallback to global default", "return", "DataObject", "::", "class", ";", "}" ]
Get the base dataclass for the list of subclasses @return string
[ "Get", "the", "base", "dataclass", "for", "the", "list", "of", "subclasses" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBClassName.php#L86-L104
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBClassName.php
DBClassName.getShortName
public function getShortName() { $value = $this->getValue(); if (empty($value) || !ClassInfo::exists($value)) { return null; } return ClassInfo::shortName($value); }
php
public function getShortName() { $value = $this->getValue(); if (empty($value) || !ClassInfo::exists($value)) { return null; } return ClassInfo::shortName($value); }
[ "public", "function", "getShortName", "(", ")", "{", "$", "value", "=", "$", "this", "->", "getValue", "(", ")", ";", "if", "(", "empty", "(", "$", "value", ")", "||", "!", "ClassInfo", "::", "exists", "(", "$", "value", ")", ")", "{", "return", "null", ";", "}", "return", "ClassInfo", "::", "shortName", "(", "$", "value", ")", ";", "}" ]
Get the base name of the current class Useful as a non-fully qualified CSS Class name in templates. @return string|null
[ "Get", "the", "base", "name", "of", "the", "current", "class", "Useful", "as", "a", "non", "-", "fully", "qualified", "CSS", "Class", "name", "in", "templates", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBClassName.php#L112-L119
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBClassName.php
DBClassName.getEnum
public function getEnum() { $classNames = ClassInfo::subclassesFor($this->getBaseClass()); $dataobject = strtolower(DataObject::class); unset($classNames[$dataobject]); return array_values($classNames); }
php
public function getEnum() { $classNames = ClassInfo::subclassesFor($this->getBaseClass()); $dataobject = strtolower(DataObject::class); unset($classNames[$dataobject]); return array_values($classNames); }
[ "public", "function", "getEnum", "(", ")", "{", "$", "classNames", "=", "ClassInfo", "::", "subclassesFor", "(", "$", "this", "->", "getBaseClass", "(", ")", ")", ";", "$", "dataobject", "=", "strtolower", "(", "DataObject", "::", "class", ")", ";", "unset", "(", "$", "classNames", "[", "$", "dataobject", "]", ")", ";", "return", "array_values", "(", "$", "classNames", ")", ";", "}" ]
Get list of classnames that should be selectable @return array
[ "Get", "list", "of", "classnames", "that", "should", "be", "selectable" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBClassName.php#L138-L144
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.name_to_label
public static function name_to_label($fieldName) { // Handle dot delimiters if (strpos($fieldName, '.') !== false) { $parts = explode('.', $fieldName); // Ensure that any letter following a dot is uppercased, so that the regex below can break it up // into words $label = implode(array_map('ucfirst', $parts)); } else { $label = $fieldName; } // Replace any capital letter that is followed by a lowercase letter with a space, the lowercased // version of itself then the remaining lowercase letters. $labelWithSpaces = preg_replace_callback('/([A-Z])([a-z]+)/', function ($matches) { return ' ' . strtolower($matches[1]) . $matches[2]; }, $label); // Add a space before any capital letter block that is at the end of the string $labelWithSpaces = preg_replace('/([a-z])([A-Z]+)$/', '$1 $2', $labelWithSpaces); // The first letter should be uppercase return ucfirst(trim($labelWithSpaces)); }
php
public static function name_to_label($fieldName) { // Handle dot delimiters if (strpos($fieldName, '.') !== false) { $parts = explode('.', $fieldName); // Ensure that any letter following a dot is uppercased, so that the regex below can break it up // into words $label = implode(array_map('ucfirst', $parts)); } else { $label = $fieldName; } // Replace any capital letter that is followed by a lowercase letter with a space, the lowercased // version of itself then the remaining lowercase letters. $labelWithSpaces = preg_replace_callback('/([A-Z])([a-z]+)/', function ($matches) { return ' ' . strtolower($matches[1]) . $matches[2]; }, $label); // Add a space before any capital letter block that is at the end of the string $labelWithSpaces = preg_replace('/([a-z])([A-Z]+)$/', '$1 $2', $labelWithSpaces); // The first letter should be uppercase return ucfirst(trim($labelWithSpaces)); }
[ "public", "static", "function", "name_to_label", "(", "$", "fieldName", ")", "{", "// Handle dot delimiters", "if", "(", "strpos", "(", "$", "fieldName", ",", "'.'", ")", "!==", "false", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "fieldName", ")", ";", "// Ensure that any letter following a dot is uppercased, so that the regex below can break it up", "// into words", "$", "label", "=", "implode", "(", "array_map", "(", "'ucfirst'", ",", "$", "parts", ")", ")", ";", "}", "else", "{", "$", "label", "=", "$", "fieldName", ";", "}", "// Replace any capital letter that is followed by a lowercase letter with a space, the lowercased", "// version of itself then the remaining lowercase letters.", "$", "labelWithSpaces", "=", "preg_replace_callback", "(", "'/([A-Z])([a-z]+)/'", ",", "function", "(", "$", "matches", ")", "{", "return", "' '", ".", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ".", "$", "matches", "[", "2", "]", ";", "}", ",", "$", "label", ")", ";", "// Add a space before any capital letter block that is at the end of the string", "$", "labelWithSpaces", "=", "preg_replace", "(", "'/([a-z])([A-Z]+)$/'", ",", "'$1 $2'", ",", "$", "labelWithSpaces", ")", ";", "// The first letter should be uppercase", "return", "ucfirst", "(", "trim", "(", "$", "labelWithSpaces", ")", ")", ";", "}" ]
Takes a field name and converts camelcase to spaced words. Also resolves combined field names with dot syntax to spaced words. Examples: - 'TotalAmount' will return 'Total amount' - 'Organisation.ZipCode' will return 'Organisation zip code' @param string $fieldName @return string
[ "Takes", "a", "field", "name", "and", "converts", "camelcase", "to", "spaced", "words", ".", "Also", "resolves", "combined", "field", "names", "with", "dot", "syntax", "to", "spaced", "words", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L305-L328
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.Link
public function Link($action = null) { if (!$this->form) { throw new LogicException( 'Field must be associated with a form to call Link(). Please use $field->setForm($form);' ); } $link = Controller::join_links($this->form->FormAction(), 'field/' . $this->name, $action); $this->extend('updateLink', $link, $action); return $link; }
php
public function Link($action = null) { if (!$this->form) { throw new LogicException( 'Field must be associated with a form to call Link(). Please use $field->setForm($form);' ); } $link = Controller::join_links($this->form->FormAction(), 'field/' . $this->name, $action); $this->extend('updateLink', $link, $action); return $link; }
[ "public", "function", "Link", "(", "$", "action", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "form", ")", "{", "throw", "new", "LogicException", "(", "'Field must be associated with a form to call Link(). Please use $field->setForm($form);'", ")", ";", "}", "$", "link", "=", "Controller", "::", "join_links", "(", "$", "this", "->", "form", "->", "FormAction", "(", ")", ",", "'field/'", ".", "$", "this", "->", "name", ",", "$", "action", ")", ";", "$", "this", "->", "extend", "(", "'updateLink'", ",", "$", "link", ",", "$", "action", ")", ";", "return", "$", "link", ";", "}" ]
Return a link to this field @param string $action @return string @throws LogicException If no form is set yet
[ "Return", "a", "link", "to", "this", "field" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L377-L388
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.getAttributes
public function getAttributes() { $attributes = array( 'type' => $this->getInputType(), 'name' => $this->getName(), 'value' => $this->Value(), 'class' => $this->extraClass(), 'id' => $this->ID(), 'disabled' => $this->isDisabled(), 'readonly' => $this->isReadonly(), 'autofocus' => $this->isAutofocus() ); if ($this->Required()) { $attributes['required'] = 'required'; $attributes['aria-required'] = 'true'; } $attributes = array_merge($attributes, $this->attributes); $this->extend('updateAttributes', $attributes); return $attributes; }
php
public function getAttributes() { $attributes = array( 'type' => $this->getInputType(), 'name' => $this->getName(), 'value' => $this->Value(), 'class' => $this->extraClass(), 'id' => $this->ID(), 'disabled' => $this->isDisabled(), 'readonly' => $this->isReadonly(), 'autofocus' => $this->isAutofocus() ); if ($this->Required()) { $attributes['required'] = 'required'; $attributes['aria-required'] = 'true'; } $attributes = array_merge($attributes, $this->attributes); $this->extend('updateAttributes', $attributes); return $attributes; }
[ "public", "function", "getAttributes", "(", ")", "{", "$", "attributes", "=", "array", "(", "'type'", "=>", "$", "this", "->", "getInputType", "(", ")", ",", "'name'", "=>", "$", "this", "->", "getName", "(", ")", ",", "'value'", "=>", "$", "this", "->", "Value", "(", ")", ",", "'class'", "=>", "$", "this", "->", "extraClass", "(", ")", ",", "'id'", "=>", "$", "this", "->", "ID", "(", ")", ",", "'disabled'", "=>", "$", "this", "->", "isDisabled", "(", ")", ",", "'readonly'", "=>", "$", "this", "->", "isReadonly", "(", ")", ",", "'autofocus'", "=>", "$", "this", "->", "isAutofocus", "(", ")", ")", ";", "if", "(", "$", "this", "->", "Required", "(", ")", ")", "{", "$", "attributes", "[", "'required'", "]", "=", "'required'", ";", "$", "attributes", "[", "'aria-required'", "]", "=", "'true'", ";", "}", "$", "attributes", "=", "array_merge", "(", "$", "attributes", ",", "$", "this", "->", "attributes", ")", ";", "$", "this", "->", "extend", "(", "'updateAttributes'", ",", "$", "attributes", ")", ";", "return", "$", "attributes", ";", "}" ]
Allows customization through an 'updateAttributes' hook on the base class. Existing attributes are passed in as the first argument and can be manipulated, but any attributes added through a subclass implementation won't be included. @return array
[ "Allows", "customization", "through", "an", "updateAttributes", "hook", "on", "the", "base", "class", ".", "Existing", "attributes", "are", "passed", "in", "as", "the", "first", "argument", "and", "can", "be", "manipulated", "but", "any", "attributes", "added", "through", "a", "subclass", "implementation", "won", "t", "be", "included", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L679-L702
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.Field
public function Field($properties = array()) { $context = $this; $this->extend('onBeforeRender', $context, $properties); if (count($properties)) { $context = $context->customise($properties); } $result = $context->renderWith($this->getTemplates()); // Trim whitespace from the result, so that trailing newlines are supressed. Works for strings and HTMLText values if (is_string($result)) { $result = trim($result); } elseif ($result instanceof DBField) { $result->setValue(trim($result->getValue())); } return $result; }
php
public function Field($properties = array()) { $context = $this; $this->extend('onBeforeRender', $context, $properties); if (count($properties)) { $context = $context->customise($properties); } $result = $context->renderWith($this->getTemplates()); // Trim whitespace from the result, so that trailing newlines are supressed. Works for strings and HTMLText values if (is_string($result)) { $result = trim($result); } elseif ($result instanceof DBField) { $result->setValue(trim($result->getValue())); } return $result; }
[ "public", "function", "Field", "(", "$", "properties", "=", "array", "(", ")", ")", "{", "$", "context", "=", "$", "this", ";", "$", "this", "->", "extend", "(", "'onBeforeRender'", ",", "$", "context", ",", "$", "properties", ")", ";", "if", "(", "count", "(", "$", "properties", ")", ")", "{", "$", "context", "=", "$", "context", "->", "customise", "(", "$", "properties", ")", ";", "}", "$", "result", "=", "$", "context", "->", "renderWith", "(", "$", "this", "->", "getTemplates", "(", ")", ")", ";", "// Trim whitespace from the result, so that trailing newlines are supressed. Works for strings and HTMLText values", "if", "(", "is_string", "(", "$", "result", ")", ")", "{", "$", "result", "=", "trim", "(", "$", "result", ")", ";", "}", "elseif", "(", "$", "result", "instanceof", "DBField", ")", "{", "$", "result", "->", "setValue", "(", "trim", "(", "$", "result", "->", "getValue", "(", ")", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns the form field. Although FieldHolder is generally what is inserted into templates, all of the field holder templates make use of $Field. It's expected that FieldHolder will give you the "complete" representation of the field on the form, whereas Field will give you the core editing widget, such as an input tag. @param array $properties @return DBHTMLText
[ "Returns", "the", "form", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1000-L1020
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.FieldHolder
public function FieldHolder($properties = array()) { $context = $this; if (count($properties)) { $context = $this->customise($properties); } return $context->renderWith($this->getFieldHolderTemplates()); }
php
public function FieldHolder($properties = array()) { $context = $this; if (count($properties)) { $context = $this->customise($properties); } return $context->renderWith($this->getFieldHolderTemplates()); }
[ "public", "function", "FieldHolder", "(", "$", "properties", "=", "array", "(", ")", ")", "{", "$", "context", "=", "$", "this", ";", "if", "(", "count", "(", "$", "properties", ")", ")", "{", "$", "context", "=", "$", "this", "->", "customise", "(", "$", "properties", ")", ";", "}", "return", "$", "context", "->", "renderWith", "(", "$", "this", "->", "getFieldHolderTemplates", "(", ")", ")", ";", "}" ]
Returns a "field holder" for this field. Forms are constructed by concatenating a number of these field holders. The default field holder is a label and a form field inside a div. @see FieldHolder.ss @param array $properties @return DBHTMLText
[ "Returns", "a", "field", "holder", "for", "this", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1035-L1044
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField._templates
protected function _templates($customTemplate = null, $customTemplateSuffix = null) { $templates = SSViewer::get_templates_by_class(static::class, $customTemplateSuffix, __CLASS__); // Prefer any custom template if ($customTemplate) { // Prioritise direct template array_unshift($templates, $customTemplate); } return $templates; }
php
protected function _templates($customTemplate = null, $customTemplateSuffix = null) { $templates = SSViewer::get_templates_by_class(static::class, $customTemplateSuffix, __CLASS__); // Prefer any custom template if ($customTemplate) { // Prioritise direct template array_unshift($templates, $customTemplate); } return $templates; }
[ "protected", "function", "_templates", "(", "$", "customTemplate", "=", "null", ",", "$", "customTemplateSuffix", "=", "null", ")", "{", "$", "templates", "=", "SSViewer", "::", "get_templates_by_class", "(", "static", "::", "class", ",", "$", "customTemplateSuffix", ",", "__CLASS__", ")", ";", "// Prefer any custom template", "if", "(", "$", "customTemplate", ")", "{", "// Prioritise direct template", "array_unshift", "(", "$", "templates", ",", "$", "customTemplate", ")", ";", "}", "return", "$", "templates", ";", "}" ]
Generate an array of class name strings to use for rendering this form field into HTML. @param string $customTemplate @param string $customTemplateSuffix @return array
[ "Generate", "an", "array", "of", "class", "name", "strings", "to", "use", "for", "rendering", "this", "form", "field", "into", "HTML", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1109-L1118
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.performReadonlyTransformation
public function performReadonlyTransformation() { $readonlyClassName = static::class . '_Readonly'; if (ClassInfo::exists($readonlyClassName)) { $clone = $this->castedCopy($readonlyClassName); } else { $clone = $this->castedCopy(ReadonlyField::class); } $clone->setReadonly(true); return $clone; }
php
public function performReadonlyTransformation() { $readonlyClassName = static::class . '_Readonly'; if (ClassInfo::exists($readonlyClassName)) { $clone = $this->castedCopy($readonlyClassName); } else { $clone = $this->castedCopy(ReadonlyField::class); } $clone->setReadonly(true); return $clone; }
[ "public", "function", "performReadonlyTransformation", "(", ")", "{", "$", "readonlyClassName", "=", "static", "::", "class", ".", "'_Readonly'", ";", "if", "(", "ClassInfo", "::", "exists", "(", "$", "readonlyClassName", ")", ")", "{", "$", "clone", "=", "$", "this", "->", "castedCopy", "(", "$", "readonlyClassName", ")", ";", "}", "else", "{", "$", "clone", "=", "$", "this", "->", "castedCopy", "(", "ReadonlyField", "::", "class", ")", ";", "}", "$", "clone", "->", "setReadonly", "(", "true", ")", ";", "return", "$", "clone", ";", "}" ]
Returns a read-only version of this field. @return FormField
[ "Returns", "a", "read", "-", "only", "version", "of", "this", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1224-L1237
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.performDisabledTransformation
public function performDisabledTransformation() { $disabledClassName = static::class . '_Disabled'; if (ClassInfo::exists($disabledClassName)) { $clone = $this->castedCopy($disabledClassName); } else { $clone = clone $this; } $clone->setDisabled(true); return $clone; }
php
public function performDisabledTransformation() { $disabledClassName = static::class . '_Disabled'; if (ClassInfo::exists($disabledClassName)) { $clone = $this->castedCopy($disabledClassName); } else { $clone = clone $this; } $clone->setDisabled(true); return $clone; }
[ "public", "function", "performDisabledTransformation", "(", ")", "{", "$", "disabledClassName", "=", "static", "::", "class", ".", "'_Disabled'", ";", "if", "(", "ClassInfo", "::", "exists", "(", "$", "disabledClassName", ")", ")", "{", "$", "clone", "=", "$", "this", "->", "castedCopy", "(", "$", "disabledClassName", ")", ";", "}", "else", "{", "$", "clone", "=", "clone", "$", "this", ";", "}", "$", "clone", "->", "setDisabled", "(", "true", ")", ";", "return", "$", "clone", ";", "}" ]
Return a disabled version of this field. Tries to find a class of the class name of this field suffixed with "_Disabled", failing that, finds a method {@link setDisabled()}. @return FormField
[ "Return", "a", "disabled", "version", "of", "this", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1247-L1260
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.hasClass
public function hasClass($class) { $classes = explode(' ', strtolower($this->extraClass())); return in_array(strtolower(trim($class)), $classes); }
php
public function hasClass($class) { $classes = explode(' ', strtolower($this->extraClass())); return in_array(strtolower(trim($class)), $classes); }
[ "public", "function", "hasClass", "(", "$", "class", ")", "{", "$", "classes", "=", "explode", "(", "' '", ",", "strtolower", "(", "$", "this", "->", "extraClass", "(", ")", ")", ")", ";", "return", "in_array", "(", "strtolower", "(", "trim", "(", "$", "class", ")", ")", ",", "$", "classes", ")", ";", "}" ]
Returns whether the current field has the given class added @param string $class @return bool
[ "Returns", "whether", "the", "current", "field", "has", "the", "given", "class", "added" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1279-L1283
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.castedCopy
public function castedCopy($classOrCopy) { $field = $classOrCopy; if (!is_object($field)) { $field = $classOrCopy::create($this->name); } $field ->setValue($this->value) ->setForm($this->form) ->setTitle($this->Title()) ->setLeftTitle($this->LeftTitle()) ->setRightTitle($this->RightTitle()) ->addExtraClass($this->extraClass) // Don't use extraClass(), since this merges calculated values ->setDescription($this->getDescription()); // Only include built-in attributes, ignore anything set through getAttributes(). // Those might change important characteristics of the field, e.g. its "type" attribute. foreach ($this->attributes as $attributeKey => $attributeValue) { $field->setAttribute($attributeKey, $attributeValue); } return $field; }
php
public function castedCopy($classOrCopy) { $field = $classOrCopy; if (!is_object($field)) { $field = $classOrCopy::create($this->name); } $field ->setValue($this->value) ->setForm($this->form) ->setTitle($this->Title()) ->setLeftTitle($this->LeftTitle()) ->setRightTitle($this->RightTitle()) ->addExtraClass($this->extraClass) // Don't use extraClass(), since this merges calculated values ->setDescription($this->getDescription()); // Only include built-in attributes, ignore anything set through getAttributes(). // Those might change important characteristics of the field, e.g. its "type" attribute. foreach ($this->attributes as $attributeKey => $attributeValue) { $field->setAttribute($attributeKey, $attributeValue); } return $field; }
[ "public", "function", "castedCopy", "(", "$", "classOrCopy", ")", "{", "$", "field", "=", "$", "classOrCopy", ";", "if", "(", "!", "is_object", "(", "$", "field", ")", ")", "{", "$", "field", "=", "$", "classOrCopy", "::", "create", "(", "$", "this", "->", "name", ")", ";", "}", "$", "field", "->", "setValue", "(", "$", "this", "->", "value", ")", "->", "setForm", "(", "$", "this", "->", "form", ")", "->", "setTitle", "(", "$", "this", "->", "Title", "(", ")", ")", "->", "setLeftTitle", "(", "$", "this", "->", "LeftTitle", "(", ")", ")", "->", "setRightTitle", "(", "$", "this", "->", "RightTitle", "(", ")", ")", "->", "addExtraClass", "(", "$", "this", "->", "extraClass", ")", "// Don't use extraClass(), since this merges calculated values", "->", "setDescription", "(", "$", "this", "->", "getDescription", "(", ")", ")", ";", "// Only include built-in attributes, ignore anything set through getAttributes().", "// Those might change important characteristics of the field, e.g. its \"type\" attribute.", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "attributeKey", "=>", "$", "attributeValue", ")", "{", "$", "field", "->", "setAttribute", "(", "$", "attributeKey", ",", "$", "attributeValue", ")", ";", "}", "return", "$", "field", ";", "}" ]
Returns another instance of this field, but "cast" to a different class. The logic tries to retain all of the instance properties, and may be overloaded by subclasses to set additional ones. Assumes the standard FormField parameter signature with its name as the only mandatory argument. Mainly geared towards creating *_Readonly or *_Disabled subclasses of the same type, or casting to a {@link ReadonlyField}. Does not copy custom field templates, since they probably won't apply to the new instance. @param mixed $classOrCopy Class name for copy, or existing copy instance to update @return FormField
[ "Returns", "another", "instance", "of", "this", "field", "but", "cast", "to", "a", "different", "class", ".", "The", "logic", "tries", "to", "retain", "all", "of", "the", "instance", "properties", "and", "may", "be", "overloaded", "by", "subclasses", "to", "set", "additional", "ones", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1434-L1458
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.getSchemaData
public function getSchemaData() { $defaults = $this->getSchemaDataDefaults(); return array_replace_recursive($defaults, array_intersect_key($this->schemaData, $defaults)); }
php
public function getSchemaData() { $defaults = $this->getSchemaDataDefaults(); return array_replace_recursive($defaults, array_intersect_key($this->schemaData, $defaults)); }
[ "public", "function", "getSchemaData", "(", ")", "{", "$", "defaults", "=", "$", "this", "->", "getSchemaDataDefaults", "(", ")", ";", "return", "array_replace_recursive", "(", "$", "defaults", ",", "array_intersect_key", "(", "$", "this", "->", "schemaData", ",", "$", "defaults", ")", ")", ";", "}" ]
Gets the schema data used to render the FormField on the front-end. @return array
[ "Gets", "the", "schema", "data", "used", "to", "render", "the", "FormField", "on", "the", "front", "-", "end", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1515-L1519
train
silverstripe/silverstripe-framework
src/Forms/FormField.php
FormField.getSchemaState
public function getSchemaState() { $defaults = $this->getSchemaStateDefaults(); return array_merge($defaults, array_intersect_key($this->schemaState, $defaults)); }
php
public function getSchemaState() { $defaults = $this->getSchemaStateDefaults(); return array_merge($defaults, array_intersect_key($this->schemaState, $defaults)); }
[ "public", "function", "getSchemaState", "(", ")", "{", "$", "defaults", "=", "$", "this", "->", "getSchemaStateDefaults", "(", ")", ";", "return", "array_merge", "(", "$", "defaults", ",", "array_intersect_key", "(", "$", "this", "->", "schemaState", ",", "$", "defaults", ")", ")", ";", "}" ]
Gets the schema state used to render the FormField on the front-end. @return array
[ "Gets", "the", "schema", "state", "used", "to", "render", "the", "FormField", "on", "the", "front", "-", "end", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormField.php#L1586-L1590
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.getPageStart
public function getPageStart() { $request = $this->getRequest(); if ($this->pageStart === null) { if ($request && isset($request[$this->getPaginationGetVar()]) && $request[$this->getPaginationGetVar()] > 0 ) { $this->pageStart = (int)$request[$this->getPaginationGetVar()]; } else { $this->pageStart = 0; } } return $this->pageStart; }
php
public function getPageStart() { $request = $this->getRequest(); if ($this->pageStart === null) { if ($request && isset($request[$this->getPaginationGetVar()]) && $request[$this->getPaginationGetVar()] > 0 ) { $this->pageStart = (int)$request[$this->getPaginationGetVar()]; } else { $this->pageStart = 0; } } return $this->pageStart; }
[ "public", "function", "getPageStart", "(", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "if", "(", "$", "this", "->", "pageStart", "===", "null", ")", "{", "if", "(", "$", "request", "&&", "isset", "(", "$", "request", "[", "$", "this", "->", "getPaginationGetVar", "(", ")", "]", ")", "&&", "$", "request", "[", "$", "this", "->", "getPaginationGetVar", "(", ")", "]", ">", "0", ")", "{", "$", "this", "->", "pageStart", "=", "(", "int", ")", "$", "request", "[", "$", "this", "->", "getPaginationGetVar", "(", ")", "]", ";", "}", "else", "{", "$", "this", "->", "pageStart", "=", "0", ";", "}", "}", "return", "$", "this", "->", "pageStart", ";", "}" ]
Returns the offset of the item the current page starts at. @return int
[ "Returns", "the", "offset", "of", "the", "item", "the", "current", "page", "starts", "at", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L111-L126
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.getTotalItems
public function getTotalItems() { if ($this->totalItems === null) { $this->totalItems = count($this->list); } return $this->totalItems; }
php
public function getTotalItems() { if ($this->totalItems === null) { $this->totalItems = count($this->list); } return $this->totalItems; }
[ "public", "function", "getTotalItems", "(", ")", "{", "if", "(", "$", "this", "->", "totalItems", "===", "null", ")", "{", "$", "this", "->", "totalItems", "=", "count", "(", "$", "this", "->", "list", ")", ";", "}", "return", "$", "this", "->", "totalItems", ";", "}" ]
Returns the total number of items in the unpaginated list. @return int
[ "Returns", "the", "total", "number", "of", "items", "in", "the", "unpaginated", "list", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L146-L153
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.setPaginationFromQuery
public function setPaginationFromQuery(SQLSelect $query) { if ($limit = $query->getLimit()) { $this->setPageLength($limit['limit']); $this->setPageStart($limit['start']); $this->setTotalItems($query->unlimitedRowCount()); } return $this; }
php
public function setPaginationFromQuery(SQLSelect $query) { if ($limit = $query->getLimit()) { $this->setPageLength($limit['limit']); $this->setPageStart($limit['start']); $this->setTotalItems($query->unlimitedRowCount()); } return $this; }
[ "public", "function", "setPaginationFromQuery", "(", "SQLSelect", "$", "query", ")", "{", "if", "(", "$", "limit", "=", "$", "query", "->", "getLimit", "(", ")", ")", "{", "$", "this", "->", "setPageLength", "(", "$", "limit", "[", "'limit'", "]", ")", ";", "$", "this", "->", "setPageStart", "(", "$", "limit", "[", "'start'", "]", ")", ";", "$", "this", "->", "setTotalItems", "(", "$", "query", "->", "unlimitedRowCount", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the page length, page start and total items from a query object's limit, offset and unlimited count. The query MUST have a limit clause. @param SQLSelect $query @return $this
[ "Sets", "the", "page", "length", "page", "start", "and", "total", "items", "from", "a", "query", "object", "s", "limit", "offset", "and", "unlimited", "count", ".", "The", "query", "MUST", "have", "a", "limit", "clause", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L175-L183
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.Pages
public function Pages($max = null) { $result = new ArrayList(); if ($max) { $start = ($this->CurrentPage() - floor($max / 2)) - 1; $end = $this->CurrentPage() + floor($max / 2); if ($start < 0) { $start = 0; $end = $max; } if ($end > $this->TotalPages()) { $end = $this->TotalPages(); $start = max(0, $end - $max); } } else { $start = 0; $end = $this->TotalPages(); } for ($i = $start; $i < $end; $i++) { $result->push(new ArrayData(array( 'PageNum' => $i + 1, 'Link' => HTTP::setGetVar( $this->getPaginationGetVar(), $i * $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ), 'CurrentBool' => $this->CurrentPage() == ($i + 1) ))); } return $result; }
php
public function Pages($max = null) { $result = new ArrayList(); if ($max) { $start = ($this->CurrentPage() - floor($max / 2)) - 1; $end = $this->CurrentPage() + floor($max / 2); if ($start < 0) { $start = 0; $end = $max; } if ($end > $this->TotalPages()) { $end = $this->TotalPages(); $start = max(0, $end - $max); } } else { $start = 0; $end = $this->TotalPages(); } for ($i = $start; $i < $end; $i++) { $result->push(new ArrayData(array( 'PageNum' => $i + 1, 'Link' => HTTP::setGetVar( $this->getPaginationGetVar(), $i * $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ), 'CurrentBool' => $this->CurrentPage() == ($i + 1) ))); } return $result; }
[ "public", "function", "Pages", "(", "$", "max", "=", "null", ")", "{", "$", "result", "=", "new", "ArrayList", "(", ")", ";", "if", "(", "$", "max", ")", "{", "$", "start", "=", "(", "$", "this", "->", "CurrentPage", "(", ")", "-", "floor", "(", "$", "max", "/", "2", ")", ")", "-", "1", ";", "$", "end", "=", "$", "this", "->", "CurrentPage", "(", ")", "+", "floor", "(", "$", "max", "/", "2", ")", ";", "if", "(", "$", "start", "<", "0", ")", "{", "$", "start", "=", "0", ";", "$", "end", "=", "$", "max", ";", "}", "if", "(", "$", "end", ">", "$", "this", "->", "TotalPages", "(", ")", ")", "{", "$", "end", "=", "$", "this", "->", "TotalPages", "(", ")", ";", "$", "start", "=", "max", "(", "0", ",", "$", "end", "-", "$", "max", ")", ";", "}", "}", "else", "{", "$", "start", "=", "0", ";", "$", "end", "=", "$", "this", "->", "TotalPages", "(", ")", ";", "}", "for", "(", "$", "i", "=", "$", "start", ";", "$", "i", "<", "$", "end", ";", "$", "i", "++", ")", "{", "$", "result", "->", "push", "(", "new", "ArrayData", "(", "array", "(", "'PageNum'", "=>", "$", "i", "+", "1", ",", "'Link'", "=>", "HTTP", "::", "setGetVar", "(", "$", "this", "->", "getPaginationGetVar", "(", ")", ",", "$", "i", "*", "$", "this", "->", "getPageLength", "(", ")", ",", "(", "$", "this", "->", "request", "instanceof", "HTTPRequest", ")", "?", "$", "this", "->", "request", "->", "getURL", "(", "true", ")", ":", "null", ")", ",", "'CurrentBool'", "=>", "$", "this", "->", "CurrentPage", "(", ")", "==", "(", "$", "i", "+", "1", ")", ")", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns a set of links to all the pages in the list. This is useful for basic pagination. By default it returns links to every page, but if you pass the $max parameter the number of pages will be limited to that number, centered around the current page. @param int $max @return SS_List
[ "Returns", "a", "set", "of", "links", "to", "all", "the", "pages", "in", "the", "list", ".", "This", "is", "useful", "for", "basic", "pagination", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L238-L273
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.PaginationSummary
public function PaginationSummary($context = 4) { $result = new ArrayList(); $current = $this->CurrentPage(); $total = $this->TotalPages(); // Make the number even for offset calculations. if ($context % 2) { $context--; } // If the first or last page is current, then show all context on one // side of it - otherwise show half on both sides. if ($current == 1 || $current == $total) { $offset = $context; } else { $offset = floor($context / 2); } $left = max($current - $offset, 1); $right = min($current + $offset, $total); $range = range($current - $offset, $current + $offset); if ($left + $context > $total) { $left = $total - $context; } for ($i = 0; $i < $total; $i++) { $link = HTTP::setGetVar( $this->getPaginationGetVar(), $i * $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); $num = $i + 1; $emptyRange = $num != 1 && $num != $total && ( $num == $left - 1 || $num == $right + 1 ); if ($emptyRange) { $result->push(new ArrayData(array( 'PageNum' => null, 'Link' => null, 'CurrentBool' => false ))); } elseif ($num == 1 || $num == $total || in_array($num, $range)) { $result->push(new ArrayData(array( 'PageNum' => $num, 'Link' => $link, 'CurrentBool' => $current == $num ))); } } return $result; }
php
public function PaginationSummary($context = 4) { $result = new ArrayList(); $current = $this->CurrentPage(); $total = $this->TotalPages(); // Make the number even for offset calculations. if ($context % 2) { $context--; } // If the first or last page is current, then show all context on one // side of it - otherwise show half on both sides. if ($current == 1 || $current == $total) { $offset = $context; } else { $offset = floor($context / 2); } $left = max($current - $offset, 1); $right = min($current + $offset, $total); $range = range($current - $offset, $current + $offset); if ($left + $context > $total) { $left = $total - $context; } for ($i = 0; $i < $total; $i++) { $link = HTTP::setGetVar( $this->getPaginationGetVar(), $i * $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); $num = $i + 1; $emptyRange = $num != 1 && $num != $total && ( $num == $left - 1 || $num == $right + 1 ); if ($emptyRange) { $result->push(new ArrayData(array( 'PageNum' => null, 'Link' => null, 'CurrentBool' => false ))); } elseif ($num == 1 || $num == $total || in_array($num, $range)) { $result->push(new ArrayData(array( 'PageNum' => $num, 'Link' => $link, 'CurrentBool' => $current == $num ))); } } return $result; }
[ "public", "function", "PaginationSummary", "(", "$", "context", "=", "4", ")", "{", "$", "result", "=", "new", "ArrayList", "(", ")", ";", "$", "current", "=", "$", "this", "->", "CurrentPage", "(", ")", ";", "$", "total", "=", "$", "this", "->", "TotalPages", "(", ")", ";", "// Make the number even for offset calculations.", "if", "(", "$", "context", "%", "2", ")", "{", "$", "context", "--", ";", "}", "// If the first or last page is current, then show all context on one", "// side of it - otherwise show half on both sides.", "if", "(", "$", "current", "==", "1", "||", "$", "current", "==", "$", "total", ")", "{", "$", "offset", "=", "$", "context", ";", "}", "else", "{", "$", "offset", "=", "floor", "(", "$", "context", "/", "2", ")", ";", "}", "$", "left", "=", "max", "(", "$", "current", "-", "$", "offset", ",", "1", ")", ";", "$", "right", "=", "min", "(", "$", "current", "+", "$", "offset", ",", "$", "total", ")", ";", "$", "range", "=", "range", "(", "$", "current", "-", "$", "offset", ",", "$", "current", "+", "$", "offset", ")", ";", "if", "(", "$", "left", "+", "$", "context", ">", "$", "total", ")", "{", "$", "left", "=", "$", "total", "-", "$", "context", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "total", ";", "$", "i", "++", ")", "{", "$", "link", "=", "HTTP", "::", "setGetVar", "(", "$", "this", "->", "getPaginationGetVar", "(", ")", ",", "$", "i", "*", "$", "this", "->", "getPageLength", "(", ")", ",", "(", "$", "this", "->", "request", "instanceof", "HTTPRequest", ")", "?", "$", "this", "->", "request", "->", "getURL", "(", "true", ")", ":", "null", ")", ";", "$", "num", "=", "$", "i", "+", "1", ";", "$", "emptyRange", "=", "$", "num", "!=", "1", "&&", "$", "num", "!=", "$", "total", "&&", "(", "$", "num", "==", "$", "left", "-", "1", "||", "$", "num", "==", "$", "right", "+", "1", ")", ";", "if", "(", "$", "emptyRange", ")", "{", "$", "result", "->", "push", "(", "new", "ArrayData", "(", "array", "(", "'PageNum'", "=>", "null", ",", "'Link'", "=>", "null", ",", "'CurrentBool'", "=>", "false", ")", ")", ")", ";", "}", "elseif", "(", "$", "num", "==", "1", "||", "$", "num", "==", "$", "total", "||", "in_array", "(", "$", "num", ",", "$", "range", ")", ")", "{", "$", "result", "->", "push", "(", "new", "ArrayData", "(", "array", "(", "'PageNum'", "=>", "$", "num", ",", "'Link'", "=>", "$", "link", ",", "'CurrentBool'", "=>", "$", "current", "==", "$", "num", ")", ")", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Returns a summarised pagination which limits the number of pages shown around the current page for visually balanced. Example: 25 pages total, currently on page 6, context of 4 pages [prev] [1] ... [4] [5] [[6]] [7] [8] ... [25] [next] Example template usage: <code> <% if MyPages.MoreThanOnePage %> <% if MyPages.NotFirstPage %> <a class="prev" href="$MyPages.PrevLink">Prev</a> <% end_if %> <% loop MyPages.PaginationSummary(4) %> <% if CurrentBool %> $PageNum <% else %> <% if Link %> <a href="$Link">$PageNum</a> <% else %> ... <% end_if %> <% end_if %> <% end_loop %> <% if MyPages.NotLastPage %> <a class="next" href="$MyPages.NextLink">Next</a> <% end_if %> <% end_if %> </code> @param int $context The number of pages to display around the current page. The number should be event, as half the number of each pages are displayed on either side of the current one. @return SS_List
[ "Returns", "a", "summarised", "pagination", "which", "limits", "the", "number", "of", "pages", "shown", "around", "the", "current", "page", "for", "visually", "balanced", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L310-L365
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.LastItem
public function LastItem() { $pageLength = $this->getPageLength(); if (!$pageLength) { return $this->getTotalItems(); } elseif ($start = $this->getPageStart()) { return min($start + $pageLength, $this->getTotalItems()); } else { return min($pageLength, $this->getTotalItems()); } }
php
public function LastItem() { $pageLength = $this->getPageLength(); if (!$pageLength) { return $this->getTotalItems(); } elseif ($start = $this->getPageStart()) { return min($start + $pageLength, $this->getTotalItems()); } else { return min($pageLength, $this->getTotalItems()); } }
[ "public", "function", "LastItem", "(", ")", "{", "$", "pageLength", "=", "$", "this", "->", "getPageLength", "(", ")", ";", "if", "(", "!", "$", "pageLength", ")", "{", "return", "$", "this", "->", "getTotalItems", "(", ")", ";", "}", "elseif", "(", "$", "start", "=", "$", "this", "->", "getPageStart", "(", ")", ")", "{", "return", "min", "(", "$", "start", "+", "$", "pageLength", ",", "$", "this", "->", "getTotalItems", "(", ")", ")", ";", "}", "else", "{", "return", "min", "(", "$", "pageLength", ",", "$", "this", "->", "getTotalItems", "(", ")", ")", ";", "}", "}" ]
Returns the number of the last item being displayed on this page. @return int
[ "Returns", "the", "number", "of", "the", "last", "item", "being", "displayed", "on", "this", "page", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L429-L439
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.FirstLink
public function FirstLink() { return HTTP::setGetVar( $this->getPaginationGetVar(), 0, ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); }
php
public function FirstLink() { return HTTP::setGetVar( $this->getPaginationGetVar(), 0, ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); }
[ "public", "function", "FirstLink", "(", ")", "{", "return", "HTTP", "::", "setGetVar", "(", "$", "this", "->", "getPaginationGetVar", "(", ")", ",", "0", ",", "(", "$", "this", "->", "request", "instanceof", "HTTPRequest", ")", "?", "$", "this", "->", "request", "->", "getURL", "(", "true", ")", ":", "null", ")", ";", "}" ]
Returns a link to the first page. @return string
[ "Returns", "a", "link", "to", "the", "first", "page", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L446-L453
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.LastLink
public function LastLink() { return HTTP::setGetVar( $this->getPaginationGetVar(), ($this->TotalPages() - 1) * $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); }
php
public function LastLink() { return HTTP::setGetVar( $this->getPaginationGetVar(), ($this->TotalPages() - 1) * $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); }
[ "public", "function", "LastLink", "(", ")", "{", "return", "HTTP", "::", "setGetVar", "(", "$", "this", "->", "getPaginationGetVar", "(", ")", ",", "(", "$", "this", "->", "TotalPages", "(", ")", "-", "1", ")", "*", "$", "this", "->", "getPageLength", "(", ")", ",", "(", "$", "this", "->", "request", "instanceof", "HTTPRequest", ")", "?", "$", "this", "->", "request", "->", "getURL", "(", "true", ")", ":", "null", ")", ";", "}" ]
Returns a link to the last page. @return string
[ "Returns", "a", "link", "to", "the", "last", "page", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L460-L467
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.NextLink
public function NextLink() { if ($this->NotLastPage()) { return HTTP::setGetVar( $this->getPaginationGetVar(), $this->getPageStart() + $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); } }
php
public function NextLink() { if ($this->NotLastPage()) { return HTTP::setGetVar( $this->getPaginationGetVar(), $this->getPageStart() + $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); } }
[ "public", "function", "NextLink", "(", ")", "{", "if", "(", "$", "this", "->", "NotLastPage", "(", ")", ")", "{", "return", "HTTP", "::", "setGetVar", "(", "$", "this", "->", "getPaginationGetVar", "(", ")", ",", "$", "this", "->", "getPageStart", "(", ")", "+", "$", "this", "->", "getPageLength", "(", ")", ",", "(", "$", "this", "->", "request", "instanceof", "HTTPRequest", ")", "?", "$", "this", "->", "request", "->", "getURL", "(", "true", ")", ":", "null", ")", ";", "}", "}" ]
Returns a link to the next page, if there is another page after the current one. @return string
[ "Returns", "a", "link", "to", "the", "next", "page", "if", "there", "is", "another", "page", "after", "the", "current", "one", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L475-L484
train
silverstripe/silverstripe-framework
src/ORM/PaginatedList.php
PaginatedList.PrevLink
public function PrevLink() { if ($this->NotFirstPage()) { return HTTP::setGetVar( $this->getPaginationGetVar(), $this->getPageStart() - $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); } }
php
public function PrevLink() { if ($this->NotFirstPage()) { return HTTP::setGetVar( $this->getPaginationGetVar(), $this->getPageStart() - $this->getPageLength(), ($this->request instanceof HTTPRequest) ? $this->request->getURL(true) : null ); } }
[ "public", "function", "PrevLink", "(", ")", "{", "if", "(", "$", "this", "->", "NotFirstPage", "(", ")", ")", "{", "return", "HTTP", "::", "setGetVar", "(", "$", "this", "->", "getPaginationGetVar", "(", ")", ",", "$", "this", "->", "getPageStart", "(", ")", "-", "$", "this", "->", "getPageLength", "(", ")", ",", "(", "$", "this", "->", "request", "instanceof", "HTTPRequest", ")", "?", "$", "this", "->", "request", "->", "getURL", "(", "true", ")", ":", "null", ")", ";", "}", "}" ]
Returns a link to the previous page, if the first page is not currently active. @return string
[ "Returns", "a", "link", "to", "the", "previous", "page", "if", "the", "first", "page", "is", "not", "currently", "active", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/PaginatedList.php#L492-L501
train
silverstripe/silverstripe-framework
src/Forms/FormScaffolder.php
FormScaffolder.addManyManyRelationshipFields
public static function addManyManyRelationshipFields( FieldList &$fields, $relationship, $overrideFieldClass, $tabbed, DataObject $dataObject ) { if ($tabbed) { $fields->findOrMakeTab( "Root.$relationship", $dataObject->fieldLabel($relationship) ); } $fieldClass = $overrideFieldClass ?: GridField::class; /** @var GridField $grid */ $grid = Injector::inst()->create( $fieldClass, $relationship, $dataObject->fieldLabel($relationship), $dataObject->$relationship(), GridFieldConfig_RelationEditor::create() ); if ($tabbed) { $fields->addFieldToTab("Root.$relationship", $grid); } else { $fields->push($grid); } }
php
public static function addManyManyRelationshipFields( FieldList &$fields, $relationship, $overrideFieldClass, $tabbed, DataObject $dataObject ) { if ($tabbed) { $fields->findOrMakeTab( "Root.$relationship", $dataObject->fieldLabel($relationship) ); } $fieldClass = $overrideFieldClass ?: GridField::class; /** @var GridField $grid */ $grid = Injector::inst()->create( $fieldClass, $relationship, $dataObject->fieldLabel($relationship), $dataObject->$relationship(), GridFieldConfig_RelationEditor::create() ); if ($tabbed) { $fields->addFieldToTab("Root.$relationship", $grid); } else { $fields->push($grid); } }
[ "public", "static", "function", "addManyManyRelationshipFields", "(", "FieldList", "&", "$", "fields", ",", "$", "relationship", ",", "$", "overrideFieldClass", ",", "$", "tabbed", ",", "DataObject", "$", "dataObject", ")", "{", "if", "(", "$", "tabbed", ")", "{", "$", "fields", "->", "findOrMakeTab", "(", "\"Root.$relationship\"", ",", "$", "dataObject", "->", "fieldLabel", "(", "$", "relationship", ")", ")", ";", "}", "$", "fieldClass", "=", "$", "overrideFieldClass", "?", ":", "GridField", "::", "class", ";", "/** @var GridField $grid */", "$", "grid", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "fieldClass", ",", "$", "relationship", ",", "$", "dataObject", "->", "fieldLabel", "(", "$", "relationship", ")", ",", "$", "dataObject", "->", "$", "relationship", "(", ")", ",", "GridFieldConfig_RelationEditor", "::", "create", "(", ")", ")", ";", "if", "(", "$", "tabbed", ")", "{", "$", "fields", "->", "addFieldToTab", "(", "\"Root.$relationship\"", ",", "$", "grid", ")", ";", "}", "else", "{", "$", "fields", "->", "push", "(", "$", "grid", ")", ";", "}", "}" ]
Adds the default many-many relation fields for the relationship provided. @param FieldList $fields Reference to the @FieldList to add fields to. @param string $relationship The relationship identifier. @param mixed $overrideFieldClass Specify the field class to use here or leave as null to use default. @param bool $tabbed Whether this relationship has it's own tab or not. @param DataObject $dataObject The @DataObject that has the relation.
[ "Adds", "the", "default", "many", "-", "many", "relation", "fields", "for", "the", "relationship", "provided", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormScaffolder.php#L199-L229
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.register
public function register($shortcode, $callback) { if (is_callable($callback)) { $this->shortcodes[$shortcode] = $callback; } else { throw new InvalidArgumentException("Callback is not callable"); } return $this; }
php
public function register($shortcode, $callback) { if (is_callable($callback)) { $this->shortcodes[$shortcode] = $callback; } else { throw new InvalidArgumentException("Callback is not callable"); } return $this; }
[ "public", "function", "register", "(", "$", "shortcode", ",", "$", "callback", ")", "{", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "this", "->", "shortcodes", "[", "$", "shortcode", "]", "=", "$", "callback", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "\"Callback is not callable\"", ")", ";", "}", "return", "$", "this", ";", "}" ]
Register a shortcode, and attach it to a PHP callback. The callback for a shortcode will have the following arguments passed to it: - Any parameters attached to the shortcode as an associative array (keys are lower-case). - Any content enclosed within the shortcode (if it is an enclosing shortcode). Note that any content within this will not have been parsed, and can optionally be fed back into the parser. - The {@link ShortcodeParser} instance used to parse the content. - The shortcode tag name that was matched within the parsed content. - An associative array of extra information about the shortcode being parsed. @param string $shortcode The shortcode tag to map to the callback - normally in lowercase_underscore format. @param callback $callback The callback to replace the shortcode with. @return $this
[ "Register", "a", "shortcode", "and", "attach", "it", "to", "a", "PHP", "callback", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L105-L113
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.callShortcode
public function callShortcode($tag, $attributes, $content, $extra = array()) { if (!$tag || !isset($this->shortcodes[$tag])) { return false; } return call_user_func($this->shortcodes[$tag], $attributes, $content, $this, $tag, $extra); }
php
public function callShortcode($tag, $attributes, $content, $extra = array()) { if (!$tag || !isset($this->shortcodes[$tag])) { return false; } return call_user_func($this->shortcodes[$tag], $attributes, $content, $this, $tag, $extra); }
[ "public", "function", "callShortcode", "(", "$", "tag", ",", "$", "attributes", ",", "$", "content", ",", "$", "extra", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "tag", "||", "!", "isset", "(", "$", "this", "->", "shortcodes", "[", "$", "tag", "]", ")", ")", "{", "return", "false", ";", "}", "return", "call_user_func", "(", "$", "this", "->", "shortcodes", "[", "$", "tag", "]", ",", "$", "attributes", ",", "$", "content", ",", "$", "this", ",", "$", "tag", ",", "$", "extra", ")", ";", "}" ]
Call a shortcode and return its replacement text Returns false if the shortcode isn't registered @param string $tag @param array $attributes @param string $content @param array $extra @return mixed
[ "Call", "a", "shortcode", "and", "return", "its", "replacement", "text", "Returns", "false", "if", "the", "shortcode", "isn", "t", "registered" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L166-L172
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.replaceTagsWithText
protected function replaceTagsWithText($content, $tags, $generator) { // The string with tags replaced with markers $str = ''; // The start index of the next tag, remembered as we step backwards through the list $li = null; $i = count($tags); while ($i--) { if ($li === null) { $tail = substr($content, $tags[$i]['e']); } else { $tail = substr($content, $tags[$i]['e'], $li - $tags[$i]['e']); } if ($tags[$i]['escaped']) { $str = substr($content, $tags[$i]['s']+1, $tags[$i]['e'] - $tags[$i]['s'] - 2) . $tail . $str; } else { $str = $generator($i, $tags[$i]) . $tail . $str; } $li = $tags[$i]['s']; } return substr($content, 0, $tags[0]['s']) . $str; }
php
protected function replaceTagsWithText($content, $tags, $generator) { // The string with tags replaced with markers $str = ''; // The start index of the next tag, remembered as we step backwards through the list $li = null; $i = count($tags); while ($i--) { if ($li === null) { $tail = substr($content, $tags[$i]['e']); } else { $tail = substr($content, $tags[$i]['e'], $li - $tags[$i]['e']); } if ($tags[$i]['escaped']) { $str = substr($content, $tags[$i]['s']+1, $tags[$i]['e'] - $tags[$i]['s'] - 2) . $tail . $str; } else { $str = $generator($i, $tags[$i]) . $tail . $str; } $li = $tags[$i]['s']; } return substr($content, 0, $tags[0]['s']) . $str; }
[ "protected", "function", "replaceTagsWithText", "(", "$", "content", ",", "$", "tags", ",", "$", "generator", ")", "{", "// The string with tags replaced with markers", "$", "str", "=", "''", ";", "// The start index of the next tag, remembered as we step backwards through the list", "$", "li", "=", "null", ";", "$", "i", "=", "count", "(", "$", "tags", ")", ";", "while", "(", "$", "i", "--", ")", "{", "if", "(", "$", "li", "===", "null", ")", "{", "$", "tail", "=", "substr", "(", "$", "content", ",", "$", "tags", "[", "$", "i", "]", "[", "'e'", "]", ")", ";", "}", "else", "{", "$", "tail", "=", "substr", "(", "$", "content", ",", "$", "tags", "[", "$", "i", "]", "[", "'e'", "]", ",", "$", "li", "-", "$", "tags", "[", "$", "i", "]", "[", "'e'", "]", ")", ";", "}", "if", "(", "$", "tags", "[", "$", "i", "]", "[", "'escaped'", "]", ")", "{", "$", "str", "=", "substr", "(", "$", "content", ",", "$", "tags", "[", "$", "i", "]", "[", "'s'", "]", "+", "1", ",", "$", "tags", "[", "$", "i", "]", "[", "'e'", "]", "-", "$", "tags", "[", "$", "i", "]", "[", "'s'", "]", "-", "2", ")", ".", "$", "tail", ".", "$", "str", ";", "}", "else", "{", "$", "str", "=", "$", "generator", "(", "$", "i", ",", "$", "tags", "[", "$", "i", "]", ")", ".", "$", "tail", ".", "$", "str", ";", "}", "$", "li", "=", "$", "tags", "[", "$", "i", "]", "[", "'s'", "]", ";", "}", "return", "substr", "(", "$", "content", ",", "0", ",", "$", "tags", "[", "0", "]", "[", "'s'", "]", ")", ".", "$", "str", ";", "}" ]
Replaces the shortcode tags extracted by extractTags with HTML element "markers", so that we can parse the resulting string as HTML and easily mutate the shortcodes in the DOM @param string $content The HTML string with [tag] style shortcodes embedded @param array $tags The tags extracted by extractTags @param callable $generator @return string The HTML string with [tag] style shortcodes replaced by markers
[ "Replaces", "the", "shortcode", "tags", "extracted", "by", "extractTags", "with", "HTML", "element", "markers", "so", "that", "we", "can", "parse", "the", "resulting", "string", "as", "HTML", "and", "easily", "mutate", "the", "shortcodes", "in", "the", "DOM" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L432-L457
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.replaceAttributeTagsWithContent
protected function replaceAttributeTagsWithContent($htmlvalue) { $attributes = $htmlvalue->query('//@*[contains(.,"[")][contains(.,"]")]'); $parser = $this; for ($i = 0; $i < $attributes->length; $i++) { $node = $attributes->item($i); $tags = $this->extractTags($node->nodeValue); $extra = array('node' => $node, 'element' => $node->ownerElement); if ($tags) { $node->nodeValue = $this->replaceTagsWithText( htmlspecialchars($node->nodeValue), $tags, function ($idx, $tag) use ($parser, $extra) { return $parser->getShortcodeReplacementText($tag, $extra, false); } ); } } }
php
protected function replaceAttributeTagsWithContent($htmlvalue) { $attributes = $htmlvalue->query('//@*[contains(.,"[")][contains(.,"]")]'); $parser = $this; for ($i = 0; $i < $attributes->length; $i++) { $node = $attributes->item($i); $tags = $this->extractTags($node->nodeValue); $extra = array('node' => $node, 'element' => $node->ownerElement); if ($tags) { $node->nodeValue = $this->replaceTagsWithText( htmlspecialchars($node->nodeValue), $tags, function ($idx, $tag) use ($parser, $extra) { return $parser->getShortcodeReplacementText($tag, $extra, false); } ); } } }
[ "protected", "function", "replaceAttributeTagsWithContent", "(", "$", "htmlvalue", ")", "{", "$", "attributes", "=", "$", "htmlvalue", "->", "query", "(", "'//@*[contains(.,\"[\")][contains(.,\"]\")]'", ")", ";", "$", "parser", "=", "$", "this", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "attributes", "->", "length", ";", "$", "i", "++", ")", "{", "$", "node", "=", "$", "attributes", "->", "item", "(", "$", "i", ")", ";", "$", "tags", "=", "$", "this", "->", "extractTags", "(", "$", "node", "->", "nodeValue", ")", ";", "$", "extra", "=", "array", "(", "'node'", "=>", "$", "node", ",", "'element'", "=>", "$", "node", "->", "ownerElement", ")", ";", "if", "(", "$", "tags", ")", "{", "$", "node", "->", "nodeValue", "=", "$", "this", "->", "replaceTagsWithText", "(", "htmlspecialchars", "(", "$", "node", "->", "nodeValue", ")", ",", "$", "tags", ",", "function", "(", "$", "idx", ",", "$", "tag", ")", "use", "(", "$", "parser", ",", "$", "extra", ")", "{", "return", "$", "parser", "->", "getShortcodeReplacementText", "(", "$", "tag", ",", "$", "extra", ",", "false", ")", ";", "}", ")", ";", "}", "}", "}" ]
Replace the shortcodes in attribute values with the calculated content We don't use markers with attributes because there's no point, it's easier to do all the matching in-DOM after the XML parse @param HTMLValue $htmlvalue
[ "Replace", "the", "shortcodes", "in", "attribute", "values", "with", "the", "calculated", "content" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L467-L487
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.replaceElementTagsWithMarkers
protected function replaceElementTagsWithMarkers($content) { $tags = $this->extractTags($content); if ($tags) { $markerClass = self::$marker_class; $content = $this->replaceTagsWithText($content, $tags, function ($idx, $tag) use ($markerClass) { return '<img class="' . $markerClass . '" data-tagid="' . $idx . '" />'; }); } return array($content, $tags); }
php
protected function replaceElementTagsWithMarkers($content) { $tags = $this->extractTags($content); if ($tags) { $markerClass = self::$marker_class; $content = $this->replaceTagsWithText($content, $tags, function ($idx, $tag) use ($markerClass) { return '<img class="' . $markerClass . '" data-tagid="' . $idx . '" />'; }); } return array($content, $tags); }
[ "protected", "function", "replaceElementTagsWithMarkers", "(", "$", "content", ")", "{", "$", "tags", "=", "$", "this", "->", "extractTags", "(", "$", "content", ")", ";", "if", "(", "$", "tags", ")", "{", "$", "markerClass", "=", "self", "::", "$", "marker_class", ";", "$", "content", "=", "$", "this", "->", "replaceTagsWithText", "(", "$", "content", ",", "$", "tags", ",", "function", "(", "$", "idx", ",", "$", "tag", ")", "use", "(", "$", "markerClass", ")", "{", "return", "'<img class=\"'", ".", "$", "markerClass", ".", "'\" data-tagid=\"'", ".", "$", "idx", ".", "'\" />'", ";", "}", ")", ";", "}", "return", "array", "(", "$", "content", ",", "$", "tags", ")", ";", "}" ]
Replace the element-scoped tags with markers @param string $content @return array
[ "Replace", "the", "element", "-", "scoped", "tags", "with", "markers" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L495-L508
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.moveMarkerToCompliantHome
protected function moveMarkerToCompliantHome($node, $parent, $location) { // Move before block parent if ($location == self::BEFORE) { if (isset($parent->parentNode)) { $parent->parentNode->insertBefore($node, $parent); } } elseif ($location == self::AFTER) { // Move after block parent $this->insertAfter($node, $parent); } elseif ($location == self::SPLIT) { // Split parent at node $at = $node; $splitee = $node->parentNode; while ($splitee !== $parent->parentNode) { /** @var DOMElement $spliter */ $spliter = $splitee->cloneNode(false); $this->insertAfter($spliter, $splitee); while ($at->nextSibling) { $spliter->appendChild($at->nextSibling); } $at = $splitee; $splitee = $splitee->parentNode; } $this->insertAfter($node, $parent); } elseif ($location == self::INLINE) { // Do nothing if (in_array(strtolower($node->tagName), self::$block_level_elements)) { user_error( 'Requested to insert block tag ' . $node->tagName . ' inline - probably this will break HTML compliance', E_USER_WARNING ); } // NOP } else { user_error('Unknown value for $location argument ' . $location, E_USER_ERROR); } }
php
protected function moveMarkerToCompliantHome($node, $parent, $location) { // Move before block parent if ($location == self::BEFORE) { if (isset($parent->parentNode)) { $parent->parentNode->insertBefore($node, $parent); } } elseif ($location == self::AFTER) { // Move after block parent $this->insertAfter($node, $parent); } elseif ($location == self::SPLIT) { // Split parent at node $at = $node; $splitee = $node->parentNode; while ($splitee !== $parent->parentNode) { /** @var DOMElement $spliter */ $spliter = $splitee->cloneNode(false); $this->insertAfter($spliter, $splitee); while ($at->nextSibling) { $spliter->appendChild($at->nextSibling); } $at = $splitee; $splitee = $splitee->parentNode; } $this->insertAfter($node, $parent); } elseif ($location == self::INLINE) { // Do nothing if (in_array(strtolower($node->tagName), self::$block_level_elements)) { user_error( 'Requested to insert block tag ' . $node->tagName . ' inline - probably this will break HTML compliance', E_USER_WARNING ); } // NOP } else { user_error('Unknown value for $location argument ' . $location, E_USER_ERROR); } }
[ "protected", "function", "moveMarkerToCompliantHome", "(", "$", "node", ",", "$", "parent", ",", "$", "location", ")", "{", "// Move before block parent", "if", "(", "$", "location", "==", "self", "::", "BEFORE", ")", "{", "if", "(", "isset", "(", "$", "parent", "->", "parentNode", ")", ")", "{", "$", "parent", "->", "parentNode", "->", "insertBefore", "(", "$", "node", ",", "$", "parent", ")", ";", "}", "}", "elseif", "(", "$", "location", "==", "self", "::", "AFTER", ")", "{", "// Move after block parent", "$", "this", "->", "insertAfter", "(", "$", "node", ",", "$", "parent", ")", ";", "}", "elseif", "(", "$", "location", "==", "self", "::", "SPLIT", ")", "{", "// Split parent at node", "$", "at", "=", "$", "node", ";", "$", "splitee", "=", "$", "node", "->", "parentNode", ";", "while", "(", "$", "splitee", "!==", "$", "parent", "->", "parentNode", ")", "{", "/** @var DOMElement $spliter */", "$", "spliter", "=", "$", "splitee", "->", "cloneNode", "(", "false", ")", ";", "$", "this", "->", "insertAfter", "(", "$", "spliter", ",", "$", "splitee", ")", ";", "while", "(", "$", "at", "->", "nextSibling", ")", "{", "$", "spliter", "->", "appendChild", "(", "$", "at", "->", "nextSibling", ")", ";", "}", "$", "at", "=", "$", "splitee", ";", "$", "splitee", "=", "$", "splitee", "->", "parentNode", ";", "}", "$", "this", "->", "insertAfter", "(", "$", "node", ",", "$", "parent", ")", ";", "}", "elseif", "(", "$", "location", "==", "self", "::", "INLINE", ")", "{", "// Do nothing", "if", "(", "in_array", "(", "strtolower", "(", "$", "node", "->", "tagName", ")", ",", "self", "::", "$", "block_level_elements", ")", ")", "{", "user_error", "(", "'Requested to insert block tag '", ".", "$", "node", "->", "tagName", ".", "' inline - probably this will break HTML compliance'", ",", "E_USER_WARNING", ")", ";", "}", "// NOP", "}", "else", "{", "user_error", "(", "'Unknown value for $location argument '", ".", "$", "location", ",", "E_USER_ERROR", ")", ";", "}", "}" ]
Given a node with represents a shortcode marker and a location string, mutates the DOM to put the marker in the compliant location For shortcodes inserted BEFORE, that location is just before the block container that the marker is in For shortcodes inserted AFTER, that location is just after the block container that the marker is in For shortcodes inserted SPLIT, that location is where the marker is, but the DOM is split around it up to the block container the marker is in - for instance, <p>A<span>B<marker />C</span>D</p> becomes <p>A<span>B</span></p><marker /><p><span>C</span>D</p> For shortcodes inserted INLINE, no modification is needed (but in that case the shortcode handler needs to generate only inline blocks) @param DOMElement $node @param DOMElement $parent @param int $location ShortcodeParser::BEFORE, ShortcodeParser::SPLIT or ShortcodeParser::INLINE
[ "Given", "a", "node", "with", "represents", "a", "shortcode", "marker", "and", "a", "location", "string", "mutates", "the", "DOM", "to", "put", "the", "marker", "in", "the", "compliant", "location" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L566-L608
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.replaceMarkerWithContent
protected function replaceMarkerWithContent($node, $tag) { $content = $this->getShortcodeReplacementText($tag); if ($content) { /** @var HTMLValue $parsed */ $parsed = HTMLValue::create($content); $body = $parsed->getBody(); if ($body) { $this->insertListAfter($body->childNodes, $node); } } $this->removeNode($node); }
php
protected function replaceMarkerWithContent($node, $tag) { $content = $this->getShortcodeReplacementText($tag); if ($content) { /** @var HTMLValue $parsed */ $parsed = HTMLValue::create($content); $body = $parsed->getBody(); if ($body) { $this->insertListAfter($body->childNodes, $node); } } $this->removeNode($node); }
[ "protected", "function", "replaceMarkerWithContent", "(", "$", "node", ",", "$", "tag", ")", "{", "$", "content", "=", "$", "this", "->", "getShortcodeReplacementText", "(", "$", "tag", ")", ";", "if", "(", "$", "content", ")", "{", "/** @var HTMLValue $parsed */", "$", "parsed", "=", "HTMLValue", "::", "create", "(", "$", "content", ")", ";", "$", "body", "=", "$", "parsed", "->", "getBody", "(", ")", ";", "if", "(", "$", "body", ")", "{", "$", "this", "->", "insertListAfter", "(", "$", "body", "->", "childNodes", ",", "$", "node", ")", ";", "}", "}", "$", "this", "->", "removeNode", "(", "$", "node", ")", ";", "}" ]
Given a node with represents a shortcode marker and some information about the shortcode, call the shortcode handler & replace the marker with the actual content @param DOMElement $node @param array $tag
[ "Given", "a", "node", "with", "represents", "a", "shortcode", "marker", "and", "some", "information", "about", "the", "shortcode", "call", "the", "shortcode", "handler", "&", "replace", "the", "marker", "with", "the", "actual", "content" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L617-L631
train
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
ShortcodeParser.parse
public function parse($content) { $this->extend('onBeforeParse', $content); $continue = true; // If no shortcodes defined, don't try and parse any if (!$this->shortcodes) { $continue = false; } elseif (!trim($content)) { // If no content, don't try and parse it $continue = false; } elseif (strpos($content, '[') === false) { // If no shortcode tag, don't try and parse it $continue = false; } if ($continue) { // First we operate in text mode, replacing any shortcodes with marker elements so that later we can // use a proper DOM list($content, $tags) = $this->replaceElementTagsWithMarkers($content); /** @var HTMLValue $htmlvalue */ $htmlvalue = Injector::inst()->create('HTMLValue', $content); // Now parse the result into a DOM if (!$htmlvalue->isValid()) { if (self::$error_behavior == self::ERROR) { user_error('Couldn\'t decode HTML when processing short codes', E_USER_ERROR); } else { $continue = false; } } } if ($continue) { // First, replace any shortcodes that are in attributes $this->replaceAttributeTagsWithContent($htmlvalue); // Find all the element scoped shortcode markers $shortcodes = $htmlvalue->query('//img[@class="' . self::$marker_class . '"]'); // Find the parents. Do this before DOM modification, since SPLIT might cause parents to move otherwise $parents = $this->findParentsForMarkers($shortcodes); /** @var DOMElement $shortcode */ foreach ($shortcodes as $shortcode) { $tag = $tags[$shortcode->getAttribute('data-tagid')]; $parent = $parents[$shortcode->getAttribute('data-parentid')]; $class = null; if (!empty($tag['attrs']['location'])) { $class = $tag['attrs']['location']; } elseif (!empty($tag['attrs']['class'])) { $class = $tag['attrs']['class']; } $location = self::INLINE; if ($class == 'left' || $class == 'right') { $location = self::BEFORE; } /** * Below code disabled due to https://github.com/silverstripe/silverstripe-framework/issues/5987 if ($class == 'center' || $class == 'leftAlone') { $location = self::SPLIT; } */ if (!$parent) { if ($location !== self::INLINE) { user_error( "Parent block for shortcode couldn't be found, but location wasn't INLINE", E_USER_ERROR ); } } else { $this->moveMarkerToCompliantHome($shortcode, $parent, $location); } $this->replaceMarkerWithContent($shortcode, $tag); } $content = $htmlvalue->getContent(); // Clean up any marker classes left over, for example, those injected into <script> tags $parser = $this; $content = preg_replace_callback( // Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers() // hasn't been heavily modified '/<img[^>]+class="' . preg_quote(self::$marker_class) . '"[^>]+data-tagid="([^"]+)"[^>]*>/i', function ($matches) use ($tags, $parser) { $tag = $tags[$matches[1]]; return $parser->getShortcodeReplacementText($tag); }, $content ); } $this->extend('onAfterParse', $content); return $content; }
php
public function parse($content) { $this->extend('onBeforeParse', $content); $continue = true; // If no shortcodes defined, don't try and parse any if (!$this->shortcodes) { $continue = false; } elseif (!trim($content)) { // If no content, don't try and parse it $continue = false; } elseif (strpos($content, '[') === false) { // If no shortcode tag, don't try and parse it $continue = false; } if ($continue) { // First we operate in text mode, replacing any shortcodes with marker elements so that later we can // use a proper DOM list($content, $tags) = $this->replaceElementTagsWithMarkers($content); /** @var HTMLValue $htmlvalue */ $htmlvalue = Injector::inst()->create('HTMLValue', $content); // Now parse the result into a DOM if (!$htmlvalue->isValid()) { if (self::$error_behavior == self::ERROR) { user_error('Couldn\'t decode HTML when processing short codes', E_USER_ERROR); } else { $continue = false; } } } if ($continue) { // First, replace any shortcodes that are in attributes $this->replaceAttributeTagsWithContent($htmlvalue); // Find all the element scoped shortcode markers $shortcodes = $htmlvalue->query('//img[@class="' . self::$marker_class . '"]'); // Find the parents. Do this before DOM modification, since SPLIT might cause parents to move otherwise $parents = $this->findParentsForMarkers($shortcodes); /** @var DOMElement $shortcode */ foreach ($shortcodes as $shortcode) { $tag = $tags[$shortcode->getAttribute('data-tagid')]; $parent = $parents[$shortcode->getAttribute('data-parentid')]; $class = null; if (!empty($tag['attrs']['location'])) { $class = $tag['attrs']['location']; } elseif (!empty($tag['attrs']['class'])) { $class = $tag['attrs']['class']; } $location = self::INLINE; if ($class == 'left' || $class == 'right') { $location = self::BEFORE; } /** * Below code disabled due to https://github.com/silverstripe/silverstripe-framework/issues/5987 if ($class == 'center' || $class == 'leftAlone') { $location = self::SPLIT; } */ if (!$parent) { if ($location !== self::INLINE) { user_error( "Parent block for shortcode couldn't be found, but location wasn't INLINE", E_USER_ERROR ); } } else { $this->moveMarkerToCompliantHome($shortcode, $parent, $location); } $this->replaceMarkerWithContent($shortcode, $tag); } $content = $htmlvalue->getContent(); // Clean up any marker classes left over, for example, those injected into <script> tags $parser = $this; $content = preg_replace_callback( // Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers() // hasn't been heavily modified '/<img[^>]+class="' . preg_quote(self::$marker_class) . '"[^>]+data-tagid="([^"]+)"[^>]*>/i', function ($matches) use ($tags, $parser) { $tag = $tags[$matches[1]]; return $parser->getShortcodeReplacementText($tag); }, $content ); } $this->extend('onAfterParse', $content); return $content; }
[ "public", "function", "parse", "(", "$", "content", ")", "{", "$", "this", "->", "extend", "(", "'onBeforeParse'", ",", "$", "content", ")", ";", "$", "continue", "=", "true", ";", "// If no shortcodes defined, don't try and parse any", "if", "(", "!", "$", "this", "->", "shortcodes", ")", "{", "$", "continue", "=", "false", ";", "}", "elseif", "(", "!", "trim", "(", "$", "content", ")", ")", "{", "// If no content, don't try and parse it", "$", "continue", "=", "false", ";", "}", "elseif", "(", "strpos", "(", "$", "content", ",", "'['", ")", "===", "false", ")", "{", "// If no shortcode tag, don't try and parse it", "$", "continue", "=", "false", ";", "}", "if", "(", "$", "continue", ")", "{", "// First we operate in text mode, replacing any shortcodes with marker elements so that later we can", "// use a proper DOM", "list", "(", "$", "content", ",", "$", "tags", ")", "=", "$", "this", "->", "replaceElementTagsWithMarkers", "(", "$", "content", ")", ";", "/** @var HTMLValue $htmlvalue */", "$", "htmlvalue", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "'HTMLValue'", ",", "$", "content", ")", ";", "// Now parse the result into a DOM", "if", "(", "!", "$", "htmlvalue", "->", "isValid", "(", ")", ")", "{", "if", "(", "self", "::", "$", "error_behavior", "==", "self", "::", "ERROR", ")", "{", "user_error", "(", "'Couldn\\'t decode HTML when processing short codes'", ",", "E_USER_ERROR", ")", ";", "}", "else", "{", "$", "continue", "=", "false", ";", "}", "}", "}", "if", "(", "$", "continue", ")", "{", "// First, replace any shortcodes that are in attributes", "$", "this", "->", "replaceAttributeTagsWithContent", "(", "$", "htmlvalue", ")", ";", "// Find all the element scoped shortcode markers", "$", "shortcodes", "=", "$", "htmlvalue", "->", "query", "(", "'//img[@class=\"'", ".", "self", "::", "$", "marker_class", ".", "'\"]'", ")", ";", "// Find the parents. Do this before DOM modification, since SPLIT might cause parents to move otherwise", "$", "parents", "=", "$", "this", "->", "findParentsForMarkers", "(", "$", "shortcodes", ")", ";", "/** @var DOMElement $shortcode */", "foreach", "(", "$", "shortcodes", "as", "$", "shortcode", ")", "{", "$", "tag", "=", "$", "tags", "[", "$", "shortcode", "->", "getAttribute", "(", "'data-tagid'", ")", "]", ";", "$", "parent", "=", "$", "parents", "[", "$", "shortcode", "->", "getAttribute", "(", "'data-parentid'", ")", "]", ";", "$", "class", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "tag", "[", "'attrs'", "]", "[", "'location'", "]", ")", ")", "{", "$", "class", "=", "$", "tag", "[", "'attrs'", "]", "[", "'location'", "]", ";", "}", "elseif", "(", "!", "empty", "(", "$", "tag", "[", "'attrs'", "]", "[", "'class'", "]", ")", ")", "{", "$", "class", "=", "$", "tag", "[", "'attrs'", "]", "[", "'class'", "]", ";", "}", "$", "location", "=", "self", "::", "INLINE", ";", "if", "(", "$", "class", "==", "'left'", "||", "$", "class", "==", "'right'", ")", "{", "$", "location", "=", "self", "::", "BEFORE", ";", "}", "/**\n * Below code disabled due to https://github.com/silverstripe/silverstripe-framework/issues/5987\n if ($class == 'center' || $class == 'leftAlone') {\n $location = self::SPLIT;\n }\n */", "if", "(", "!", "$", "parent", ")", "{", "if", "(", "$", "location", "!==", "self", "::", "INLINE", ")", "{", "user_error", "(", "\"Parent block for shortcode couldn't be found, but location wasn't INLINE\"", ",", "E_USER_ERROR", ")", ";", "}", "}", "else", "{", "$", "this", "->", "moveMarkerToCompliantHome", "(", "$", "shortcode", ",", "$", "parent", ",", "$", "location", ")", ";", "}", "$", "this", "->", "replaceMarkerWithContent", "(", "$", "shortcode", ",", "$", "tag", ")", ";", "}", "$", "content", "=", "$", "htmlvalue", "->", "getContent", "(", ")", ";", "// Clean up any marker classes left over, for example, those injected into <script> tags", "$", "parser", "=", "$", "this", ";", "$", "content", "=", "preg_replace_callback", "(", "// Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers()", "// hasn't been heavily modified", "'/<img[^>]+class=\"'", ".", "preg_quote", "(", "self", "::", "$", "marker_class", ")", ".", "'\"[^>]+data-tagid=\"([^\"]+)\"[^>]*>/i'", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "tags", ",", "$", "parser", ")", "{", "$", "tag", "=", "$", "tags", "[", "$", "matches", "[", "1", "]", "]", ";", "return", "$", "parser", "->", "getShortcodeReplacementText", "(", "$", "tag", ")", ";", "}", ",", "$", "content", ")", ";", "}", "$", "this", "->", "extend", "(", "'onAfterParse'", ",", "$", "content", ")", ";", "return", "$", "content", ";", "}" ]
Parse a string, and replace any registered shortcodes within it with the result of the mapped callback. @param string $content @return string
[ "Parse", "a", "string", "and", "replace", "any", "registered", "shortcodes", "within", "it", "with", "the", "result", "of", "the", "mapped", "callback", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/ShortcodeParser.php#L639-L740
train
silverstripe/silverstripe-framework
src/View/ArrayData.php
ArrayData.getField
public function getField($field) { $value = $this->array[$field]; if (is_object($value) && !$value instanceof ViewableData) { return new ArrayData($value); } elseif (ArrayLib::is_associative($value)) { return new ArrayData($value); } else { return $value; } }
php
public function getField($field) { $value = $this->array[$field]; if (is_object($value) && !$value instanceof ViewableData) { return new ArrayData($value); } elseif (ArrayLib::is_associative($value)) { return new ArrayData($value); } else { return $value; } }
[ "public", "function", "getField", "(", "$", "field", ")", "{", "$", "value", "=", "$", "this", "->", "array", "[", "$", "field", "]", ";", "if", "(", "is_object", "(", "$", "value", ")", "&&", "!", "$", "value", "instanceof", "ViewableData", ")", "{", "return", "new", "ArrayData", "(", "$", "value", ")", ";", "}", "elseif", "(", "ArrayLib", "::", "is_associative", "(", "$", "value", ")", ")", "{", "return", "new", "ArrayData", "(", "$", "value", ")", ";", "}", "else", "{", "return", "$", "value", ";", "}", "}" ]
Gets a field from this object. If the value is an object but not an instance of ViewableData, it will be converted recursively to an ArrayData. If the value is an associative array, it will likewise be converted recursively to an ArrayData. @param string $field @return mixed
[ "Gets", "a", "field", "from", "this", "object", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ArrayData.php#L71-L81
train
silverstripe/silverstripe-framework
src/View/ArrayData.php
ArrayData.array_to_object
public static function array_to_object($arr = null) { $obj = new stdClass(); if ($arr) { foreach ($arr as $name => $value) { $obj->$name = $value; } } return $obj; }
php
public static function array_to_object($arr = null) { $obj = new stdClass(); if ($arr) { foreach ($arr as $name => $value) { $obj->$name = $value; } } return $obj; }
[ "public", "static", "function", "array_to_object", "(", "$", "arr", "=", "null", ")", "{", "$", "obj", "=", "new", "stdClass", "(", ")", ";", "if", "(", "$", "arr", ")", "{", "foreach", "(", "$", "arr", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "obj", "->", "$", "name", "=", "$", "value", ";", "}", "}", "return", "$", "obj", ";", "}" ]
Converts an associative array to a simple object @param array @return stdClass $obj
[ "Converts", "an", "associative", "array", "to", "a", "simple", "object" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ArrayData.php#L112-L121
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.getParser
public function getParser() { if (!$this->parser) { $this->parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); } return $this->parser; }
php
public function getParser() { if (!$this->parser) { $this->parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); } return $this->parser; }
[ "public", "function", "getParser", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parser", ")", "{", "$", "this", "->", "parser", "=", "(", "new", "ParserFactory", ")", "->", "create", "(", "ParserFactory", "::", "PREFER_PHP7", ")", ";", "}", "return", "$", "this", "->", "parser", ";", "}" ]
Get or create active parser @return Parser
[ "Get", "or", "create", "active", "parser" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L218-L225
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.getTraverser
public function getTraverser() { if (!$this->traverser) { $this->traverser = new NodeTraverser; $this->traverser->addVisitor(new NameResolver); $this->traverser->addVisitor($this->getVisitor()); } return $this->traverser; }
php
public function getTraverser() { if (!$this->traverser) { $this->traverser = new NodeTraverser; $this->traverser->addVisitor(new NameResolver); $this->traverser->addVisitor($this->getVisitor()); } return $this->traverser; }
[ "public", "function", "getTraverser", "(", ")", "{", "if", "(", "!", "$", "this", "->", "traverser", ")", "{", "$", "this", "->", "traverser", "=", "new", "NodeTraverser", ";", "$", "this", "->", "traverser", "->", "addVisitor", "(", "new", "NameResolver", ")", ";", "$", "this", "->", "traverser", "->", "addVisitor", "(", "$", "this", "->", "getVisitor", "(", ")", ")", ";", "}", "return", "$", "this", "->", "traverser", ";", "}" ]
Get node traverser for parsing class files @return NodeTraverser
[ "Get", "node", "traverser", "for", "parsing", "class", "files" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L232-L241
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.getItemPath
public function getItemPath($name) { $lowerName = strtolower($name); foreach ([ $this->classes, $this->interfaces, $this->traits, ] as $source) { if (isset($source[$lowerName]) && file_exists($source[$lowerName])) { return $source[$lowerName]; } } return null; }
php
public function getItemPath($name) { $lowerName = strtolower($name); foreach ([ $this->classes, $this->interfaces, $this->traits, ] as $source) { if (isset($source[$lowerName]) && file_exists($source[$lowerName])) { return $source[$lowerName]; } } return null; }
[ "public", "function", "getItemPath", "(", "$", "name", ")", "{", "$", "lowerName", "=", "strtolower", "(", "$", "name", ")", ";", "foreach", "(", "[", "$", "this", "->", "classes", ",", "$", "this", "->", "interfaces", ",", "$", "this", "->", "traits", ",", "]", "as", "$", "source", ")", "{", "if", "(", "isset", "(", "$", "source", "[", "$", "lowerName", "]", ")", "&&", "file_exists", "(", "$", "source", "[", "$", "lowerName", "]", ")", ")", "{", "return", "$", "source", "[", "$", "lowerName", "]", ";", "}", "}", "return", "null", ";", "}" ]
Returns the file path to a class or interface if it exists in the manifest. @param string $name @return string|null
[ "Returns", "the", "file", "path", "to", "a", "class", "or", "interface", "if", "it", "exists", "in", "the", "manifest", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L264-L277
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.getItemName
public function getItemName($name) { $lowerName = strtolower($name); foreach ([ $this->classNames, $this->interfaceNames, $this->traitNames, ] as $source) { if (isset($source[$lowerName])) { return $source[$lowerName]; } } return null; }
php
public function getItemName($name) { $lowerName = strtolower($name); foreach ([ $this->classNames, $this->interfaceNames, $this->traitNames, ] as $source) { if (isset($source[$lowerName])) { return $source[$lowerName]; } } return null; }
[ "public", "function", "getItemName", "(", "$", "name", ")", "{", "$", "lowerName", "=", "strtolower", "(", "$", "name", ")", ";", "foreach", "(", "[", "$", "this", "->", "classNames", ",", "$", "this", "->", "interfaceNames", ",", "$", "this", "->", "traitNames", ",", "]", "as", "$", "source", ")", "{", "if", "(", "isset", "(", "$", "source", "[", "$", "lowerName", "]", ")", ")", "{", "return", "$", "source", "[", "$", "lowerName", "]", ";", "}", "}", "return", "null", ";", "}" ]
Return correct case name @param string $name @return string Correct case name
[ "Return", "correct", "case", "name" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L285-L298
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.getImplementorsOf
public function getImplementorsOf($interface) { $lowerInterface = strtolower($interface); if (array_key_exists($lowerInterface, $this->implementors)) { return $this->implementors[$lowerInterface]; } else { return array(); } }
php
public function getImplementorsOf($interface) { $lowerInterface = strtolower($interface); if (array_key_exists($lowerInterface, $this->implementors)) { return $this->implementors[$lowerInterface]; } else { return array(); } }
[ "public", "function", "getImplementorsOf", "(", "$", "interface", ")", "{", "$", "lowerInterface", "=", "strtolower", "(", "$", "interface", ")", ";", "if", "(", "array_key_exists", "(", "$", "lowerInterface", ",", "$", "this", "->", "implementors", ")", ")", "{", "return", "$", "this", "->", "implementors", "[", "$", "lowerInterface", "]", ";", "}", "else", "{", "return", "array", "(", ")", ";", "}", "}" ]
Returns an array containing the class names that implement a certain interface. @param string $interface @return array
[ "Returns", "an", "array", "containing", "the", "class", "names", "that", "implement", "a", "certain", "interface", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L409-L417
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.regenerate
public function regenerate($includeTests) { // Reset the manifest so stale info doesn't cause errors. $this->loadState([]); $this->roots = []; $this->children = []; $finder = new ManifestFileFinder(); $finder->setOptions(array( 'name_regex' => '/^[^_].*\\.php$/', 'ignore_files' => array('index.php', 'cli-script.php'), 'ignore_tests' => !$includeTests, 'file_callback' => function ($basename, $pathname, $depth) use ($includeTests, $finder) { $this->handleFile($basename, $pathname, $includeTests); }, )); $finder->find($this->base); foreach ($this->roots as $root) { $this->coalesceDescendants($root); } if ($this->cache) { $data = $this->getState(); $this->cache->set($this->cacheKey, $data); } }
php
public function regenerate($includeTests) { // Reset the manifest so stale info doesn't cause errors. $this->loadState([]); $this->roots = []; $this->children = []; $finder = new ManifestFileFinder(); $finder->setOptions(array( 'name_regex' => '/^[^_].*\\.php$/', 'ignore_files' => array('index.php', 'cli-script.php'), 'ignore_tests' => !$includeTests, 'file_callback' => function ($basename, $pathname, $depth) use ($includeTests, $finder) { $this->handleFile($basename, $pathname, $includeTests); }, )); $finder->find($this->base); foreach ($this->roots as $root) { $this->coalesceDescendants($root); } if ($this->cache) { $data = $this->getState(); $this->cache->set($this->cacheKey, $data); } }
[ "public", "function", "regenerate", "(", "$", "includeTests", ")", "{", "// Reset the manifest so stale info doesn't cause errors.", "$", "this", "->", "loadState", "(", "[", "]", ")", ";", "$", "this", "->", "roots", "=", "[", "]", ";", "$", "this", "->", "children", "=", "[", "]", ";", "$", "finder", "=", "new", "ManifestFileFinder", "(", ")", ";", "$", "finder", "->", "setOptions", "(", "array", "(", "'name_regex'", "=>", "'/^[^_].*\\\\.php$/'", ",", "'ignore_files'", "=>", "array", "(", "'index.php'", ",", "'cli-script.php'", ")", ",", "'ignore_tests'", "=>", "!", "$", "includeTests", ",", "'file_callback'", "=>", "function", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "use", "(", "$", "includeTests", ",", "$", "finder", ")", "{", "$", "this", "->", "handleFile", "(", "$", "basename", ",", "$", "pathname", ",", "$", "includeTests", ")", ";", "}", ",", ")", ")", ";", "$", "finder", "->", "find", "(", "$", "this", "->", "base", ")", ";", "foreach", "(", "$", "this", "->", "roots", "as", "$", "root", ")", "{", "$", "this", "->", "coalesceDescendants", "(", "$", "root", ")", ";", "}", "if", "(", "$", "this", "->", "cache", ")", "{", "$", "data", "=", "$", "this", "->", "getState", "(", ")", ";", "$", "this", "->", "cache", "->", "set", "(", "$", "this", "->", "cacheKey", ",", "$", "data", ")", ";", "}", "}" ]
Completely regenerates the manifest file. @param bool $includeTests
[ "Completely", "regenerates", "the", "manifest", "file", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L436-L462
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.coalesceDescendants
protected function coalesceDescendants($class) { // Reset descendents to immediate children initially $lowerClass = strtolower($class); if (empty($this->children[$lowerClass])) { return []; } // Coalasce children into descendent list $this->descendants[$lowerClass] = $this->children[$lowerClass]; foreach ($this->children[$lowerClass] as $childClass) { // Merge all nested descendants $this->descendants[$lowerClass] = array_merge( $this->descendants[$lowerClass], $this->coalesceDescendants($childClass) ); } return $this->descendants[$lowerClass]; }
php
protected function coalesceDescendants($class) { // Reset descendents to immediate children initially $lowerClass = strtolower($class); if (empty($this->children[$lowerClass])) { return []; } // Coalasce children into descendent list $this->descendants[$lowerClass] = $this->children[$lowerClass]; foreach ($this->children[$lowerClass] as $childClass) { // Merge all nested descendants $this->descendants[$lowerClass] = array_merge( $this->descendants[$lowerClass], $this->coalesceDescendants($childClass) ); } return $this->descendants[$lowerClass]; }
[ "protected", "function", "coalesceDescendants", "(", "$", "class", ")", "{", "// Reset descendents to immediate children initially", "$", "lowerClass", "=", "strtolower", "(", "$", "class", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "children", "[", "$", "lowerClass", "]", ")", ")", "{", "return", "[", "]", ";", "}", "// Coalasce children into descendent list", "$", "this", "->", "descendants", "[", "$", "lowerClass", "]", "=", "$", "this", "->", "children", "[", "$", "lowerClass", "]", ";", "foreach", "(", "$", "this", "->", "children", "[", "$", "lowerClass", "]", "as", "$", "childClass", ")", "{", "// Merge all nested descendants", "$", "this", "->", "descendants", "[", "$", "lowerClass", "]", "=", "array_merge", "(", "$", "this", "->", "descendants", "[", "$", "lowerClass", "]", ",", "$", "this", "->", "coalesceDescendants", "(", "$", "childClass", ")", ")", ";", "}", "return", "$", "this", "->", "descendants", "[", "$", "lowerClass", "]", ";", "}" ]
Recursively coalesces direct child information into full descendant information. @param string $class @return array
[ "Recursively", "coalesces", "direct", "child", "information", "into", "full", "descendant", "information", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L587-L605
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.loadState
protected function loadState($data) { $success = true; foreach ($this->serialisedProperties as $property) { if (!isset($data[$property]) || !is_array($data[$property])) { $success = false; $value = []; } else { $value = $data[$property]; } $this->$property = $value; } return $success; }
php
protected function loadState($data) { $success = true; foreach ($this->serialisedProperties as $property) { if (!isset($data[$property]) || !is_array($data[$property])) { $success = false; $value = []; } else { $value = $data[$property]; } $this->$property = $value; } return $success; }
[ "protected", "function", "loadState", "(", "$", "data", ")", "{", "$", "success", "=", "true", ";", "foreach", "(", "$", "this", "->", "serialisedProperties", "as", "$", "property", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "$", "property", "]", ")", "||", "!", "is_array", "(", "$", "data", "[", "$", "property", "]", ")", ")", "{", "$", "success", "=", "false", ";", "$", "value", "=", "[", "]", ";", "}", "else", "{", "$", "value", "=", "$", "data", "[", "$", "property", "]", ";", "}", "$", "this", "->", "$", "property", "=", "$", "value", ";", "}", "return", "$", "success", ";", "}" ]
Reload state from given cache data @param array $data @return bool True if cache was valid and successfully loaded
[ "Reload", "state", "from", "given", "cache", "data" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L613-L626
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.getState
protected function getState() { $data = []; foreach ($this->serialisedProperties as $property) { $data[$property] = $this->$property; } return $data; }
php
protected function getState() { $data = []; foreach ($this->serialisedProperties as $property) { $data[$property] = $this->$property; } return $data; }
[ "protected", "function", "getState", "(", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "serialisedProperties", "as", "$", "property", ")", "{", "$", "data", "[", "$", "property", "]", "=", "$", "this", "->", "$", "property", ";", "}", "return", "$", "data", ";", "}" ]
Load current state into an array of data @return array
[ "Load", "current", "state", "into", "an", "array", "of", "data" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L633-L640
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassManifest.php
ClassManifest.validateItemCache
protected function validateItemCache($data) { if (!$data || !is_array($data)) { return false; } foreach (['classes', 'interfaces', 'traits'] as $key) { // Must be set if (!isset($data[$key])) { return false; } // and an array if (!is_array($data[$key])) { return false; } // Detect legacy cache keys (non-associative) $array = $data[$key]; if (!empty($array) && is_numeric(key($array))) { return false; } } return true; }
php
protected function validateItemCache($data) { if (!$data || !is_array($data)) { return false; } foreach (['classes', 'interfaces', 'traits'] as $key) { // Must be set if (!isset($data[$key])) { return false; } // and an array if (!is_array($data[$key])) { return false; } // Detect legacy cache keys (non-associative) $array = $data[$key]; if (!empty($array) && is_numeric(key($array))) { return false; } } return true; }
[ "protected", "function", "validateItemCache", "(", "$", "data", ")", "{", "if", "(", "!", "$", "data", "||", "!", "is_array", "(", "$", "data", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "[", "'classes'", ",", "'interfaces'", ",", "'traits'", "]", "as", "$", "key", ")", "{", "// Must be set", "if", "(", "!", "isset", "(", "$", "data", "[", "$", "key", "]", ")", ")", "{", "return", "false", ";", "}", "// and an array", "if", "(", "!", "is_array", "(", "$", "data", "[", "$", "key", "]", ")", ")", "{", "return", "false", ";", "}", "// Detect legacy cache keys (non-associative)", "$", "array", "=", "$", "data", "[", "$", "key", "]", ";", "if", "(", "!", "empty", "(", "$", "array", ")", "&&", "is_numeric", "(", "key", "(", "$", "array", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Verify that cached data is valid for a single item @param array $data @return bool
[ "Verify", "that", "cached", "data", "is", "valid", "for", "a", "single", "item" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassManifest.php#L648-L669
train
silverstripe/silverstripe-framework
src/View/Parsers/HTMLValue.php
HTMLValue.getDocument
public function getDocument() { if (!$this->valid) { return false; } elseif ($this->document) { return $this->document; } else { $this->document = new DOMDocument('1.0', 'UTF-8'); $this->document->strictErrorChecking = false; $this->document->formatOutput = false; return $this->document; } }
php
public function getDocument() { if (!$this->valid) { return false; } elseif ($this->document) { return $this->document; } else { $this->document = new DOMDocument('1.0', 'UTF-8'); $this->document->strictErrorChecking = false; $this->document->formatOutput = false; return $this->document; } }
[ "public", "function", "getDocument", "(", ")", "{", "if", "(", "!", "$", "this", "->", "valid", ")", "{", "return", "false", ";", "}", "elseif", "(", "$", "this", "->", "document", ")", "{", "return", "$", "this", "->", "document", ";", "}", "else", "{", "$", "this", "->", "document", "=", "new", "DOMDocument", "(", "'1.0'", ",", "'UTF-8'", ")", ";", "$", "this", "->", "document", "->", "strictErrorChecking", "=", "false", ";", "$", "this", "->", "document", "->", "formatOutput", "=", "false", ";", "return", "$", "this", "->", "document", ";", "}", "}" ]
Get the DOMDocument for the passed content @return DOMDocument | false - Return false if HTML not valid, the DOMDocument instance otherwise
[ "Get", "the", "DOMDocument", "for", "the", "passed", "content" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/HTMLValue.php#L99-L112
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.getModelClass
public function getModelClass() { if ($this->modelClassName) { return $this->modelClassName; } /** @var DataList|ArrayList $list */ $list = $this->list; if ($list && $list->hasMethod('dataClass')) { $class = $list->dataClass(); if ($class) { return $class; } } throw new LogicException( 'GridField doesn\'t have a modelClassName, so it doesn\'t know the columns of this grid.' ); }
php
public function getModelClass() { if ($this->modelClassName) { return $this->modelClassName; } /** @var DataList|ArrayList $list */ $list = $this->list; if ($list && $list->hasMethod('dataClass')) { $class = $list->dataClass(); if ($class) { return $class; } } throw new LogicException( 'GridField doesn\'t have a modelClassName, so it doesn\'t know the columns of this grid.' ); }
[ "public", "function", "getModelClass", "(", ")", "{", "if", "(", "$", "this", "->", "modelClassName", ")", "{", "return", "$", "this", "->", "modelClassName", ";", "}", "/** @var DataList|ArrayList $list */", "$", "list", "=", "$", "this", "->", "list", ";", "if", "(", "$", "list", "&&", "$", "list", "->", "hasMethod", "(", "'dataClass'", ")", ")", "{", "$", "class", "=", "$", "list", "->", "dataClass", "(", ")", ";", "if", "(", "$", "class", ")", "{", "return", "$", "class", ";", "}", "}", "throw", "new", "LogicException", "(", "'GridField doesn\\'t have a modelClassName, so it doesn\\'t know the columns of this grid.'", ")", ";", "}" ]
Returns a data class that is a DataObject type that this GridField should look like. @return string @throws LogicException
[ "Returns", "a", "data", "class", "that", "is", "a", "DataObject", "type", "that", "this", "GridField", "should", "look", "like", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L199-L218
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.performReadonlyTransformation
public function performReadonlyTransformation() { $copy = clone $this; $copy->setReadonly(true); $copyConfig = $copy->getConfig(); // get the whitelist for allowable readonly components $allowedComponents = $this->getReadonlyComponents(); foreach ($this->getConfig()->getComponents() as $component) { // if a component doesn't exist, remove it from the readonly version. if (!in_array(get_class($component), $allowedComponents)) { $copyConfig->removeComponent($component); } } // As the edit button may have been removed, add a view button if it doesn't have one if (!$copyConfig->getComponentByType(GridFieldViewButton::class)) { $copyConfig->addComponent(new GridFieldViewButton); } return $copy; }
php
public function performReadonlyTransformation() { $copy = clone $this; $copy->setReadonly(true); $copyConfig = $copy->getConfig(); // get the whitelist for allowable readonly components $allowedComponents = $this->getReadonlyComponents(); foreach ($this->getConfig()->getComponents() as $component) { // if a component doesn't exist, remove it from the readonly version. if (!in_array(get_class($component), $allowedComponents)) { $copyConfig->removeComponent($component); } } // As the edit button may have been removed, add a view button if it doesn't have one if (!$copyConfig->getComponentByType(GridFieldViewButton::class)) { $copyConfig->addComponent(new GridFieldViewButton); } return $copy; }
[ "public", "function", "performReadonlyTransformation", "(", ")", "{", "$", "copy", "=", "clone", "$", "this", ";", "$", "copy", "->", "setReadonly", "(", "true", ")", ";", "$", "copyConfig", "=", "$", "copy", "->", "getConfig", "(", ")", ";", "// get the whitelist for allowable readonly components", "$", "allowedComponents", "=", "$", "this", "->", "getReadonlyComponents", "(", ")", ";", "foreach", "(", "$", "this", "->", "getConfig", "(", ")", "->", "getComponents", "(", ")", "as", "$", "component", ")", "{", "// if a component doesn't exist, remove it from the readonly version.", "if", "(", "!", "in_array", "(", "get_class", "(", "$", "component", ")", ",", "$", "allowedComponents", ")", ")", "{", "$", "copyConfig", "->", "removeComponent", "(", "$", "component", ")", ";", "}", "}", "// As the edit button may have been removed, add a view button if it doesn't have one", "if", "(", "!", "$", "copyConfig", "->", "getComponentByType", "(", "GridFieldViewButton", "::", "class", ")", ")", "{", "$", "copyConfig", "->", "addComponent", "(", "new", "GridFieldViewButton", ")", ";", "}", "return", "$", "copy", ";", "}" ]
Custom Readonly transformation to remove actions which shouldn't be present for a readonly state. @return GridField
[ "Custom", "Readonly", "transformation", "to", "remove", "actions", "which", "shouldn", "t", "be", "present", "for", "a", "readonly", "state", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L245-L266
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.getColumns
public function getColumns() { $columns = array(); foreach ($this->getComponents() as $item) { if ($item instanceof GridField_ColumnProvider) { $item->augmentColumns($this, $columns); } } return $columns; }
php
public function getColumns() { $columns = array(); foreach ($this->getComponents() as $item) { if ($item instanceof GridField_ColumnProvider) { $item->augmentColumns($this, $columns); } } return $columns; }
[ "public", "function", "getColumns", "(", ")", "{", "$", "columns", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getComponents", "(", ")", "as", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "GridField_ColumnProvider", ")", "{", "$", "item", "->", "augmentColumns", "(", "$", "this", ",", "$", "columns", ")", ";", "}", "}", "return", "$", "columns", ";", "}" ]
Get the columns of this GridField, they are provided by attached GridField_ColumnProvider. @return array
[ "Get", "the", "columns", "of", "this", "GridField", "they", "are", "provided", "by", "attached", "GridField_ColumnProvider", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L758-L769
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.getColumnContent
public function getColumnContent($record, $column) { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } if (!empty($this->columnDispatch[$column])) { $content = ''; foreach ($this->columnDispatch[$column] as $handler) { /** * @var GridField_ColumnProvider $handler */ $content .= $handler->getColumnContent($this, $record, $column); } return $content; } else { throw new InvalidArgumentException(sprintf( 'Bad column "%s"', $column )); } }
php
public function getColumnContent($record, $column) { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } if (!empty($this->columnDispatch[$column])) { $content = ''; foreach ($this->columnDispatch[$column] as $handler) { /** * @var GridField_ColumnProvider $handler */ $content .= $handler->getColumnContent($this, $record, $column); } return $content; } else { throw new InvalidArgumentException(sprintf( 'Bad column "%s"', $column )); } }
[ "public", "function", "getColumnContent", "(", "$", "record", ",", "$", "column", ")", "{", "if", "(", "!", "$", "this", "->", "columnDispatch", ")", "{", "$", "this", "->", "buildColumnDispatch", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", ")", ")", "{", "$", "content", "=", "''", ";", "foreach", "(", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", "as", "$", "handler", ")", "{", "/**\n * @var GridField_ColumnProvider $handler\n */", "$", "content", ".=", "$", "handler", "->", "getColumnContent", "(", "$", "this", ",", "$", "record", ",", "$", "column", ")", ";", "}", "return", "$", "content", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Bad column \"%s\"'", ",", "$", "column", ")", ")", ";", "}", "}" ]
Get the value from a column. @param DataObject $record @param string $column @return string @throws InvalidArgumentException
[ "Get", "the", "value", "from", "a", "column", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L781-L804
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.addDataFields
public function addDataFields($fields) { if ($this->customDataFields) { $this->customDataFields = array_merge($this->customDataFields, $fields); } else { $this->customDataFields = $fields; } }
php
public function addDataFields($fields) { if ($this->customDataFields) { $this->customDataFields = array_merge($this->customDataFields, $fields); } else { $this->customDataFields = $fields; } }
[ "public", "function", "addDataFields", "(", "$", "fields", ")", "{", "if", "(", "$", "this", "->", "customDataFields", ")", "{", "$", "this", "->", "customDataFields", "=", "array_merge", "(", "$", "this", "->", "customDataFields", ",", "$", "fields", ")", ";", "}", "else", "{", "$", "this", "->", "customDataFields", "=", "$", "fields", ";", "}", "}" ]
Add additional calculated data fields to be used on this GridField @param array $fields a map of fieldname to callback. The callback will be passed the record as an argument.
[ "Add", "additional", "calculated", "data", "fields", "to", "be", "used", "on", "this", "GridField" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L812-L819
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.getDataFieldValue
public function getDataFieldValue($record, $fieldName) { if (isset($this->customDataFields[$fieldName])) { $callback = $this->customDataFields[$fieldName]; return $callback($record); } if ($record->hasMethod('relField')) { return $record->relField($fieldName); } if ($record->hasMethod($fieldName)) { return $record->$fieldName(); } return $record->$fieldName; }
php
public function getDataFieldValue($record, $fieldName) { if (isset($this->customDataFields[$fieldName])) { $callback = $this->customDataFields[$fieldName]; return $callback($record); } if ($record->hasMethod('relField')) { return $record->relField($fieldName); } if ($record->hasMethod($fieldName)) { return $record->$fieldName(); } return $record->$fieldName; }
[ "public", "function", "getDataFieldValue", "(", "$", "record", ",", "$", "fieldName", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "customDataFields", "[", "$", "fieldName", "]", ")", ")", "{", "$", "callback", "=", "$", "this", "->", "customDataFields", "[", "$", "fieldName", "]", ";", "return", "$", "callback", "(", "$", "record", ")", ";", "}", "if", "(", "$", "record", "->", "hasMethod", "(", "'relField'", ")", ")", "{", "return", "$", "record", "->", "relField", "(", "$", "fieldName", ")", ";", "}", "if", "(", "$", "record", "->", "hasMethod", "(", "$", "fieldName", ")", ")", "{", "return", "$", "record", "->", "$", "fieldName", "(", ")", ";", "}", "return", "$", "record", "->", "$", "fieldName", ";", "}" ]
Get the value of a named field on the given record. Use of this method ensures that any special rules around the data for this gridfield are followed. @param DataObject $record @param string $fieldName @return mixed
[ "Get", "the", "value", "of", "a", "named", "field", "on", "the", "given", "record", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L832-L849
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.getColumnAttributes
public function getColumnAttributes($record, $column) { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } if (!empty($this->columnDispatch[$column])) { $attributes = array(); foreach ($this->columnDispatch[$column] as $handler) { /** * @var GridField_ColumnProvider $handler */ $columnAttributes = $handler->getColumnAttributes($this, $record, $column); if (is_array($columnAttributes)) { $attributes = array_merge($attributes, $columnAttributes); continue; } throw new LogicException(sprintf( 'Non-array response from %s::getColumnAttributes().', get_class($handler) )); } return $attributes; } throw new InvalidArgumentException(sprintf( 'Bad column "%s"', $column )); }
php
public function getColumnAttributes($record, $column) { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } if (!empty($this->columnDispatch[$column])) { $attributes = array(); foreach ($this->columnDispatch[$column] as $handler) { /** * @var GridField_ColumnProvider $handler */ $columnAttributes = $handler->getColumnAttributes($this, $record, $column); if (is_array($columnAttributes)) { $attributes = array_merge($attributes, $columnAttributes); continue; } throw new LogicException(sprintf( 'Non-array response from %s::getColumnAttributes().', get_class($handler) )); } return $attributes; } throw new InvalidArgumentException(sprintf( 'Bad column "%s"', $column )); }
[ "public", "function", "getColumnAttributes", "(", "$", "record", ",", "$", "column", ")", "{", "if", "(", "!", "$", "this", "->", "columnDispatch", ")", "{", "$", "this", "->", "buildColumnDispatch", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", ")", ")", "{", "$", "attributes", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", "as", "$", "handler", ")", "{", "/**\n * @var GridField_ColumnProvider $handler\n */", "$", "columnAttributes", "=", "$", "handler", "->", "getColumnAttributes", "(", "$", "this", ",", "$", "record", ",", "$", "column", ")", ";", "if", "(", "is_array", "(", "$", "columnAttributes", ")", ")", "{", "$", "attributes", "=", "array_merge", "(", "$", "attributes", ",", "$", "columnAttributes", ")", ";", "continue", ";", "}", "throw", "new", "LogicException", "(", "sprintf", "(", "'Non-array response from %s::getColumnAttributes().'", ",", "get_class", "(", "$", "handler", ")", ")", ")", ";", "}", "return", "$", "attributes", ";", "}", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Bad column \"%s\"'", ",", "$", "column", ")", ")", ";", "}" ]
Get extra columns attributes used as HTML attributes. @param DataObject $record @param string $column @return array @throws LogicException @throws InvalidArgumentException
[ "Get", "extra", "columns", "attributes", "used", "as", "HTML", "attributes", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L862-L895
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.getColumnMetadata
public function getColumnMetadata($column) { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } if (!empty($this->columnDispatch[$column])) { $metaData = array(); foreach ($this->columnDispatch[$column] as $handler) { /** * @var GridField_ColumnProvider $handler */ $columnMetaData = $handler->getColumnMetadata($this, $column); if (is_array($columnMetaData)) { $metaData = array_merge($metaData, $columnMetaData); continue; } throw new LogicException(sprintf( 'Non-array response from %s::getColumnMetadata().', get_class($handler) )); } return $metaData; } throw new InvalidArgumentException(sprintf( 'Bad column "%s"', $column )); }
php
public function getColumnMetadata($column) { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } if (!empty($this->columnDispatch[$column])) { $metaData = array(); foreach ($this->columnDispatch[$column] as $handler) { /** * @var GridField_ColumnProvider $handler */ $columnMetaData = $handler->getColumnMetadata($this, $column); if (is_array($columnMetaData)) { $metaData = array_merge($metaData, $columnMetaData); continue; } throw new LogicException(sprintf( 'Non-array response from %s::getColumnMetadata().', get_class($handler) )); } return $metaData; } throw new InvalidArgumentException(sprintf( 'Bad column "%s"', $column )); }
[ "public", "function", "getColumnMetadata", "(", "$", "column", ")", "{", "if", "(", "!", "$", "this", "->", "columnDispatch", ")", "{", "$", "this", "->", "buildColumnDispatch", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", ")", ")", "{", "$", "metaData", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", "as", "$", "handler", ")", "{", "/**\n * @var GridField_ColumnProvider $handler\n */", "$", "columnMetaData", "=", "$", "handler", "->", "getColumnMetadata", "(", "$", "this", ",", "$", "column", ")", ";", "if", "(", "is_array", "(", "$", "columnMetaData", ")", ")", "{", "$", "metaData", "=", "array_merge", "(", "$", "metaData", ",", "$", "columnMetaData", ")", ";", "continue", ";", "}", "throw", "new", "LogicException", "(", "sprintf", "(", "'Non-array response from %s::getColumnMetadata().'", ",", "get_class", "(", "$", "handler", ")", ")", ")", ";", "}", "return", "$", "metaData", ";", "}", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Bad column \"%s\"'", ",", "$", "column", ")", ")", ";", "}" ]
Get metadata for a column. @example "array('Title'=>'Email address')" @param string $column @return array @throws LogicException @throws InvalidArgumentException
[ "Get", "metadata", "for", "a", "column", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L909-L942
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.buildColumnDispatch
protected function buildColumnDispatch() { $this->columnDispatch = array(); foreach ($this->getComponents() as $item) { if ($item instanceof GridField_ColumnProvider) { $columns = $item->getColumnsHandled($this); foreach ($columns as $column) { $this->columnDispatch[$column][] = $item; } } } }
php
protected function buildColumnDispatch() { $this->columnDispatch = array(); foreach ($this->getComponents() as $item) { if ($item instanceof GridField_ColumnProvider) { $columns = $item->getColumnsHandled($this); foreach ($columns as $column) { $this->columnDispatch[$column][] = $item; } } } }
[ "protected", "function", "buildColumnDispatch", "(", ")", "{", "$", "this", "->", "columnDispatch", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getComponents", "(", ")", "as", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "GridField_ColumnProvider", ")", "{", "$", "columns", "=", "$", "item", "->", "getColumnsHandled", "(", "$", "this", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "this", "->", "columnDispatch", "[", "$", "column", "]", "[", "]", "=", "$", "item", ";", "}", "}", "}", "}" ]
Build an columnDispatch that maps a GridField_ColumnProvider to a column for reference later.
[ "Build", "an", "columnDispatch", "that", "maps", "a", "GridField_ColumnProvider", "to", "a", "column", "for", "reference", "later", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L961-L974
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.gridFieldAlterAction
public function gridFieldAlterAction($data, $form, HTTPRequest $request) { $data = $request->requestVars(); // Protection against CSRF attacks $token = $this ->getForm() ->getSecurityToken(); if (!$token->checkRequest($request)) { $this->httpError(400, _t( "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE", "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again." )); } $name = $this->getName(); $fieldData = null; if (isset($data[$name])) { $fieldData = $data[$name]; } $state = $this->getState(false); /** @skipUpgrade */ if (isset($fieldData['GridState'])) { $state->setValue($fieldData['GridState']); } // Fetch the store for the "state" of actions (not the GridField) /** @var StateStore $store */ $store = Injector::inst()->create(StateStore::class . '.' . $this->getName()); foreach ($data as $dataKey => $dataValue) { if (preg_match('/^action_gridFieldAlterAction\?StateID=(.*)/', $dataKey, $matches)) { $stateChange = $store->load($matches[1]); $actionName = $stateChange['actionName']; $arguments = array(); if (isset($stateChange['args'])) { $arguments = $stateChange['args']; }; $html = $this->handleAlterAction($actionName, $arguments, $data); if ($html) { return $html; } } } if ($request->getHeader('X-Pjax') === 'CurrentField') { if ($this->getState()->Readonly === true) { $this->performDisabledTransformation(); } return $this->FieldHolder(); } return $form->forTemplate(); }
php
public function gridFieldAlterAction($data, $form, HTTPRequest $request) { $data = $request->requestVars(); // Protection against CSRF attacks $token = $this ->getForm() ->getSecurityToken(); if (!$token->checkRequest($request)) { $this->httpError(400, _t( "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE", "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again." )); } $name = $this->getName(); $fieldData = null; if (isset($data[$name])) { $fieldData = $data[$name]; } $state = $this->getState(false); /** @skipUpgrade */ if (isset($fieldData['GridState'])) { $state->setValue($fieldData['GridState']); } // Fetch the store for the "state" of actions (not the GridField) /** @var StateStore $store */ $store = Injector::inst()->create(StateStore::class . '.' . $this->getName()); foreach ($data as $dataKey => $dataValue) { if (preg_match('/^action_gridFieldAlterAction\?StateID=(.*)/', $dataKey, $matches)) { $stateChange = $store->load($matches[1]); $actionName = $stateChange['actionName']; $arguments = array(); if (isset($stateChange['args'])) { $arguments = $stateChange['args']; }; $html = $this->handleAlterAction($actionName, $arguments, $data); if ($html) { return $html; } } } if ($request->getHeader('X-Pjax') === 'CurrentField') { if ($this->getState()->Readonly === true) { $this->performDisabledTransformation(); } return $this->FieldHolder(); } return $form->forTemplate(); }
[ "public", "function", "gridFieldAlterAction", "(", "$", "data", ",", "$", "form", ",", "HTTPRequest", "$", "request", ")", "{", "$", "data", "=", "$", "request", "->", "requestVars", "(", ")", ";", "// Protection against CSRF attacks", "$", "token", "=", "$", "this", "->", "getForm", "(", ")", "->", "getSecurityToken", "(", ")", ";", "if", "(", "!", "$", "token", "->", "checkRequest", "(", "$", "request", ")", ")", "{", "$", "this", "->", "httpError", "(", "400", ",", "_t", "(", "\"SilverStripe\\\\Forms\\\\Form.CSRF_FAILED_MESSAGE\"", ",", "\"There seems to have been a technical problem. Please click the back button, \"", ".", "\"refresh your browser, and try again.\"", ")", ")", ";", "}", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "$", "fieldData", "=", "null", ";", "if", "(", "isset", "(", "$", "data", "[", "$", "name", "]", ")", ")", "{", "$", "fieldData", "=", "$", "data", "[", "$", "name", "]", ";", "}", "$", "state", "=", "$", "this", "->", "getState", "(", "false", ")", ";", "/** @skipUpgrade */", "if", "(", "isset", "(", "$", "fieldData", "[", "'GridState'", "]", ")", ")", "{", "$", "state", "->", "setValue", "(", "$", "fieldData", "[", "'GridState'", "]", ")", ";", "}", "// Fetch the store for the \"state\" of actions (not the GridField)", "/** @var StateStore $store */", "$", "store", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "StateStore", "::", "class", ".", "'.'", ".", "$", "this", "->", "getName", "(", ")", ")", ";", "foreach", "(", "$", "data", "as", "$", "dataKey", "=>", "$", "dataValue", ")", "{", "if", "(", "preg_match", "(", "'/^action_gridFieldAlterAction\\?StateID=(.*)/'", ",", "$", "dataKey", ",", "$", "matches", ")", ")", "{", "$", "stateChange", "=", "$", "store", "->", "load", "(", "$", "matches", "[", "1", "]", ")", ";", "$", "actionName", "=", "$", "stateChange", "[", "'actionName'", "]", ";", "$", "arguments", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "stateChange", "[", "'args'", "]", ")", ")", "{", "$", "arguments", "=", "$", "stateChange", "[", "'args'", "]", ";", "}", ";", "$", "html", "=", "$", "this", "->", "handleAlterAction", "(", "$", "actionName", ",", "$", "arguments", ",", "$", "data", ")", ";", "if", "(", "$", "html", ")", "{", "return", "$", "html", ";", "}", "}", "}", "if", "(", "$", "request", "->", "getHeader", "(", "'X-Pjax'", ")", "===", "'CurrentField'", ")", "{", "if", "(", "$", "this", "->", "getState", "(", ")", "->", "Readonly", "===", "true", ")", "{", "$", "this", "->", "performDisabledTransformation", "(", ")", ";", "}", "return", "$", "this", "->", "FieldHolder", "(", ")", ";", "}", "return", "$", "form", "->", "forTemplate", "(", ")", ";", "}" ]
This is the action that gets executed when a GridField_AlterAction gets clicked. @param array $data @param Form $form @param HTTPRequest $request @return string
[ "This", "is", "the", "action", "that", "gets", "executed", "when", "a", "GridField_AlterAction", "gets", "clicked", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L985-L1047
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
GridField.handleRequest
public function handleRequest(HTTPRequest $request) { if ($this->brokenOnConstruct) { user_error( sprintf( "parent::__construct() needs to be called on %s::__construct()", __CLASS__ ), E_USER_WARNING ); } $this->setRequest($request); $fieldData = $this->getRequest()->requestVar($this->getName()); /** @skipUpgrade */ if ($fieldData && isset($fieldData['GridState'])) { $this->getState(false)->setValue($fieldData['GridState']); } foreach ($this->getComponents() as $component) { if ($component instanceof GridField_URLHandler && $urlHandlers = $component->getURLHandlers($this)) { foreach ($urlHandlers as $rule => $action) { if ($params = $request->match($rule, true)) { // Actions can reference URL parameters. // e.g. '$Action/$ID/$OtherID' → '$Action' if ($action[0] == '$') { $action = $params[substr($action, 1)]; } if (!method_exists($component, 'checkAccessAction') || $component->checkAccessAction($action)) { if (!$action) { $action = "index"; } if (!is_string($action)) { throw new LogicException(sprintf( 'Non-string method name: %s', var_export($action, true) )); } try { $result = $component->$action($this, $request); } catch (HTTPResponse_Exception $responseException) { $result = $responseException->getResponse(); } if ($result instanceof HTTPResponse && $result->isError()) { return $result; } if ($this !== $result && !$request->isEmptyPattern($rule) && ($result instanceof RequestHandler || $result instanceof HasRequestHandler) ) { if ($result instanceof HasRequestHandler) { $result = $result->getRequestHandler(); } $returnValue = $result->handleRequest($request); if (is_array($returnValue)) { throw new LogicException( 'GridField_URLHandler handlers can\'t return arrays' ); } return $returnValue; } if ($request->allParsed()) { return $result; } return $this->httpError( 404, sprintf( 'I can\'t handle sub-URLs of a %s object.', get_class($result) ) ); } } } } } return parent::handleRequest($request); }
php
public function handleRequest(HTTPRequest $request) { if ($this->brokenOnConstruct) { user_error( sprintf( "parent::__construct() needs to be called on %s::__construct()", __CLASS__ ), E_USER_WARNING ); } $this->setRequest($request); $fieldData = $this->getRequest()->requestVar($this->getName()); /** @skipUpgrade */ if ($fieldData && isset($fieldData['GridState'])) { $this->getState(false)->setValue($fieldData['GridState']); } foreach ($this->getComponents() as $component) { if ($component instanceof GridField_URLHandler && $urlHandlers = $component->getURLHandlers($this)) { foreach ($urlHandlers as $rule => $action) { if ($params = $request->match($rule, true)) { // Actions can reference URL parameters. // e.g. '$Action/$ID/$OtherID' → '$Action' if ($action[0] == '$') { $action = $params[substr($action, 1)]; } if (!method_exists($component, 'checkAccessAction') || $component->checkAccessAction($action)) { if (!$action) { $action = "index"; } if (!is_string($action)) { throw new LogicException(sprintf( 'Non-string method name: %s', var_export($action, true) )); } try { $result = $component->$action($this, $request); } catch (HTTPResponse_Exception $responseException) { $result = $responseException->getResponse(); } if ($result instanceof HTTPResponse && $result->isError()) { return $result; } if ($this !== $result && !$request->isEmptyPattern($rule) && ($result instanceof RequestHandler || $result instanceof HasRequestHandler) ) { if ($result instanceof HasRequestHandler) { $result = $result->getRequestHandler(); } $returnValue = $result->handleRequest($request); if (is_array($returnValue)) { throw new LogicException( 'GridField_URLHandler handlers can\'t return arrays' ); } return $returnValue; } if ($request->allParsed()) { return $result; } return $this->httpError( 404, sprintf( 'I can\'t handle sub-URLs of a %s object.', get_class($result) ) ); } } } } } return parent::handleRequest($request); }
[ "public", "function", "handleRequest", "(", "HTTPRequest", "$", "request", ")", "{", "if", "(", "$", "this", "->", "brokenOnConstruct", ")", "{", "user_error", "(", "sprintf", "(", "\"parent::__construct() needs to be called on %s::__construct()\"", ",", "__CLASS__", ")", ",", "E_USER_WARNING", ")", ";", "}", "$", "this", "->", "setRequest", "(", "$", "request", ")", ";", "$", "fieldData", "=", "$", "this", "->", "getRequest", "(", ")", "->", "requestVar", "(", "$", "this", "->", "getName", "(", ")", ")", ";", "/** @skipUpgrade */", "if", "(", "$", "fieldData", "&&", "isset", "(", "$", "fieldData", "[", "'GridState'", "]", ")", ")", "{", "$", "this", "->", "getState", "(", "false", ")", "->", "setValue", "(", "$", "fieldData", "[", "'GridState'", "]", ")", ";", "}", "foreach", "(", "$", "this", "->", "getComponents", "(", ")", "as", "$", "component", ")", "{", "if", "(", "$", "component", "instanceof", "GridField_URLHandler", "&&", "$", "urlHandlers", "=", "$", "component", "->", "getURLHandlers", "(", "$", "this", ")", ")", "{", "foreach", "(", "$", "urlHandlers", "as", "$", "rule", "=>", "$", "action", ")", "{", "if", "(", "$", "params", "=", "$", "request", "->", "match", "(", "$", "rule", ",", "true", ")", ")", "{", "// Actions can reference URL parameters.", "// e.g. '$Action/$ID/$OtherID' → '$Action'", "if", "(", "$", "action", "[", "0", "]", "==", "'$'", ")", "{", "$", "action", "=", "$", "params", "[", "substr", "(", "$", "action", ",", "1", ")", "]", ";", "}", "if", "(", "!", "method_exists", "(", "$", "component", ",", "'checkAccessAction'", ")", "||", "$", "component", "->", "checkAccessAction", "(", "$", "action", ")", ")", "{", "if", "(", "!", "$", "action", ")", "{", "$", "action", "=", "\"index\"", ";", "}", "if", "(", "!", "is_string", "(", "$", "action", ")", ")", "{", "throw", "new", "LogicException", "(", "sprintf", "(", "'Non-string method name: %s'", ",", "var_export", "(", "$", "action", ",", "true", ")", ")", ")", ";", "}", "try", "{", "$", "result", "=", "$", "component", "->", "$", "action", "(", "$", "this", ",", "$", "request", ")", ";", "}", "catch", "(", "HTTPResponse_Exception", "$", "responseException", ")", "{", "$", "result", "=", "$", "responseException", "->", "getResponse", "(", ")", ";", "}", "if", "(", "$", "result", "instanceof", "HTTPResponse", "&&", "$", "result", "->", "isError", "(", ")", ")", "{", "return", "$", "result", ";", "}", "if", "(", "$", "this", "!==", "$", "result", "&&", "!", "$", "request", "->", "isEmptyPattern", "(", "$", "rule", ")", "&&", "(", "$", "result", "instanceof", "RequestHandler", "||", "$", "result", "instanceof", "HasRequestHandler", ")", ")", "{", "if", "(", "$", "result", "instanceof", "HasRequestHandler", ")", "{", "$", "result", "=", "$", "result", "->", "getRequestHandler", "(", ")", ";", "}", "$", "returnValue", "=", "$", "result", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "is_array", "(", "$", "returnValue", ")", ")", "{", "throw", "new", "LogicException", "(", "'GridField_URLHandler handlers can\\'t return arrays'", ")", ";", "}", "return", "$", "returnValue", ";", "}", "if", "(", "$", "request", "->", "allParsed", "(", ")", ")", "{", "return", "$", "result", ";", "}", "return", "$", "this", "->", "httpError", "(", "404", ",", "sprintf", "(", "'I can\\'t handle sub-URLs of a %s object.'", ",", "get_class", "(", "$", "result", ")", ")", ")", ";", "}", "}", "}", "}", "}", "return", "parent", "::", "handleRequest", "(", "$", "request", ")", ";", "}" ]
Custom request handler that will check component handlers before proceeding to the default implementation. @todo copy less code from RequestHandler. @param HTTPRequest $request @return array|RequestHandler|HTTPResponse|string @throws HTTPResponse_Exception
[ "Custom", "request", "handler", "that", "will", "check", "component", "handlers", "before", "proceeding", "to", "the", "default", "implementation", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField.php#L1090-L1180
train
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
DefaultAdminService.setDefaultAdmin
public static function setDefaultAdmin($username, $password) { // don't overwrite if already set if (static::hasDefaultAdmin()) { throw new BadMethodCallException( "Default admin already exists. Use clearDefaultAdmin() first." ); } if (empty($username) || empty($password)) { throw new InvalidArgumentException("Default admin username / password cannot be empty"); } static::$default_username = $username; static::$default_password = $password; static::$has_default_admin = true; }
php
public static function setDefaultAdmin($username, $password) { // don't overwrite if already set if (static::hasDefaultAdmin()) { throw new BadMethodCallException( "Default admin already exists. Use clearDefaultAdmin() first." ); } if (empty($username) || empty($password)) { throw new InvalidArgumentException("Default admin username / password cannot be empty"); } static::$default_username = $username; static::$default_password = $password; static::$has_default_admin = true; }
[ "public", "static", "function", "setDefaultAdmin", "(", "$", "username", ",", "$", "password", ")", "{", "// don't overwrite if already set", "if", "(", "static", "::", "hasDefaultAdmin", "(", ")", ")", "{", "throw", "new", "BadMethodCallException", "(", "\"Default admin already exists. Use clearDefaultAdmin() first.\"", ")", ";", "}", "if", "(", "empty", "(", "$", "username", ")", "||", "empty", "(", "$", "password", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Default admin username / password cannot be empty\"", ")", ";", "}", "static", "::", "$", "default_username", "=", "$", "username", ";", "static", "::", "$", "default_password", "=", "$", "password", ";", "static", "::", "$", "has_default_admin", "=", "true", ";", "}" ]
Set the default admin credentials @param string $username @param string $password
[ "Set", "the", "default", "admin", "credentials" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/DefaultAdminService.php#L49-L65
train
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
DefaultAdminService.hasDefaultAdmin
public static function hasDefaultAdmin() { // Check environment if not explicitly set if (!isset(static::$has_default_admin)) { return !empty(Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME')) && !empty(Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD')); } return static::$has_default_admin; }
php
public static function hasDefaultAdmin() { // Check environment if not explicitly set if (!isset(static::$has_default_admin)) { return !empty(Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME')) && !empty(Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD')); } return static::$has_default_admin; }
[ "public", "static", "function", "hasDefaultAdmin", "(", ")", "{", "// Check environment if not explicitly set", "if", "(", "!", "isset", "(", "static", "::", "$", "has_default_admin", ")", ")", "{", "return", "!", "empty", "(", "Environment", "::", "getEnv", "(", "'SS_DEFAULT_ADMIN_USERNAME'", ")", ")", "&&", "!", "empty", "(", "Environment", "::", "getEnv", "(", "'SS_DEFAULT_ADMIN_PASSWORD'", ")", ")", ";", "}", "return", "static", "::", "$", "has_default_admin", ";", "}" ]
Check if there is a default admin @return bool
[ "Check", "if", "there", "is", "a", "default", "admin" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/DefaultAdminService.php#L100-L108
train
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
DefaultAdminService.findOrCreateAdmin
public function findOrCreateAdmin($email, $name = null) { $this->extend('beforeFindOrCreateAdmin', $email, $name); // Find member /** @var Member $admin */ $admin = Member::get() ->filter('Email', $email) ->first(); // Find or create admin group $adminGroup = $this->findOrCreateAdminGroup(); // If no admin is found, create one if ($admin) { $inGroup = $admin->inGroup($adminGroup); } else { // Note: This user won't be able to login until a password is set // Set 'Email' to identify this as the default admin $inGroup = false; $admin = Member::create(); $admin->FirstName = $name ?: $email; $admin->Email = $email; $admin->PasswordEncryption = 'none'; $admin->write(); } // Ensure this user is in an admin group if (!$inGroup) { // Add member to group instead of adding group to member // This bypasses the privilege escallation code in Member_GroupSet $adminGroup ->DirectMembers() ->add($admin); } $this->extend('afterFindOrCreateAdmin', $admin); return $admin; }
php
public function findOrCreateAdmin($email, $name = null) { $this->extend('beforeFindOrCreateAdmin', $email, $name); // Find member /** @var Member $admin */ $admin = Member::get() ->filter('Email', $email) ->first(); // Find or create admin group $adminGroup = $this->findOrCreateAdminGroup(); // If no admin is found, create one if ($admin) { $inGroup = $admin->inGroup($adminGroup); } else { // Note: This user won't be able to login until a password is set // Set 'Email' to identify this as the default admin $inGroup = false; $admin = Member::create(); $admin->FirstName = $name ?: $email; $admin->Email = $email; $admin->PasswordEncryption = 'none'; $admin->write(); } // Ensure this user is in an admin group if (!$inGroup) { // Add member to group instead of adding group to member // This bypasses the privilege escallation code in Member_GroupSet $adminGroup ->DirectMembers() ->add($admin); } $this->extend('afterFindOrCreateAdmin', $admin); return $admin; }
[ "public", "function", "findOrCreateAdmin", "(", "$", "email", ",", "$", "name", "=", "null", ")", "{", "$", "this", "->", "extend", "(", "'beforeFindOrCreateAdmin'", ",", "$", "email", ",", "$", "name", ")", ";", "// Find member", "/** @var Member $admin */", "$", "admin", "=", "Member", "::", "get", "(", ")", "->", "filter", "(", "'Email'", ",", "$", "email", ")", "->", "first", "(", ")", ";", "// Find or create admin group", "$", "adminGroup", "=", "$", "this", "->", "findOrCreateAdminGroup", "(", ")", ";", "// If no admin is found, create one", "if", "(", "$", "admin", ")", "{", "$", "inGroup", "=", "$", "admin", "->", "inGroup", "(", "$", "adminGroup", ")", ";", "}", "else", "{", "// Note: This user won't be able to login until a password is set", "// Set 'Email' to identify this as the default admin", "$", "inGroup", "=", "false", ";", "$", "admin", "=", "Member", "::", "create", "(", ")", ";", "$", "admin", "->", "FirstName", "=", "$", "name", "?", ":", "$", "email", ";", "$", "admin", "->", "Email", "=", "$", "email", ";", "$", "admin", "->", "PasswordEncryption", "=", "'none'", ";", "$", "admin", "->", "write", "(", ")", ";", "}", "// Ensure this user is in an admin group", "if", "(", "!", "$", "inGroup", ")", "{", "// Add member to group instead of adding group to member", "// This bypasses the privilege escallation code in Member_GroupSet", "$", "adminGroup", "->", "DirectMembers", "(", ")", "->", "add", "(", "$", "admin", ")", ";", "}", "$", "this", "->", "extend", "(", "'afterFindOrCreateAdmin'", ",", "$", "admin", ")", ";", "return", "$", "admin", ";", "}" ]
Find or create a Member with admin permissions @skipUpgrade @param string $email @param string $name @return Member
[ "Find", "or", "create", "a", "Member", "with", "admin", "permissions" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/DefaultAdminService.php#L151-L190
train
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
DefaultAdminService.findOrCreateAdminGroup
protected function findOrCreateAdminGroup() { // Check pre-existing group $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Check if default records create the group Group::singleton()->requireDefaultRecords(); $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Create new admin group directly $adminGroup = Group::create(); $adminGroup->Code = 'administrators'; $adminGroup->Title = _t('SilverStripe\\Security\\Group.DefaultGroupTitleAdministrators', 'Administrators'); $adminGroup->Sort = 0; $adminGroup->write(); Permission::grant($adminGroup->ID, 'ADMIN'); return $adminGroup; }
php
protected function findOrCreateAdminGroup() { // Check pre-existing group $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Check if default records create the group Group::singleton()->requireDefaultRecords(); $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Create new admin group directly $adminGroup = Group::create(); $adminGroup->Code = 'administrators'; $adminGroup->Title = _t('SilverStripe\\Security\\Group.DefaultGroupTitleAdministrators', 'Administrators'); $adminGroup->Sort = 0; $adminGroup->write(); Permission::grant($adminGroup->ID, 'ADMIN'); return $adminGroup; }
[ "protected", "function", "findOrCreateAdminGroup", "(", ")", "{", "// Check pre-existing group", "$", "adminGroup", "=", "Permission", "::", "get_groups_by_permission", "(", "'ADMIN'", ")", "->", "first", "(", ")", ";", "if", "(", "$", "adminGroup", ")", "{", "return", "$", "adminGroup", ";", "}", "// Check if default records create the group", "Group", "::", "singleton", "(", ")", "->", "requireDefaultRecords", "(", ")", ";", "$", "adminGroup", "=", "Permission", "::", "get_groups_by_permission", "(", "'ADMIN'", ")", "->", "first", "(", ")", ";", "if", "(", "$", "adminGroup", ")", "{", "return", "$", "adminGroup", ";", "}", "// Create new admin group directly", "$", "adminGroup", "=", "Group", "::", "create", "(", ")", ";", "$", "adminGroup", "->", "Code", "=", "'administrators'", ";", "$", "adminGroup", "->", "Title", "=", "_t", "(", "'SilverStripe\\\\Security\\\\Group.DefaultGroupTitleAdministrators'", ",", "'Administrators'", ")", ";", "$", "adminGroup", "->", "Sort", "=", "0", ";", "$", "adminGroup", "->", "write", "(", ")", ";", "Permission", "::", "grant", "(", "$", "adminGroup", "->", "ID", ",", "'ADMIN'", ")", ";", "return", "$", "adminGroup", ";", "}" ]
Ensure a Group exists with admin permission @return Group
[ "Ensure", "a", "Group", "exists", "with", "admin", "permission" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/DefaultAdminService.php#L197-L220
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
LostPasswordHandler.redirectToLostPassword
public function redirectToLostPassword() { $lostPasswordLink = Security::singleton()->Link('lostpassword'); return $this->redirect($this->addBackURLParam($lostPasswordLink)); }
php
public function redirectToLostPassword() { $lostPasswordLink = Security::singleton()->Link('lostpassword'); return $this->redirect($this->addBackURLParam($lostPasswordLink)); }
[ "public", "function", "redirectToLostPassword", "(", ")", "{", "$", "lostPasswordLink", "=", "Security", "::", "singleton", "(", ")", "->", "Link", "(", "'lostpassword'", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "addBackURLParam", "(", "$", "lostPasswordLink", ")", ")", ";", "}" ]
Redirect to password recovery form @return HTTPResponse
[ "Redirect", "to", "password", "recovery", "form" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LostPasswordHandler.php#L142-L147
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
LostPasswordHandler.forgotPassword
public function forgotPassword($data, $form) { // Run a first pass validation check on the data $dataValidation = $this->validateForgotPasswordData($data, $form); if ($dataValidation instanceof HTTPResponse) { return $dataValidation; } /** @var Member $member */ $member = $this->getMemberFromData($data); // Allow vetoing forgot password requests $results = $this->extend('forgotPassword', $member); if ($results && is_array($results) && in_array(false, $results, true)) { return $this->redirectToLostPassword(); } if ($member) { $token = $member->generateAutologinTokenAndStoreHash(); $this->sendEmail($member, $token); } return $this->redirectToSuccess($data); }
php
public function forgotPassword($data, $form) { // Run a first pass validation check on the data $dataValidation = $this->validateForgotPasswordData($data, $form); if ($dataValidation instanceof HTTPResponse) { return $dataValidation; } /** @var Member $member */ $member = $this->getMemberFromData($data); // Allow vetoing forgot password requests $results = $this->extend('forgotPassword', $member); if ($results && is_array($results) && in_array(false, $results, true)) { return $this->redirectToLostPassword(); } if ($member) { $token = $member->generateAutologinTokenAndStoreHash(); $this->sendEmail($member, $token); } return $this->redirectToSuccess($data); }
[ "public", "function", "forgotPassword", "(", "$", "data", ",", "$", "form", ")", "{", "// Run a first pass validation check on the data", "$", "dataValidation", "=", "$", "this", "->", "validateForgotPasswordData", "(", "$", "data", ",", "$", "form", ")", ";", "if", "(", "$", "dataValidation", "instanceof", "HTTPResponse", ")", "{", "return", "$", "dataValidation", ";", "}", "/** @var Member $member */", "$", "member", "=", "$", "this", "->", "getMemberFromData", "(", "$", "data", ")", ";", "// Allow vetoing forgot password requests", "$", "results", "=", "$", "this", "->", "extend", "(", "'forgotPassword'", ",", "$", "member", ")", ";", "if", "(", "$", "results", "&&", "is_array", "(", "$", "results", ")", "&&", "in_array", "(", "false", ",", "$", "results", ",", "true", ")", ")", "{", "return", "$", "this", "->", "redirectToLostPassword", "(", ")", ";", "}", "if", "(", "$", "member", ")", "{", "$", "token", "=", "$", "member", "->", "generateAutologinTokenAndStoreHash", "(", ")", ";", "$", "this", "->", "sendEmail", "(", "$", "member", ",", "$", "token", ")", ";", "}", "return", "$", "this", "->", "redirectToSuccess", "(", "$", "data", ")", ";", "}" ]
Forgot password form handler method. Called when the user clicks on "I've lost my password". Extensions can use the 'forgotPassword' method to veto executing the logic, by returning FALSE. In this case, the user will be redirected back to the form without further action. It is recommended to set a message in the form detailing why the action was denied. @skipUpgrade @param array $data Submitted data @param LostPasswordForm $form @return HTTPResponse
[ "Forgot", "password", "form", "handler", "method", ".", "Called", "when", "the", "user", "clicks", "on", "I", "ve", "lost", "my", "password", ".", "Extensions", "can", "use", "the", "forgotPassword", "method", "to", "veto", "executing", "the", "logic", "by", "returning", "FALSE", ".", "In", "this", "case", "the", "user", "will", "be", "redirected", "back", "to", "the", "form", "without", "further", "action", ".", "It", "is", "recommended", "to", "set", "a", "message", "in", "the", "form", "detailing", "why", "the", "action", "was", "denied", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LostPasswordHandler.php#L162-L186
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
LostPasswordHandler.validateForgotPasswordData
protected function validateForgotPasswordData(array $data, LostPasswordForm $form) { if (empty($data['Email'])) { $form->sessionMessage( _t( 'SilverStripe\\Security\\Member.ENTEREMAIL', 'Please enter an email address to get a password reset link.' ), 'bad' ); return $this->redirectToLostPassword(); } }
php
protected function validateForgotPasswordData(array $data, LostPasswordForm $form) { if (empty($data['Email'])) { $form->sessionMessage( _t( 'SilverStripe\\Security\\Member.ENTEREMAIL', 'Please enter an email address to get a password reset link.' ), 'bad' ); return $this->redirectToLostPassword(); } }
[ "protected", "function", "validateForgotPasswordData", "(", "array", "$", "data", ",", "LostPasswordForm", "$", "form", ")", "{", "if", "(", "empty", "(", "$", "data", "[", "'Email'", "]", ")", ")", "{", "$", "form", "->", "sessionMessage", "(", "_t", "(", "'SilverStripe\\\\Security\\\\Member.ENTEREMAIL'", ",", "'Please enter an email address to get a password reset link.'", ")", ",", "'bad'", ")", ";", "return", "$", "this", "->", "redirectToLostPassword", "(", ")", ";", "}", "}" ]
Ensure that the user has provided an email address. Note that the "Email" key is specific to this implementation, but child classes can override this method to use another unique identifier field for validation. @param array $data @param LostPasswordForm $form @return HTTPResponse|null
[ "Ensure", "that", "the", "user", "has", "provided", "an", "email", "address", ".", "Note", "that", "the", "Email", "key", "is", "specific", "to", "this", "implementation", "but", "child", "classes", "can", "override", "this", "method", "to", "use", "another", "unique", "identifier", "field", "for", "validation", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LostPasswordHandler.php#L197-L210
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
LostPasswordHandler.getMemberFromData
protected function getMemberFromData(array $data) { if (!empty($data['Email'])) { $uniqueIdentifier = Member::config()->get('unique_identifier_field'); return Member::get()->filter([$uniqueIdentifier => $data['Email']])->first(); } }
php
protected function getMemberFromData(array $data) { if (!empty($data['Email'])) { $uniqueIdentifier = Member::config()->get('unique_identifier_field'); return Member::get()->filter([$uniqueIdentifier => $data['Email']])->first(); } }
[ "protected", "function", "getMemberFromData", "(", "array", "$", "data", ")", "{", "if", "(", "!", "empty", "(", "$", "data", "[", "'Email'", "]", ")", ")", "{", "$", "uniqueIdentifier", "=", "Member", "::", "config", "(", ")", "->", "get", "(", "'unique_identifier_field'", ")", ";", "return", "Member", "::", "get", "(", ")", "->", "filter", "(", "[", "$", "uniqueIdentifier", "=>", "$", "data", "[", "'Email'", "]", "]", ")", "->", "first", "(", ")", ";", "}", "}" ]
Load an existing Member from the provided data @param array $data @return Member|null
[ "Load", "an", "existing", "Member", "from", "the", "provided", "data" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LostPasswordHandler.php#L218-L224
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
LostPasswordHandler.sendEmail
protected function sendEmail($member, $token) { /** @var Email $email */ $email = Email::create() ->setHTMLTemplate('SilverStripe\\Control\\Email\\ForgotPasswordEmail') ->setData($member) ->setSubject(_t( 'SilverStripe\\Security\\Member.SUBJECTPASSWORDRESET', "Your password reset link", 'Email subject' )) ->addData('PasswordResetLink', Security::getPasswordResetLink($member, $token)) ->setTo($member->Email); return $email->send(); }
php
protected function sendEmail($member, $token) { /** @var Email $email */ $email = Email::create() ->setHTMLTemplate('SilverStripe\\Control\\Email\\ForgotPasswordEmail') ->setData($member) ->setSubject(_t( 'SilverStripe\\Security\\Member.SUBJECTPASSWORDRESET', "Your password reset link", 'Email subject' )) ->addData('PasswordResetLink', Security::getPasswordResetLink($member, $token)) ->setTo($member->Email); return $email->send(); }
[ "protected", "function", "sendEmail", "(", "$", "member", ",", "$", "token", ")", "{", "/** @var Email $email */", "$", "email", "=", "Email", "::", "create", "(", ")", "->", "setHTMLTemplate", "(", "'SilverStripe\\\\Control\\\\Email\\\\ForgotPasswordEmail'", ")", "->", "setData", "(", "$", "member", ")", "->", "setSubject", "(", "_t", "(", "'SilverStripe\\\\Security\\\\Member.SUBJECTPASSWORDRESET'", ",", "\"Your password reset link\"", ",", "'Email subject'", ")", ")", "->", "addData", "(", "'PasswordResetLink'", ",", "Security", "::", "getPasswordResetLink", "(", "$", "member", ",", "$", "token", ")", ")", "->", "setTo", "(", "$", "member", "->", "Email", ")", ";", "return", "$", "email", "->", "send", "(", ")", ";", "}" ]
Send the email to the member that requested a reset link @param Member $member @param string $token @return bool
[ "Send", "the", "email", "to", "the", "member", "that", "requested", "a", "reset", "link" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LostPasswordHandler.php#L232-L246
train