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/View/SSViewer.php
SSViewer.flush_template_cache
public static function flush_template_cache($force = false) { if (!self::$template_cache_flushed || $force) { $dir = dir(TEMP_PATH); while (false !== ($file = $dir->read())) { if (strstr($file, '.cache')) { unlink(TEMP_PATH . DIRECTORY_SEPARATOR . $file); } } self::$template_cache_flushed = true; } }
php
public static function flush_template_cache($force = false) { if (!self::$template_cache_flushed || $force) { $dir = dir(TEMP_PATH); while (false !== ($file = $dir->read())) { if (strstr($file, '.cache')) { unlink(TEMP_PATH . DIRECTORY_SEPARATOR . $file); } } self::$template_cache_flushed = true; } }
[ "public", "static", "function", "flush_template_cache", "(", "$", "force", "=", "false", ")", "{", "if", "(", "!", "self", "::", "$", "template_cache_flushed", "||", "$", "force", ")", "{", "$", "dir", "=", "dir", "(", "TEMP_PATH", ")", ";", "while", "(", "false", "!==", "(", "$", "file", "=", "$", "dir", "->", "read", "(", ")", ")", ")", "{", "if", "(", "strstr", "(", "$", "file", ",", "'.cache'", ")", ")", "{", "unlink", "(", "TEMP_PATH", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ")", ";", "}", "}", "self", "::", "$", "template_cache_flushed", "=", "true", ";", "}", "}" ]
Clears all parsed template files in the cache folder. Can only be called once per request (there may be multiple SSViewer instances). @param bool $force Set this to true to force a re-flush. If left to false, flushing may only be performed once a request.
[ "Clears", "all", "parsed", "template", "files", "in", "the", "cache", "folder", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer.php#L505-L516
train
silverstripe/silverstripe-framework
src/View/SSViewer.php
SSViewer.flush_cacheblock_cache
public static function flush_cacheblock_cache($force = false) { if (!self::$cacheblock_cache_flushed || $force) { $cache = Injector::inst()->get(CacheInterface::class . '.cacheblock'); $cache->clear(); self::$cacheblock_cache_flushed = true; } }
php
public static function flush_cacheblock_cache($force = false) { if (!self::$cacheblock_cache_flushed || $force) { $cache = Injector::inst()->get(CacheInterface::class . '.cacheblock'); $cache->clear(); self::$cacheblock_cache_flushed = true; } }
[ "public", "static", "function", "flush_cacheblock_cache", "(", "$", "force", "=", "false", ")", "{", "if", "(", "!", "self", "::", "$", "cacheblock_cache_flushed", "||", "$", "force", ")", "{", "$", "cache", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "CacheInterface", "::", "class", ".", "'.cacheblock'", ")", ";", "$", "cache", "->", "clear", "(", ")", ";", "self", "::", "$", "cacheblock_cache_flushed", "=", "true", ";", "}", "}" ]
Clears all partial cache blocks. Can only be called once per request (there may be multiple SSViewer instances). @param bool $force Set this to true to force a re-flush. If left to false, flushing may only be performed once a request.
[ "Clears", "all", "partial", "cache", "blocks", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer.php#L526-L535
train
silverstripe/silverstripe-framework
src/View/SSViewer.php
SSViewer.includeGeneratedTemplate
protected function includeGeneratedTemplate($cacheFile, $item, $overlay, $underlay, $inheritedScope = null) { if (isset($_GET['showtemplate']) && $_GET['showtemplate'] && Permission::check('ADMIN')) { $lines = file($cacheFile); echo "<h2>Template: $cacheFile</h2>"; echo "<pre>"; foreach ($lines as $num => $line) { echo str_pad($num+1, 5) . htmlentities($line, ENT_COMPAT, 'UTF-8'); } echo "</pre>"; } $cache = $this->getPartialCacheStore(); $scope = new SSViewer_DataPresenter($item, $overlay, $underlay, $inheritedScope); $val = ''; // Placeholder for values exposed to $cacheFile [$cache, $scope, $val]; include($cacheFile); return $val; }
php
protected function includeGeneratedTemplate($cacheFile, $item, $overlay, $underlay, $inheritedScope = null) { if (isset($_GET['showtemplate']) && $_GET['showtemplate'] && Permission::check('ADMIN')) { $lines = file($cacheFile); echo "<h2>Template: $cacheFile</h2>"; echo "<pre>"; foreach ($lines as $num => $line) { echo str_pad($num+1, 5) . htmlentities($line, ENT_COMPAT, 'UTF-8'); } echo "</pre>"; } $cache = $this->getPartialCacheStore(); $scope = new SSViewer_DataPresenter($item, $overlay, $underlay, $inheritedScope); $val = ''; // Placeholder for values exposed to $cacheFile [$cache, $scope, $val]; include($cacheFile); return $val; }
[ "protected", "function", "includeGeneratedTemplate", "(", "$", "cacheFile", ",", "$", "item", ",", "$", "overlay", ",", "$", "underlay", ",", "$", "inheritedScope", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "_GET", "[", "'showtemplate'", "]", ")", "&&", "$", "_GET", "[", "'showtemplate'", "]", "&&", "Permission", "::", "check", "(", "'ADMIN'", ")", ")", "{", "$", "lines", "=", "file", "(", "$", "cacheFile", ")", ";", "echo", "\"<h2>Template: $cacheFile</h2>\"", ";", "echo", "\"<pre>\"", ";", "foreach", "(", "$", "lines", "as", "$", "num", "=>", "$", "line", ")", "{", "echo", "str_pad", "(", "$", "num", "+", "1", ",", "5", ")", ".", "htmlentities", "(", "$", "line", ",", "ENT_COMPAT", ",", "'UTF-8'", ")", ";", "}", "echo", "\"</pre>\"", ";", "}", "$", "cache", "=", "$", "this", "->", "getPartialCacheStore", "(", ")", ";", "$", "scope", "=", "new", "SSViewer_DataPresenter", "(", "$", "item", ",", "$", "overlay", ",", "$", "underlay", ",", "$", "inheritedScope", ")", ";", "$", "val", "=", "''", ";", "// Placeholder for values exposed to $cacheFile", "[", "$", "cache", ",", "$", "scope", ",", "$", "val", "]", ";", "include", "(", "$", "cacheFile", ")", ";", "return", "$", "val", ";", "}" ]
An internal utility function to set up variables in preparation for including a compiled template, then do the include Effectively this is the common code that both SSViewer#process and SSViewer_FromString#process call @param string $cacheFile The path to the file that contains the template compiled to PHP @param ViewableData $item The item to use as the root scope for the template @param array $overlay Any variables to layer on top of the scope @param array $underlay Any variables to layer underneath the scope @param ViewableData $inheritedScope The current scope of a parent template including a sub-template @return string The result of executing the template
[ "An", "internal", "utility", "function", "to", "set", "up", "variables", "in", "preparation", "for", "including", "a", "compiled", "template", "then", "do", "the", "include" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer.php#L584-L605
train
silverstripe/silverstripe-framework
src/View/SSViewer.php
SSViewer.getSubtemplateFor
protected function getSubtemplateFor($subtemplate) { // Get explicit subtemplate name if (isset($this->subTemplates[$subtemplate])) { return $this->subTemplates[$subtemplate]; } // Don't apply sub-templates if type is already specified (e.g. 'Includes') if (isset($this->templates['type'])) { return null; } // Filter out any other typed templates as we can only add, not change type $templates = array_filter( (array)$this->templates, function ($template) { return !isset($template['type']); } ); if (empty($templates)) { return null; } // Set type to subtemplate $templates['type'] = $subtemplate; return $templates; }
php
protected function getSubtemplateFor($subtemplate) { // Get explicit subtemplate name if (isset($this->subTemplates[$subtemplate])) { return $this->subTemplates[$subtemplate]; } // Don't apply sub-templates if type is already specified (e.g. 'Includes') if (isset($this->templates['type'])) { return null; } // Filter out any other typed templates as we can only add, not change type $templates = array_filter( (array)$this->templates, function ($template) { return !isset($template['type']); } ); if (empty($templates)) { return null; } // Set type to subtemplate $templates['type'] = $subtemplate; return $templates; }
[ "protected", "function", "getSubtemplateFor", "(", "$", "subtemplate", ")", "{", "// Get explicit subtemplate name", "if", "(", "isset", "(", "$", "this", "->", "subTemplates", "[", "$", "subtemplate", "]", ")", ")", "{", "return", "$", "this", "->", "subTemplates", "[", "$", "subtemplate", "]", ";", "}", "// Don't apply sub-templates if type is already specified (e.g. 'Includes')", "if", "(", "isset", "(", "$", "this", "->", "templates", "[", "'type'", "]", ")", ")", "{", "return", "null", ";", "}", "// Filter out any other typed templates as we can only add, not change type", "$", "templates", "=", "array_filter", "(", "(", "array", ")", "$", "this", "->", "templates", ",", "function", "(", "$", "template", ")", "{", "return", "!", "isset", "(", "$", "template", "[", "'type'", "]", ")", ";", "}", ")", ";", "if", "(", "empty", "(", "$", "templates", ")", ")", "{", "return", "null", ";", "}", "// Set type to subtemplate", "$", "templates", "[", "'type'", "]", "=", "$", "subtemplate", ";", "return", "$", "templates", ";", "}" ]
Get the appropriate template to use for the named sub-template, or null if none are appropriate @param string $subtemplate Sub-template to use @return array|null
[ "Get", "the", "appropriate", "template", "to", "use", "for", "the", "named", "sub", "-", "template", "or", "null", "if", "none", "are", "appropriate" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer.php#L712-L738
train
silverstripe/silverstripe-framework
src/View/SSViewer.php
SSViewer.execute_string
public static function execute_string($content, $data, $arguments = null, $globalRequirements = false) { $v = SSViewer::fromString($content); if ($globalRequirements) { $v->includeRequirements(false); } else { //nest a requirements backend for our template rendering $origBackend = Requirements::backend(); Requirements::set_backend(Requirements_Backend::create()); } try { return $v->process($data, $arguments); } finally { if (!$globalRequirements) { Requirements::set_backend($origBackend); } } }
php
public static function execute_string($content, $data, $arguments = null, $globalRequirements = false) { $v = SSViewer::fromString($content); if ($globalRequirements) { $v->includeRequirements(false); } else { //nest a requirements backend for our template rendering $origBackend = Requirements::backend(); Requirements::set_backend(Requirements_Backend::create()); } try { return $v->process($data, $arguments); } finally { if (!$globalRequirements) { Requirements::set_backend($origBackend); } } }
[ "public", "static", "function", "execute_string", "(", "$", "content", ",", "$", "data", ",", "$", "arguments", "=", "null", ",", "$", "globalRequirements", "=", "false", ")", "{", "$", "v", "=", "SSViewer", "::", "fromString", "(", "$", "content", ")", ";", "if", "(", "$", "globalRequirements", ")", "{", "$", "v", "->", "includeRequirements", "(", "false", ")", ";", "}", "else", "{", "//nest a requirements backend for our template rendering", "$", "origBackend", "=", "Requirements", "::", "backend", "(", ")", ";", "Requirements", "::", "set_backend", "(", "Requirements_Backend", "::", "create", "(", ")", ")", ";", "}", "try", "{", "return", "$", "v", "->", "process", "(", "$", "data", ",", "$", "arguments", ")", ";", "}", "finally", "{", "if", "(", "!", "$", "globalRequirements", ")", "{", "Requirements", "::", "set_backend", "(", "$", "origBackend", ")", ";", "}", "}", "}" ]
Execute the evaluated string, passing it the given data. Used by partial caching to evaluate custom cache keys expressed using template expressions @param string $content Input string @param mixed $data Data context @param array $arguments Additional arguments @param bool $globalRequirements @return string Evaluated result
[ "Execute", "the", "evaluated", "string", "passing", "it", "the", "given", "data", ".", "Used", "by", "partial", "caching", "to", "evaluate", "custom", "cache", "keys", "expressed", "using", "template", "expressions" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer.php#L784-L802
train
silverstripe/silverstripe-framework
src/View/SSViewer.php
SSViewer.parseTemplateContent
public function parseTemplateContent($content, $template = "") { return $this->getParser()->compileString( $content, $template, Director::isDev() && SSViewer::config()->uninherited('source_file_comments') ); }
php
public function parseTemplateContent($content, $template = "") { return $this->getParser()->compileString( $content, $template, Director::isDev() && SSViewer::config()->uninherited('source_file_comments') ); }
[ "public", "function", "parseTemplateContent", "(", "$", "content", ",", "$", "template", "=", "\"\"", ")", "{", "return", "$", "this", "->", "getParser", "(", ")", "->", "compileString", "(", "$", "content", ",", "$", "template", ",", "Director", "::", "isDev", "(", ")", "&&", "SSViewer", "::", "config", "(", ")", "->", "uninherited", "(", "'source_file_comments'", ")", ")", ";", "}" ]
Parse given template contents @param string $content The template contents @param string $template The template file name @return string
[ "Parse", "given", "template", "contents" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer.php#L811-L818
train
silverstripe/silverstripe-framework
src/Dev/FixtureFactory.php
FixtureFactory.createObject
public function createObject($name, $identifier, $data = null) { if (!isset($this->blueprints[$name])) { $this->blueprints[$name] = new FixtureBlueprint($name); } $blueprint = $this->blueprints[$name]; $obj = $blueprint->createObject($identifier, $data, $this->fixtures); $class = $blueprint->getClass(); if (!isset($this->fixtures[$class])) { $this->fixtures[$class] = array(); } $this->fixtures[$class][$identifier] = $obj->ID; return $obj; }
php
public function createObject($name, $identifier, $data = null) { if (!isset($this->blueprints[$name])) { $this->blueprints[$name] = new FixtureBlueprint($name); } $blueprint = $this->blueprints[$name]; $obj = $blueprint->createObject($identifier, $data, $this->fixtures); $class = $blueprint->getClass(); if (!isset($this->fixtures[$class])) { $this->fixtures[$class] = array(); } $this->fixtures[$class][$identifier] = $obj->ID; return $obj; }
[ "public", "function", "createObject", "(", "$", "name", ",", "$", "identifier", ",", "$", "data", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "blueprints", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "blueprints", "[", "$", "name", "]", "=", "new", "FixtureBlueprint", "(", "$", "name", ")", ";", "}", "$", "blueprint", "=", "$", "this", "->", "blueprints", "[", "$", "name", "]", ";", "$", "obj", "=", "$", "blueprint", "->", "createObject", "(", "$", "identifier", ",", "$", "data", ",", "$", "this", "->", "fixtures", ")", ";", "$", "class", "=", "$", "blueprint", "->", "getClass", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "fixtures", "[", "$", "class", "]", ")", ")", "{", "$", "this", "->", "fixtures", "[", "$", "class", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "fixtures", "[", "$", "class", "]", "[", "$", "identifier", "]", "=", "$", "obj", "->", "ID", ";", "return", "$", "obj", ";", "}" ]
Writes the fixture into the database using DataObjects @param string $name Name of the {@link FixtureBlueprint} to use, usually a DataObject subclass. @param string $identifier Unique identifier for this fixture type @param array $data Map of properties. Overrides default data. @return DataObject
[ "Writes", "the", "fixture", "into", "the", "database", "using", "DataObjects" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/FixtureFactory.php#L79-L94
train
silverstripe/silverstripe-framework
src/Dev/FixtureFactory.php
FixtureFactory.createRaw
public function createRaw($table, $identifier, $data) { $fields = array(); foreach ($data as $fieldName => $fieldVal) { $fields["\"{$fieldName}\""] = $this->parseValue($fieldVal); } $insert = new SQLInsert("\"{$table}\"", $fields); $insert->execute(); $id = DB::get_generated_id($table); $this->fixtures[$table][$identifier] = $id; return $id; }
php
public function createRaw($table, $identifier, $data) { $fields = array(); foreach ($data as $fieldName => $fieldVal) { $fields["\"{$fieldName}\""] = $this->parseValue($fieldVal); } $insert = new SQLInsert("\"{$table}\"", $fields); $insert->execute(); $id = DB::get_generated_id($table); $this->fixtures[$table][$identifier] = $id; return $id; }
[ "public", "function", "createRaw", "(", "$", "table", ",", "$", "identifier", ",", "$", "data", ")", "{", "$", "fields", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "fieldName", "=>", "$", "fieldVal", ")", "{", "$", "fields", "[", "\"\\\"{$fieldName}\\\"\"", "]", "=", "$", "this", "->", "parseValue", "(", "$", "fieldVal", ")", ";", "}", "$", "insert", "=", "new", "SQLInsert", "(", "\"\\\"{$table}\\\"\"", ",", "$", "fields", ")", ";", "$", "insert", "->", "execute", "(", ")", ";", "$", "id", "=", "DB", "::", "get_generated_id", "(", "$", "table", ")", ";", "$", "this", "->", "fixtures", "[", "$", "table", "]", "[", "$", "identifier", "]", "=", "$", "id", ";", "return", "$", "id", ";", "}" ]
Writes the fixture into the database directly using a database manipulation. Does not use blueprints. Only supports tables with a primary key. @param string $table Existing database table name @param string $identifier Unique identifier for this fixture type @param array $data Map of properties @return int Database identifier
[ "Writes", "the", "fixture", "into", "the", "database", "directly", "using", "a", "database", "manipulation", ".", "Does", "not", "use", "blueprints", ".", "Only", "supports", "tables", "with", "a", "primary", "key", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/FixtureFactory.php#L105-L117
train
silverstripe/silverstripe-framework
src/Dev/FixtureFactory.php
FixtureFactory.getId
public function getId($class, $identifier) { if (isset($this->fixtures[$class][$identifier])) { return $this->fixtures[$class][$identifier]; } else { return false; } }
php
public function getId($class, $identifier) { if (isset($this->fixtures[$class][$identifier])) { return $this->fixtures[$class][$identifier]; } else { return false; } }
[ "public", "function", "getId", "(", "$", "class", ",", "$", "identifier", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "fixtures", "[", "$", "class", "]", "[", "$", "identifier", "]", ")", ")", "{", "return", "$", "this", "->", "fixtures", "[", "$", "class", "]", "[", "$", "identifier", "]", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Get the ID of an object from the fixture. @param string $class The data class, as specified in your fixture file. Parent classes won't work @param string $identifier The identifier string, as provided in your fixture file @return int
[ "Get", "the", "ID", "of", "an", "object", "from", "the", "fixture", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/FixtureFactory.php#L126-L133
train
silverstripe/silverstripe-framework
src/Dev/FixtureFactory.php
FixtureFactory.get
public function get($class, $identifier) { $id = $this->getId($class, $identifier); if (!$id) { return null; } // If the class doesn't exist, look for a table instead if (!class_exists($class)) { $tableNames = DataObject::getSchema()->getTableNames(); $potential = array_search($class, $tableNames); if (!$potential) { throw new \LogicException("'$class' is neither a class nor a table name"); } $class = $potential; } return DataObject::get_by_id($class, $id); }
php
public function get($class, $identifier) { $id = $this->getId($class, $identifier); if (!$id) { return null; } // If the class doesn't exist, look for a table instead if (!class_exists($class)) { $tableNames = DataObject::getSchema()->getTableNames(); $potential = array_search($class, $tableNames); if (!$potential) { throw new \LogicException("'$class' is neither a class nor a table name"); } $class = $potential; } return DataObject::get_by_id($class, $id); }
[ "public", "function", "get", "(", "$", "class", ",", "$", "identifier", ")", "{", "$", "id", "=", "$", "this", "->", "getId", "(", "$", "class", ",", "$", "identifier", ")", ";", "if", "(", "!", "$", "id", ")", "{", "return", "null", ";", "}", "// If the class doesn't exist, look for a table instead", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "{", "$", "tableNames", "=", "DataObject", "::", "getSchema", "(", ")", "->", "getTableNames", "(", ")", ";", "$", "potential", "=", "array_search", "(", "$", "class", ",", "$", "tableNames", ")", ";", "if", "(", "!", "$", "potential", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"'$class' is neither a class nor a table name\"", ")", ";", "}", "$", "class", "=", "$", "potential", ";", "}", "return", "DataObject", "::", "get_by_id", "(", "$", "class", ",", "$", "id", ")", ";", "}" ]
Get an object from the fixture. @param string $class The data class or table name, as specified in your fixture file. Parent classes won't work @param string $identifier The identifier string, as provided in your fixture file @return DataObject
[ "Get", "an", "object", "from", "the", "fixture", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/FixtureFactory.php#L169-L187
train
silverstripe/silverstripe-framework
src/Core/TempFolder.php
TempFolder.getTempFolder
public static function getTempFolder($base) { $parent = static::getTempParentFolder($base); // The actual temp folder is a subfolder of getTempParentFolder(), named by username $subfolder = Path::join($parent, static::getTempFolderUsername()); if (!@file_exists($subfolder)) { mkdir($subfolder); } return $subfolder; }
php
public static function getTempFolder($base) { $parent = static::getTempParentFolder($base); // The actual temp folder is a subfolder of getTempParentFolder(), named by username $subfolder = Path::join($parent, static::getTempFolderUsername()); if (!@file_exists($subfolder)) { mkdir($subfolder); } return $subfolder; }
[ "public", "static", "function", "getTempFolder", "(", "$", "base", ")", "{", "$", "parent", "=", "static", "::", "getTempParentFolder", "(", "$", "base", ")", ";", "// The actual temp folder is a subfolder of getTempParentFolder(), named by username", "$", "subfolder", "=", "Path", "::", "join", "(", "$", "parent", ",", "static", "::", "getTempFolderUsername", "(", ")", ")", ";", "if", "(", "!", "@", "file_exists", "(", "$", "subfolder", ")", ")", "{", "mkdir", "(", "$", "subfolder", ")", ";", "}", "return", "$", "subfolder", ";", "}" ]
Returns the temporary folder path that silverstripe should use for its cache files. @param string $base The base path to use for determining the temporary path @return string Path to temp
[ "Returns", "the", "temporary", "folder", "path", "that", "silverstripe", "should", "use", "for", "its", "cache", "files", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/TempFolder.php#L18-L30
train
silverstripe/silverstripe-framework
src/Core/TempFolder.php
TempFolder.getTempFolderUsername
public static function getTempFolderUsername() { $user = Environment::getEnv('APACHE_RUN_USER'); if (!$user) { $user = Environment::getEnv('USER'); } if (!$user) { $user = Environment::getEnv('USERNAME'); } if (!$user && function_exists('posix_getpwuid') && function_exists('posix_getuid')) { $userDetails = posix_getpwuid(posix_getuid()); $user = $userDetails['name']; } if (!$user) { $user = 'unknown'; } $user = preg_replace('/[^A-Za-z0-9_\-]/', '', $user); return $user; }
php
public static function getTempFolderUsername() { $user = Environment::getEnv('APACHE_RUN_USER'); if (!$user) { $user = Environment::getEnv('USER'); } if (!$user) { $user = Environment::getEnv('USERNAME'); } if (!$user && function_exists('posix_getpwuid') && function_exists('posix_getuid')) { $userDetails = posix_getpwuid(posix_getuid()); $user = $userDetails['name']; } if (!$user) { $user = 'unknown'; } $user = preg_replace('/[^A-Za-z0-9_\-]/', '', $user); return $user; }
[ "public", "static", "function", "getTempFolderUsername", "(", ")", "{", "$", "user", "=", "Environment", "::", "getEnv", "(", "'APACHE_RUN_USER'", ")", ";", "if", "(", "!", "$", "user", ")", "{", "$", "user", "=", "Environment", "::", "getEnv", "(", "'USER'", ")", ";", "}", "if", "(", "!", "$", "user", ")", "{", "$", "user", "=", "Environment", "::", "getEnv", "(", "'USERNAME'", ")", ";", "}", "if", "(", "!", "$", "user", "&&", "function_exists", "(", "'posix_getpwuid'", ")", "&&", "function_exists", "(", "'posix_getuid'", ")", ")", "{", "$", "userDetails", "=", "posix_getpwuid", "(", "posix_getuid", "(", ")", ")", ";", "$", "user", "=", "$", "userDetails", "[", "'name'", "]", ";", "}", "if", "(", "!", "$", "user", ")", "{", "$", "user", "=", "'unknown'", ";", "}", "$", "user", "=", "preg_replace", "(", "'/[^A-Za-z0-9_\\-]/'", ",", "''", ",", "$", "user", ")", ";", "return", "$", "user", ";", "}" ]
Returns as best a representation of the current username as we can glean. @return string
[ "Returns", "as", "best", "a", "representation", "of", "the", "current", "username", "as", "we", "can", "glean", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/TempFolder.php#L37-L55
train
silverstripe/silverstripe-framework
src/Core/TempFolder.php
TempFolder.getTempParentFolder
protected static function getTempParentFolder($base) { // first, try finding a silverstripe-cache dir built off the base path $localPath = Path::join($base, 'silverstripe-cache'); if (@file_exists($localPath)) { if ((fileperms($localPath) & 0777) != 0777) { @chmod($localPath, 0777); } return $localPath; } // failing the above, try finding a namespaced silverstripe-cache dir in the system temp $tempPath = Path::join( sys_get_temp_dir(), 'silverstripe-cache-php' . preg_replace('/[^\w\-\.+]+/', '-', PHP_VERSION) . str_replace(array(' ', '/', ':', '\\'), '-', $base) ); if (!@file_exists($tempPath)) { $oldUMask = umask(0); @mkdir($tempPath, 0777); umask($oldUMask); // if the folder already exists, correct perms } else { if ((fileperms($tempPath) & 0777) != 0777) { @chmod($tempPath, 0777); } } $worked = @file_exists($tempPath) && @is_writable($tempPath); // failing to use the system path, attempt to create a local silverstripe-cache dir if (!$worked) { $tempPath = $localPath; if (!@file_exists($tempPath)) { $oldUMask = umask(0); @mkdir($tempPath, 0777); umask($oldUMask); } $worked = @file_exists($tempPath) && @is_writable($tempPath); } if (!$worked) { throw new Exception( 'Permission problem gaining access to a temp folder. ' . 'Please create a folder named silverstripe-cache in the base folder ' . 'of the installation and ensure it has the correct permissions' ); } return $tempPath; }
php
protected static function getTempParentFolder($base) { // first, try finding a silverstripe-cache dir built off the base path $localPath = Path::join($base, 'silverstripe-cache'); if (@file_exists($localPath)) { if ((fileperms($localPath) & 0777) != 0777) { @chmod($localPath, 0777); } return $localPath; } // failing the above, try finding a namespaced silverstripe-cache dir in the system temp $tempPath = Path::join( sys_get_temp_dir(), 'silverstripe-cache-php' . preg_replace('/[^\w\-\.+]+/', '-', PHP_VERSION) . str_replace(array(' ', '/', ':', '\\'), '-', $base) ); if (!@file_exists($tempPath)) { $oldUMask = umask(0); @mkdir($tempPath, 0777); umask($oldUMask); // if the folder already exists, correct perms } else { if ((fileperms($tempPath) & 0777) != 0777) { @chmod($tempPath, 0777); } } $worked = @file_exists($tempPath) && @is_writable($tempPath); // failing to use the system path, attempt to create a local silverstripe-cache dir if (!$worked) { $tempPath = $localPath; if (!@file_exists($tempPath)) { $oldUMask = umask(0); @mkdir($tempPath, 0777); umask($oldUMask); } $worked = @file_exists($tempPath) && @is_writable($tempPath); } if (!$worked) { throw new Exception( 'Permission problem gaining access to a temp folder. ' . 'Please create a folder named silverstripe-cache in the base folder ' . 'of the installation and ensure it has the correct permissions' ); } return $tempPath; }
[ "protected", "static", "function", "getTempParentFolder", "(", "$", "base", ")", "{", "// first, try finding a silverstripe-cache dir built off the base path", "$", "localPath", "=", "Path", "::", "join", "(", "$", "base", ",", "'silverstripe-cache'", ")", ";", "if", "(", "@", "file_exists", "(", "$", "localPath", ")", ")", "{", "if", "(", "(", "fileperms", "(", "$", "localPath", ")", "&", "0777", ")", "!=", "0777", ")", "{", "@", "chmod", "(", "$", "localPath", ",", "0777", ")", ";", "}", "return", "$", "localPath", ";", "}", "// failing the above, try finding a namespaced silverstripe-cache dir in the system temp", "$", "tempPath", "=", "Path", "::", "join", "(", "sys_get_temp_dir", "(", ")", ",", "'silverstripe-cache-php'", ".", "preg_replace", "(", "'/[^\\w\\-\\.+]+/'", ",", "'-'", ",", "PHP_VERSION", ")", ".", "str_replace", "(", "array", "(", "' '", ",", "'/'", ",", "':'", ",", "'\\\\'", ")", ",", "'-'", ",", "$", "base", ")", ")", ";", "if", "(", "!", "@", "file_exists", "(", "$", "tempPath", ")", ")", "{", "$", "oldUMask", "=", "umask", "(", "0", ")", ";", "@", "mkdir", "(", "$", "tempPath", ",", "0777", ")", ";", "umask", "(", "$", "oldUMask", ")", ";", "// if the folder already exists, correct perms", "}", "else", "{", "if", "(", "(", "fileperms", "(", "$", "tempPath", ")", "&", "0777", ")", "!=", "0777", ")", "{", "@", "chmod", "(", "$", "tempPath", ",", "0777", ")", ";", "}", "}", "$", "worked", "=", "@", "file_exists", "(", "$", "tempPath", ")", "&&", "@", "is_writable", "(", "$", "tempPath", ")", ";", "// failing to use the system path, attempt to create a local silverstripe-cache dir", "if", "(", "!", "$", "worked", ")", "{", "$", "tempPath", "=", "$", "localPath", ";", "if", "(", "!", "@", "file_exists", "(", "$", "tempPath", ")", ")", "{", "$", "oldUMask", "=", "umask", "(", "0", ")", ";", "@", "mkdir", "(", "$", "tempPath", ",", "0777", ")", ";", "umask", "(", "$", "oldUMask", ")", ";", "}", "$", "worked", "=", "@", "file_exists", "(", "$", "tempPath", ")", "&&", "@", "is_writable", "(", "$", "tempPath", ")", ";", "}", "if", "(", "!", "$", "worked", ")", "{", "throw", "new", "Exception", "(", "'Permission problem gaining access to a temp folder. '", ".", "'Please create a folder named silverstripe-cache in the base folder '", ".", "'of the installation and ensure it has the correct permissions'", ")", ";", "}", "return", "$", "tempPath", ";", "}" ]
Return the parent folder of the temp folder. The temp folder will be a subfolder of this, named by username. This structure prevents permission problems. @param string $base @return string @throws Exception
[ "Return", "the", "parent", "folder", "of", "the", "temp", "folder", ".", "The", "temp", "folder", "will", "be", "a", "subfolder", "of", "this", "named", "by", "username", ".", "This", "structure", "prevents", "permission", "problems", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/TempFolder.php#L66-L116
train
silverstripe/silverstripe-framework
src/i18n/Data/Sources.php
Sources.getSortedModules
public function getSortedModules() { $i18nOrder = Sources::config()->uninherited('module_priority'); $sortedModules = []; if ($i18nOrder) { Deprecation::notice('5.0', sprintf( '%s.module_priority is deprecated. Use %s.module_priority instead.', __CLASS__, ModuleManifest::class )); } foreach (ModuleLoader::inst()->getManifest()->getModules() as $module) { $sortedModules[$module->getName()] = $module->getPath(); }; return $sortedModules; }
php
public function getSortedModules() { $i18nOrder = Sources::config()->uninherited('module_priority'); $sortedModules = []; if ($i18nOrder) { Deprecation::notice('5.0', sprintf( '%s.module_priority is deprecated. Use %s.module_priority instead.', __CLASS__, ModuleManifest::class )); } foreach (ModuleLoader::inst()->getManifest()->getModules() as $module) { $sortedModules[$module->getName()] = $module->getPath(); }; return $sortedModules; }
[ "public", "function", "getSortedModules", "(", ")", "{", "$", "i18nOrder", "=", "Sources", "::", "config", "(", ")", "->", "uninherited", "(", "'module_priority'", ")", ";", "$", "sortedModules", "=", "[", "]", ";", "if", "(", "$", "i18nOrder", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "sprintf", "(", "'%s.module_priority is deprecated. Use %s.module_priority instead.'", ",", "__CLASS__", ",", "ModuleManifest", "::", "class", ")", ")", ";", "}", "foreach", "(", "ModuleLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getModules", "(", ")", "as", "$", "module", ")", "{", "$", "sortedModules", "[", "$", "module", "->", "getName", "(", ")", "]", "=", "$", "module", "->", "getPath", "(", ")", ";", "}", ";", "return", "$", "sortedModules", ";", "}" ]
Get sorted modules @return array Array of module names -> path
[ "Get", "sorted", "modules" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/Data/Sources.php#L37-L54
train
silverstripe/silverstripe-framework
src/i18n/Data/Sources.php
Sources.getLangFiles
protected function getLangFiles() { if (static::$cache_lang_files) { return static::$cache_lang_files; } $locales = []; foreach ($this->getLangDirs() as $langPath) { $langFiles = scandir($langPath); foreach ($langFiles as $langFile) { $locale = pathinfo($langFile, PATHINFO_FILENAME); $ext = pathinfo($langFile, PATHINFO_EXTENSION); if ($locale && $ext === 'yml') { $locales[$locale] = $locale; } } } ksort($locales); static::$cache_lang_files = $locales; return $locales; }
php
protected function getLangFiles() { if (static::$cache_lang_files) { return static::$cache_lang_files; } $locales = []; foreach ($this->getLangDirs() as $langPath) { $langFiles = scandir($langPath); foreach ($langFiles as $langFile) { $locale = pathinfo($langFile, PATHINFO_FILENAME); $ext = pathinfo($langFile, PATHINFO_EXTENSION); if ($locale && $ext === 'yml') { $locales[$locale] = $locale; } } } ksort($locales); static::$cache_lang_files = $locales; return $locales; }
[ "protected", "function", "getLangFiles", "(", ")", "{", "if", "(", "static", "::", "$", "cache_lang_files", ")", "{", "return", "static", "::", "$", "cache_lang_files", ";", "}", "$", "locales", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getLangDirs", "(", ")", "as", "$", "langPath", ")", "{", "$", "langFiles", "=", "scandir", "(", "$", "langPath", ")", ";", "foreach", "(", "$", "langFiles", "as", "$", "langFile", ")", "{", "$", "locale", "=", "pathinfo", "(", "$", "langFile", ",", "PATHINFO_FILENAME", ")", ";", "$", "ext", "=", "pathinfo", "(", "$", "langFile", ",", "PATHINFO_EXTENSION", ")", ";", "if", "(", "$", "locale", "&&", "$", "ext", "===", "'yml'", ")", "{", "$", "locales", "[", "$", "locale", "]", "=", "$", "locale", ";", "}", "}", "}", "ksort", "(", "$", "locales", ")", ";", "static", "::", "$", "cache_lang_files", "=", "$", "locales", ";", "return", "$", "locales", ";", "}" ]
Search directories for list of distinct locale filenames @return array Map of locale key => key of all distinct localisation file names
[ "Search", "directories", "for", "list", "of", "distinct", "locale", "filenames" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/Data/Sources.php#L111-L131
train
silverstripe/silverstripe-framework
src/Core/Injector/InjectorLoader.php
InjectorLoader.getManifest
public function getManifest() { if ($this !== self::$instance) { throw new BadMethodCallException( "Non-current injector manifest cannot be accessed. Please call ->activate() first" ); } if (empty($this->manifests)) { throw new BadMethodCallException("No injector manifests available"); } return $this->manifests[count($this->manifests) - 1]; }
php
public function getManifest() { if ($this !== self::$instance) { throw new BadMethodCallException( "Non-current injector manifest cannot be accessed. Please call ->activate() first" ); } if (empty($this->manifests)) { throw new BadMethodCallException("No injector manifests available"); } return $this->manifests[count($this->manifests) - 1]; }
[ "public", "function", "getManifest", "(", ")", "{", "if", "(", "$", "this", "!==", "self", "::", "$", "instance", ")", "{", "throw", "new", "BadMethodCallException", "(", "\"Non-current injector manifest cannot be accessed. Please call ->activate() first\"", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "manifests", ")", ")", "{", "throw", "new", "BadMethodCallException", "(", "\"No injector manifests available\"", ")", ";", "}", "return", "$", "this", "->", "manifests", "[", "count", "(", "$", "this", "->", "manifests", ")", "-", "1", "]", ";", "}" ]
Returns the currently active class manifest instance that is used for loading classes. @return Injector
[ "Returns", "the", "currently", "active", "class", "manifest", "instance", "that", "is", "used", "for", "loading", "classes", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Injector/InjectorLoader.php#L37-L48
train
silverstripe/silverstripe-framework
src/Forms/CheckboxField.php
CheckboxField.performReadonlyTransformation
public function performReadonlyTransformation() { $field = new CheckboxField_Readonly($this->name, $this->title, $this->value); $field->setForm($this->form); return $field; }
php
public function performReadonlyTransformation() { $field = new CheckboxField_Readonly($this->name, $this->title, $this->value); $field->setForm($this->form); return $field; }
[ "public", "function", "performReadonlyTransformation", "(", ")", "{", "$", "field", "=", "new", "CheckboxField_Readonly", "(", "$", "this", "->", "name", ",", "$", "this", "->", "title", ",", "$", "this", "->", "value", ")", ";", "$", "field", "->", "setForm", "(", "$", "this", "->", "form", ")", ";", "return", "$", "field", ";", "}" ]
Returns a readonly version of this field
[ "Returns", "a", "readonly", "version", "of", "this", "field" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/CheckboxField.php#L51-L56
train
silverstripe/silverstripe-framework
src/Forms/GroupedDropdownField.php
GroupedDropdownField.getFieldOption
protected function getFieldOption($valueOrGroup, $titleOrOptions) { // Return flat option if (!is_array($titleOrOptions)) { return parent::getFieldOption($valueOrGroup, $titleOrOptions); } // Build children from options list $options = new ArrayList(); foreach ($titleOrOptions as $childValue => $childTitle) { $options->push($this->getFieldOption($childValue, $childTitle)); } return new ArrayData(array( 'Title' => $valueOrGroup, 'Options' => $options )); }
php
protected function getFieldOption($valueOrGroup, $titleOrOptions) { // Return flat option if (!is_array($titleOrOptions)) { return parent::getFieldOption($valueOrGroup, $titleOrOptions); } // Build children from options list $options = new ArrayList(); foreach ($titleOrOptions as $childValue => $childTitle) { $options->push($this->getFieldOption($childValue, $childTitle)); } return new ArrayData(array( 'Title' => $valueOrGroup, 'Options' => $options )); }
[ "protected", "function", "getFieldOption", "(", "$", "valueOrGroup", ",", "$", "titleOrOptions", ")", "{", "// Return flat option", "if", "(", "!", "is_array", "(", "$", "titleOrOptions", ")", ")", "{", "return", "parent", "::", "getFieldOption", "(", "$", "valueOrGroup", ",", "$", "titleOrOptions", ")", ";", "}", "// Build children from options list", "$", "options", "=", "new", "ArrayList", "(", ")", ";", "foreach", "(", "$", "titleOrOptions", "as", "$", "childValue", "=>", "$", "childTitle", ")", "{", "$", "options", "->", "push", "(", "$", "this", "->", "getFieldOption", "(", "$", "childValue", ",", "$", "childTitle", ")", ")", ";", "}", "return", "new", "ArrayData", "(", "array", "(", "'Title'", "=>", "$", "valueOrGroup", ",", "'Options'", "=>", "$", "options", ")", ")", ";", "}" ]
Build a potentially nested fieldgroup @param mixed $valueOrGroup Value of item, or title of group @param string|array $titleOrOptions Title of item, or options in grouip @return ArrayData Data for this item
[ "Build", "a", "potentially", "nested", "fieldgroup" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GroupedDropdownField.php#L69-L86
train
silverstripe/silverstripe-framework
src/Core/EnvironmentLoader.php
EnvironmentLoader.loadFile
public function loadFile($path, $overload = false) { // Not readable if (!file_exists($path) || !is_readable($path)) { return null; } // Parse and cleanup content $result = []; $variables = Parser::parse(file_get_contents($path)); foreach ($variables as $name => $value) { // Conditionally prevent overloading if (!$overload) { $existing = Environment::getEnv($name); if ($existing !== false) { $result[$name] = $existing; continue; } } // Overload or create var Environment::setEnv($name, $value); $result[$name] = $value; } return $result; }
php
public function loadFile($path, $overload = false) { // Not readable if (!file_exists($path) || !is_readable($path)) { return null; } // Parse and cleanup content $result = []; $variables = Parser::parse(file_get_contents($path)); foreach ($variables as $name => $value) { // Conditionally prevent overloading if (!$overload) { $existing = Environment::getEnv($name); if ($existing !== false) { $result[$name] = $existing; continue; } } // Overload or create var Environment::setEnv($name, $value); $result[$name] = $value; } return $result; }
[ "public", "function", "loadFile", "(", "$", "path", ",", "$", "overload", "=", "false", ")", "{", "// Not readable", "if", "(", "!", "file_exists", "(", "$", "path", ")", "||", "!", "is_readable", "(", "$", "path", ")", ")", "{", "return", "null", ";", "}", "// Parse and cleanup content", "$", "result", "=", "[", "]", ";", "$", "variables", "=", "Parser", "::", "parse", "(", "file_get_contents", "(", "$", "path", ")", ")", ";", "foreach", "(", "$", "variables", "as", "$", "name", "=>", "$", "value", ")", "{", "// Conditionally prevent overloading", "if", "(", "!", "$", "overload", ")", "{", "$", "existing", "=", "Environment", "::", "getEnv", "(", "$", "name", ")", ";", "if", "(", "$", "existing", "!==", "false", ")", "{", "$", "result", "[", "$", "name", "]", "=", "$", "existing", ";", "continue", ";", "}", "}", "// Overload or create var", "Environment", "::", "setEnv", "(", "$", "name", ",", "$", "value", ")", ";", "$", "result", "[", "$", "name", "]", "=", "$", "value", ";", "}", "return", "$", "result", ";", "}" ]
Load environment variables from .env file @param string $path Path to the file @param bool $overload Set to true to allow vars to overload. Recommended to leave false. @return array|null List of values parsed as an associative array, or null if not loaded If overloading, this list will reflect the final state for all variables
[ "Load", "environment", "variables", "from", ".", "env", "file" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/EnvironmentLoader.php#L21-L46
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
GridFieldFilterHeader.handleAction
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if (!$this->checkDataType($gridField->getList())) { return; } $state = $gridField->State->GridFieldFilterHeader; $state->Columns = null; if ($actionName === 'filter') { if (isset($data['filter'][$gridField->getName()])) { foreach ($data['filter'][$gridField->getName()] as $key => $filter) { $state->Columns->$key = $filter; } } } }
php
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if (!$this->checkDataType($gridField->getList())) { return; } $state = $gridField->State->GridFieldFilterHeader; $state->Columns = null; if ($actionName === 'filter') { if (isset($data['filter'][$gridField->getName()])) { foreach ($data['filter'][$gridField->getName()] as $key => $filter) { $state->Columns->$key = $filter; } } } }
[ "public", "function", "handleAction", "(", "GridField", "$", "gridField", ",", "$", "actionName", ",", "$", "arguments", ",", "$", "data", ")", "{", "if", "(", "!", "$", "this", "->", "checkDataType", "(", "$", "gridField", "->", "getList", "(", ")", ")", ")", "{", "return", ";", "}", "$", "state", "=", "$", "gridField", "->", "State", "->", "GridFieldFilterHeader", ";", "$", "state", "->", "Columns", "=", "null", ";", "if", "(", "$", "actionName", "===", "'filter'", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'filter'", "]", "[", "$", "gridField", "->", "getName", "(", ")", "]", ")", ")", "{", "foreach", "(", "$", "data", "[", "'filter'", "]", "[", "$", "gridField", "->", "getName", "(", ")", "]", "as", "$", "key", "=>", "$", "filter", ")", "{", "$", "state", "->", "Columns", "->", "$", "key", "=", "$", "filter", ";", "}", "}", "}", "}" ]
If the GridField has a filterable datalist, return an array of actions @param GridField $gridField @return void
[ "If", "the", "GridField", "has", "a", "filterable", "datalist", "return", "an", "array", "of", "actions" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldFilterHeader.php#L170-L185
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
GridFieldFilterHeader.getSearchFieldSchema
public function getSearchFieldSchema(GridField $gridField) { $schemaUrl = Controller::join_links($gridField->Link(), 'schema/SearchForm'); $context = $this->getSearchContext($gridField); $params = $gridField->getRequest()->postVar('filter') ?: []; if (array_key_exists($gridField->getName(), $params)) { $params = $params[$gridField->getName()]; } if ($context->getSearchParams()) { $params = array_merge($context->getSearchParams(), $params); } $context->setSearchParams($params); $searchField = $context->getSearchFields()->first(); $searchField = $searchField && property_exists($searchField, 'name') ? $searchField->name : null; $name = $gridField->Title ?: singleton($gridField->getModelClass())->i18n_plural_name(); // Prefix "Search__" onto the filters for the React component $filters = $context->getSearchParams(); if (!$this->useLegacyFilterHeader && !empty($filters)) { $filters = array_combine(array_map(function ($key) { return 'Search__' . $key; }, array_keys($filters)), $filters); } $searchAction = GridField_FormAction::create($gridField, 'filter', false, 'filter', null); $clearAction = GridField_FormAction::create($gridField, 'reset', false, 'reset', null); $schema = [ 'formSchemaUrl' => $schemaUrl, 'name' => $searchField, 'placeholder' => _t(__CLASS__ . '.Search', 'Search "{name}"', ['name' => $name]), 'filters' => $filters ?: new \stdClass, // stdClass maps to empty json object '{}' 'gridfield' => $gridField->getName(), 'searchAction' => $searchAction->getAttribute('name'), 'searchActionState' => $searchAction->getAttribute('data-action-state'), 'clearAction' => $clearAction->getAttribute('name'), 'clearActionState' => $clearAction->getAttribute('data-action-state'), ]; return json_encode($schema); }
php
public function getSearchFieldSchema(GridField $gridField) { $schemaUrl = Controller::join_links($gridField->Link(), 'schema/SearchForm'); $context = $this->getSearchContext($gridField); $params = $gridField->getRequest()->postVar('filter') ?: []; if (array_key_exists($gridField->getName(), $params)) { $params = $params[$gridField->getName()]; } if ($context->getSearchParams()) { $params = array_merge($context->getSearchParams(), $params); } $context->setSearchParams($params); $searchField = $context->getSearchFields()->first(); $searchField = $searchField && property_exists($searchField, 'name') ? $searchField->name : null; $name = $gridField->Title ?: singleton($gridField->getModelClass())->i18n_plural_name(); // Prefix "Search__" onto the filters for the React component $filters = $context->getSearchParams(); if (!$this->useLegacyFilterHeader && !empty($filters)) { $filters = array_combine(array_map(function ($key) { return 'Search__' . $key; }, array_keys($filters)), $filters); } $searchAction = GridField_FormAction::create($gridField, 'filter', false, 'filter', null); $clearAction = GridField_FormAction::create($gridField, 'reset', false, 'reset', null); $schema = [ 'formSchemaUrl' => $schemaUrl, 'name' => $searchField, 'placeholder' => _t(__CLASS__ . '.Search', 'Search "{name}"', ['name' => $name]), 'filters' => $filters ?: new \stdClass, // stdClass maps to empty json object '{}' 'gridfield' => $gridField->getName(), 'searchAction' => $searchAction->getAttribute('name'), 'searchActionState' => $searchAction->getAttribute('data-action-state'), 'clearAction' => $clearAction->getAttribute('name'), 'clearActionState' => $clearAction->getAttribute('data-action-state'), ]; return json_encode($schema); }
[ "public", "function", "getSearchFieldSchema", "(", "GridField", "$", "gridField", ")", "{", "$", "schemaUrl", "=", "Controller", "::", "join_links", "(", "$", "gridField", "->", "Link", "(", ")", ",", "'schema/SearchForm'", ")", ";", "$", "context", "=", "$", "this", "->", "getSearchContext", "(", "$", "gridField", ")", ";", "$", "params", "=", "$", "gridField", "->", "getRequest", "(", ")", "->", "postVar", "(", "'filter'", ")", "?", ":", "[", "]", ";", "if", "(", "array_key_exists", "(", "$", "gridField", "->", "getName", "(", ")", ",", "$", "params", ")", ")", "{", "$", "params", "=", "$", "params", "[", "$", "gridField", "->", "getName", "(", ")", "]", ";", "}", "if", "(", "$", "context", "->", "getSearchParams", "(", ")", ")", "{", "$", "params", "=", "array_merge", "(", "$", "context", "->", "getSearchParams", "(", ")", ",", "$", "params", ")", ";", "}", "$", "context", "->", "setSearchParams", "(", "$", "params", ")", ";", "$", "searchField", "=", "$", "context", "->", "getSearchFields", "(", ")", "->", "first", "(", ")", ";", "$", "searchField", "=", "$", "searchField", "&&", "property_exists", "(", "$", "searchField", ",", "'name'", ")", "?", "$", "searchField", "->", "name", ":", "null", ";", "$", "name", "=", "$", "gridField", "->", "Title", "?", ":", "singleton", "(", "$", "gridField", "->", "getModelClass", "(", ")", ")", "->", "i18n_plural_name", "(", ")", ";", "// Prefix \"Search__\" onto the filters for the React component", "$", "filters", "=", "$", "context", "->", "getSearchParams", "(", ")", ";", "if", "(", "!", "$", "this", "->", "useLegacyFilterHeader", "&&", "!", "empty", "(", "$", "filters", ")", ")", "{", "$", "filters", "=", "array_combine", "(", "array_map", "(", "function", "(", "$", "key", ")", "{", "return", "'Search__'", ".", "$", "key", ";", "}", ",", "array_keys", "(", "$", "filters", ")", ")", ",", "$", "filters", ")", ";", "}", "$", "searchAction", "=", "GridField_FormAction", "::", "create", "(", "$", "gridField", ",", "'filter'", ",", "false", ",", "'filter'", ",", "null", ")", ";", "$", "clearAction", "=", "GridField_FormAction", "::", "create", "(", "$", "gridField", ",", "'reset'", ",", "false", ",", "'reset'", ",", "null", ")", ";", "$", "schema", "=", "[", "'formSchemaUrl'", "=>", "$", "schemaUrl", ",", "'name'", "=>", "$", "searchField", ",", "'placeholder'", "=>", "_t", "(", "__CLASS__", ".", "'.Search'", ",", "'Search \"{name}\"'", ",", "[", "'name'", "=>", "$", "name", "]", ")", ",", "'filters'", "=>", "$", "filters", "?", ":", "new", "\\", "stdClass", ",", "// stdClass maps to empty json object '{}'", "'gridfield'", "=>", "$", "gridField", "->", "getName", "(", ")", ",", "'searchAction'", "=>", "$", "searchAction", "->", "getAttribute", "(", "'name'", ")", ",", "'searchActionState'", "=>", "$", "searchAction", "->", "getAttribute", "(", "'data-action-state'", ")", ",", "'clearAction'", "=>", "$", "clearAction", "->", "getAttribute", "(", "'name'", ")", ",", "'clearActionState'", "=>", "$", "clearAction", "->", "getAttribute", "(", "'data-action-state'", ")", ",", "]", ";", "return", "json_encode", "(", "$", "schema", ")", ";", "}" ]
Returns the search field schema for the component @param GridField $gridfield @return string
[ "Returns", "the", "search", "field", "schema", "for", "the", "component" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldFilterHeader.php#L265-L307
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
GridFieldFilterHeader.getSearchForm
public function getSearchForm(GridField $gridField) { $searchContext = $this->getSearchContext($gridField); $searchFields = $searchContext->getSearchFields(); if ($searchFields->count() === 0) { return null; } if ($this->searchForm) { return $this->searchForm; } // Append a prefix to search field names to prevent conflicts with other fields in the search form foreach ($searchFields as $field) { $field->setName('Search__' . $field->getName()); } $columns = $gridField->getColumns(); // Update field titles to match column titles foreach ($columns as $columnField) { $metadata = $gridField->getColumnMetadata($columnField); // Get the field name, without any modifications $name = explode('.', $columnField); $title = $metadata['title']; $field = $searchFields->fieldByName($name[0]); if ($field) { $field->setTitle($title); } } foreach ($searchFields->getIterator() as $field) { $field->addExtraClass('stacked'); } $name = $gridField->Title ?: singleton($gridField->getModelClass())->i18n_plural_name(); $this->searchForm = $form = new Form( $gridField, $name . "SearchForm", $searchFields, new FieldList() ); $form->setFormMethod('get'); $form->setFormAction($gridField->Link()); $form->addExtraClass('cms-search-form form--no-dividers'); $form->disableSecurityToken(); // This form is not tied to session so we disable this $form->loadDataFrom($searchContext->getSearchParams()); if ($this->updateSearchFormCallback) { call_user_func($this->updateSearchFormCallback, $form); } return $this->searchForm; }
php
public function getSearchForm(GridField $gridField) { $searchContext = $this->getSearchContext($gridField); $searchFields = $searchContext->getSearchFields(); if ($searchFields->count() === 0) { return null; } if ($this->searchForm) { return $this->searchForm; } // Append a prefix to search field names to prevent conflicts with other fields in the search form foreach ($searchFields as $field) { $field->setName('Search__' . $field->getName()); } $columns = $gridField->getColumns(); // Update field titles to match column titles foreach ($columns as $columnField) { $metadata = $gridField->getColumnMetadata($columnField); // Get the field name, without any modifications $name = explode('.', $columnField); $title = $metadata['title']; $field = $searchFields->fieldByName($name[0]); if ($field) { $field->setTitle($title); } } foreach ($searchFields->getIterator() as $field) { $field->addExtraClass('stacked'); } $name = $gridField->Title ?: singleton($gridField->getModelClass())->i18n_plural_name(); $this->searchForm = $form = new Form( $gridField, $name . "SearchForm", $searchFields, new FieldList() ); $form->setFormMethod('get'); $form->setFormAction($gridField->Link()); $form->addExtraClass('cms-search-form form--no-dividers'); $form->disableSecurityToken(); // This form is not tied to session so we disable this $form->loadDataFrom($searchContext->getSearchParams()); if ($this->updateSearchFormCallback) { call_user_func($this->updateSearchFormCallback, $form); } return $this->searchForm; }
[ "public", "function", "getSearchForm", "(", "GridField", "$", "gridField", ")", "{", "$", "searchContext", "=", "$", "this", "->", "getSearchContext", "(", "$", "gridField", ")", ";", "$", "searchFields", "=", "$", "searchContext", "->", "getSearchFields", "(", ")", ";", "if", "(", "$", "searchFields", "->", "count", "(", ")", "===", "0", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "searchForm", ")", "{", "return", "$", "this", "->", "searchForm", ";", "}", "// Append a prefix to search field names to prevent conflicts with other fields in the search form", "foreach", "(", "$", "searchFields", "as", "$", "field", ")", "{", "$", "field", "->", "setName", "(", "'Search__'", ".", "$", "field", "->", "getName", "(", ")", ")", ";", "}", "$", "columns", "=", "$", "gridField", "->", "getColumns", "(", ")", ";", "// Update field titles to match column titles", "foreach", "(", "$", "columns", "as", "$", "columnField", ")", "{", "$", "metadata", "=", "$", "gridField", "->", "getColumnMetadata", "(", "$", "columnField", ")", ";", "// Get the field name, without any modifications", "$", "name", "=", "explode", "(", "'.'", ",", "$", "columnField", ")", ";", "$", "title", "=", "$", "metadata", "[", "'title'", "]", ";", "$", "field", "=", "$", "searchFields", "->", "fieldByName", "(", "$", "name", "[", "0", "]", ")", ";", "if", "(", "$", "field", ")", "{", "$", "field", "->", "setTitle", "(", "$", "title", ")", ";", "}", "}", "foreach", "(", "$", "searchFields", "->", "getIterator", "(", ")", "as", "$", "field", ")", "{", "$", "field", "->", "addExtraClass", "(", "'stacked'", ")", ";", "}", "$", "name", "=", "$", "gridField", "->", "Title", "?", ":", "singleton", "(", "$", "gridField", "->", "getModelClass", "(", ")", ")", "->", "i18n_plural_name", "(", ")", ";", "$", "this", "->", "searchForm", "=", "$", "form", "=", "new", "Form", "(", "$", "gridField", ",", "$", "name", ".", "\"SearchForm\"", ",", "$", "searchFields", ",", "new", "FieldList", "(", ")", ")", ";", "$", "form", "->", "setFormMethod", "(", "'get'", ")", ";", "$", "form", "->", "setFormAction", "(", "$", "gridField", "->", "Link", "(", ")", ")", ";", "$", "form", "->", "addExtraClass", "(", "'cms-search-form form--no-dividers'", ")", ";", "$", "form", "->", "disableSecurityToken", "(", ")", ";", "// This form is not tied to session so we disable this", "$", "form", "->", "loadDataFrom", "(", "$", "searchContext", "->", "getSearchParams", "(", ")", ")", ";", "if", "(", "$", "this", "->", "updateSearchFormCallback", ")", "{", "call_user_func", "(", "$", "this", "->", "updateSearchFormCallback", ",", "$", "form", ")", ";", "}", "return", "$", "this", "->", "searchForm", ";", "}" ]
Returns the search form for the component @param GridField $gridField @return Form|null
[ "Returns", "the", "search", "form", "for", "the", "component" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldFilterHeader.php#L315-L372
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
GridFieldFilterHeader.getSearchFormSchema
public function getSearchFormSchema(GridField $gridField) { $form = $this->getSearchForm($gridField); // If there are no filterable fields, return a 400 response if (!$form) { return new HTTPResponse(_t(__CLASS__ . '.SearchFormFaliure', 'No search form could be generated'), 400); } $parts = $gridField->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER); $schemaID = $gridField->getRequest()->getURL(); $data = FormSchema::singleton() ->getMultipartSchema($parts, $schemaID, $form); $response = new HTTPResponse(json_encode($data)); $response->addHeader('Content-Type', 'application/json'); return $response; }
php
public function getSearchFormSchema(GridField $gridField) { $form = $this->getSearchForm($gridField); // If there are no filterable fields, return a 400 response if (!$form) { return new HTTPResponse(_t(__CLASS__ . '.SearchFormFaliure', 'No search form could be generated'), 400); } $parts = $gridField->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER); $schemaID = $gridField->getRequest()->getURL(); $data = FormSchema::singleton() ->getMultipartSchema($parts, $schemaID, $form); $response = new HTTPResponse(json_encode($data)); $response->addHeader('Content-Type', 'application/json'); return $response; }
[ "public", "function", "getSearchFormSchema", "(", "GridField", "$", "gridField", ")", "{", "$", "form", "=", "$", "this", "->", "getSearchForm", "(", "$", "gridField", ")", ";", "// If there are no filterable fields, return a 400 response", "if", "(", "!", "$", "form", ")", "{", "return", "new", "HTTPResponse", "(", "_t", "(", "__CLASS__", ".", "'.SearchFormFaliure'", ",", "'No search form could be generated'", ")", ",", "400", ")", ";", "}", "$", "parts", "=", "$", "gridField", "->", "getRequest", "(", ")", "->", "getHeader", "(", "LeftAndMain", "::", "SCHEMA_HEADER", ")", ";", "$", "schemaID", "=", "$", "gridField", "->", "getRequest", "(", ")", "->", "getURL", "(", ")", ";", "$", "data", "=", "FormSchema", "::", "singleton", "(", ")", "->", "getMultipartSchema", "(", "$", "parts", ",", "$", "schemaID", ",", "$", "form", ")", ";", "$", "response", "=", "new", "HTTPResponse", "(", "json_encode", "(", "$", "data", ")", ")", ";", "$", "response", "->", "addHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "return", "$", "response", ";", "}" ]
Returns the search form schema for the component @param GridField $gridfield @return HTTPResponse
[ "Returns", "the", "search", "form", "schema", "for", "the", "component" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldFilterHeader.php#L380-L397
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
GridFieldFilterHeader.getHTMLFragments
public function getHTMLFragments($gridField) { $forTemplate = new ArrayData([]); if (!$this->canFilterAnyColumns($gridField)) { return null; } if ($this->useLegacyFilterHeader) { $fieldsList = $this->getLegacyFilterHeader($gridField); $forTemplate->Fields = $fieldsList; $filterTemplates = SSViewer::get_templates_by_class($this, '_Row', __CLASS__); return ['header' => $forTemplate->renderWith($filterTemplates)]; } else { $fieldSchema = $this->getSearchFieldSchema($gridField); $forTemplate->SearchFieldSchema = $fieldSchema; $searchTemplates = SSViewer::get_templates_by_class($this, '_Search', __CLASS__); return [ 'before' => $forTemplate->renderWith($searchTemplates), 'buttons-before-right' => sprintf( '<button type="button" name="showFilter" aria-label="%s" title="%s"' . ' class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>', _t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter"), _t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter") ) ]; } }
php
public function getHTMLFragments($gridField) { $forTemplate = new ArrayData([]); if (!$this->canFilterAnyColumns($gridField)) { return null; } if ($this->useLegacyFilterHeader) { $fieldsList = $this->getLegacyFilterHeader($gridField); $forTemplate->Fields = $fieldsList; $filterTemplates = SSViewer::get_templates_by_class($this, '_Row', __CLASS__); return ['header' => $forTemplate->renderWith($filterTemplates)]; } else { $fieldSchema = $this->getSearchFieldSchema($gridField); $forTemplate->SearchFieldSchema = $fieldSchema; $searchTemplates = SSViewer::get_templates_by_class($this, '_Search', __CLASS__); return [ 'before' => $forTemplate->renderWith($searchTemplates), 'buttons-before-right' => sprintf( '<button type="button" name="showFilter" aria-label="%s" title="%s"' . ' class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>', _t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter"), _t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter") ) ]; } }
[ "public", "function", "getHTMLFragments", "(", "$", "gridField", ")", "{", "$", "forTemplate", "=", "new", "ArrayData", "(", "[", "]", ")", ";", "if", "(", "!", "$", "this", "->", "canFilterAnyColumns", "(", "$", "gridField", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "useLegacyFilterHeader", ")", "{", "$", "fieldsList", "=", "$", "this", "->", "getLegacyFilterHeader", "(", "$", "gridField", ")", ";", "$", "forTemplate", "->", "Fields", "=", "$", "fieldsList", ";", "$", "filterTemplates", "=", "SSViewer", "::", "get_templates_by_class", "(", "$", "this", ",", "'_Row'", ",", "__CLASS__", ")", ";", "return", "[", "'header'", "=>", "$", "forTemplate", "->", "renderWith", "(", "$", "filterTemplates", ")", "]", ";", "}", "else", "{", "$", "fieldSchema", "=", "$", "this", "->", "getSearchFieldSchema", "(", "$", "gridField", ")", ";", "$", "forTemplate", "->", "SearchFieldSchema", "=", "$", "fieldSchema", ";", "$", "searchTemplates", "=", "SSViewer", "::", "get_templates_by_class", "(", "$", "this", ",", "'_Search'", ",", "__CLASS__", ")", ";", "return", "[", "'before'", "=>", "$", "forTemplate", "->", "renderWith", "(", "$", "searchTemplates", ")", ",", "'buttons-before-right'", "=>", "sprintf", "(", "'<button type=\"button\" name=\"showFilter\" aria-label=\"%s\" title=\"%s\"'", ".", "' class=\"btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open\"></button>'", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\GridField\\\\GridField.OpenFilter'", ",", "\"Open search and filter\"", ")", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\GridField\\\\GridField.OpenFilter'", ",", "\"Open search and filter\"", ")", ")", "]", ";", "}", "}" ]
Either returns the legacy filter header or the search button and field @param GridField $gridField @return array|null
[ "Either", "returns", "the", "legacy", "filter", "header", "or", "the", "search", "button", "and", "field" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldFilterHeader.php#L481-L508
train
silverstripe/silverstripe-framework
thirdparty/difflib/difflib.php
Diff.finalize
public function finalize() { $lines = array(); foreach ($this->edits as $edit) { if ($edit->final) array_splice($lines, sizeof($lines), 0, $edit->final); } return $lines; }
php
public function finalize() { $lines = array(); foreach ($this->edits as $edit) { if ($edit->final) array_splice($lines, sizeof($lines), 0, $edit->final); } return $lines; }
[ "public", "function", "finalize", "(", ")", "{", "$", "lines", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "edits", "as", "$", "edit", ")", "{", "if", "(", "$", "edit", "->", "final", ")", "array_splice", "(", "$", "lines", ",", "sizeof", "(", "$", "lines", ")", ",", "0", ",", "$", "edit", "->", "final", ")", ";", "}", "return", "$", "lines", ";", "}" ]
Get the final set of lines. This reconstructs the $to_lines parameter passed to the constructor. @return array The sequence of strings.
[ "Get", "the", "final", "set", "of", "lines", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/thirdparty/difflib/difflib.php#L590-L599
train
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
DatabaseAdapterRegistry.register
public static function register($config) { // Validate config $missing = array_diff(['title', 'class', 'helperClass', 'supported'], array_keys($config)); if ($missing) { throw new InvalidArgumentException( "Missing database helper config keys: '" . implode("', '", $missing) . "'" ); } // Guess missing module text if not given if (empty($config['missingModuleText'])) { if (empty($config['module'])) { $moduleText = 'Module for database connector ' . $config['title'] . 'is missing.'; } else { $moduleText = "The SilverStripe module '" . $config['module'] . "' is missing."; } $config['missingModuleText'] = $moduleText . ' Please install it via composer or from http://addons.silverstripe.org/.'; } // Set missing text if (empty($config['missingExtensionText'])) { $config['missingExtensionText'] = 'The PHP extension is missing, please enable or install it.'; } // set default fields if none are defined already if (!isset($config['fields'])) { $config['fields'] = self::$default_fields; } self::$adapters[$config['class']] = $config; }
php
public static function register($config) { // Validate config $missing = array_diff(['title', 'class', 'helperClass', 'supported'], array_keys($config)); if ($missing) { throw new InvalidArgumentException( "Missing database helper config keys: '" . implode("', '", $missing) . "'" ); } // Guess missing module text if not given if (empty($config['missingModuleText'])) { if (empty($config['module'])) { $moduleText = 'Module for database connector ' . $config['title'] . 'is missing.'; } else { $moduleText = "The SilverStripe module '" . $config['module'] . "' is missing."; } $config['missingModuleText'] = $moduleText . ' Please install it via composer or from http://addons.silverstripe.org/.'; } // Set missing text if (empty($config['missingExtensionText'])) { $config['missingExtensionText'] = 'The PHP extension is missing, please enable or install it.'; } // set default fields if none are defined already if (!isset($config['fields'])) { $config['fields'] = self::$default_fields; } self::$adapters[$config['class']] = $config; }
[ "public", "static", "function", "register", "(", "$", "config", ")", "{", "// Validate config", "$", "missing", "=", "array_diff", "(", "[", "'title'", ",", "'class'", ",", "'helperClass'", ",", "'supported'", "]", ",", "array_keys", "(", "$", "config", ")", ")", ";", "if", "(", "$", "missing", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Missing database helper config keys: '\"", ".", "implode", "(", "\"', '\"", ",", "$", "missing", ")", ".", "\"'\"", ")", ";", "}", "// Guess missing module text if not given", "if", "(", "empty", "(", "$", "config", "[", "'missingModuleText'", "]", ")", ")", "{", "if", "(", "empty", "(", "$", "config", "[", "'module'", "]", ")", ")", "{", "$", "moduleText", "=", "'Module for database connector '", ".", "$", "config", "[", "'title'", "]", ".", "'is missing.'", ";", "}", "else", "{", "$", "moduleText", "=", "\"The SilverStripe module '\"", ".", "$", "config", "[", "'module'", "]", ".", "\"' is missing.\"", ";", "}", "$", "config", "[", "'missingModuleText'", "]", "=", "$", "moduleText", ".", "' Please install it via composer or from http://addons.silverstripe.org/.'", ";", "}", "// Set missing text", "if", "(", "empty", "(", "$", "config", "[", "'missingExtensionText'", "]", ")", ")", "{", "$", "config", "[", "'missingExtensionText'", "]", "=", "'The PHP extension is missing, please enable or install it.'", ";", "}", "// set default fields if none are defined already", "if", "(", "!", "isset", "(", "$", "config", "[", "'fields'", "]", ")", ")", "{", "$", "config", "[", "'fields'", "]", "=", "self", "::", "$", "default_fields", ";", "}", "self", "::", "$", "adapters", "[", "$", "config", "[", "'class'", "]", "]", "=", "$", "config", ";", "}" ]
Add new adapter to the registry @param array $config Associative array of configuration details. This must include: - title - class - helperClass - supported This SHOULD include: - fields - helperPath (if helperClass can't be autoloaded via psr-4/-0) - missingExtensionText - module OR missingModuleText
[ "Add", "new", "adapter", "to", "the", "registry" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/DatabaseAdapterRegistry.php#L69-L101
train
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
DatabaseAdapterRegistry.getDatabaseConfigurationHelper
public static function getDatabaseConfigurationHelper($databaseClass) { $adapters = static::get_adapters(); if (empty($adapters[$databaseClass]) || empty($adapters[$databaseClass]['helperClass'])) { return null; } // Load if path given if (isset($adapters[$databaseClass]['helperPath'])) { include_once $adapters[$databaseClass]['helperPath']; } // Construct $class = $adapters[$databaseClass]['helperClass']; return (class_exists($class)) ? new $class() : null; }
php
public static function getDatabaseConfigurationHelper($databaseClass) { $adapters = static::get_adapters(); if (empty($adapters[$databaseClass]) || empty($adapters[$databaseClass]['helperClass'])) { return null; } // Load if path given if (isset($adapters[$databaseClass]['helperPath'])) { include_once $adapters[$databaseClass]['helperPath']; } // Construct $class = $adapters[$databaseClass]['helperClass']; return (class_exists($class)) ? new $class() : null; }
[ "public", "static", "function", "getDatabaseConfigurationHelper", "(", "$", "databaseClass", ")", "{", "$", "adapters", "=", "static", "::", "get_adapters", "(", ")", ";", "if", "(", "empty", "(", "$", "adapters", "[", "$", "databaseClass", "]", ")", "||", "empty", "(", "$", "adapters", "[", "$", "databaseClass", "]", "[", "'helperClass'", "]", ")", ")", "{", "return", "null", ";", "}", "// Load if path given", "if", "(", "isset", "(", "$", "adapters", "[", "$", "databaseClass", "]", "[", "'helperPath'", "]", ")", ")", "{", "include_once", "$", "adapters", "[", "$", "databaseClass", "]", "[", "'helperPath'", "]", ";", "}", "// Construct", "$", "class", "=", "$", "adapters", "[", "$", "databaseClass", "]", "[", "'helperClass'", "]", ";", "return", "(", "class_exists", "(", "$", "class", ")", ")", "?", "new", "$", "class", "(", ")", ":", "null", ";", "}" ]
Build configuration helper for a given class @param string $databaseClass Name of class @return DatabaseConfigurationHelper|null Instance of helper, or null if cannot be loaded
[ "Build", "configuration", "helper", "for", "a", "given", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/DatabaseAdapterRegistry.php#L199-L214
train
silverstripe/silverstripe-framework
src/Core/Config/Middleware/ExtensionMiddleware.php
ExtensionMiddleware.getExtraConfig
protected function getExtraConfig($class, $classConfig, $excludeMiddleware) { // Note: 'extensions' config needs to come from it's own middleware call in case // applied by delta middleware (e.g. Object::add_extension) $extensionSourceConfig = Config::inst()->get($class, null, Config::UNINHERITED | $excludeMiddleware | $this->disableFlag); if (empty($extensionSourceConfig['extensions'])) { return; } $extensions = $extensionSourceConfig['extensions']; foreach ($extensions as $extension) { list($extensionClass, $extensionArgs) = ClassInfo::parse_class_spec($extension); // Strip service name specifier $extensionClass = strtok($extensionClass, '.'); if (!class_exists($extensionClass)) { throw new InvalidArgumentException("$class references nonexistent $extensionClass in 'extensions'"); } // Init extension call_user_func(array($extensionClass, 'add_to_class'), $class, $extensionClass, $extensionArgs); // Check class hierarchy from root up foreach (ClassInfo::ancestry($extensionClass) as $extensionClassParent) { // Skip base classes switch ($extensionClassParent) { case Extension::class: case DataExtension::class: continue 2; default: // continue } // Merge config from extension $extensionConfig = Config::inst()->get( $extensionClassParent, null, Config::EXCLUDE_EXTRA_SOURCES | Config::UNINHERITED ); if ($extensionConfig) { yield $extensionConfig; } if (ClassInfo::has_method_from($extensionClassParent, 'get_extra_config', $extensionClassParent)) { $extensionConfig = call_user_func( [ $extensionClassParent, 'get_extra_config' ], $class, $extensionClass, $extensionArgs ); if ($extensionConfig) { yield $extensionConfig; } } } } }
php
protected function getExtraConfig($class, $classConfig, $excludeMiddleware) { // Note: 'extensions' config needs to come from it's own middleware call in case // applied by delta middleware (e.g. Object::add_extension) $extensionSourceConfig = Config::inst()->get($class, null, Config::UNINHERITED | $excludeMiddleware | $this->disableFlag); if (empty($extensionSourceConfig['extensions'])) { return; } $extensions = $extensionSourceConfig['extensions']; foreach ($extensions as $extension) { list($extensionClass, $extensionArgs) = ClassInfo::parse_class_spec($extension); // Strip service name specifier $extensionClass = strtok($extensionClass, '.'); if (!class_exists($extensionClass)) { throw new InvalidArgumentException("$class references nonexistent $extensionClass in 'extensions'"); } // Init extension call_user_func(array($extensionClass, 'add_to_class'), $class, $extensionClass, $extensionArgs); // Check class hierarchy from root up foreach (ClassInfo::ancestry($extensionClass) as $extensionClassParent) { // Skip base classes switch ($extensionClassParent) { case Extension::class: case DataExtension::class: continue 2; default: // continue } // Merge config from extension $extensionConfig = Config::inst()->get( $extensionClassParent, null, Config::EXCLUDE_EXTRA_SOURCES | Config::UNINHERITED ); if ($extensionConfig) { yield $extensionConfig; } if (ClassInfo::has_method_from($extensionClassParent, 'get_extra_config', $extensionClassParent)) { $extensionConfig = call_user_func( [ $extensionClassParent, 'get_extra_config' ], $class, $extensionClass, $extensionArgs ); if ($extensionConfig) { yield $extensionConfig; } } } } }
[ "protected", "function", "getExtraConfig", "(", "$", "class", ",", "$", "classConfig", ",", "$", "excludeMiddleware", ")", "{", "// Note: 'extensions' config needs to come from it's own middleware call in case", "// applied by delta middleware (e.g. Object::add_extension)", "$", "extensionSourceConfig", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "null", ",", "Config", "::", "UNINHERITED", "|", "$", "excludeMiddleware", "|", "$", "this", "->", "disableFlag", ")", ";", "if", "(", "empty", "(", "$", "extensionSourceConfig", "[", "'extensions'", "]", ")", ")", "{", "return", ";", "}", "$", "extensions", "=", "$", "extensionSourceConfig", "[", "'extensions'", "]", ";", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "list", "(", "$", "extensionClass", ",", "$", "extensionArgs", ")", "=", "ClassInfo", "::", "parse_class_spec", "(", "$", "extension", ")", ";", "// Strip service name specifier", "$", "extensionClass", "=", "strtok", "(", "$", "extensionClass", ",", "'.'", ")", ";", "if", "(", "!", "class_exists", "(", "$", "extensionClass", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"$class references nonexistent $extensionClass in 'extensions'\"", ")", ";", "}", "// Init extension", "call_user_func", "(", "array", "(", "$", "extensionClass", ",", "'add_to_class'", ")", ",", "$", "class", ",", "$", "extensionClass", ",", "$", "extensionArgs", ")", ";", "// Check class hierarchy from root up", "foreach", "(", "ClassInfo", "::", "ancestry", "(", "$", "extensionClass", ")", "as", "$", "extensionClassParent", ")", "{", "// Skip base classes", "switch", "(", "$", "extensionClassParent", ")", "{", "case", "Extension", "::", "class", ":", "case", "DataExtension", "::", "class", ":", "continue", "2", ";", "default", ":", "// continue", "}", "// Merge config from extension", "$", "extensionConfig", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "extensionClassParent", ",", "null", ",", "Config", "::", "EXCLUDE_EXTRA_SOURCES", "|", "Config", "::", "UNINHERITED", ")", ";", "if", "(", "$", "extensionConfig", ")", "{", "yield", "$", "extensionConfig", ";", "}", "if", "(", "ClassInfo", "::", "has_method_from", "(", "$", "extensionClassParent", ",", "'get_extra_config'", ",", "$", "extensionClassParent", ")", ")", "{", "$", "extensionConfig", "=", "call_user_func", "(", "[", "$", "extensionClassParent", ",", "'get_extra_config'", "]", ",", "$", "class", ",", "$", "extensionClass", ",", "$", "extensionArgs", ")", ";", "if", "(", "$", "extensionConfig", ")", "{", "yield", "$", "extensionConfig", ";", "}", "}", "}", "}", "}" ]
Applied config to a class from its extensions @param string $class @param array $classConfig @param int $excludeMiddleware @return Generator
[ "Applied", "config", "to", "a", "class", "from", "its", "extensions" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/Middleware/ExtensionMiddleware.php#L55-L108
train
silverstripe/silverstripe-framework
src/Core/Startup/ErrorDirector.php
ErrorDirector.handleRequestWithTokenChain
public function handleRequestWithTokenChain( HTTPRequest $request, ConfirmationTokenChain $confirmationTokenChain, Kernel $kernel ) { Injector::inst()->registerService($request, HTTPRequest::class); // Next, check if we're in dev mode, or the database doesn't have any security data, or we are admin $reload = function (HTTPRequest $request) use ($confirmationTokenChain, $kernel) { if ($kernel->getEnvironment() === Kernel::DEV || !Security::database_is_ready() || Permission::check('ADMIN')) { return $confirmationTokenChain->reloadWithTokens(); } return null; }; try { return $this->callMiddleware($request, $reload); } finally { // Ensure registered request is un-registered Injector::inst()->unregisterNamedObject(HTTPRequest::class); } }
php
public function handleRequestWithTokenChain( HTTPRequest $request, ConfirmationTokenChain $confirmationTokenChain, Kernel $kernel ) { Injector::inst()->registerService($request, HTTPRequest::class); // Next, check if we're in dev mode, or the database doesn't have any security data, or we are admin $reload = function (HTTPRequest $request) use ($confirmationTokenChain, $kernel) { if ($kernel->getEnvironment() === Kernel::DEV || !Security::database_is_ready() || Permission::check('ADMIN')) { return $confirmationTokenChain->reloadWithTokens(); } return null; }; try { return $this->callMiddleware($request, $reload); } finally { // Ensure registered request is un-registered Injector::inst()->unregisterNamedObject(HTTPRequest::class); } }
[ "public", "function", "handleRequestWithTokenChain", "(", "HTTPRequest", "$", "request", ",", "ConfirmationTokenChain", "$", "confirmationTokenChain", ",", "Kernel", "$", "kernel", ")", "{", "Injector", "::", "inst", "(", ")", "->", "registerService", "(", "$", "request", ",", "HTTPRequest", "::", "class", ")", ";", "// Next, check if we're in dev mode, or the database doesn't have any security data, or we are admin", "$", "reload", "=", "function", "(", "HTTPRequest", "$", "request", ")", "use", "(", "$", "confirmationTokenChain", ",", "$", "kernel", ")", "{", "if", "(", "$", "kernel", "->", "getEnvironment", "(", ")", "===", "Kernel", "::", "DEV", "||", "!", "Security", "::", "database_is_ready", "(", ")", "||", "Permission", "::", "check", "(", "'ADMIN'", ")", ")", "{", "return", "$", "confirmationTokenChain", "->", "reloadWithTokens", "(", ")", ";", "}", "return", "null", ";", "}", ";", "try", "{", "return", "$", "this", "->", "callMiddleware", "(", "$", "request", ",", "$", "reload", ")", ";", "}", "finally", "{", "// Ensure registered request is un-registered", "Injector", "::", "inst", "(", ")", "->", "unregisterNamedObject", "(", "HTTPRequest", "::", "class", ")", ";", "}", "}" ]
Redirect with token if allowed, or null if not allowed @param HTTPRequest $request @param ConfirmationTokenChain $confirmationTokenChain @param Kernel $kernel @return null|HTTPResponse Redirection response, or null if not able to redirect
[ "Redirect", "with", "token", "if", "allowed", "or", "null", "if", "not", "allowed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Startup/ErrorDirector.php#L28-L49
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LogoutHandler.php
LogoutHandler.logout
public function logout() { $member = Security::getCurrentUser(); // If the user doesn't have a security token, show them a form where they can get one. // This protects against nuisance CSRF attacks to log out users. if ($member && !SecurityToken::inst()->checkRequest($this->getRequest())) { Security::singleton()->setSessionMessage( _t( 'SilverStripe\\Security\\Security.CONFIRMLOGOUT', "Please click the button below to confirm that you wish to log out." ), ValidationResult::TYPE_WARNING ); return [ 'Form' => $this->logoutForm() ]; } return $this->doLogOut($member); }
php
public function logout() { $member = Security::getCurrentUser(); // If the user doesn't have a security token, show them a form where they can get one. // This protects against nuisance CSRF attacks to log out users. if ($member && !SecurityToken::inst()->checkRequest($this->getRequest())) { Security::singleton()->setSessionMessage( _t( 'SilverStripe\\Security\\Security.CONFIRMLOGOUT', "Please click the button below to confirm that you wish to log out." ), ValidationResult::TYPE_WARNING ); return [ 'Form' => $this->logoutForm() ]; } return $this->doLogOut($member); }
[ "public", "function", "logout", "(", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "// If the user doesn't have a security token, show them a form where they can get one.", "// This protects against nuisance CSRF attacks to log out users.", "if", "(", "$", "member", "&&", "!", "SecurityToken", "::", "inst", "(", ")", "->", "checkRequest", "(", "$", "this", "->", "getRequest", "(", ")", ")", ")", "{", "Security", "::", "singleton", "(", ")", "->", "setSessionMessage", "(", "_t", "(", "'SilverStripe\\\\Security\\\\Security.CONFIRMLOGOUT'", ",", "\"Please click the button below to confirm that you wish to log out.\"", ")", ",", "ValidationResult", "::", "TYPE_WARNING", ")", ";", "return", "[", "'Form'", "=>", "$", "this", "->", "logoutForm", "(", ")", "]", ";", "}", "return", "$", "this", "->", "doLogOut", "(", "$", "member", ")", ";", "}" ]
Log out form handler method This method is called when the user clicks on "logout" on the form created when the parameter <i>$checkCurrentUser</i> of the {@link __construct constructor} was set to TRUE and the user was currently logged in. @return array|HTTPResponse
[ "Log", "out", "form", "handler", "method" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LogoutHandler.php#L51-L72
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.collateFamilyIDs
public function collateFamilyIDs() { if (!$this->exists()) { throw new \InvalidArgumentException("Cannot call collateFamilyIDs on unsaved Group."); } $familyIDs = array(); $chunkToAdd = array($this->ID); while ($chunkToAdd) { $familyIDs = array_merge($familyIDs, $chunkToAdd); // Get the children of *all* the groups identified in the previous chunk. // This minimises the number of SQL queries necessary $chunkToAdd = Group::get()->filter("ParentID", $chunkToAdd)->column('ID'); } return $familyIDs; }
php
public function collateFamilyIDs() { if (!$this->exists()) { throw new \InvalidArgumentException("Cannot call collateFamilyIDs on unsaved Group."); } $familyIDs = array(); $chunkToAdd = array($this->ID); while ($chunkToAdd) { $familyIDs = array_merge($familyIDs, $chunkToAdd); // Get the children of *all* the groups identified in the previous chunk. // This minimises the number of SQL queries necessary $chunkToAdd = Group::get()->filter("ParentID", $chunkToAdd)->column('ID'); } return $familyIDs; }
[ "public", "function", "collateFamilyIDs", "(", ")", "{", "if", "(", "!", "$", "this", "->", "exists", "(", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Cannot call collateFamilyIDs on unsaved Group.\"", ")", ";", "}", "$", "familyIDs", "=", "array", "(", ")", ";", "$", "chunkToAdd", "=", "array", "(", "$", "this", "->", "ID", ")", ";", "while", "(", "$", "chunkToAdd", ")", "{", "$", "familyIDs", "=", "array_merge", "(", "$", "familyIDs", ",", "$", "chunkToAdd", ")", ";", "// Get the children of *all* the groups identified in the previous chunk.", "// This minimises the number of SQL queries necessary", "$", "chunkToAdd", "=", "Group", "::", "get", "(", ")", "->", "filter", "(", "\"ParentID\"", ",", "$", "chunkToAdd", ")", "->", "column", "(", "'ID'", ")", ";", "}", "return", "$", "familyIDs", ";", "}" ]
Return a set of this record's "family" of IDs - the IDs of this record and all its descendants. @return array
[ "Return", "a", "set", "of", "this", "record", "s", "family", "of", "IDs", "-", "the", "IDs", "of", "this", "record", "and", "all", "its", "descendants", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L352-L370
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.collateAncestorIDs
public function collateAncestorIDs() { $parent = $this; $items = []; while ($parent instanceof Group) { $items[] = $parent->ID; $parent = $parent->getParent(); } return $items; }
php
public function collateAncestorIDs() { $parent = $this; $items = []; while ($parent instanceof Group) { $items[] = $parent->ID; $parent = $parent->getParent(); } return $items; }
[ "public", "function", "collateAncestorIDs", "(", ")", "{", "$", "parent", "=", "$", "this", ";", "$", "items", "=", "[", "]", ";", "while", "(", "$", "parent", "instanceof", "Group", ")", "{", "$", "items", "[", "]", "=", "$", "parent", "->", "ID", ";", "$", "parent", "=", "$", "parent", "->", "getParent", "(", ")", ";", "}", "return", "$", "items", ";", "}" ]
Returns an array of the IDs of this group and all its parents @return array
[ "Returns", "an", "array", "of", "the", "IDs", "of", "this", "group", "and", "all", "its", "parents" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L377-L386
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.inGroups
public function inGroups($groups, $requireAll = false) { $ancestorIDs = $this->collateAncestorIDs(); $candidateIDs = []; foreach ($groups as $group) { $groupID = $this->identifierToGroupID($group); if ($groupID) { $candidateIDs[] = $groupID; } elseif ($requireAll) { return false; } } if (empty($candidateIDs)) { return false; } $matches = array_intersect($candidateIDs, $ancestorIDs); if ($requireAll) { return count($candidateIDs) === count($matches); } return !empty($matches); }
php
public function inGroups($groups, $requireAll = false) { $ancestorIDs = $this->collateAncestorIDs(); $candidateIDs = []; foreach ($groups as $group) { $groupID = $this->identifierToGroupID($group); if ($groupID) { $candidateIDs[] = $groupID; } elseif ($requireAll) { return false; } } if (empty($candidateIDs)) { return false; } $matches = array_intersect($candidateIDs, $ancestorIDs); if ($requireAll) { return count($candidateIDs) === count($matches); } return !empty($matches); }
[ "public", "function", "inGroups", "(", "$", "groups", ",", "$", "requireAll", "=", "false", ")", "{", "$", "ancestorIDs", "=", "$", "this", "->", "collateAncestorIDs", "(", ")", ";", "$", "candidateIDs", "=", "[", "]", ";", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "$", "groupID", "=", "$", "this", "->", "identifierToGroupID", "(", "$", "group", ")", ";", "if", "(", "$", "groupID", ")", "{", "$", "candidateIDs", "[", "]", "=", "$", "groupID", ";", "}", "elseif", "(", "$", "requireAll", ")", "{", "return", "false", ";", "}", "}", "if", "(", "empty", "(", "$", "candidateIDs", ")", ")", "{", "return", "false", ";", "}", "$", "matches", "=", "array_intersect", "(", "$", "candidateIDs", ",", "$", "ancestorIDs", ")", ";", "if", "(", "$", "requireAll", ")", "{", "return", "count", "(", "$", "candidateIDs", ")", "===", "count", "(", "$", "matches", ")", ";", "}", "return", "!", "empty", "(", "$", "matches", ")", ";", "}" ]
Check if the group is a child of the given groups or any parent groups @param (string|int|Group)[] $groups @param bool $requireAll set to TRUE if must be in ALL groups, or FALSE if must be in ANY @return bool Returns TRUE if the Group is a child of any of the given groups, otherwise FALSE
[ "Check", "if", "the", "group", "is", "a", "child", "of", "the", "given", "groups", "or", "any", "parent", "groups" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L406-L426
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.identifierToGroupID
protected function identifierToGroupID($groupID) { if (is_numeric($groupID) && Group::get()->byID($groupID)) { return $groupID; } elseif (is_string($groupID) && $groupByCode = Group::get()->filter(['Code' => $groupID])->first()) { return $groupByCode->ID; } elseif ($groupID instanceof Group && $groupID->exists()) { return $groupID->ID; } return null; }
php
protected function identifierToGroupID($groupID) { if (is_numeric($groupID) && Group::get()->byID($groupID)) { return $groupID; } elseif (is_string($groupID) && $groupByCode = Group::get()->filter(['Code' => $groupID])->first()) { return $groupByCode->ID; } elseif ($groupID instanceof Group && $groupID->exists()) { return $groupID->ID; } return null; }
[ "protected", "function", "identifierToGroupID", "(", "$", "groupID", ")", "{", "if", "(", "is_numeric", "(", "$", "groupID", ")", "&&", "Group", "::", "get", "(", ")", "->", "byID", "(", "$", "groupID", ")", ")", "{", "return", "$", "groupID", ";", "}", "elseif", "(", "is_string", "(", "$", "groupID", ")", "&&", "$", "groupByCode", "=", "Group", "::", "get", "(", ")", "->", "filter", "(", "[", "'Code'", "=>", "$", "groupID", "]", ")", "->", "first", "(", ")", ")", "{", "return", "$", "groupByCode", "->", "ID", ";", "}", "elseif", "(", "$", "groupID", "instanceof", "Group", "&&", "$", "groupID", "->", "exists", "(", ")", ")", "{", "return", "$", "groupID", "->", "ID", ";", "}", "return", "null", ";", "}" ]
Turn a string|int|Group into a GroupID @param string|int|Group $groupID Group instance, Group Code or ID @return int|null the Group ID or NULL if not found
[ "Turn", "a", "string|int|Group", "into", "a", "GroupID" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L434-L444
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.stageChildren
public function stageChildren() { return Group::get() ->filter("ParentID", $this->ID) ->exclude("ID", $this->ID) ->sort('"Sort"'); }
php
public function stageChildren() { return Group::get() ->filter("ParentID", $this->ID) ->exclude("ID", $this->ID) ->sort('"Sort"'); }
[ "public", "function", "stageChildren", "(", ")", "{", "return", "Group", "::", "get", "(", ")", "->", "filter", "(", "\"ParentID\"", ",", "$", "this", "->", "ID", ")", "->", "exclude", "(", "\"ID\"", ",", "$", "this", "->", "ID", ")", "->", "sort", "(", "'\"Sort\"'", ")", ";", "}" ]
Override this so groups are ordered in the CMS
[ "Override", "this", "so", "groups", "are", "ordered", "in", "the", "CMS" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L457-L463
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.canEdit
public function canEdit($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // extended access checks $results = $this->extend('canEdit', $member); if ($results && is_array($results)) { if (!min($results)) { return false; } } if (// either we have an ADMIN (bool)Permission::checkMember($member, "ADMIN") || ( // or a privileged CMS user and a group without ADMIN permissions. // without this check, a user would be able to add himself to an administrators group // with just access to the "Security" admin interface Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin") && !Permission::get()->filter(array('GroupID' => $this->ID, 'Code' => 'ADMIN'))->exists() ) ) { return true; } return false; }
php
public function canEdit($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // extended access checks $results = $this->extend('canEdit', $member); if ($results && is_array($results)) { if (!min($results)) { return false; } } if (// either we have an ADMIN (bool)Permission::checkMember($member, "ADMIN") || ( // or a privileged CMS user and a group without ADMIN permissions. // without this check, a user would be able to add himself to an administrators group // with just access to the "Security" admin interface Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin") && !Permission::get()->filter(array('GroupID' => $this->ID, 'Code' => 'ADMIN'))->exists() ) ) { return true; } return false; }
[ "public", "function", "canEdit", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "// extended access checks", "$", "results", "=", "$", "this", "->", "extend", "(", "'canEdit'", ",", "$", "member", ")", ";", "if", "(", "$", "results", "&&", "is_array", "(", "$", "results", ")", ")", "{", "if", "(", "!", "min", "(", "$", "results", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "// either we have an ADMIN", "(", "bool", ")", "Permission", "::", "checkMember", "(", "$", "member", ",", "\"ADMIN\"", ")", "||", "(", "// or a privileged CMS user and a group without ADMIN permissions.", "// without this check, a user would be able to add himself to an administrators group", "// with just access to the \"Security\" admin interface", "Permission", "::", "checkMember", "(", "$", "member", ",", "\"CMS_ACCESS_SecurityAdmin\"", ")", "&&", "!", "Permission", "::", "get", "(", ")", "->", "filter", "(", "array", "(", "'GroupID'", "=>", "$", "this", "->", "ID", ",", "'Code'", "=>", "'ADMIN'", ")", ")", "->", "exists", "(", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks for permission-code CMS_ACCESS_SecurityAdmin. If the group has ADMIN permissions, it requires the user to have ADMIN permissions as well. @param Member $member Member @return boolean
[ "Checks", "for", "permission", "-", "code", "CMS_ACCESS_SecurityAdmin", ".", "If", "the", "group", "has", "ADMIN", "permissions", "it", "requires", "the", "user", "to", "have", "ADMIN", "permissions", "as", "well", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L545-L573
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.canView
public function canView($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // extended access checks $results = $this->extend('canView', $member); if ($results && is_array($results)) { if (!min($results)) { return false; } } // user needs access to CMS_ACCESS_SecurityAdmin if (Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin")) { return true; } return false; }
php
public function canView($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // extended access checks $results = $this->extend('canView', $member); if ($results && is_array($results)) { if (!min($results)) { return false; } } // user needs access to CMS_ACCESS_SecurityAdmin if (Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin")) { return true; } return false; }
[ "public", "function", "canView", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "// extended access checks", "$", "results", "=", "$", "this", "->", "extend", "(", "'canView'", ",", "$", "member", ")", ";", "if", "(", "$", "results", "&&", "is_array", "(", "$", "results", ")", ")", "{", "if", "(", "!", "min", "(", "$", "results", ")", ")", "{", "return", "false", ";", "}", "}", "// user needs access to CMS_ACCESS_SecurityAdmin", "if", "(", "Permission", "::", "checkMember", "(", "$", "member", ",", "\"CMS_ACCESS_SecurityAdmin\"", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks for permission-code CMS_ACCESS_SecurityAdmin. @param Member $member @return boolean
[ "Checks", "for", "permission", "-", "code", "CMS_ACCESS_SecurityAdmin", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L581-L601
train
silverstripe/silverstripe-framework
src/Security/Group.php
Group.AllChildrenIncludingDeleted
public function AllChildrenIncludingDeleted() { $children = parent::AllChildrenIncludingDeleted(); $filteredChildren = new ArrayList(); if ($children) { foreach ($children as $child) { /** @var DataObject $child */ if ($child->canView()) { $filteredChildren->push($child); } } } return $filteredChildren; }
php
public function AllChildrenIncludingDeleted() { $children = parent::AllChildrenIncludingDeleted(); $filteredChildren = new ArrayList(); if ($children) { foreach ($children as $child) { /** @var DataObject $child */ if ($child->canView()) { $filteredChildren->push($child); } } } return $filteredChildren; }
[ "public", "function", "AllChildrenIncludingDeleted", "(", ")", "{", "$", "children", "=", "parent", "::", "AllChildrenIncludingDeleted", "(", ")", ";", "$", "filteredChildren", "=", "new", "ArrayList", "(", ")", ";", "if", "(", "$", "children", ")", "{", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "/** @var DataObject $child */", "if", "(", "$", "child", "->", "canView", "(", ")", ")", "{", "$", "filteredChildren", "->", "push", "(", "$", "child", ")", ";", "}", "}", "}", "return", "$", "filteredChildren", ";", "}" ]
Returns all of the children for the CMS Tree. Filters to only those groups that the current user can edit @return ArrayList
[ "Returns", "all", "of", "the", "children", "for", "the", "CMS", "Tree", ".", "Filters", "to", "only", "those", "groups", "that", "the", "current", "user", "can", "edit" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Group.php#L626-L642
train
silverstripe/silverstripe-framework
src/Dev/CSVParser.php
CSVParser.mapColumns
public function mapColumns($columnMap) { if ($columnMap) { $lowerColumnMap = array(); foreach ($columnMap as $k => $v) { $lowerColumnMap[strtolower($k)] = $v; } $this->columnMap = array_merge($this->columnMap, $lowerColumnMap); } }
php
public function mapColumns($columnMap) { if ($columnMap) { $lowerColumnMap = array(); foreach ($columnMap as $k => $v) { $lowerColumnMap[strtolower($k)] = $v; } $this->columnMap = array_merge($this->columnMap, $lowerColumnMap); } }
[ "public", "function", "mapColumns", "(", "$", "columnMap", ")", "{", "if", "(", "$", "columnMap", ")", "{", "$", "lowerColumnMap", "=", "array", "(", ")", ";", "foreach", "(", "$", "columnMap", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "lowerColumnMap", "[", "strtolower", "(", "$", "k", ")", "]", "=", "$", "v", ";", "}", "$", "this", "->", "columnMap", "=", "array_merge", "(", "$", "this", "->", "columnMap", ",", "$", "lowerColumnMap", ")", ";", "}", "}" ]
Re-map columns in the CSV file. This can be useful for identifying synonyms in the file. For example: <code> $csv->mapColumns(array( 'firstname' => 'FirstName', 'last name' => 'Surname', )); </code> @param array
[ "Re", "-", "map", "columns", "in", "the", "CSV", "file", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CSVParser.php#L139-L150
train
silverstripe/silverstripe-framework
src/Dev/CSVParser.php
CSVParser.openFile
protected function openFile() { ini_set('auto_detect_line_endings', 1); $this->fileHandle = fopen($this->filename, 'r'); if ($this->providedHeaderRow) { $this->headerRow = $this->remapHeader($this->providedHeaderRow); } }
php
protected function openFile() { ini_set('auto_detect_line_endings', 1); $this->fileHandle = fopen($this->filename, 'r'); if ($this->providedHeaderRow) { $this->headerRow = $this->remapHeader($this->providedHeaderRow); } }
[ "protected", "function", "openFile", "(", ")", "{", "ini_set", "(", "'auto_detect_line_endings'", ",", "1", ")", ";", "$", "this", "->", "fileHandle", "=", "fopen", "(", "$", "this", "->", "filename", ",", "'r'", ")", ";", "if", "(", "$", "this", "->", "providedHeaderRow", ")", "{", "$", "this", "->", "headerRow", "=", "$", "this", "->", "remapHeader", "(", "$", "this", "->", "providedHeaderRow", ")", ";", "}", "}" ]
Open the CSV file for reading.
[ "Open", "the", "CSV", "file", "for", "reading", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CSVParser.php#L169-L177
train
silverstripe/silverstripe-framework
src/Dev/CSVParser.php
CSVParser.closeFile
protected function closeFile() { if ($this->fileHandle) { fclose($this->fileHandle); } $this->fileHandle = null; $this->rowNum = 0; $this->currentRow = null; $this->headerRow = null; }
php
protected function closeFile() { if ($this->fileHandle) { fclose($this->fileHandle); } $this->fileHandle = null; $this->rowNum = 0; $this->currentRow = null; $this->headerRow = null; }
[ "protected", "function", "closeFile", "(", ")", "{", "if", "(", "$", "this", "->", "fileHandle", ")", "{", "fclose", "(", "$", "this", "->", "fileHandle", ")", ";", "}", "$", "this", "->", "fileHandle", "=", "null", ";", "$", "this", "->", "rowNum", "=", "0", ";", "$", "this", "->", "currentRow", "=", "null", ";", "$", "this", "->", "headerRow", "=", "null", ";", "}" ]
Close the CSV file and re-set all of the internal variables.
[ "Close", "the", "CSV", "file", "and", "re", "-", "set", "all", "of", "the", "internal", "variables", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CSVParser.php#L182-L192
train
silverstripe/silverstripe-framework
src/Dev/CSVParser.php
CSVParser.fetchCSVHeader
protected function fetchCSVHeader() { $srcRow = fgetcsv( $this->fileHandle, 0, $this->delimiter, $this->enclosure ); $this->headerRow = $this->remapHeader($srcRow); }
php
protected function fetchCSVHeader() { $srcRow = fgetcsv( $this->fileHandle, 0, $this->delimiter, $this->enclosure ); $this->headerRow = $this->remapHeader($srcRow); }
[ "protected", "function", "fetchCSVHeader", "(", ")", "{", "$", "srcRow", "=", "fgetcsv", "(", "$", "this", "->", "fileHandle", ",", "0", ",", "$", "this", "->", "delimiter", ",", "$", "this", "->", "enclosure", ")", ";", "$", "this", "->", "headerRow", "=", "$", "this", "->", "remapHeader", "(", "$", "srcRow", ")", ";", "}" ]
Get a header row from the CSV file.
[ "Get", "a", "header", "row", "from", "the", "CSV", "file", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CSVParser.php#L198-L208
train
silverstripe/silverstripe-framework
src/View/ThemeManifest.php
ThemeManifest.getCacheKey
public function getCacheKey($includeTests = false) { return sha1(sprintf( "manifest-%s-%s-%u", $this->base, $this->project, $includeTests )); }
php
public function getCacheKey($includeTests = false) { return sha1(sprintf( "manifest-%s-%s-%u", $this->base, $this->project, $includeTests )); }
[ "public", "function", "getCacheKey", "(", "$", "includeTests", "=", "false", ")", "{", "return", "sha1", "(", "sprintf", "(", "\"manifest-%s-%s-%u\"", ",", "$", "this", "->", "base", ",", "$", "this", "->", "project", ",", "$", "includeTests", ")", ")", ";", "}" ]
Generate a unique cache key to avoid manifest cache collisions. We compartmentalise based on the base path, the given project, and whether or not we intend to include tests. @param bool $includeTests @return string
[ "Generate", "a", "unique", "cache", "key", "to", "avoid", "manifest", "cache", "collisions", ".", "We", "compartmentalise", "based", "on", "the", "base", "path", "the", "given", "project", "and", "whether", "or", "not", "we", "intend", "to", "include", "tests", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeManifest.php#L110-L118
train
silverstripe/silverstripe-framework
src/View/ThemeManifest.php
ThemeManifest.handleDirectory
public function handleDirectory($basename, $pathname, $depth) { if ($basename !== self::TEMPLATES_DIR) { return; } $dir = trim(substr(dirname($pathname), strlen($this->base)), '/\\'); $this->themes[] = "/" . $dir; }
php
public function handleDirectory($basename, $pathname, $depth) { if ($basename !== self::TEMPLATES_DIR) { return; } $dir = trim(substr(dirname($pathname), strlen($this->base)), '/\\'); $this->themes[] = "/" . $dir; }
[ "public", "function", "handleDirectory", "(", "$", "basename", ",", "$", "pathname", ",", "$", "depth", ")", "{", "if", "(", "$", "basename", "!==", "self", "::", "TEMPLATES_DIR", ")", "{", "return", ";", "}", "$", "dir", "=", "trim", "(", "substr", "(", "dirname", "(", "$", "pathname", ")", ",", "strlen", "(", "$", "this", "->", "base", ")", ")", ",", "'/\\\\'", ")", ";", "$", "this", "->", "themes", "[", "]", "=", "\"/\"", ".", "$", "dir", ";", "}" ]
Add a directory to the manifest @param string $basename @param string $pathname @param int $depth
[ "Add", "a", "directory", "to", "the", "manifest" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeManifest.php#L162-L169
train
silverstripe/silverstripe-framework
src/View/ThemeResourceLoader.php
ThemeResourceLoader.getSet
public function getSet($set) { if (isset($this->sets[$set])) { return $this->sets[$set]; } return null; }
php
public function getSet($set) { if (isset($this->sets[$set])) { return $this->sets[$set]; } return null; }
[ "public", "function", "getSet", "(", "$", "set", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "sets", "[", "$", "set", "]", ")", ")", "{", "return", "$", "this", "->", "sets", "[", "$", "set", "]", ";", "}", "return", "null", ";", "}" ]
Get a named theme set @param string $set @return ThemeList
[ "Get", "a", "named", "theme", "set" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeResourceLoader.php#L83-L89
train
silverstripe/silverstripe-framework
src/View/ThemeResourceLoader.php
ThemeResourceLoader.getPath
public function getPath($identifier) { $slashPos = strpos($identifier, '/'); $parts = explode(':', $identifier, 2); // If identifier starts with "/", it's a path from root if ($slashPos === 0) { if (count($parts) > 1) { throw new InvalidArgumentException("Invalid theme identifier {$identifier}"); } return Path::normalise($identifier, true); } // If there is no slash / colon it's a legacy theme if ($slashPos === false && count($parts) === 1) { return Path::join(THEMES_DIR, $identifier); } // Extract from <vendor>/<module>:<theme> format. // <vendor> is optional, and if <theme> is omitted it defaults to the module root dir. // If <theme> is included, this is the name of the directory under moduleroot/themes/ // which contains the theme. // <module> is always the name of the install directory, not necessarily the composer name. // Find module from first part $moduleName = $parts[0]; $module = ModuleLoader::inst()->getManifest()->getModule($moduleName); if ($module) { $modulePath = $module->getRelativePath(); } else { // If no module could be found, assume based on basename // with a warning if (strstr('/', $moduleName)) { list(, $modulePath) = explode('/', $parts[0], 2); } else { $modulePath = $moduleName; } trigger_error("No module named {$moduleName} found. Assuming path {$modulePath}", E_USER_WARNING); } // Parse relative path for this theme within this module $theme = count($parts) > 1 ? $parts[1] : ''; if (empty($theme)) { // "module/vendor:" // "module/vendor" $subpath = ''; } elseif (strpos($theme, '/') === 0) { // "module/vendor:/sub/path" $subpath = rtrim($theme, '/'); } else { // "module/vendor:subtheme" $subpath = '/themes/' . $theme; } // Join module with subpath return Path::normalise($modulePath . $subpath, true); }
php
public function getPath($identifier) { $slashPos = strpos($identifier, '/'); $parts = explode(':', $identifier, 2); // If identifier starts with "/", it's a path from root if ($slashPos === 0) { if (count($parts) > 1) { throw new InvalidArgumentException("Invalid theme identifier {$identifier}"); } return Path::normalise($identifier, true); } // If there is no slash / colon it's a legacy theme if ($slashPos === false && count($parts) === 1) { return Path::join(THEMES_DIR, $identifier); } // Extract from <vendor>/<module>:<theme> format. // <vendor> is optional, and if <theme> is omitted it defaults to the module root dir. // If <theme> is included, this is the name of the directory under moduleroot/themes/ // which contains the theme. // <module> is always the name of the install directory, not necessarily the composer name. // Find module from first part $moduleName = $parts[0]; $module = ModuleLoader::inst()->getManifest()->getModule($moduleName); if ($module) { $modulePath = $module->getRelativePath(); } else { // If no module could be found, assume based on basename // with a warning if (strstr('/', $moduleName)) { list(, $modulePath) = explode('/', $parts[0], 2); } else { $modulePath = $moduleName; } trigger_error("No module named {$moduleName} found. Assuming path {$modulePath}", E_USER_WARNING); } // Parse relative path for this theme within this module $theme = count($parts) > 1 ? $parts[1] : ''; if (empty($theme)) { // "module/vendor:" // "module/vendor" $subpath = ''; } elseif (strpos($theme, '/') === 0) { // "module/vendor:/sub/path" $subpath = rtrim($theme, '/'); } else { // "module/vendor:subtheme" $subpath = '/themes/' . $theme; } // Join module with subpath return Path::normalise($modulePath . $subpath, true); }
[ "public", "function", "getPath", "(", "$", "identifier", ")", "{", "$", "slashPos", "=", "strpos", "(", "$", "identifier", ",", "'/'", ")", ";", "$", "parts", "=", "explode", "(", "':'", ",", "$", "identifier", ",", "2", ")", ";", "// If identifier starts with \"/\", it's a path from root", "if", "(", "$", "slashPos", "===", "0", ")", "{", "if", "(", "count", "(", "$", "parts", ")", ">", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid theme identifier {$identifier}\"", ")", ";", "}", "return", "Path", "::", "normalise", "(", "$", "identifier", ",", "true", ")", ";", "}", "// If there is no slash / colon it's a legacy theme", "if", "(", "$", "slashPos", "===", "false", "&&", "count", "(", "$", "parts", ")", "===", "1", ")", "{", "return", "Path", "::", "join", "(", "THEMES_DIR", ",", "$", "identifier", ")", ";", "}", "// Extract from <vendor>/<module>:<theme> format.", "// <vendor> is optional, and if <theme> is omitted it defaults to the module root dir.", "// If <theme> is included, this is the name of the directory under moduleroot/themes/", "// which contains the theme.", "// <module> is always the name of the install directory, not necessarily the composer name.", "// Find module from first part", "$", "moduleName", "=", "$", "parts", "[", "0", "]", ";", "$", "module", "=", "ModuleLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getModule", "(", "$", "moduleName", ")", ";", "if", "(", "$", "module", ")", "{", "$", "modulePath", "=", "$", "module", "->", "getRelativePath", "(", ")", ";", "}", "else", "{", "// If no module could be found, assume based on basename", "// with a warning", "if", "(", "strstr", "(", "'/'", ",", "$", "moduleName", ")", ")", "{", "list", "(", ",", "$", "modulePath", ")", "=", "explode", "(", "'/'", ",", "$", "parts", "[", "0", "]", ",", "2", ")", ";", "}", "else", "{", "$", "modulePath", "=", "$", "moduleName", ";", "}", "trigger_error", "(", "\"No module named {$moduleName} found. Assuming path {$modulePath}\"", ",", "E_USER_WARNING", ")", ";", "}", "// Parse relative path for this theme within this module", "$", "theme", "=", "count", "(", "$", "parts", ")", ">", "1", "?", "$", "parts", "[", "1", "]", ":", "''", ";", "if", "(", "empty", "(", "$", "theme", ")", ")", "{", "// \"module/vendor:\"", "// \"module/vendor\"", "$", "subpath", "=", "''", ";", "}", "elseif", "(", "strpos", "(", "$", "theme", ",", "'/'", ")", "===", "0", ")", "{", "// \"module/vendor:/sub/path\"", "$", "subpath", "=", "rtrim", "(", "$", "theme", ",", "'/'", ")", ";", "}", "else", "{", "// \"module/vendor:subtheme\"", "$", "subpath", "=", "'/themes/'", ".", "$", "theme", ";", "}", "// Join module with subpath", "return", "Path", "::", "normalise", "(", "$", "modulePath", ".", "$", "subpath", ",", "true", ")", ";", "}" ]
Given a theme identifier, determine the path from the root directory The mapping from $identifier to path follows these rules: - A simple theme name ('mytheme') which maps to the standard themes dir (/themes/mytheme) - A theme path with a leading slash ('/mymodule/themes/mytheme') which maps directly to that path. - or a vendored theme path. (vendor/mymodule:mytheme) which maps to the nested 'theme' within that module. ('/mymodule/themes/mytheme'). - A vendored module with no nested theme (vendor/mymodule) which maps to the root directory of that module. ('/mymodule'). @param string $identifier Theme identifier. @return string Path from root, not including leading or trailing forward slash. E.g. themes/mytheme
[ "Given", "a", "theme", "identifier", "determine", "the", "path", "from", "the", "root", "directory" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeResourceLoader.php#L105-L161
train
silverstripe/silverstripe-framework
src/View/ThemeResourceLoader.php
ThemeResourceLoader.findTemplate
public function findTemplate($template, $themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } // Look for a cached result for this data set $cacheKey = md5(json_encode($template) . json_encode($themes)); if ($this->getCache()->has($cacheKey)) { return $this->getCache()->get($cacheKey); } $type = ''; if (is_array($template)) { // Check if templates has type specified if (array_key_exists('type', $template)) { $type = $template['type']; unset($template['type']); } // Templates are either nested in 'templates' or just the rest of the list $templateList = array_key_exists('templates', $template) ? $template['templates'] : $template; } else { $templateList = array($template); } foreach ($templateList as $i => $template) { // Check if passed list of templates in array format if (is_array($template)) { $path = $this->findTemplate($template, $themes); if ($path) { $this->getCache()->set($cacheKey, $path); return $path; } continue; } // If we have an .ss extension, this is a path, not a template name. We should // pass in templates without extensions in order for template manifest to find // files dynamically. if (substr($template, -3) == '.ss' && file_exists($template)) { $this->getCache()->set($cacheKey, $template); return $template; } // Check string template identifier $template = str_replace('\\', '/', $template); $parts = explode('/', $template); $tail = array_pop($parts); $head = implode('/', $parts); $themePaths = $this->getThemePaths($themes); foreach ($themePaths as $themePath) { // Join path $pathParts = [ $this->base, $themePath, 'templates', $head, $type, $tail ]; $path = Path::join($pathParts) . '.ss'; if (file_exists($path)) { $this->getCache()->set($cacheKey, $path); return $path; } } } // No template found $this->getCache()->set($cacheKey, null); return null; }
php
public function findTemplate($template, $themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } // Look for a cached result for this data set $cacheKey = md5(json_encode($template) . json_encode($themes)); if ($this->getCache()->has($cacheKey)) { return $this->getCache()->get($cacheKey); } $type = ''; if (is_array($template)) { // Check if templates has type specified if (array_key_exists('type', $template)) { $type = $template['type']; unset($template['type']); } // Templates are either nested in 'templates' or just the rest of the list $templateList = array_key_exists('templates', $template) ? $template['templates'] : $template; } else { $templateList = array($template); } foreach ($templateList as $i => $template) { // Check if passed list of templates in array format if (is_array($template)) { $path = $this->findTemplate($template, $themes); if ($path) { $this->getCache()->set($cacheKey, $path); return $path; } continue; } // If we have an .ss extension, this is a path, not a template name. We should // pass in templates without extensions in order for template manifest to find // files dynamically. if (substr($template, -3) == '.ss' && file_exists($template)) { $this->getCache()->set($cacheKey, $template); return $template; } // Check string template identifier $template = str_replace('\\', '/', $template); $parts = explode('/', $template); $tail = array_pop($parts); $head = implode('/', $parts); $themePaths = $this->getThemePaths($themes); foreach ($themePaths as $themePath) { // Join path $pathParts = [ $this->base, $themePath, 'templates', $head, $type, $tail ]; $path = Path::join($pathParts) . '.ss'; if (file_exists($path)) { $this->getCache()->set($cacheKey, $path); return $path; } } } // No template found $this->getCache()->set($cacheKey, null); return null; }
[ "public", "function", "findTemplate", "(", "$", "template", ",", "$", "themes", "=", "null", ")", "{", "if", "(", "$", "themes", "===", "null", ")", "{", "$", "themes", "=", "SSViewer", "::", "get_themes", "(", ")", ";", "}", "// Look for a cached result for this data set", "$", "cacheKey", "=", "md5", "(", "json_encode", "(", "$", "template", ")", ".", "json_encode", "(", "$", "themes", ")", ")", ";", "if", "(", "$", "this", "->", "getCache", "(", ")", "->", "has", "(", "$", "cacheKey", ")", ")", "{", "return", "$", "this", "->", "getCache", "(", ")", "->", "get", "(", "$", "cacheKey", ")", ";", "}", "$", "type", "=", "''", ";", "if", "(", "is_array", "(", "$", "template", ")", ")", "{", "// Check if templates has type specified", "if", "(", "array_key_exists", "(", "'type'", ",", "$", "template", ")", ")", "{", "$", "type", "=", "$", "template", "[", "'type'", "]", ";", "unset", "(", "$", "template", "[", "'type'", "]", ")", ";", "}", "// Templates are either nested in 'templates' or just the rest of the list", "$", "templateList", "=", "array_key_exists", "(", "'templates'", ",", "$", "template", ")", "?", "$", "template", "[", "'templates'", "]", ":", "$", "template", ";", "}", "else", "{", "$", "templateList", "=", "array", "(", "$", "template", ")", ";", "}", "foreach", "(", "$", "templateList", "as", "$", "i", "=>", "$", "template", ")", "{", "// Check if passed list of templates in array format", "if", "(", "is_array", "(", "$", "template", ")", ")", "{", "$", "path", "=", "$", "this", "->", "findTemplate", "(", "$", "template", ",", "$", "themes", ")", ";", "if", "(", "$", "path", ")", "{", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "cacheKey", ",", "$", "path", ")", ";", "return", "$", "path", ";", "}", "continue", ";", "}", "// If we have an .ss extension, this is a path, not a template name. We should", "// pass in templates without extensions in order for template manifest to find", "// files dynamically.", "if", "(", "substr", "(", "$", "template", ",", "-", "3", ")", "==", "'.ss'", "&&", "file_exists", "(", "$", "template", ")", ")", "{", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "cacheKey", ",", "$", "template", ")", ";", "return", "$", "template", ";", "}", "// Check string template identifier", "$", "template", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "template", ")", ";", "$", "parts", "=", "explode", "(", "'/'", ",", "$", "template", ")", ";", "$", "tail", "=", "array_pop", "(", "$", "parts", ")", ";", "$", "head", "=", "implode", "(", "'/'", ",", "$", "parts", ")", ";", "$", "themePaths", "=", "$", "this", "->", "getThemePaths", "(", "$", "themes", ")", ";", "foreach", "(", "$", "themePaths", "as", "$", "themePath", ")", "{", "// Join path", "$", "pathParts", "=", "[", "$", "this", "->", "base", ",", "$", "themePath", ",", "'templates'", ",", "$", "head", ",", "$", "type", ",", "$", "tail", "]", ";", "$", "path", "=", "Path", "::", "join", "(", "$", "pathParts", ")", ".", "'.ss'", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "cacheKey", ",", "$", "path", ")", ";", "return", "$", "path", ";", "}", "}", "}", "// No template found", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "cacheKey", ",", "null", ")", ";", "return", "null", ";", "}" ]
Attempts to find possible candidate templates from a set of template names from modules, current theme directory and finally the application folder. The template names can be passed in as plain strings, or be in the format "type/name", where type is the type of template to search for (e.g. Includes, Layout). The results of this method will be cached for future use. @param string|array $template Template name, or template spec in array format with the keys 'type' (type string) and 'templates' (template hierarchy in order of precedence). If 'templates' is ommitted then any other item in the array will be treated as the template list, or list of templates each in the array spec given. Templates with an .ss extension will be treated as file paths, and will bypass theme-coupled resolution. @param array $themes List of themes to use to resolve themes. Defaults to {@see SSViewer::get_themes()} @return string Absolute path to resolved template file, or null if not resolved. File location will be in the format themes/<theme>/templates/<directories>/<type>/<basename>.ss Note that type (e.g. 'Layout') is not the root level directory under 'templates'.
[ "Attempts", "to", "find", "possible", "candidate", "templates", "from", "a", "set", "of", "template", "names", "from", "modules", "current", "theme", "directory", "and", "finally", "the", "application", "folder", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeResourceLoader.php#L185-L250
train
silverstripe/silverstripe-framework
src/View/ThemeResourceLoader.php
ThemeResourceLoader.findThemedJavascript
public function findThemedJavascript($name, $themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } if (substr($name, -3) !== '.js') { $name .= '.js'; } $filename = $this->findThemedResource("javascript/$name", $themes); if ($filename === null) { $filename = $this->findThemedResource($name, $themes); } return $filename; }
php
public function findThemedJavascript($name, $themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } if (substr($name, -3) !== '.js') { $name .= '.js'; } $filename = $this->findThemedResource("javascript/$name", $themes); if ($filename === null) { $filename = $this->findThemedResource($name, $themes); } return $filename; }
[ "public", "function", "findThemedJavascript", "(", "$", "name", ",", "$", "themes", "=", "null", ")", "{", "if", "(", "$", "themes", "===", "null", ")", "{", "$", "themes", "=", "SSViewer", "::", "get_themes", "(", ")", ";", "}", "if", "(", "substr", "(", "$", "name", ",", "-", "3", ")", "!==", "'.js'", ")", "{", "$", "name", ".=", "'.js'", ";", "}", "$", "filename", "=", "$", "this", "->", "findThemedResource", "(", "\"javascript/$name\"", ",", "$", "themes", ")", ";", "if", "(", "$", "filename", "===", "null", ")", "{", "$", "filename", "=", "$", "this", "->", "findThemedResource", "(", "$", "name", ",", "$", "themes", ")", ";", "}", "return", "$", "filename", ";", "}" ]
Resolve themed javascript path A javascript file in the current theme path name 'themename/javascript/$name.js' is first searched for, and it that doesn't exist and the module parameter is set then a javascript file with that name in the module is used. @param string $name The name of the file - eg '/js/File.js' would have the name 'File' @param array $themes List of themes, Defaults to {@see SSViewer::get_themes()} @return string Path to resolved javascript file (relative to base dir)
[ "Resolve", "themed", "javascript", "path" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeResourceLoader.php#L288-L304
train
silverstripe/silverstripe-framework
src/View/ThemeResourceLoader.php
ThemeResourceLoader.findThemedResource
public function findThemedResource($resource, $themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } $paths = $this->getThemePaths($themes); foreach ($paths as $themePath) { $relativePath = Path::join($themePath, $resource); $absolutePath = Path::join($this->base, $relativePath); if (file_exists($absolutePath)) { return $relativePath; } } // Resource exists in no context return null; }
php
public function findThemedResource($resource, $themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } $paths = $this->getThemePaths($themes); foreach ($paths as $themePath) { $relativePath = Path::join($themePath, $resource); $absolutePath = Path::join($this->base, $relativePath); if (file_exists($absolutePath)) { return $relativePath; } } // Resource exists in no context return null; }
[ "public", "function", "findThemedResource", "(", "$", "resource", ",", "$", "themes", "=", "null", ")", "{", "if", "(", "$", "themes", "===", "null", ")", "{", "$", "themes", "=", "SSViewer", "::", "get_themes", "(", ")", ";", "}", "$", "paths", "=", "$", "this", "->", "getThemePaths", "(", "$", "themes", ")", ";", "foreach", "(", "$", "paths", "as", "$", "themePath", ")", "{", "$", "relativePath", "=", "Path", "::", "join", "(", "$", "themePath", ",", "$", "resource", ")", ";", "$", "absolutePath", "=", "Path", "::", "join", "(", "$", "this", "->", "base", ",", "$", "relativePath", ")", ";", "if", "(", "file_exists", "(", "$", "absolutePath", ")", ")", "{", "return", "$", "relativePath", ";", "}", "}", "// Resource exists in no context", "return", "null", ";", "}" ]
Resolve a themed resource A themed resource and be any file that resides in a theme folder. @param string $resource A file path relative to the root folder of a theme @param array $themes An order listed of themes to search, Defaults to {@see SSViewer::get_themes()} @return string
[ "Resolve", "a", "themed", "resource" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeResourceLoader.php#L315-L333
train
silverstripe/silverstripe-framework
src/View/ThemeResourceLoader.php
ThemeResourceLoader.getThemePaths
public function getThemePaths($themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } $paths = []; foreach ($themes as $themename) { // Expand theme sets $set = $this->getSet($themename); $subthemes = $set ? $set->getThemes() : [$themename]; // Resolve paths foreach ($subthemes as $theme) { $paths[] = $this->getPath($theme); } } return $paths; }
php
public function getThemePaths($themes = null) { if ($themes === null) { $themes = SSViewer::get_themes(); } $paths = []; foreach ($themes as $themename) { // Expand theme sets $set = $this->getSet($themename); $subthemes = $set ? $set->getThemes() : [$themename]; // Resolve paths foreach ($subthemes as $theme) { $paths[] = $this->getPath($theme); } } return $paths; }
[ "public", "function", "getThemePaths", "(", "$", "themes", "=", "null", ")", "{", "if", "(", "$", "themes", "===", "null", ")", "{", "$", "themes", "=", "SSViewer", "::", "get_themes", "(", ")", ";", "}", "$", "paths", "=", "[", "]", ";", "foreach", "(", "$", "themes", "as", "$", "themename", ")", "{", "// Expand theme sets", "$", "set", "=", "$", "this", "->", "getSet", "(", "$", "themename", ")", ";", "$", "subthemes", "=", "$", "set", "?", "$", "set", "->", "getThemes", "(", ")", ":", "[", "$", "themename", "]", ";", "// Resolve paths", "foreach", "(", "$", "subthemes", "as", "$", "theme", ")", "{", "$", "paths", "[", "]", "=", "$", "this", "->", "getPath", "(", "$", "theme", ")", ";", "}", "}", "return", "$", "paths", ";", "}" ]
Resolve all themes to the list of root folders relative to site root @param array $themes List of themes to resolve. Supports named theme sets. Defaults to {@see SSViewer::get_themes()}. @return array List of root-relative folders in order of precendence.
[ "Resolve", "all", "themes", "to", "the", "list", "of", "root", "folders", "relative", "to", "site", "root" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ThemeResourceLoader.php#L341-L359
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.setUrl
public function setUrl($url) { $this->url = $url; // Normalize URL if its relative (strictly speaking), or has leading slashes if (Director::is_relative_url($url) || preg_match('/^\//', $url)) { $this->url = preg_replace(array('/\/+/','/^\//', '/\/$/'), array('/','',''), $this->url); } if (preg_match('/^(.*)\.([A-Za-z][A-Za-z0-9]*)$/', $this->url, $matches)) { $this->url = $matches[1]; $this->extension = $matches[2]; } if ($this->url) { $this->dirParts = preg_split('|/+|', $this->url); } else { $this->dirParts = array(); } return $this; }
php
public function setUrl($url) { $this->url = $url; // Normalize URL if its relative (strictly speaking), or has leading slashes if (Director::is_relative_url($url) || preg_match('/^\//', $url)) { $this->url = preg_replace(array('/\/+/','/^\//', '/\/$/'), array('/','',''), $this->url); } if (preg_match('/^(.*)\.([A-Za-z][A-Za-z0-9]*)$/', $this->url, $matches)) { $this->url = $matches[1]; $this->extension = $matches[2]; } if ($this->url) { $this->dirParts = preg_split('|/+|', $this->url); } else { $this->dirParts = array(); } return $this; }
[ "public", "function", "setUrl", "(", "$", "url", ")", "{", "$", "this", "->", "url", "=", "$", "url", ";", "// Normalize URL if its relative (strictly speaking), or has leading slashes", "if", "(", "Director", "::", "is_relative_url", "(", "$", "url", ")", "||", "preg_match", "(", "'/^\\//'", ",", "$", "url", ")", ")", "{", "$", "this", "->", "url", "=", "preg_replace", "(", "array", "(", "'/\\/+/'", ",", "'/^\\//'", ",", "'/\\/$/'", ")", ",", "array", "(", "'/'", ",", "''", ",", "''", ")", ",", "$", "this", "->", "url", ")", ";", "}", "if", "(", "preg_match", "(", "'/^(.*)\\.([A-Za-z][A-Za-z0-9]*)$/'", ",", "$", "this", "->", "url", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "url", "=", "$", "matches", "[", "1", "]", ";", "$", "this", "->", "extension", "=", "$", "matches", "[", "2", "]", ";", "}", "if", "(", "$", "this", "->", "url", ")", "{", "$", "this", "->", "dirParts", "=", "preg_split", "(", "'|/+|'", ",", "$", "this", "->", "url", ")", ";", "}", "else", "{", "$", "this", "->", "dirParts", "=", "array", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Allow the setting of a URL This is here so that RootURLController can change the URL of the request without us loosing all the other info attached (like headers) @param string $url The new URL @return HTTPRequest The updated request
[ "Allow", "the", "setting", "of", "a", "URL" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L176-L195
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.addHeader
public function addHeader($header, $value) { $header = strtolower($header); $this->headers[$header] = $value; return $this; }
php
public function addHeader($header, $value) { $header = strtolower($header); $this->headers[$header] = $value; return $this; }
[ "public", "function", "addHeader", "(", "$", "header", ",", "$", "value", ")", "{", "$", "header", "=", "strtolower", "(", "$", "header", ")", ";", "$", "this", "->", "headers", "[", "$", "header", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Add a HTTP header to the response, replacing any header of the same name. @param string $header Example: "content-type" @param string $value Example: "text/xml"
[ "Add", "a", "HTTP", "header", "to", "the", "response", "replacing", "any", "header", "of", "the", "same", "name", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L355-L360
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.getURL
public function getURL($includeGetVars = false) { $url = ($this->getExtension()) ? $this->url . '.' . $this->getExtension() : $this->url; if ($includeGetVars) { $vars = $this->getVars(); if (count($vars)) { $url .= '?' . http_build_query($vars); } } elseif (strpos($url, "?") !== false) { $url = substr($url, 0, strpos($url, "?")); } return $url; }
php
public function getURL($includeGetVars = false) { $url = ($this->getExtension()) ? $this->url . '.' . $this->getExtension() : $this->url; if ($includeGetVars) { $vars = $this->getVars(); if (count($vars)) { $url .= '?' . http_build_query($vars); } } elseif (strpos($url, "?") !== false) { $url = substr($url, 0, strpos($url, "?")); } return $url; }
[ "public", "function", "getURL", "(", "$", "includeGetVars", "=", "false", ")", "{", "$", "url", "=", "(", "$", "this", "->", "getExtension", "(", ")", ")", "?", "$", "this", "->", "url", ".", "'.'", ".", "$", "this", "->", "getExtension", "(", ")", ":", "$", "this", "->", "url", ";", "if", "(", "$", "includeGetVars", ")", "{", "$", "vars", "=", "$", "this", "->", "getVars", "(", ")", ";", "if", "(", "count", "(", "$", "vars", ")", ")", "{", "$", "url", ".=", "'?'", ".", "http_build_query", "(", "$", "vars", ")", ";", "}", "}", "elseif", "(", "strpos", "(", "$", "url", ",", "\"?\"", ")", "!==", "false", ")", "{", "$", "url", "=", "substr", "(", "$", "url", ",", "0", ",", "strpos", "(", "$", "url", ",", "\"?\"", ")", ")", ";", "}", "return", "$", "url", ";", "}" ]
Returns the URL used to generate the page @param bool $includeGetVars whether or not to include the get parameters\ @return string
[ "Returns", "the", "URL", "used", "to", "generate", "the", "page" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L402-L416
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.shiftAllParams
public function shiftAllParams() { $keys = array_keys($this->allParams); $values = array_values($this->allParams); $value = array_shift($values); // push additional unparsed URL parts onto the parameter stack if (array_key_exists($this->unshiftedButParsedParts, $this->dirParts)) { $values[] = $this->dirParts[$this->unshiftedButParsedParts]; } foreach ($keys as $position => $key) { $this->allParams[$key] = isset($values[$position]) ? $values[$position] : null; } return $value; }
php
public function shiftAllParams() { $keys = array_keys($this->allParams); $values = array_values($this->allParams); $value = array_shift($values); // push additional unparsed URL parts onto the parameter stack if (array_key_exists($this->unshiftedButParsedParts, $this->dirParts)) { $values[] = $this->dirParts[$this->unshiftedButParsedParts]; } foreach ($keys as $position => $key) { $this->allParams[$key] = isset($values[$position]) ? $values[$position] : null; } return $value; }
[ "public", "function", "shiftAllParams", "(", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "this", "->", "allParams", ")", ";", "$", "values", "=", "array_values", "(", "$", "this", "->", "allParams", ")", ";", "$", "value", "=", "array_shift", "(", "$", "values", ")", ";", "// push additional unparsed URL parts onto the parameter stack", "if", "(", "array_key_exists", "(", "$", "this", "->", "unshiftedButParsedParts", ",", "$", "this", "->", "dirParts", ")", ")", "{", "$", "values", "[", "]", "=", "$", "this", "->", "dirParts", "[", "$", "this", "->", "unshiftedButParsedParts", "]", ";", "}", "foreach", "(", "$", "keys", "as", "$", "position", "=>", "$", "key", ")", "{", "$", "this", "->", "allParams", "[", "$", "key", "]", "=", "isset", "(", "$", "values", "[", "$", "position", "]", ")", "?", "$", "values", "[", "$", "position", "]", ":", "null", ";", "}", "return", "$", "value", ";", "}" ]
Shift all the parameter values down a key space, and return the shifted value. @return string
[ "Shift", "all", "the", "parameter", "values", "down", "a", "key", "space", "and", "return", "the", "shifted", "value", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L621-L637
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.isEmptyPattern
public function isEmptyPattern($pattern) { if (preg_match('/^([A-Za-z]+) +(.*)$/', $pattern, $matches)) { $pattern = $matches[2]; } if (trim($pattern) == "") { return true; } return false; }
php
public function isEmptyPattern($pattern) { if (preg_match('/^([A-Za-z]+) +(.*)$/', $pattern, $matches)) { $pattern = $matches[2]; } if (trim($pattern) == "") { return true; } return false; }
[ "public", "function", "isEmptyPattern", "(", "$", "pattern", ")", "{", "if", "(", "preg_match", "(", "'/^([A-Za-z]+) +(.*)$/'", ",", "$", "pattern", ",", "$", "matches", ")", ")", "{", "$", "pattern", "=", "$", "matches", "[", "2", "]", ";", "}", "if", "(", "trim", "(", "$", "pattern", ")", "==", "\"\"", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Returns true if this is a URL that will match without shifting off any of the URL. This is used by the request handler to prevent infinite parsing loops. @param string $pattern @return bool
[ "Returns", "true", "if", "this", "is", "a", "URL", "that", "will", "match", "without", "shifting", "off", "any", "of", "the", "URL", ".", "This", "is", "used", "by", "the", "request", "handler", "to", "prevent", "infinite", "parsing", "loops", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L722-L732
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.shift
public function shift($count = 1) { $return = array(); if ($count == 1) { return array_shift($this->dirParts); } for ($i=0; $i<$count; $i++) { $value = array_shift($this->dirParts); if ($value === null) { break; } $return[] = $value; } return $return; }
php
public function shift($count = 1) { $return = array(); if ($count == 1) { return array_shift($this->dirParts); } for ($i=0; $i<$count; $i++) { $value = array_shift($this->dirParts); if ($value === null) { break; } $return[] = $value; } return $return; }
[ "public", "function", "shift", "(", "$", "count", "=", "1", ")", "{", "$", "return", "=", "array", "(", ")", ";", "if", "(", "$", "count", "==", "1", ")", "{", "return", "array_shift", "(", "$", "this", "->", "dirParts", ")", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "value", "=", "array_shift", "(", "$", "this", "->", "dirParts", ")", ";", "if", "(", "$", "value", "===", "null", ")", "{", "break", ";", "}", "$", "return", "[", "]", "=", "$", "value", ";", "}", "return", "$", "return", ";", "}" ]
Shift one or more parts off the beginning of the URL. If you specify shifting more than 1 item off, then the items will be returned as an array @param int $count Shift Count @return string|array
[ "Shift", "one", "or", "more", "parts", "off", "the", "beginning", "of", "the", "URL", ".", "If", "you", "specify", "shifting", "more", "than", "1", "item", "off", "then", "the", "items", "will", "be", "returned", "as", "an", "array" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L741-L760
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.setIP
public function setIP($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { throw new InvalidArgumentException("Invalid ip $ip"); } $this->ip = $ip; return $this; }
php
public function setIP($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { throw new InvalidArgumentException("Invalid ip $ip"); } $this->ip = $ip; return $this; }
[ "public", "function", "setIP", "(", "$", "ip", ")", "{", "if", "(", "!", "filter_var", "(", "$", "ip", ",", "FILTER_VALIDATE_IP", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid ip $ip\"", ")", ";", "}", "$", "this", "->", "ip", "=", "$", "ip", ";", "return", "$", "this", ";", "}" ]
Sets the client IP address which originated this request. Use setIPFromHeaderValue if assigning from header value. @param $ip string @return $this
[ "Sets", "the", "client", "IP", "address", "which", "originated", "this", "request", ".", "Use", "setIPFromHeaderValue", "if", "assigning", "from", "header", "value", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L798-L805
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.getAcceptMimetypes
public function getAcceptMimetypes($includeQuality = false) { $mimetypes = array(); $mimetypesWithQuality = preg_split('#\s*,\s*#', $this->getHeader('accept')); foreach ($mimetypesWithQuality as $mimetypeWithQuality) { $mimetypes[] = ($includeQuality) ? $mimetypeWithQuality : preg_replace('/;.*/', '', $mimetypeWithQuality); } return $mimetypes; }
php
public function getAcceptMimetypes($includeQuality = false) { $mimetypes = array(); $mimetypesWithQuality = preg_split('#\s*,\s*#', $this->getHeader('accept')); foreach ($mimetypesWithQuality as $mimetypeWithQuality) { $mimetypes[] = ($includeQuality) ? $mimetypeWithQuality : preg_replace('/;.*/', '', $mimetypeWithQuality); } return $mimetypes; }
[ "public", "function", "getAcceptMimetypes", "(", "$", "includeQuality", "=", "false", ")", "{", "$", "mimetypes", "=", "array", "(", ")", ";", "$", "mimetypesWithQuality", "=", "preg_split", "(", "'#\\s*,\\s*#'", ",", "$", "this", "->", "getHeader", "(", "'accept'", ")", ")", ";", "foreach", "(", "$", "mimetypesWithQuality", "as", "$", "mimetypeWithQuality", ")", "{", "$", "mimetypes", "[", "]", "=", "(", "$", "includeQuality", ")", "?", "$", "mimetypeWithQuality", ":", "preg_replace", "(", "'/;.*/'", ",", "''", ",", "$", "mimetypeWithQuality", ")", ";", "}", "return", "$", "mimetypes", ";", "}" ]
Returns all mimetypes from the HTTP "Accept" header as an array. @param boolean $includeQuality Don't strip away optional "quality indicators", e.g. "application/xml;q=0.9" (Default: false) @return array
[ "Returns", "all", "mimetypes", "from", "the", "HTTP", "Accept", "header", "as", "an", "array", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L815-L823
train
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
HTTPRequest.detect_method
public static function detect_method($origMethod, $postVars) { if (isset($postVars['_method'])) { if (!in_array(strtoupper($postVars['_method']), array('GET','POST','PUT','DELETE','HEAD'))) { user_error('HTTPRequest::detect_method(): Invalid "_method" parameter', E_USER_ERROR); } return strtoupper($postVars['_method']); } else { return $origMethod; } }
php
public static function detect_method($origMethod, $postVars) { if (isset($postVars['_method'])) { if (!in_array(strtoupper($postVars['_method']), array('GET','POST','PUT','DELETE','HEAD'))) { user_error('HTTPRequest::detect_method(): Invalid "_method" parameter', E_USER_ERROR); } return strtoupper($postVars['_method']); } else { return $origMethod; } }
[ "public", "static", "function", "detect_method", "(", "$", "origMethod", ",", "$", "postVars", ")", "{", "if", "(", "isset", "(", "$", "postVars", "[", "'_method'", "]", ")", ")", "{", "if", "(", "!", "in_array", "(", "strtoupper", "(", "$", "postVars", "[", "'_method'", "]", ")", ",", "array", "(", "'GET'", ",", "'POST'", ",", "'PUT'", ",", "'DELETE'", ",", "'HEAD'", ")", ")", ")", "{", "user_error", "(", "'HTTPRequest::detect_method(): Invalid \"_method\" parameter'", ",", "E_USER_ERROR", ")", ";", "}", "return", "strtoupper", "(", "$", "postVars", "[", "'_method'", "]", ")", ";", "}", "else", "{", "return", "$", "origMethod", ";", "}", "}" ]
Gets the "real" HTTP method for a request. Used to work around browser limitations of form submissions to GET and POST, by overriding the HTTP method with a POST parameter called "_method" for PUT, DELETE, HEAD. Using GET for the "_method" override is not supported, as GET should never carry out state changes. Alternatively you can use a custom HTTP header 'X-HTTP-Method-Override' to override the original method. The '_method' POST parameter overrules the custom HTTP header. @param string $origMethod Original HTTP method from the browser request @param array $postVars @return string HTTP method (all uppercase)
[ "Gets", "the", "real", "HTTP", "method", "for", "a", "request", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPRequest.php#L873-L883
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBField.php
DBField.create_field
public static function create_field($spec, $value, $name = null, ...$args) { // Raise warning if inconsistent with DataObject::dbObject() behaviour // This will cause spec args to be shifted down by the number of provided $args if ($args && strpos($spec, '(') !== false) { trigger_error('Additional args provided in both $spec and $args', E_USER_WARNING); } // Ensure name is always first argument array_unshift($args, $name); /** @var DBField $dbField */ $dbField = Injector::inst()->createWithArgs($spec, $args); $dbField->setValue($value, null, false); return $dbField; }
php
public static function create_field($spec, $value, $name = null, ...$args) { // Raise warning if inconsistent with DataObject::dbObject() behaviour // This will cause spec args to be shifted down by the number of provided $args if ($args && strpos($spec, '(') !== false) { trigger_error('Additional args provided in both $spec and $args', E_USER_WARNING); } // Ensure name is always first argument array_unshift($args, $name); /** @var DBField $dbField */ $dbField = Injector::inst()->createWithArgs($spec, $args); $dbField->setValue($value, null, false); return $dbField; }
[ "public", "static", "function", "create_field", "(", "$", "spec", ",", "$", "value", ",", "$", "name", "=", "null", ",", "...", "$", "args", ")", "{", "// Raise warning if inconsistent with DataObject::dbObject() behaviour", "// This will cause spec args to be shifted down by the number of provided $args", "if", "(", "$", "args", "&&", "strpos", "(", "$", "spec", ",", "'('", ")", "!==", "false", ")", "{", "trigger_error", "(", "'Additional args provided in both $spec and $args'", ",", "E_USER_WARNING", ")", ";", "}", "// Ensure name is always first argument", "array_unshift", "(", "$", "args", ",", "$", "name", ")", ";", "/** @var DBField $dbField */", "$", "dbField", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "$", "spec", ",", "$", "args", ")", ";", "$", "dbField", "->", "setValue", "(", "$", "value", ",", "null", ",", "false", ")", ";", "return", "$", "dbField", ";", "}" ]
Create a DBField object that's not bound to any particular field. Useful for accessing the classes behaviour for other parts of your code. @param string $spec Class specification to construct. May include both service name and additional constructor arguments in the same format as DataObject.db config. @param mixed $value value of field @param string $name Name of field @param mixed $args Additional arguments to pass to constructor if not using args in service $spec Note: Will raise a warning if using both @return static
[ "Create", "a", "DBField", "object", "that", "s", "not", "bound", "to", "any", "particular", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBField.php#L164-L178
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBField.php
DBField.setName
public function setName($name) { if ($this->name && $this->name !== $name) { user_error("DBField::setName() shouldn't be called once a DBField already has a name." . "It's partially immutable - it shouldn't be altered after it's given a value.", E_USER_WARNING); } $this->name = $name; return $this; }
php
public function setName($name) { if ($this->name && $this->name !== $name) { user_error("DBField::setName() shouldn't be called once a DBField already has a name." . "It's partially immutable - it shouldn't be altered after it's given a value.", E_USER_WARNING); } $this->name = $name; return $this; }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "if", "(", "$", "this", "->", "name", "&&", "$", "this", "->", "name", "!==", "$", "name", ")", "{", "user_error", "(", "\"DBField::setName() shouldn't be called once a DBField already has a name.\"", ".", "\"It's partially immutable - it shouldn't be altered after it's given a value.\"", ",", "E_USER_WARNING", ")", ";", "}", "$", "this", "->", "name", "=", "$", "name", ";", "return", "$", "this", ";", "}" ]
Set the name of this field. The name should never be altered, but it if was never given a name in the first place you can set a name. If you try an alter the name a warning will be thrown. @param string $name @return $this
[ "Set", "the", "name", "of", "this", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBField.php#L192-L202
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBField.php
DBField.prepValueForDB
public function prepValueForDB($value) { if ($value === null || $value === "" || $value === false || ($this->scalarValueOnly() && !is_scalar($value)) ) { return null; } else { return $value; } }
php
public function prepValueForDB($value) { if ($value === null || $value === "" || $value === false || ($this->scalarValueOnly() && !is_scalar($value)) ) { return null; } else { return $value; } }
[ "public", "function", "prepValueForDB", "(", "$", "value", ")", "{", "if", "(", "$", "value", "===", "null", "||", "$", "value", "===", "\"\"", "||", "$", "value", "===", "false", "||", "(", "$", "this", "->", "scalarValueOnly", "(", ")", "&&", "!", "is_scalar", "(", "$", "value", ")", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "$", "value", ";", "}", "}" ]
Return the transformed value ready to be sent to the database. This value will be escaped automatically by the prepared query processor, so it should not be escaped or quoted at all. @param $value mixed The value to check @return mixed The raw value, or escaped parameterised details
[ "Return", "the", "transformed", "value", "ready", "to", "be", "sent", "to", "the", "database", ".", "This", "value", "will", "be", "escaped", "automatically", "by", "the", "prepared", "query", "processor", "so", "it", "should", "not", "be", "escaped", "or", "quoted", "at", "all", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBField.php#L341-L352
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBField.php
DBField.saveInto
public function saveInto($dataObject) { $fieldName = $this->name; if (empty($fieldName)) { throw new \BadMethodCallException( "DBField::saveInto() Called on a nameless '" . static::class . "' object" ); } $dataObject->$fieldName = $this->value; }
php
public function saveInto($dataObject) { $fieldName = $this->name; if (empty($fieldName)) { throw new \BadMethodCallException( "DBField::saveInto() Called on a nameless '" . static::class . "' object" ); } $dataObject->$fieldName = $this->value; }
[ "public", "function", "saveInto", "(", "$", "dataObject", ")", "{", "$", "fieldName", "=", "$", "this", "->", "name", ";", "if", "(", "empty", "(", "$", "fieldName", ")", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "\"DBField::saveInto() Called on a nameless '\"", ".", "static", "::", "class", ".", "\"' object\"", ")", ";", "}", "$", "dataObject", "->", "$", "fieldName", "=", "$", "this", "->", "value", ";", "}" ]
Saves this field to the given data object. @param DataObject $dataObject
[ "Saves", "this", "field", "to", "the", "given", "data", "object", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBField.php#L537-L546
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBField.php
DBField.scaffoldFormField
public function scaffoldFormField($title = null, $params = null) { return TextField::create($this->name, $title); }
php
public function scaffoldFormField($title = null, $params = null) { return TextField::create($this->name, $title); }
[ "public", "function", "scaffoldFormField", "(", "$", "title", "=", "null", ",", "$", "params", "=", "null", ")", "{", "return", "TextField", "::", "create", "(", "$", "this", "->", "name", ",", "$", "title", ")", ";", "}" ]
Returns a FormField instance used as a default for form scaffolding. Used by {@link SearchContext}, {@link ModelAdmin}, {@link DataObject::scaffoldFormFields()} @param string $title Optional. Localized title of the generated instance @param array $params @return FormField
[ "Returns", "a", "FormField", "instance", "used", "as", "a", "default", "for", "form", "scaffolding", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBField.php#L558-L561
train
silverstripe/silverstripe-framework
thirdparty/php-peg/Compiler.php
Rule.compile
function compile($indent) { $function_name = $this->function_name( $this->name ) ; // Build the typestack $typestack = array(); $class=$this; do { $typestack[] = $this->function_name($class->name); } while($class = $class->extends); $typestack = "array('" . implode("','", $typestack) . "')"; // Build an array of additional arguments to add to result node (if any) if (empty($this->arguments)) { $arguments = 'null'; } else { $arguments = "array("; foreach ($this->arguments as $k=>$v) { $arguments .= "'$k' => '$v'"; } $arguments .= ")"; } $match = PHPBuilder::build() ; $match->l("protected \$match_{$function_name}_typestack = $typestack;"); $match->b( "function match_{$function_name} (\$stack = array())", '$matchrule = "'.$function_name.'"; $result = $this->construct($matchrule, $matchrule, '.$arguments.');', $this->parsed->compile()->replace(array( 'MATCH' => 'return $this->finalise($result);', 'FAIL' => 'return FALSE;' )) ); $functions = array() ; foreach( $this->functions as $name => $function ) { $function_name = $this->function_name( preg_match( '/^_/', $name ) ? $this->name.$name : $this->name.'_'.$name ) ; $functions[] = implode( PHP_EOL, array( 'function ' . $function_name . ' ' . $function )); } // print_r( $match ) ; return '' ; return $match->render(NULL, $indent) . PHP_EOL . PHP_EOL . implode( PHP_EOL, $functions ) ; }
php
function compile($indent) { $function_name = $this->function_name( $this->name ) ; // Build the typestack $typestack = array(); $class=$this; do { $typestack[] = $this->function_name($class->name); } while($class = $class->extends); $typestack = "array('" . implode("','", $typestack) . "')"; // Build an array of additional arguments to add to result node (if any) if (empty($this->arguments)) { $arguments = 'null'; } else { $arguments = "array("; foreach ($this->arguments as $k=>$v) { $arguments .= "'$k' => '$v'"; } $arguments .= ")"; } $match = PHPBuilder::build() ; $match->l("protected \$match_{$function_name}_typestack = $typestack;"); $match->b( "function match_{$function_name} (\$stack = array())", '$matchrule = "'.$function_name.'"; $result = $this->construct($matchrule, $matchrule, '.$arguments.');', $this->parsed->compile()->replace(array( 'MATCH' => 'return $this->finalise($result);', 'FAIL' => 'return FALSE;' )) ); $functions = array() ; foreach( $this->functions as $name => $function ) { $function_name = $this->function_name( preg_match( '/^_/', $name ) ? $this->name.$name : $this->name.'_'.$name ) ; $functions[] = implode( PHP_EOL, array( 'function ' . $function_name . ' ' . $function )); } // print_r( $match ) ; return '' ; return $match->render(NULL, $indent) . PHP_EOL . PHP_EOL . implode( PHP_EOL, $functions ) ; }
[ "function", "compile", "(", "$", "indent", ")", "{", "$", "function_name", "=", "$", "this", "->", "function_name", "(", "$", "this", "->", "name", ")", ";", "// Build the typestack", "$", "typestack", "=", "array", "(", ")", ";", "$", "class", "=", "$", "this", ";", "do", "{", "$", "typestack", "[", "]", "=", "$", "this", "->", "function_name", "(", "$", "class", "->", "name", ")", ";", "}", "while", "(", "$", "class", "=", "$", "class", "->", "extends", ")", ";", "$", "typestack", "=", "\"array('\"", ".", "implode", "(", "\"','\"", ",", "$", "typestack", ")", ".", "\"')\"", ";", "// Build an array of additional arguments to add to result node (if any)", "if", "(", "empty", "(", "$", "this", "->", "arguments", ")", ")", "{", "$", "arguments", "=", "'null'", ";", "}", "else", "{", "$", "arguments", "=", "\"array(\"", ";", "foreach", "(", "$", "this", "->", "arguments", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "arguments", ".=", "\"'$k' => '$v'\"", ";", "}", "$", "arguments", ".=", "\")\"", ";", "}", "$", "match", "=", "PHPBuilder", "::", "build", "(", ")", ";", "$", "match", "->", "l", "(", "\"protected \\$match_{$function_name}_typestack = $typestack;\"", ")", ";", "$", "match", "->", "b", "(", "\"function match_{$function_name} (\\$stack = array())\"", ",", "'$matchrule = \"'", ".", "$", "function_name", ".", "'\"; $result = $this->construct($matchrule, $matchrule, '", ".", "$", "arguments", ".", "');'", ",", "$", "this", "->", "parsed", "->", "compile", "(", ")", "->", "replace", "(", "array", "(", "'MATCH'", "=>", "'return $this->finalise($result);'", ",", "'FAIL'", "=>", "'return FALSE;'", ")", ")", ")", ";", "$", "functions", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "functions", "as", "$", "name", "=>", "$", "function", ")", "{", "$", "function_name", "=", "$", "this", "->", "function_name", "(", "preg_match", "(", "'/^_/'", ",", "$", "name", ")", "?", "$", "this", "->", "name", ".", "$", "name", ":", "$", "this", "->", "name", ".", "'_'", ".", "$", "name", ")", ";", "$", "functions", "[", "]", "=", "implode", "(", "PHP_EOL", ",", "array", "(", "'function '", ".", "$", "function_name", ".", "' '", ".", "$", "function", ")", ")", ";", "}", "// print_r( $match ) ; return '' ;", "return", "$", "match", "->", "render", "(", "NULL", ",", "$", "indent", ")", ".", "PHP_EOL", ".", "PHP_EOL", ".", "implode", "(", "PHP_EOL", ",", "$", "functions", ")", ";", "}" ]
Generate the PHP code for a function to match against a string for this rule
[ "Generate", "the", "PHP", "code", "for", "a", "function", "to", "match", "against", "a", "string", "for", "this", "rule" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/thirdparty/php-peg/Compiler.php#L714-L758
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLDelete.php
SQLDelete.addDelete
public function addDelete($tables) { if (is_array($tables)) { $this->delete = array_merge($this->delete, $tables); } elseif (!empty($tables)) { $this->delete[str_replace(array('"','`'), '', $tables)] = $tables; } return $this; }
php
public function addDelete($tables) { if (is_array($tables)) { $this->delete = array_merge($this->delete, $tables); } elseif (!empty($tables)) { $this->delete[str_replace(array('"','`'), '', $tables)] = $tables; } return $this; }
[ "public", "function", "addDelete", "(", "$", "tables", ")", "{", "if", "(", "is_array", "(", "$", "tables", ")", ")", "{", "$", "this", "->", "delete", "=", "array_merge", "(", "$", "this", "->", "delete", ",", "$", "tables", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "tables", ")", ")", "{", "$", "this", "->", "delete", "[", "str_replace", "(", "array", "(", "'\"'", ",", "'`'", ")", ",", "''", ",", "$", "tables", ")", "]", "=", "$", "tables", ";", "}", "return", "$", "this", ";", "}" ]
Sets the list of tables to limit the delete to, if multiple tables are specified in the condition clause @param string|array $tables Escaped SQL statement, usually an unquoted table name @return $this Self reference
[ "Sets", "the", "list", "of", "tables", "to", "limit", "the", "delete", "to", "if", "multiple", "tables", "are", "specified", "in", "the", "condition", "clause" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLDelete.php#L83-L91
train
silverstripe/silverstripe-framework
src/i18n/Messages/Symfony/SymfonyMessageProvider.php
SymfonyMessageProvider.load
protected function load($locale) { if (isset($this->loadedLocales[$locale])) { return; } // Add full locale file. E.g. 'en_NZ' $this ->getTranslator() ->addResource('ss', $this->getSourceDirs(), $locale); // Add lang-only file. E.g. 'en' $lang = i18n::getData()->langFromLocale($locale); if ($lang !== $locale) { $this ->getTranslator() ->addResource('ss', $this->getSourceDirs(), $lang); } $this->loadedLocales[$locale] = true; }
php
protected function load($locale) { if (isset($this->loadedLocales[$locale])) { return; } // Add full locale file. E.g. 'en_NZ' $this ->getTranslator() ->addResource('ss', $this->getSourceDirs(), $locale); // Add lang-only file. E.g. 'en' $lang = i18n::getData()->langFromLocale($locale); if ($lang !== $locale) { $this ->getTranslator() ->addResource('ss', $this->getSourceDirs(), $lang); } $this->loadedLocales[$locale] = true; }
[ "protected", "function", "load", "(", "$", "locale", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "loadedLocales", "[", "$", "locale", "]", ")", ")", "{", "return", ";", "}", "// Add full locale file. E.g. 'en_NZ'", "$", "this", "->", "getTranslator", "(", ")", "->", "addResource", "(", "'ss'", ",", "$", "this", "->", "getSourceDirs", "(", ")", ",", "$", "locale", ")", ";", "// Add lang-only file. E.g. 'en'", "$", "lang", "=", "i18n", "::", "getData", "(", ")", "->", "langFromLocale", "(", "$", "locale", ")", ";", "if", "(", "$", "lang", "!==", "$", "locale", ")", "{", "$", "this", "->", "getTranslator", "(", ")", "->", "addResource", "(", "'ss'", ",", "$", "this", "->", "getSourceDirs", "(", ")", ",", "$", "lang", ")", ";", "}", "$", "this", "->", "loadedLocales", "[", "$", "locale", "]", "=", "true", ";", "}" ]
Load resources for the given locale @param string $locale
[ "Load", "resources", "for", "the", "given", "locale" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/Messages/Symfony/SymfonyMessageProvider.php#L64-L85
train
silverstripe/silverstripe-framework
src/i18n/Messages/Symfony/SymfonyMessageProvider.php
SymfonyMessageProvider.templateInjection
protected function templateInjection($injection) { $injection = $injection ?: []; // Rewrite injection to {} surrounded placeholders $arguments = array_combine( array_map(function ($val) { return '{' . $val . '}'; }, array_keys($injection)), $injection ); return $arguments; }
php
protected function templateInjection($injection) { $injection = $injection ?: []; // Rewrite injection to {} surrounded placeholders $arguments = array_combine( array_map(function ($val) { return '{' . $val . '}'; }, array_keys($injection)), $injection ); return $arguments; }
[ "protected", "function", "templateInjection", "(", "$", "injection", ")", "{", "$", "injection", "=", "$", "injection", "?", ":", "[", "]", ";", "// Rewrite injection to {} surrounded placeholders", "$", "arguments", "=", "array_combine", "(", "array_map", "(", "function", "(", "$", "val", ")", "{", "return", "'{'", ".", "$", "val", ".", "'}'", ";", "}", ",", "array_keys", "(", "$", "injection", ")", ")", ",", "$", "injection", ")", ";", "return", "$", "arguments", ";", "}" ]
Generate template safe injection parameters @param array $injection @return array Injection array with all keys surrounded with {} placeholders
[ "Generate", "template", "safe", "injection", "parameters" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/Messages/Symfony/SymfonyMessageProvider.php#L165-L176
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.schemaUpdate
public function schemaUpdate($callback) { // Begin schema update $this->schemaIsUpdating = true; // Update table list $this->tableList = array(); $tables = $this->tableList(); foreach ($tables as $table) { $this->tableList[strtolower($table)] = $table; } // Clear update list for client code to mess around with $this->schemaUpdateTransaction = array(); /** @var Exception $error */ $error = null; try { // Yield control to client code $callback(); // If the client code has cancelled the update then abort if (!$this->isSchemaUpdating()) { return; } // End schema update foreach ($this->schemaUpdateTransaction as $tableName => $changes) { $advancedOptions = isset($changes['advancedOptions']) ? $changes['advancedOptions'] : null; switch ($changes['command']) { case 'create': $this->createTable( $tableName, $changes['newFields'], $changes['newIndexes'], $changes['options'], $advancedOptions ); break; case 'alter': $this->alterTable( $tableName, $changes['newFields'], $changes['newIndexes'], $changes['alteredFields'], $changes['alteredIndexes'], $changes['alteredOptions'], $advancedOptions ); break; } } } finally { $this->schemaUpdateTransaction = null; $this->schemaIsUpdating = false; } }
php
public function schemaUpdate($callback) { // Begin schema update $this->schemaIsUpdating = true; // Update table list $this->tableList = array(); $tables = $this->tableList(); foreach ($tables as $table) { $this->tableList[strtolower($table)] = $table; } // Clear update list for client code to mess around with $this->schemaUpdateTransaction = array(); /** @var Exception $error */ $error = null; try { // Yield control to client code $callback(); // If the client code has cancelled the update then abort if (!$this->isSchemaUpdating()) { return; } // End schema update foreach ($this->schemaUpdateTransaction as $tableName => $changes) { $advancedOptions = isset($changes['advancedOptions']) ? $changes['advancedOptions'] : null; switch ($changes['command']) { case 'create': $this->createTable( $tableName, $changes['newFields'], $changes['newIndexes'], $changes['options'], $advancedOptions ); break; case 'alter': $this->alterTable( $tableName, $changes['newFields'], $changes['newIndexes'], $changes['alteredFields'], $changes['alteredIndexes'], $changes['alteredOptions'], $advancedOptions ); break; } } } finally { $this->schemaUpdateTransaction = null; $this->schemaIsUpdating = false; } }
[ "public", "function", "schemaUpdate", "(", "$", "callback", ")", "{", "// Begin schema update", "$", "this", "->", "schemaIsUpdating", "=", "true", ";", "// Update table list", "$", "this", "->", "tableList", "=", "array", "(", ")", ";", "$", "tables", "=", "$", "this", "->", "tableList", "(", ")", ";", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "$", "this", "->", "tableList", "[", "strtolower", "(", "$", "table", ")", "]", "=", "$", "table", ";", "}", "// Clear update list for client code to mess around with", "$", "this", "->", "schemaUpdateTransaction", "=", "array", "(", ")", ";", "/** @var Exception $error */", "$", "error", "=", "null", ";", "try", "{", "// Yield control to client code", "$", "callback", "(", ")", ";", "// If the client code has cancelled the update then abort", "if", "(", "!", "$", "this", "->", "isSchemaUpdating", "(", ")", ")", "{", "return", ";", "}", "// End schema update", "foreach", "(", "$", "this", "->", "schemaUpdateTransaction", "as", "$", "tableName", "=>", "$", "changes", ")", "{", "$", "advancedOptions", "=", "isset", "(", "$", "changes", "[", "'advancedOptions'", "]", ")", "?", "$", "changes", "[", "'advancedOptions'", "]", ":", "null", ";", "switch", "(", "$", "changes", "[", "'command'", "]", ")", "{", "case", "'create'", ":", "$", "this", "->", "createTable", "(", "$", "tableName", ",", "$", "changes", "[", "'newFields'", "]", ",", "$", "changes", "[", "'newIndexes'", "]", ",", "$", "changes", "[", "'options'", "]", ",", "$", "advancedOptions", ")", ";", "break", ";", "case", "'alter'", ":", "$", "this", "->", "alterTable", "(", "$", "tableName", ",", "$", "changes", "[", "'newFields'", "]", ",", "$", "changes", "[", "'newIndexes'", "]", ",", "$", "changes", "[", "'alteredFields'", "]", ",", "$", "changes", "[", "'alteredIndexes'", "]", ",", "$", "changes", "[", "'alteredOptions'", "]", ",", "$", "advancedOptions", ")", ";", "break", ";", "}", "}", "}", "finally", "{", "$", "this", "->", "schemaUpdateTransaction", "=", "null", ";", "$", "this", "->", "schemaIsUpdating", "=", "false", ";", "}", "}" ]
Initiates a schema update within a single callback @param callable $callback
[ "Initiates", "a", "schema", "update", "within", "a", "single", "callback" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L143-L200
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.transCreateTable
public function transCreateTable($table, $options = null, $advanced_options = null) { $this->schemaUpdateTransaction[$table] = array( 'command' => 'create', 'newFields' => array(), 'newIndexes' => array(), 'options' => $options, 'advancedOptions' => $advanced_options ); }
php
public function transCreateTable($table, $options = null, $advanced_options = null) { $this->schemaUpdateTransaction[$table] = array( 'command' => 'create', 'newFields' => array(), 'newIndexes' => array(), 'options' => $options, 'advancedOptions' => $advanced_options ); }
[ "public", "function", "transCreateTable", "(", "$", "table", ",", "$", "options", "=", "null", ",", "$", "advanced_options", "=", "null", ")", "{", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "=", "array", "(", "'command'", "=>", "'create'", ",", "'newFields'", "=>", "array", "(", ")", ",", "'newIndexes'", "=>", "array", "(", ")", ",", "'options'", "=>", "$", "options", ",", "'advancedOptions'", "=>", "$", "advanced_options", ")", ";", "}" ]
Instruct the schema manager to record a table creation to later execute @param string $table Name of the table @param array $options Create table options (ENGINE, etc.) @param array $advanced_options Advanced table creation options
[ "Instruct", "the", "schema", "manager", "to", "record", "a", "table", "creation", "to", "later", "execute" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L240-L249
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.transAlterTable
public function transAlterTable($table, $options, $advanced_options) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredOptions'] = $options; $this->schemaUpdateTransaction[$table]['advancedOptions'] = $advanced_options; }
php
public function transAlterTable($table, $options, $advanced_options) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredOptions'] = $options; $this->schemaUpdateTransaction[$table]['advancedOptions'] = $advanced_options; }
[ "public", "function", "transAlterTable", "(", "$", "table", ",", "$", "options", ",", "$", "advanced_options", ")", "{", "$", "this", "->", "transInitTable", "(", "$", "table", ")", ";", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "[", "'alteredOptions'", "]", "=", "$", "options", ";", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "[", "'advancedOptions'", "]", "=", "$", "advanced_options", ";", "}" ]
Instruct the schema manager to record a table alteration to later execute @param string $table Name of the table @param array $options Create table options (ENGINE, etc.) @param array $advanced_options Advanced table creation options
[ "Instruct", "the", "schema", "manager", "to", "record", "a", "table", "alteration", "to", "later", "execute" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L258-L263
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.transCreateField
public function transCreateField($table, $field, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['newFields'][$field] = $schema; }
php
public function transCreateField($table, $field, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['newFields'][$field] = $schema; }
[ "public", "function", "transCreateField", "(", "$", "table", ",", "$", "field", ",", "$", "schema", ")", "{", "$", "this", "->", "transInitTable", "(", "$", "table", ")", ";", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "[", "'newFields'", "]", "[", "$", "field", "]", "=", "$", "schema", ";", "}" ]
Instruct the schema manager to record a field to be later created @param string $table Name of the table to hold this field @param string $field Name of the field to create @param string $schema Field specification as a string
[ "Instruct", "the", "schema", "manager", "to", "record", "a", "field", "to", "be", "later", "created" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L272-L276
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.transCreateIndex
public function transCreateIndex($table, $index, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['newIndexes'][$index] = $schema; }
php
public function transCreateIndex($table, $index, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['newIndexes'][$index] = $schema; }
[ "public", "function", "transCreateIndex", "(", "$", "table", ",", "$", "index", ",", "$", "schema", ")", "{", "$", "this", "->", "transInitTable", "(", "$", "table", ")", ";", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "[", "'newIndexes'", "]", "[", "$", "index", "]", "=", "$", "schema", ";", "}" ]
Instruct the schema manager to record an index to be later created @param string $table Name of the table to hold this index @param string $index Name of the index to create @param array $schema Already parsed index specification
[ "Instruct", "the", "schema", "manager", "to", "record", "an", "index", "to", "be", "later", "created" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L285-L289
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.transAlterField
public function transAlterField($table, $field, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredFields'][$field] = $schema; }
php
public function transAlterField($table, $field, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredFields'][$field] = $schema; }
[ "public", "function", "transAlterField", "(", "$", "table", ",", "$", "field", ",", "$", "schema", ")", "{", "$", "this", "->", "transInitTable", "(", "$", "table", ")", ";", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "[", "'alteredFields'", "]", "[", "$", "field", "]", "=", "$", "schema", ";", "}" ]
Instruct the schema manager to record a field to be later updated @param string $table Name of the table to hold this field @param string $field Name of the field to update @param string $schema Field specification as a string
[ "Instruct", "the", "schema", "manager", "to", "record", "a", "field", "to", "be", "later", "updated" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L298-L302
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.transAlterIndex
public function transAlterIndex($table, $index, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredIndexes'][$index] = $schema; }
php
public function transAlterIndex($table, $index, $schema) { $this->transInitTable($table); $this->schemaUpdateTransaction[$table]['alteredIndexes'][$index] = $schema; }
[ "public", "function", "transAlterIndex", "(", "$", "table", ",", "$", "index", ",", "$", "schema", ")", "{", "$", "this", "->", "transInitTable", "(", "$", "table", ")", ";", "$", "this", "->", "schemaUpdateTransaction", "[", "$", "table", "]", "[", "'alteredIndexes'", "]", "[", "$", "index", "]", "=", "$", "schema", ";", "}" ]
Instruct the schema manager to record an index to be later updated @param string $table Name of the table to hold this index @param string $index Name of the index to update @param array $schema Already parsed index specification
[ "Instruct", "the", "schema", "manager", "to", "record", "an", "index", "to", "be", "later", "updated" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L311-L315
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.determineIndexType
protected function determineIndexType($spec) { // check array spec if (is_array($spec) && isset($spec['type'])) { return $spec['type']; } elseif (!is_array($spec) && preg_match('/(?<type>\w+)\s*\(/', $spec, $matchType)) { return strtolower($matchType['type']); } else { return 'index'; } }
php
protected function determineIndexType($spec) { // check array spec if (is_array($spec) && isset($spec['type'])) { return $spec['type']; } elseif (!is_array($spec) && preg_match('/(?<type>\w+)\s*\(/', $spec, $matchType)) { return strtolower($matchType['type']); } else { return 'index'; } }
[ "protected", "function", "determineIndexType", "(", "$", "spec", ")", "{", "// check array spec", "if", "(", "is_array", "(", "$", "spec", ")", "&&", "isset", "(", "$", "spec", "[", "'type'", "]", ")", ")", "{", "return", "$", "spec", "[", "'type'", "]", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "spec", ")", "&&", "preg_match", "(", "'/(?<type>\\w+)\\s*\\(/'", ",", "$", "spec", ",", "$", "matchType", ")", ")", "{", "return", "strtolower", "(", "$", "matchType", "[", "'type'", "]", ")", ";", "}", "else", "{", "return", "'index'", ";", "}", "}" ]
Given an index spec determines the index type @param array|string $spec @return string
[ "Given", "an", "index", "spec", "determines", "the", "index", "type" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L577-L587
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.hasField
public function hasField($tableName, $fieldName) { if (!$this->hasTable($tableName)) { return false; } $fields = $this->fieldList($tableName); return array_key_exists($fieldName, $fields); }
php
public function hasField($tableName, $fieldName) { if (!$this->hasTable($tableName)) { return false; } $fields = $this->fieldList($tableName); return array_key_exists($fieldName, $fields); }
[ "public", "function", "hasField", "(", "$", "tableName", ",", "$", "fieldName", ")", "{", "if", "(", "!", "$", "this", "->", "hasTable", "(", "$", "tableName", ")", ")", "{", "return", "false", ";", "}", "$", "fields", "=", "$", "this", "->", "fieldList", "(", "$", "tableName", ")", ";", "return", "array_key_exists", "(", "$", "fieldName", ",", "$", "fields", ")", ";", "}" ]
Return true if the table exists and already has a the field specified @param string $tableName - The table to check @param string $fieldName - The field to check @return bool - True if the table exists and the field exists on the table
[ "Return", "true", "if", "the", "table", "exists", "and", "already", "has", "a", "the", "field", "specified" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L637-L644
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.alterationMessage
public function alterationMessage($message, $type = "") { if (!$this->supressOutput) { if (Director::is_cli()) { switch ($type) { case "created": case "changed": case "repaired": $sign = "+"; break; case "obsolete": case "deleted": $sign = '-'; break; case "notice": $sign = '*'; break; case "error": $sign = "!"; break; default: $sign = " "; } $message = strip_tags($message); echo " $sign $message\n"; } else { switch ($type) { case "created": $class = "success"; break; case "obsolete": $class = "error"; break; case "notice": $class = "warning"; break; case "error": $class = "error"; break; case "deleted": $class = "error"; break; case "changed": $class = "info"; break; case "repaired": $class = "info"; break; default: $class = ""; } echo "<li class=\"$class\">$message</li>"; } } }
php
public function alterationMessage($message, $type = "") { if (!$this->supressOutput) { if (Director::is_cli()) { switch ($type) { case "created": case "changed": case "repaired": $sign = "+"; break; case "obsolete": case "deleted": $sign = '-'; break; case "notice": $sign = '*'; break; case "error": $sign = "!"; break; default: $sign = " "; } $message = strip_tags($message); echo " $sign $message\n"; } else { switch ($type) { case "created": $class = "success"; break; case "obsolete": $class = "error"; break; case "notice": $class = "warning"; break; case "error": $class = "error"; break; case "deleted": $class = "error"; break; case "changed": $class = "info"; break; case "repaired": $class = "info"; break; default: $class = ""; } echo "<li class=\"$class\">$message</li>"; } } }
[ "public", "function", "alterationMessage", "(", "$", "message", ",", "$", "type", "=", "\"\"", ")", "{", "if", "(", "!", "$", "this", "->", "supressOutput", ")", "{", "if", "(", "Director", "::", "is_cli", "(", ")", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "\"created\"", ":", "case", "\"changed\"", ":", "case", "\"repaired\"", ":", "$", "sign", "=", "\"+\"", ";", "break", ";", "case", "\"obsolete\"", ":", "case", "\"deleted\"", ":", "$", "sign", "=", "'-'", ";", "break", ";", "case", "\"notice\"", ":", "$", "sign", "=", "'*'", ";", "break", ";", "case", "\"error\"", ":", "$", "sign", "=", "\"!\"", ";", "break", ";", "default", ":", "$", "sign", "=", "\" \"", ";", "}", "$", "message", "=", "strip_tags", "(", "$", "message", ")", ";", "echo", "\" $sign $message\\n\"", ";", "}", "else", "{", "switch", "(", "$", "type", ")", "{", "case", "\"created\"", ":", "$", "class", "=", "\"success\"", ";", "break", ";", "case", "\"obsolete\"", ":", "$", "class", "=", "\"error\"", ";", "break", ";", "case", "\"notice\"", ":", "$", "class", "=", "\"warning\"", ";", "break", ";", "case", "\"error\"", ":", "$", "class", "=", "\"error\"", ";", "break", ";", "case", "\"deleted\"", ":", "$", "class", "=", "\"error\"", ";", "break", ";", "case", "\"changed\"", ":", "$", "class", "=", "\"info\"", ";", "break", ";", "case", "\"repaired\"", ":", "$", "class", "=", "\"info\"", ";", "break", ";", "default", ":", "$", "class", "=", "\"\"", ";", "}", "echo", "\"<li class=\\\"$class\\\">$message</li>\"", ";", "}", "}", "}" ]
Show a message about database alteration @param string $message to display @param string $type one of [created|changed|repaired|obsolete|deleted|error]
[ "Show", "a", "message", "about", "database", "alteration" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L786-L840
train
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
DBSchemaManager.fixTableCase
public function fixTableCase($tableName) { // Check if table exists $tables = $this->tableList(); if (!array_key_exists(strtolower($tableName), $tables)) { return; } // Check if case differs $currentName = $tables[strtolower($tableName)]; if ($currentName === $tableName) { return; } $this->alterationMessage( "Table $tableName: renamed from $currentName", "repaired" ); // Rename via temp table to avoid case-sensitivity issues $tempTable = "__TEMP__{$tableName}"; $this->renameTable($currentName, $tempTable); $this->renameTable($tempTable, $tableName); }
php
public function fixTableCase($tableName) { // Check if table exists $tables = $this->tableList(); if (!array_key_exists(strtolower($tableName), $tables)) { return; } // Check if case differs $currentName = $tables[strtolower($tableName)]; if ($currentName === $tableName) { return; } $this->alterationMessage( "Table $tableName: renamed from $currentName", "repaired" ); // Rename via temp table to avoid case-sensitivity issues $tempTable = "__TEMP__{$tableName}"; $this->renameTable($currentName, $tempTable); $this->renameTable($tempTable, $tableName); }
[ "public", "function", "fixTableCase", "(", "$", "tableName", ")", "{", "// Check if table exists", "$", "tables", "=", "$", "this", "->", "tableList", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "strtolower", "(", "$", "tableName", ")", ",", "$", "tables", ")", ")", "{", "return", ";", "}", "// Check if case differs", "$", "currentName", "=", "$", "tables", "[", "strtolower", "(", "$", "tableName", ")", "]", ";", "if", "(", "$", "currentName", "===", "$", "tableName", ")", "{", "return", ";", "}", "$", "this", "->", "alterationMessage", "(", "\"Table $tableName: renamed from $currentName\"", ",", "\"repaired\"", ")", ";", "// Rename via temp table to avoid case-sensitivity issues", "$", "tempTable", "=", "\"__TEMP__{$tableName}\"", ";", "$", "this", "->", "renameTable", "(", "$", "currentName", ",", "$", "tempTable", ")", ";", "$", "this", "->", "renameTable", "(", "$", "tempTable", ",", "$", "tableName", ")", ";", "}" ]
Ensure the given table has the correct case @param string $tableName Name of table in desired case
[ "Ensure", "the", "given", "table", "has", "the", "correct", "case" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBSchemaManager.php#L865-L888
train
silverstripe/silverstripe-framework
src/Dev/Tasks/i18nTextCollectorTask.php
i18nTextCollectorTask.getIsMerge
protected function getIsMerge($request) { $merge = $request->getVar('merge'); // Default to true if not given if (!isset($merge)) { return true; } // merge=0 or merge=false will disable merge return !in_array($merge, array('0', 'false')); }
php
protected function getIsMerge($request) { $merge = $request->getVar('merge'); // Default to true if not given if (!isset($merge)) { return true; } // merge=0 or merge=false will disable merge return !in_array($merge, array('0', 'false')); }
[ "protected", "function", "getIsMerge", "(", "$", "request", ")", "{", "$", "merge", "=", "$", "request", "->", "getVar", "(", "'merge'", ")", ";", "// Default to true if not given", "if", "(", "!", "isset", "(", "$", "merge", ")", ")", "{", "return", "true", ";", "}", "// merge=0 or merge=false will disable merge", "return", "!", "in_array", "(", "$", "merge", ",", "array", "(", "'0'", ",", "'false'", ")", ")", ";", "}" ]
Check if we should merge @param HTTPRequest $request @return bool
[ "Check", "if", "we", "should", "merge" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Tasks/i18nTextCollectorTask.php#L72-L83
train
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
ManyManyList.linkJoinTable
protected function linkJoinTable() { // Join to the many-many join table $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); $this->dataQuery->innerJoin( $this->joinTable, "\"{$this->joinTable}\".\"{$this->localKey}\" = {$dataClassIDColumn}" ); // Add the extra fields to the query if ($this->extraFields) { $this->appendExtraFieldsToQuery(); } }
php
protected function linkJoinTable() { // Join to the many-many join table $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); $this->dataQuery->innerJoin( $this->joinTable, "\"{$this->joinTable}\".\"{$this->localKey}\" = {$dataClassIDColumn}" ); // Add the extra fields to the query if ($this->extraFields) { $this->appendExtraFieldsToQuery(); } }
[ "protected", "function", "linkJoinTable", "(", ")", "{", "// Join to the many-many join table", "$", "dataClassIDColumn", "=", "DataObject", "::", "getSchema", "(", ")", "->", "sqlColumnForField", "(", "$", "this", "->", "dataClass", "(", ")", ",", "'ID'", ")", ";", "$", "this", "->", "dataQuery", "->", "innerJoin", "(", "$", "this", "->", "joinTable", ",", "\"\\\"{$this->joinTable}\\\".\\\"{$this->localKey}\\\" = {$dataClassIDColumn}\"", ")", ";", "// Add the extra fields to the query", "if", "(", "$", "this", "->", "extraFields", ")", "{", "$", "this", "->", "appendExtraFieldsToQuery", "(", ")", ";", "}", "}" ]
Setup the join between this dataobject and the necessary mapping table
[ "Setup", "the", "join", "between", "this", "dataobject", "and", "the", "necessary", "mapping", "table" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ManyManyList.php#L77-L90
train
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
ManyManyList.createDataObject
public function createDataObject($row) { // remove any composed fields $add = []; if ($this->_compositeExtraFields) { foreach ($this->_compositeExtraFields as $fieldName => $composed) { // convert joined extra fields into their composite field types. $value = []; foreach ($composed as $subField) { if (isset($row[$fieldName . $subField])) { $value[$subField] = $row[$fieldName . $subField]; // don't duplicate data in the record unset($row[$fieldName . $subField]); } } $obj = Injector::inst()->create($this->extraFields[$fieldName], $fieldName); $obj->setValue($value, null, false); $add[$fieldName] = $obj; } } $dataObject = parent::createDataObject($row); foreach ($add as $fieldName => $obj) { $dataObject->$fieldName = $obj; } return $dataObject; }
php
public function createDataObject($row) { // remove any composed fields $add = []; if ($this->_compositeExtraFields) { foreach ($this->_compositeExtraFields as $fieldName => $composed) { // convert joined extra fields into their composite field types. $value = []; foreach ($composed as $subField) { if (isset($row[$fieldName . $subField])) { $value[$subField] = $row[$fieldName . $subField]; // don't duplicate data in the record unset($row[$fieldName . $subField]); } } $obj = Injector::inst()->create($this->extraFields[$fieldName], $fieldName); $obj->setValue($value, null, false); $add[$fieldName] = $obj; } } $dataObject = parent::createDataObject($row); foreach ($add as $fieldName => $obj) { $dataObject->$fieldName = $obj; } return $dataObject; }
[ "public", "function", "createDataObject", "(", "$", "row", ")", "{", "// remove any composed fields", "$", "add", "=", "[", "]", ";", "if", "(", "$", "this", "->", "_compositeExtraFields", ")", "{", "foreach", "(", "$", "this", "->", "_compositeExtraFields", "as", "$", "fieldName", "=>", "$", "composed", ")", "{", "// convert joined extra fields into their composite field types.", "$", "value", "=", "[", "]", ";", "foreach", "(", "$", "composed", "as", "$", "subField", ")", "{", "if", "(", "isset", "(", "$", "row", "[", "$", "fieldName", ".", "$", "subField", "]", ")", ")", "{", "$", "value", "[", "$", "subField", "]", "=", "$", "row", "[", "$", "fieldName", ".", "$", "subField", "]", ";", "// don't duplicate data in the record", "unset", "(", "$", "row", "[", "$", "fieldName", ".", "$", "subField", "]", ")", ";", "}", "}", "$", "obj", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "this", "->", "extraFields", "[", "$", "fieldName", "]", ",", "$", "fieldName", ")", ";", "$", "obj", "->", "setValue", "(", "$", "value", ",", "null", ",", "false", ")", ";", "$", "add", "[", "$", "fieldName", "]", "=", "$", "obj", ";", "}", "}", "$", "dataObject", "=", "parent", "::", "createDataObject", "(", "$", "row", ")", ";", "foreach", "(", "$", "add", "as", "$", "fieldName", "=>", "$", "obj", ")", "{", "$", "dataObject", "->", "$", "fieldName", "=", "$", "obj", ";", "}", "return", "$", "dataObject", ";", "}" ]
Create a DataObject from the given SQL row. @param array $row @return DataObject
[ "Create", "a", "DataObject", "from", "the", "given", "SQL", "row", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ManyManyList.php#L130-L162
train
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
ManyManyList.foreignIDFilter
protected function foreignIDFilter($id = null) { if ($id === null) { $id = $this->getForeignID(); } // Apply relation filter $key = "\"{$this->joinTable}\".\"{$this->foreignKey}\""; if (is_array($id)) { return ["$key IN (" . DB::placeholders($id) . ")" => $id]; } if ($id !== null) { return [$key => $id]; } return null; }
php
protected function foreignIDFilter($id = null) { if ($id === null) { $id = $this->getForeignID(); } // Apply relation filter $key = "\"{$this->joinTable}\".\"{$this->foreignKey}\""; if (is_array($id)) { return ["$key IN (" . DB::placeholders($id) . ")" => $id]; } if ($id !== null) { return [$key => $id]; } return null; }
[ "protected", "function", "foreignIDFilter", "(", "$", "id", "=", "null", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "$", "id", "=", "$", "this", "->", "getForeignID", "(", ")", ";", "}", "// Apply relation filter", "$", "key", "=", "\"\\\"{$this->joinTable}\\\".\\\"{$this->foreignKey}\\\"\"", ";", "if", "(", "is_array", "(", "$", "id", ")", ")", "{", "return", "[", "\"$key IN (\"", ".", "DB", "::", "placeholders", "(", "$", "id", ")", ".", "\")\"", "=>", "$", "id", "]", ";", "}", "if", "(", "$", "id", "!==", "null", ")", "{", "return", "[", "$", "key", "=>", "$", "id", "]", ";", "}", "return", "null", ";", "}" ]
Return a filter expression for when getting the contents of the relationship for some foreign ID @param int|null|string|array $id @return array
[ "Return", "a", "filter", "expression", "for", "when", "getting", "the", "contents", "of", "the", "relationship", "for", "some", "foreign", "ID" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ManyManyList.php#L172-L187
train
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
ManyManyList.getExtraData
public function getExtraData($componentName, $itemID) { $result = []; // Skip if no extrafields or unsaved record if (empty($this->extraFields) || empty($itemID)) { return $result; } if (!is_numeric($itemID)) { throw new InvalidArgumentException('ManyManyList::getExtraData() passed a non-numeric child ID'); } $cleanExtraFields = []; foreach ($this->extraFields as $fieldName => $dbFieldSpec) { $cleanExtraFields[] = "\"{$fieldName}\""; } $query = SQLSelect::create($cleanExtraFields, "\"{$this->joinTable}\""); $filter = $this->foreignIDWriteFilter($this->getForeignID()); if ($filter) { $query->setWhere($filter); } else { throw new BadMethodCallException("Can't call ManyManyList::getExtraData() until a foreign ID is set"); } $query->addWhere([ "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID ]); $queryResult = $query->execute()->current(); if ($queryResult) { foreach ($queryResult as $fieldName => $value) { $result[$fieldName] = $value; } } return $result; }
php
public function getExtraData($componentName, $itemID) { $result = []; // Skip if no extrafields or unsaved record if (empty($this->extraFields) || empty($itemID)) { return $result; } if (!is_numeric($itemID)) { throw new InvalidArgumentException('ManyManyList::getExtraData() passed a non-numeric child ID'); } $cleanExtraFields = []; foreach ($this->extraFields as $fieldName => $dbFieldSpec) { $cleanExtraFields[] = "\"{$fieldName}\""; } $query = SQLSelect::create($cleanExtraFields, "\"{$this->joinTable}\""); $filter = $this->foreignIDWriteFilter($this->getForeignID()); if ($filter) { $query->setWhere($filter); } else { throw new BadMethodCallException("Can't call ManyManyList::getExtraData() until a foreign ID is set"); } $query->addWhere([ "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID ]); $queryResult = $query->execute()->current(); if ($queryResult) { foreach ($queryResult as $fieldName => $value) { $result[$fieldName] = $value; } } return $result; }
[ "public", "function", "getExtraData", "(", "$", "componentName", ",", "$", "itemID", ")", "{", "$", "result", "=", "[", "]", ";", "// Skip if no extrafields or unsaved record", "if", "(", "empty", "(", "$", "this", "->", "extraFields", ")", "||", "empty", "(", "$", "itemID", ")", ")", "{", "return", "$", "result", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "itemID", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'ManyManyList::getExtraData() passed a non-numeric child ID'", ")", ";", "}", "$", "cleanExtraFields", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "extraFields", "as", "$", "fieldName", "=>", "$", "dbFieldSpec", ")", "{", "$", "cleanExtraFields", "[", "]", "=", "\"\\\"{$fieldName}\\\"\"", ";", "}", "$", "query", "=", "SQLSelect", "::", "create", "(", "$", "cleanExtraFields", ",", "\"\\\"{$this->joinTable}\\\"\"", ")", ";", "$", "filter", "=", "$", "this", "->", "foreignIDWriteFilter", "(", "$", "this", "->", "getForeignID", "(", ")", ")", ";", "if", "(", "$", "filter", ")", "{", "$", "query", "->", "setWhere", "(", "$", "filter", ")", ";", "}", "else", "{", "throw", "new", "BadMethodCallException", "(", "\"Can't call ManyManyList::getExtraData() until a foreign ID is set\"", ")", ";", "}", "$", "query", "->", "addWhere", "(", "[", "\"\\\"{$this->joinTable}\\\".\\\"{$this->localKey}\\\"\"", "=>", "$", "itemID", "]", ")", ";", "$", "queryResult", "=", "$", "query", "->", "execute", "(", ")", "->", "current", "(", ")", ";", "if", "(", "$", "queryResult", ")", "{", "foreach", "(", "$", "queryResult", "as", "$", "fieldName", "=>", "$", "value", ")", "{", "$", "result", "[", "$", "fieldName", "]", "=", "$", "value", ";", "}", "}", "return", "$", "result", ";", "}" ]
Find the extra field data for a single row of the relationship join table, given the known child ID. @param string $componentName The name of the component @param int $itemID The ID of the child for the relationship @return array Map of fieldName => fieldValue
[ "Find", "the", "extra", "field", "data", "for", "a", "single", "row", "of", "the", "relationship", "join", "table", "given", "the", "known", "child", "ID", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ManyManyList.php#L418-L453
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.AllChildrenIncludingDeleted
public function AllChildrenIncludingDeleted() { /** @var DataObject|Hierarchy|Versioned $owner */ $owner = $this->owner; $stageChildren = $owner->stageChildren(true); // Add live site content that doesn't exist on the stage site, if required. if ($owner->hasExtension(Versioned::class) && $owner->hasStages()) { // Next, go through the live children. Only some of these will be listed $liveChildren = $owner->liveChildren(true, true); if ($liveChildren) { $merged = new ArrayList(); $merged->merge($stageChildren); $merged->merge($liveChildren); $stageChildren = $merged; } } $owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren); return $stageChildren; }
php
public function AllChildrenIncludingDeleted() { /** @var DataObject|Hierarchy|Versioned $owner */ $owner = $this->owner; $stageChildren = $owner->stageChildren(true); // Add live site content that doesn't exist on the stage site, if required. if ($owner->hasExtension(Versioned::class) && $owner->hasStages()) { // Next, go through the live children. Only some of these will be listed $liveChildren = $owner->liveChildren(true, true); if ($liveChildren) { $merged = new ArrayList(); $merged->merge($stageChildren); $merged->merge($liveChildren); $stageChildren = $merged; } } $owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren); return $stageChildren; }
[ "public", "function", "AllChildrenIncludingDeleted", "(", ")", "{", "/** @var DataObject|Hierarchy|Versioned $owner */", "$", "owner", "=", "$", "this", "->", "owner", ";", "$", "stageChildren", "=", "$", "owner", "->", "stageChildren", "(", "true", ")", ";", "// Add live site content that doesn't exist on the stage site, if required.", "if", "(", "$", "owner", "->", "hasExtension", "(", "Versioned", "::", "class", ")", "&&", "$", "owner", "->", "hasStages", "(", ")", ")", "{", "// Next, go through the live children. Only some of these will be listed", "$", "liveChildren", "=", "$", "owner", "->", "liveChildren", "(", "true", ",", "true", ")", ";", "if", "(", "$", "liveChildren", ")", "{", "$", "merged", "=", "new", "ArrayList", "(", ")", ";", "$", "merged", "->", "merge", "(", "$", "stageChildren", ")", ";", "$", "merged", "->", "merge", "(", "$", "liveChildren", ")", ";", "$", "stageChildren", "=", "$", "merged", ";", "}", "}", "$", "owner", "->", "extend", "(", "\"augmentAllChildrenIncludingDeleted\"", ",", "$", "stageChildren", ")", ";", "return", "$", "stageChildren", ";", "}" ]
Return all children, including those that have been deleted but are still in live. - Deleted children will be marked as "DeletedFromStage" - Added children will be marked as "AddedToStage" - Modified children will be marked as "ModifiedOnStage" - Everything else has "SameOnStage" set, as an indicator that this information has been looked up. @return ArrayList
[ "Return", "all", "children", "including", "those", "that", "have", "been", "deleted", "but", "are", "still", "in", "live", ".", "-", "Deleted", "children", "will", "be", "marked", "as", "DeletedFromStage", "-", "Added", "children", "will", "be", "marked", "as", "AddedToStage", "-", "Modified", "children", "will", "be", "marked", "as", "ModifiedOnStage", "-", "Everything", "else", "has", "SameOnStage", "set", "as", "an", "indicator", "that", "this", "information", "has", "been", "looked", "up", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L229-L248
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.AllHistoricalChildren
public function AllHistoricalChildren() { /** @var DataObject|Versioned|Hierarchy $owner */ $owner = $this->owner; if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { throw new Exception( 'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging' ); } $baseTable = $owner->baseTable(); $parentIDColumn = $owner->getSchema()->sqlColumnForField($owner, 'ParentID'); return Versioned::get_including_deleted( $owner->baseClass(), [ $parentIDColumn => $owner->ID ], "\"{$baseTable}\".\"ID\" ASC" ); }
php
public function AllHistoricalChildren() { /** @var DataObject|Versioned|Hierarchy $owner */ $owner = $this->owner; if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { throw new Exception( 'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging' ); } $baseTable = $owner->baseTable(); $parentIDColumn = $owner->getSchema()->sqlColumnForField($owner, 'ParentID'); return Versioned::get_including_deleted( $owner->baseClass(), [ $parentIDColumn => $owner->ID ], "\"{$baseTable}\".\"ID\" ASC" ); }
[ "public", "function", "AllHistoricalChildren", "(", ")", "{", "/** @var DataObject|Versioned|Hierarchy $owner */", "$", "owner", "=", "$", "this", "->", "owner", ";", "if", "(", "!", "$", "owner", "->", "hasExtension", "(", "Versioned", "::", "class", ")", "||", "!", "$", "owner", "->", "hasStages", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging'", ")", ";", "}", "$", "baseTable", "=", "$", "owner", "->", "baseTable", "(", ")", ";", "$", "parentIDColumn", "=", "$", "owner", "->", "getSchema", "(", ")", "->", "sqlColumnForField", "(", "$", "owner", ",", "'ParentID'", ")", ";", "return", "Versioned", "::", "get_including_deleted", "(", "$", "owner", "->", "baseClass", "(", ")", ",", "[", "$", "parentIDColumn", "=>", "$", "owner", "->", "ID", "]", ",", "\"\\\"{$baseTable}\\\".\\\"ID\\\" ASC\"", ")", ";", "}" ]
Return all the children that this page had, including pages that were deleted from both stage & live. @return DataList @throws Exception
[ "Return", "all", "the", "children", "that", "this", "page", "had", "including", "pages", "that", "were", "deleted", "from", "both", "stage", "&", "live", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L256-L273
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.showingCMSTree
public function showingCMSTree() { if (!Controller::has_curr() || !class_exists(LeftAndMain::class)) { return false; } $controller = Controller::curr(); return $controller instanceof LeftAndMain && in_array($controller->getAction(), array("treeview", "listview", "getsubtree")); }
php
public function showingCMSTree() { if (!Controller::has_curr() || !class_exists(LeftAndMain::class)) { return false; } $controller = Controller::curr(); return $controller instanceof LeftAndMain && in_array($controller->getAction(), array("treeview", "listview", "getsubtree")); }
[ "public", "function", "showingCMSTree", "(", ")", "{", "if", "(", "!", "Controller", "::", "has_curr", "(", ")", "||", "!", "class_exists", "(", "LeftAndMain", "::", "class", ")", ")", "{", "return", "false", ";", "}", "$", "controller", "=", "Controller", "::", "curr", "(", ")", ";", "return", "$", "controller", "instanceof", "LeftAndMain", "&&", "in_array", "(", "$", "controller", "->", "getAction", "(", ")", ",", "array", "(", "\"treeview\"", ",", "\"listview\"", ",", "\"getsubtree\"", ")", ")", ";", "}" ]
Checks if we're on a controller where we should filter. ie. Are we loading the SiteTree? @return bool
[ "Checks", "if", "we", "re", "on", "a", "controller", "where", "we", "should", "filter", ".", "ie", ".", "Are", "we", "loading", "the", "SiteTree?" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L402-L410
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.stageChildren
public function stageChildren($showAll = false, $skipParentIDFilter = false) { $hideFromHierarchy = $this->owner->config()->hide_from_hierarchy; $hideFromCMSTree = $this->owner->config()->hide_from_cms_tree; $baseClass = $this->owner->baseClass(); $baseTable = $this->owner->baseTable(); $staged = DataObject::get($baseClass)->where(sprintf( '%s.%s <> %s.%s', Convert::symbol2sql($baseTable), Convert::symbol2sql("ParentID"), Convert::symbol2sql($baseTable), Convert::symbol2sql("ID") )); if (!$skipParentIDFilter) { // There's no filtering by ID if we don't have an ID. $staged = $staged->filter('ParentID', (int)$this->owner->ID); } if ($hideFromHierarchy) { $staged = $staged->exclude('ClassName', $hideFromHierarchy); } if ($hideFromCMSTree && $this->showingCMSTree()) { $staged = $staged->exclude('ClassName', $hideFromCMSTree); } if (!$showAll && DataObject::getSchema()->fieldSpec($this->owner, 'ShowInMenus')) { $staged = $staged->filter('ShowInMenus', 1); } $this->owner->extend("augmentStageChildren", $staged, $showAll); return $staged; }
php
public function stageChildren($showAll = false, $skipParentIDFilter = false) { $hideFromHierarchy = $this->owner->config()->hide_from_hierarchy; $hideFromCMSTree = $this->owner->config()->hide_from_cms_tree; $baseClass = $this->owner->baseClass(); $baseTable = $this->owner->baseTable(); $staged = DataObject::get($baseClass)->where(sprintf( '%s.%s <> %s.%s', Convert::symbol2sql($baseTable), Convert::symbol2sql("ParentID"), Convert::symbol2sql($baseTable), Convert::symbol2sql("ID") )); if (!$skipParentIDFilter) { // There's no filtering by ID if we don't have an ID. $staged = $staged->filter('ParentID', (int)$this->owner->ID); } if ($hideFromHierarchy) { $staged = $staged->exclude('ClassName', $hideFromHierarchy); } if ($hideFromCMSTree && $this->showingCMSTree()) { $staged = $staged->exclude('ClassName', $hideFromCMSTree); } if (!$showAll && DataObject::getSchema()->fieldSpec($this->owner, 'ShowInMenus')) { $staged = $staged->filter('ShowInMenus', 1); } $this->owner->extend("augmentStageChildren", $staged, $showAll); return $staged; }
[ "public", "function", "stageChildren", "(", "$", "showAll", "=", "false", ",", "$", "skipParentIDFilter", "=", "false", ")", "{", "$", "hideFromHierarchy", "=", "$", "this", "->", "owner", "->", "config", "(", ")", "->", "hide_from_hierarchy", ";", "$", "hideFromCMSTree", "=", "$", "this", "->", "owner", "->", "config", "(", ")", "->", "hide_from_cms_tree", ";", "$", "baseClass", "=", "$", "this", "->", "owner", "->", "baseClass", "(", ")", ";", "$", "baseTable", "=", "$", "this", "->", "owner", "->", "baseTable", "(", ")", ";", "$", "staged", "=", "DataObject", "::", "get", "(", "$", "baseClass", ")", "->", "where", "(", "sprintf", "(", "'%s.%s <> %s.%s'", ",", "Convert", "::", "symbol2sql", "(", "$", "baseTable", ")", ",", "Convert", "::", "symbol2sql", "(", "\"ParentID\"", ")", ",", "Convert", "::", "symbol2sql", "(", "$", "baseTable", ")", ",", "Convert", "::", "symbol2sql", "(", "\"ID\"", ")", ")", ")", ";", "if", "(", "!", "$", "skipParentIDFilter", ")", "{", "// There's no filtering by ID if we don't have an ID.", "$", "staged", "=", "$", "staged", "->", "filter", "(", "'ParentID'", ",", "(", "int", ")", "$", "this", "->", "owner", "->", "ID", ")", ";", "}", "if", "(", "$", "hideFromHierarchy", ")", "{", "$", "staged", "=", "$", "staged", "->", "exclude", "(", "'ClassName'", ",", "$", "hideFromHierarchy", ")", ";", "}", "if", "(", "$", "hideFromCMSTree", "&&", "$", "this", "->", "showingCMSTree", "(", ")", ")", "{", "$", "staged", "=", "$", "staged", "->", "exclude", "(", "'ClassName'", ",", "$", "hideFromCMSTree", ")", ";", "}", "if", "(", "!", "$", "showAll", "&&", "DataObject", "::", "getSchema", "(", ")", "->", "fieldSpec", "(", "$", "this", "->", "owner", ",", "'ShowInMenus'", ")", ")", "{", "$", "staged", "=", "$", "staged", "->", "filter", "(", "'ShowInMenus'", ",", "1", ")", ";", "}", "$", "this", "->", "owner", "->", "extend", "(", "\"augmentStageChildren\"", ",", "$", "staged", ",", "$", "showAll", ")", ";", "return", "$", "staged", ";", "}" ]
Return children in the stage site. @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when extension is applied to {@link SiteTree}. @param bool $skipParentIDFilter Set to true to supress the ParentID and ID where statements. @return DataList
[ "Return", "children", "in", "the", "stage", "site", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L420-L450
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.liveChildren
public function liveChildren($showAll = false, $onlyDeletedFromStage = false) { /** @var Versioned|DataObject|Hierarchy $owner */ $owner = $this->owner; if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied with staging'); } $hideFromHierarchy = $owner->config()->hide_from_hierarchy; $hideFromCMSTree = $owner->config()->hide_from_cms_tree; $children = DataObject::get($owner->baseClass()) ->filter('ParentID', (int)$owner->ID) ->exclude('ID', (int)$owner->ID) ->setDataQueryParam(array( 'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage', 'Versioned.stage' => 'Live' )); if ($hideFromHierarchy) { $children = $children->exclude('ClassName', $hideFromHierarchy); } if ($hideFromCMSTree && $this->showingCMSTree()) { $children = $children->exclude('ClassName', $hideFromCMSTree); } if (!$showAll && DataObject::getSchema()->fieldSpec($owner, 'ShowInMenus')) { $children = $children->filter('ShowInMenus', 1); } return $children; }
php
public function liveChildren($showAll = false, $onlyDeletedFromStage = false) { /** @var Versioned|DataObject|Hierarchy $owner */ $owner = $this->owner; if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied with staging'); } $hideFromHierarchy = $owner->config()->hide_from_hierarchy; $hideFromCMSTree = $owner->config()->hide_from_cms_tree; $children = DataObject::get($owner->baseClass()) ->filter('ParentID', (int)$owner->ID) ->exclude('ID', (int)$owner->ID) ->setDataQueryParam(array( 'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage', 'Versioned.stage' => 'Live' )); if ($hideFromHierarchy) { $children = $children->exclude('ClassName', $hideFromHierarchy); } if ($hideFromCMSTree && $this->showingCMSTree()) { $children = $children->exclude('ClassName', $hideFromCMSTree); } if (!$showAll && DataObject::getSchema()->fieldSpec($owner, 'ShowInMenus')) { $children = $children->filter('ShowInMenus', 1); } return $children; }
[ "public", "function", "liveChildren", "(", "$", "showAll", "=", "false", ",", "$", "onlyDeletedFromStage", "=", "false", ")", "{", "/** @var Versioned|DataObject|Hierarchy $owner */", "$", "owner", "=", "$", "this", "->", "owner", ";", "if", "(", "!", "$", "owner", "->", "hasExtension", "(", "Versioned", "::", "class", ")", "||", "!", "$", "owner", "->", "hasStages", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Hierarchy->liveChildren() only works with Versioned extension applied with staging'", ")", ";", "}", "$", "hideFromHierarchy", "=", "$", "owner", "->", "config", "(", ")", "->", "hide_from_hierarchy", ";", "$", "hideFromCMSTree", "=", "$", "owner", "->", "config", "(", ")", "->", "hide_from_cms_tree", ";", "$", "children", "=", "DataObject", "::", "get", "(", "$", "owner", "->", "baseClass", "(", ")", ")", "->", "filter", "(", "'ParentID'", ",", "(", "int", ")", "$", "owner", "->", "ID", ")", "->", "exclude", "(", "'ID'", ",", "(", "int", ")", "$", "owner", "->", "ID", ")", "->", "setDataQueryParam", "(", "array", "(", "'Versioned.mode'", "=>", "$", "onlyDeletedFromStage", "?", "'stage_unique'", ":", "'stage'", ",", "'Versioned.stage'", "=>", "'Live'", ")", ")", ";", "if", "(", "$", "hideFromHierarchy", ")", "{", "$", "children", "=", "$", "children", "->", "exclude", "(", "'ClassName'", ",", "$", "hideFromHierarchy", ")", ";", "}", "if", "(", "$", "hideFromCMSTree", "&&", "$", "this", "->", "showingCMSTree", "(", ")", ")", "{", "$", "children", "=", "$", "children", "->", "exclude", "(", "'ClassName'", ",", "$", "hideFromCMSTree", ")", ";", "}", "if", "(", "!", "$", "showAll", "&&", "DataObject", "::", "getSchema", "(", ")", "->", "fieldSpec", "(", "$", "owner", ",", "'ShowInMenus'", ")", ")", "{", "$", "children", "=", "$", "children", "->", "filter", "(", "'ShowInMenus'", ",", "1", ")", ";", "}", "return", "$", "children", ";", "}" ]
Return children in the live site, if it exists. @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when extension is applied to {@link SiteTree}. @param bool $onlyDeletedFromStage Only return items that have been deleted from stage @return DataList @throws Exception
[ "Return", "children", "in", "the", "live", "site", "if", "it", "exists", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L461-L489
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.getParent
public function getParent($filter = null) { $parentID = $this->owner->ParentID; if (empty($parentID)) { return null; } $baseClass = $this->owner->baseClass(); $idSQL = $this->owner->getSchema()->sqlColumnForField($baseClass, 'ID'); return DataObject::get_one($baseClass, [ [$idSQL => $parentID], $filter ]); }
php
public function getParent($filter = null) { $parentID = $this->owner->ParentID; if (empty($parentID)) { return null; } $baseClass = $this->owner->baseClass(); $idSQL = $this->owner->getSchema()->sqlColumnForField($baseClass, 'ID'); return DataObject::get_one($baseClass, [ [$idSQL => $parentID], $filter ]); }
[ "public", "function", "getParent", "(", "$", "filter", "=", "null", ")", "{", "$", "parentID", "=", "$", "this", "->", "owner", "->", "ParentID", ";", "if", "(", "empty", "(", "$", "parentID", ")", ")", "{", "return", "null", ";", "}", "$", "baseClass", "=", "$", "this", "->", "owner", "->", "baseClass", "(", ")", ";", "$", "idSQL", "=", "$", "this", "->", "owner", "->", "getSchema", "(", ")", "->", "sqlColumnForField", "(", "$", "baseClass", ",", "'ID'", ")", ";", "return", "DataObject", "::", "get_one", "(", "$", "baseClass", ",", "[", "[", "$", "idSQL", "=>", "$", "parentID", "]", ",", "$", "filter", "]", ")", ";", "}" ]
Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing is returned. @param string $filter @return DataObject
[ "Get", "this", "object", "s", "parent", "optionally", "filtered", "by", "an", "SQL", "clause", ".", "If", "the", "clause", "doesn", "t", "match", "the", "parent", "nothing", "is", "returned", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L498-L510
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
Hierarchy.getAncestors
public function getAncestors($includeSelf = false) { $ancestors = new ArrayList(); $object = $this->owner; if ($includeSelf) { $ancestors->push($object); } while ($object = $object->getParent()) { $ancestors->push($object); } return $ancestors; }
php
public function getAncestors($includeSelf = false) { $ancestors = new ArrayList(); $object = $this->owner; if ($includeSelf) { $ancestors->push($object); } while ($object = $object->getParent()) { $ancestors->push($object); } return $ancestors; }
[ "public", "function", "getAncestors", "(", "$", "includeSelf", "=", "false", ")", "{", "$", "ancestors", "=", "new", "ArrayList", "(", ")", ";", "$", "object", "=", "$", "this", "->", "owner", ";", "if", "(", "$", "includeSelf", ")", "{", "$", "ancestors", "->", "push", "(", "$", "object", ")", ";", "}", "while", "(", "$", "object", "=", "$", "object", "->", "getParent", "(", ")", ")", "{", "$", "ancestors", "->", "push", "(", "$", "object", ")", ";", "}", "return", "$", "ancestors", ";", "}" ]
Return all the parents of this class in a set ordered from the closest to furtherest parent. @param bool $includeSelf @return ArrayList
[ "Return", "all", "the", "parents", "of", "this", "class", "in", "a", "set", "ordered", "from", "the", "closest", "to", "furtherest", "parent", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/Hierarchy.php#L518-L531
train
silverstripe/silverstripe-framework
src/Dev/Install/Installer.php
Installer.writeConfigEnv
protected function writeConfigEnv($config) { if (!$config['usingEnv']) { return; } $path = $this->getBaseDir() . '.env'; $vars = []; // Retain existing vars $env = new EnvironmentLoader(); if (file_exists($path)) { $vars = $env->loadFile($path) ?: []; } // Set base URL if (!isset($vars['SS_BASE_URL']) && isset($_SERVER['HTTP_HOST'])) { $vars['SS_BASE_URL'] = 'http://' . $_SERVER['HTTP_HOST'] . BASE_URL; } // Set DB env if (empty($config['db']['database'])) { $vars['SS_DATABASE_CHOOSE_NAME'] = true; } else { $vars['SS_DATABASE_NAME'] = $config['db']['database']; } $vars['SS_DATABASE_CLASS'] = $config['db']['type']; if (isset($config['db']['server'])) { $vars['SS_DATABASE_SERVER'] = $config['db']['server']; } if (isset($config['db']['username'])) { $vars['SS_DATABASE_USERNAME'] = $config['db']['username']; } if (isset($config['db']['password'])) { $vars['SS_DATABASE_PASSWORD'] = $config['db']['password']; } if (isset($config['db']['path'])) { $vars['SS_DATABASE_PATH'] = $config['db']['path']; // sqlite compat $vars['SS_SQLITE_DATABASE_PATH'] = $config['db']['path']; } if (isset($config['db']['key'])) { $vars['SS_DATABASE_KEY'] = $config['db']['key']; // sqlite compat $vars['SS_SQLITE_DATABASE_KEY'] = $config['db']['key']; } // Write all env vars $lines = [ '# Generated by SilverStripe Installer' ]; ksort($vars); foreach ($vars as $key => $value) { $lines[] = $key . '="' . addcslashes($value, '"') . '"'; } $this->writeToFile('.env', implode("\n", $lines)); // Re-load env vars for installer access $env->loadFile($path); }
php
protected function writeConfigEnv($config) { if (!$config['usingEnv']) { return; } $path = $this->getBaseDir() . '.env'; $vars = []; // Retain existing vars $env = new EnvironmentLoader(); if (file_exists($path)) { $vars = $env->loadFile($path) ?: []; } // Set base URL if (!isset($vars['SS_BASE_URL']) && isset($_SERVER['HTTP_HOST'])) { $vars['SS_BASE_URL'] = 'http://' . $_SERVER['HTTP_HOST'] . BASE_URL; } // Set DB env if (empty($config['db']['database'])) { $vars['SS_DATABASE_CHOOSE_NAME'] = true; } else { $vars['SS_DATABASE_NAME'] = $config['db']['database']; } $vars['SS_DATABASE_CLASS'] = $config['db']['type']; if (isset($config['db']['server'])) { $vars['SS_DATABASE_SERVER'] = $config['db']['server']; } if (isset($config['db']['username'])) { $vars['SS_DATABASE_USERNAME'] = $config['db']['username']; } if (isset($config['db']['password'])) { $vars['SS_DATABASE_PASSWORD'] = $config['db']['password']; } if (isset($config['db']['path'])) { $vars['SS_DATABASE_PATH'] = $config['db']['path']; // sqlite compat $vars['SS_SQLITE_DATABASE_PATH'] = $config['db']['path']; } if (isset($config['db']['key'])) { $vars['SS_DATABASE_KEY'] = $config['db']['key']; // sqlite compat $vars['SS_SQLITE_DATABASE_KEY'] = $config['db']['key']; } // Write all env vars $lines = [ '# Generated by SilverStripe Installer' ]; ksort($vars); foreach ($vars as $key => $value) { $lines[] = $key . '="' . addcslashes($value, '"') . '"'; } $this->writeToFile('.env', implode("\n", $lines)); // Re-load env vars for installer access $env->loadFile($path); }
[ "protected", "function", "writeConfigEnv", "(", "$", "config", ")", "{", "if", "(", "!", "$", "config", "[", "'usingEnv'", "]", ")", "{", "return", ";", "}", "$", "path", "=", "$", "this", "->", "getBaseDir", "(", ")", ".", "'.env'", ";", "$", "vars", "=", "[", "]", ";", "// Retain existing vars", "$", "env", "=", "new", "EnvironmentLoader", "(", ")", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "vars", "=", "$", "env", "->", "loadFile", "(", "$", "path", ")", "?", ":", "[", "]", ";", "}", "// Set base URL", "if", "(", "!", "isset", "(", "$", "vars", "[", "'SS_BASE_URL'", "]", ")", "&&", "isset", "(", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", ")", "{", "$", "vars", "[", "'SS_BASE_URL'", "]", "=", "'http://'", ".", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ".", "BASE_URL", ";", "}", "// Set DB env", "if", "(", "empty", "(", "$", "config", "[", "'db'", "]", "[", "'database'", "]", ")", ")", "{", "$", "vars", "[", "'SS_DATABASE_CHOOSE_NAME'", "]", "=", "true", ";", "}", "else", "{", "$", "vars", "[", "'SS_DATABASE_NAME'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'database'", "]", ";", "}", "$", "vars", "[", "'SS_DATABASE_CLASS'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'type'", "]", ";", "if", "(", "isset", "(", "$", "config", "[", "'db'", "]", "[", "'server'", "]", ")", ")", "{", "$", "vars", "[", "'SS_DATABASE_SERVER'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'server'", "]", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'db'", "]", "[", "'username'", "]", ")", ")", "{", "$", "vars", "[", "'SS_DATABASE_USERNAME'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'username'", "]", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'db'", "]", "[", "'password'", "]", ")", ")", "{", "$", "vars", "[", "'SS_DATABASE_PASSWORD'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'password'", "]", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'db'", "]", "[", "'path'", "]", ")", ")", "{", "$", "vars", "[", "'SS_DATABASE_PATH'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'path'", "]", ";", "// sqlite compat", "$", "vars", "[", "'SS_SQLITE_DATABASE_PATH'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'path'", "]", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'db'", "]", "[", "'key'", "]", ")", ")", "{", "$", "vars", "[", "'SS_DATABASE_KEY'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'key'", "]", ";", "// sqlite compat", "$", "vars", "[", "'SS_SQLITE_DATABASE_KEY'", "]", "=", "$", "config", "[", "'db'", "]", "[", "'key'", "]", ";", "}", "// Write all env vars", "$", "lines", "=", "[", "'# Generated by SilverStripe Installer'", "]", ";", "ksort", "(", "$", "vars", ")", ";", "foreach", "(", "$", "vars", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "lines", "[", "]", "=", "$", "key", ".", "'=\"'", ".", "addcslashes", "(", "$", "value", ",", "'\"'", ")", ".", "'\"'", ";", "}", "$", "this", "->", "writeToFile", "(", "'.env'", ",", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ")", ";", "// Re-load env vars for installer access", "$", "env", "->", "loadFile", "(", "$", "path", ")", ";", "}" ]
Write all .env files @param $config
[ "Write", "all", ".", "env", "files" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/Installer.php#L281-L341
train
silverstripe/silverstripe-framework
src/Dev/Install/Installer.php
Installer.writeToFile
public function writeToFile($filename, $content, $absolute = false) { // Get absolute / relative paths by either combining or removing base from path list($absolutePath, $relativePath) = $absolute ? [ $filename, substr($filename, strlen($this->getBaseDir()))] : [ $this->getBaseDir() . $filename, $filename ]; $this->statusMessage("Setting up $relativePath"); if ((@$fh = fopen($absolutePath, 'wb')) && fwrite($fh, $content) && fclose($fh)) { // Set permissions to writable @chmod($absolutePath, 0775); return true; } $this->error("Couldn't write to file $relativePath"); return false; }
php
public function writeToFile($filename, $content, $absolute = false) { // Get absolute / relative paths by either combining or removing base from path list($absolutePath, $relativePath) = $absolute ? [ $filename, substr($filename, strlen($this->getBaseDir()))] : [ $this->getBaseDir() . $filename, $filename ]; $this->statusMessage("Setting up $relativePath"); if ((@$fh = fopen($absolutePath, 'wb')) && fwrite($fh, $content) && fclose($fh)) { // Set permissions to writable @chmod($absolutePath, 0775); return true; } $this->error("Couldn't write to file $relativePath"); return false; }
[ "public", "function", "writeToFile", "(", "$", "filename", ",", "$", "content", ",", "$", "absolute", "=", "false", ")", "{", "// Get absolute / relative paths by either combining or removing base from path", "list", "(", "$", "absolutePath", ",", "$", "relativePath", ")", "=", "$", "absolute", "?", "[", "$", "filename", ",", "substr", "(", "$", "filename", ",", "strlen", "(", "$", "this", "->", "getBaseDir", "(", ")", ")", ")", "]", ":", "[", "$", "this", "->", "getBaseDir", "(", ")", ".", "$", "filename", ",", "$", "filename", "]", ";", "$", "this", "->", "statusMessage", "(", "\"Setting up $relativePath\"", ")", ";", "if", "(", "(", "@", "$", "fh", "=", "fopen", "(", "$", "absolutePath", ",", "'wb'", ")", ")", "&&", "fwrite", "(", "$", "fh", ",", "$", "content", ")", "&&", "fclose", "(", "$", "fh", ")", ")", "{", "// Set permissions to writable", "@", "chmod", "(", "$", "absolutePath", ",", "0775", ")", ";", "return", "true", ";", "}", "$", "this", "->", "error", "(", "\"Couldn't write to file $relativePath\"", ")", ";", "return", "false", ";", "}" ]
Write file to given location @param string $filename @param string $content @param bool $absolute If $filename is absolute path set to true @return bool
[ "Write", "file", "to", "given", "location" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/Installer.php#L439-L459
train
silverstripe/silverstripe-framework
src/Dev/Install/Installer.php
Installer.createHtaccess
public function createHtaccess() { $start = "### SILVERSTRIPE START ###\n"; $end = "\n### SILVERSTRIPE END ###"; $base = dirname($_SERVER['SCRIPT_NAME']); $base = Convert::slashes($base, '/'); if ($base != '.') { $baseClause = "RewriteBase '$base'\n"; } else { $baseClause = ""; } if (strpos(strtolower(php_sapi_name()), "cgi") !== false) { $cgiClause = "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n"; } else { $cgiClause = ""; } $rewrite = <<<TEXT # Deny access to templates (but allow from localhost) <Files *.ss> Order deny,allow Deny from all Allow from 127.0.0.1 </Files> # Deny access to IIS configuration <Files web.config> Order deny,allow Deny from all </Files> # Deny access to YAML configuration files which might include sensitive information <Files ~ "\.ya?ml$"> Order allow,deny Deny from all </Files> # Route errors to static pages automatically generated by SilverStripe ErrorDocument 404 /assets/error-404.html ErrorDocument 500 /assets/error-500.html <IfModule mod_rewrite.c> # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4 <IfModule mod_dir.c> DirectoryIndex disabled DirectorySlash On </IfModule> SetEnv HTTP_MOD_REWRITE On RewriteEngine On $baseClause $cgiClause # Deny access to potentially sensitive files and folders RewriteRule ^vendor(/|$) - [F,L,NC] RewriteRule ^\.env - [F,L,NC] RewriteRule silverstripe-cache(/|$) - [F,L,NC] RewriteRule composer\.(json|lock) - [F,L,NC] RewriteRule (error|silverstripe|debug)\.log - [F,L,NC] # Process through SilverStripe if no file with the requested name exists. # Pass through the original path as a query parameter, and retain the existing parameters. # Try finding framework in the vendor folder first RewriteCond %{REQUEST_URI} ^(.*)$ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php </IfModule> TEXT; $htaccessPath = $this->getPublicDir() . '.htaccess'; if (file_exists($htaccessPath)) { $htaccess = file_get_contents($htaccessPath); if (strpos($htaccess, '### SILVERSTRIPE START ###') === false && strpos($htaccess, '### SILVERSTRIPE END ###') === false ) { $htaccess .= "\n### SILVERSTRIPE START ###\n### SILVERSTRIPE END ###\n"; } if (strpos($htaccess, '### SILVERSTRIPE START ###') !== false && strpos($htaccess, '### SILVERSTRIPE END ###') !== false ) { $start = substr($htaccess, 0, strpos($htaccess, '### SILVERSTRIPE START ###')) . "### SILVERSTRIPE START ###\n"; $end = "\n" . substr($htaccess, strpos($htaccess, '### SILVERSTRIPE END ###')); } } $this->writeToFile($htaccessPath, $start . $rewrite . $end, true); }
php
public function createHtaccess() { $start = "### SILVERSTRIPE START ###\n"; $end = "\n### SILVERSTRIPE END ###"; $base = dirname($_SERVER['SCRIPT_NAME']); $base = Convert::slashes($base, '/'); if ($base != '.') { $baseClause = "RewriteBase '$base'\n"; } else { $baseClause = ""; } if (strpos(strtolower(php_sapi_name()), "cgi") !== false) { $cgiClause = "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n"; } else { $cgiClause = ""; } $rewrite = <<<TEXT # Deny access to templates (but allow from localhost) <Files *.ss> Order deny,allow Deny from all Allow from 127.0.0.1 </Files> # Deny access to IIS configuration <Files web.config> Order deny,allow Deny from all </Files> # Deny access to YAML configuration files which might include sensitive information <Files ~ "\.ya?ml$"> Order allow,deny Deny from all </Files> # Route errors to static pages automatically generated by SilverStripe ErrorDocument 404 /assets/error-404.html ErrorDocument 500 /assets/error-500.html <IfModule mod_rewrite.c> # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4 <IfModule mod_dir.c> DirectoryIndex disabled DirectorySlash On </IfModule> SetEnv HTTP_MOD_REWRITE On RewriteEngine On $baseClause $cgiClause # Deny access to potentially sensitive files and folders RewriteRule ^vendor(/|$) - [F,L,NC] RewriteRule ^\.env - [F,L,NC] RewriteRule silverstripe-cache(/|$) - [F,L,NC] RewriteRule composer\.(json|lock) - [F,L,NC] RewriteRule (error|silverstripe|debug)\.log - [F,L,NC] # Process through SilverStripe if no file with the requested name exists. # Pass through the original path as a query parameter, and retain the existing parameters. # Try finding framework in the vendor folder first RewriteCond %{REQUEST_URI} ^(.*)$ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php </IfModule> TEXT; $htaccessPath = $this->getPublicDir() . '.htaccess'; if (file_exists($htaccessPath)) { $htaccess = file_get_contents($htaccessPath); if (strpos($htaccess, '### SILVERSTRIPE START ###') === false && strpos($htaccess, '### SILVERSTRIPE END ###') === false ) { $htaccess .= "\n### SILVERSTRIPE START ###\n### SILVERSTRIPE END ###\n"; } if (strpos($htaccess, '### SILVERSTRIPE START ###') !== false && strpos($htaccess, '### SILVERSTRIPE END ###') !== false ) { $start = substr($htaccess, 0, strpos($htaccess, '### SILVERSTRIPE START ###')) . "### SILVERSTRIPE START ###\n"; $end = "\n" . substr($htaccess, strpos($htaccess, '### SILVERSTRIPE END ###')); } } $this->writeToFile($htaccessPath, $start . $rewrite . $end, true); }
[ "public", "function", "createHtaccess", "(", ")", "{", "$", "start", "=", "\"### SILVERSTRIPE START ###\\n\"", ";", "$", "end", "=", "\"\\n### SILVERSTRIPE END ###\"", ";", "$", "base", "=", "dirname", "(", "$", "_SERVER", "[", "'SCRIPT_NAME'", "]", ")", ";", "$", "base", "=", "Convert", "::", "slashes", "(", "$", "base", ",", "'/'", ")", ";", "if", "(", "$", "base", "!=", "'.'", ")", "{", "$", "baseClause", "=", "\"RewriteBase '$base'\\n\"", ";", "}", "else", "{", "$", "baseClause", "=", "\"\"", ";", "}", "if", "(", "strpos", "(", "strtolower", "(", "php_sapi_name", "(", ")", ")", ",", "\"cgi\"", ")", "!==", "false", ")", "{", "$", "cgiClause", "=", "\"RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\\n\"", ";", "}", "else", "{", "$", "cgiClause", "=", "\"\"", ";", "}", "$", "rewrite", "=", " <<<TEXT\n# Deny access to templates (but allow from localhost)\n<Files *.ss>\n Order deny,allow\n Deny from all\n Allow from 127.0.0.1\n</Files>\n\n# Deny access to IIS configuration\n<Files web.config>\n Order deny,allow\n Deny from all\n</Files>\n\n# Deny access to YAML configuration files which might include sensitive information\n<Files ~ \"\\.ya?ml$\">\n Order allow,deny\n Deny from all\n</Files>\n\n# Route errors to static pages automatically generated by SilverStripe\nErrorDocument 404 /assets/error-404.html\nErrorDocument 500 /assets/error-500.html\n\n<IfModule mod_rewrite.c>\n\n # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4\n <IfModule mod_dir.c>\n DirectoryIndex disabled\n DirectorySlash On\n </IfModule>\n\n SetEnv HTTP_MOD_REWRITE On\n RewriteEngine On\n $baseClause\n $cgiClause\n\n # Deny access to potentially sensitive files and folders\n RewriteRule ^vendor(/|$) - [F,L,NC]\n RewriteRule ^\\.env - [F,L,NC]\n RewriteRule silverstripe-cache(/|$) - [F,L,NC]\n RewriteRule composer\\.(json|lock) - [F,L,NC]\n RewriteRule (error|silverstripe|debug)\\.log - [F,L,NC]\n\n # Process through SilverStripe if no file with the requested name exists.\n # Pass through the original path as a query parameter, and retain the existing parameters.\n # Try finding framework in the vendor folder first\n RewriteCond %{REQUEST_URI} ^(.*)$\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteRule .* index.php\n</IfModule>\nTEXT", ";", "$", "htaccessPath", "=", "$", "this", "->", "getPublicDir", "(", ")", ".", "'.htaccess'", ";", "if", "(", "file_exists", "(", "$", "htaccessPath", ")", ")", "{", "$", "htaccess", "=", "file_get_contents", "(", "$", "htaccessPath", ")", ";", "if", "(", "strpos", "(", "$", "htaccess", ",", "'### SILVERSTRIPE START ###'", ")", "===", "false", "&&", "strpos", "(", "$", "htaccess", ",", "'### SILVERSTRIPE END ###'", ")", "===", "false", ")", "{", "$", "htaccess", ".=", "\"\\n### SILVERSTRIPE START ###\\n### SILVERSTRIPE END ###\\n\"", ";", "}", "if", "(", "strpos", "(", "$", "htaccess", ",", "'### SILVERSTRIPE START ###'", ")", "!==", "false", "&&", "strpos", "(", "$", "htaccess", ",", "'### SILVERSTRIPE END ###'", ")", "!==", "false", ")", "{", "$", "start", "=", "substr", "(", "$", "htaccess", ",", "0", ",", "strpos", "(", "$", "htaccess", ",", "'### SILVERSTRIPE START ###'", ")", ")", ".", "\"### SILVERSTRIPE START ###\\n\"", ";", "$", "end", "=", "\"\\n\"", ".", "substr", "(", "$", "htaccess", ",", "strpos", "(", "$", "htaccess", ",", "'### SILVERSTRIPE END ###'", ")", ")", ";", "}", "}", "$", "this", "->", "writeToFile", "(", "$", "htaccessPath", ",", "$", "start", ".", "$", "rewrite", ".", "$", "end", ",", "true", ")", ";", "}" ]
Ensure root .htaccess is setup
[ "Ensure", "root", ".", "htaccess", "is", "setup" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/Installer.php#L464-L555
train
silverstripe/silverstripe-framework
src/Dev/Install/Installer.php
Installer.createWebConfig
public function createWebConfig() { $content = <<<TEXT <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <security> <requestFiltering> <hiddenSegments applyToWebDAV="false"> <add segment="silverstripe-cache" /> <add segment="composer.json" /> <add segment="composer.lock" /> </hiddenSegments> <fileExtensions allowUnlisted="true" > <add fileExtension=".ss" allowed="false"/> <add fileExtension=".yml" allowed="false"/> </fileExtensions> </requestFiltering> </security> <rewrite> <rules> <rule name="SilverStripe Clean URLs" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> </conditions> <action type="Rewrite" url="index.php" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> TEXT; $path = $this->getPublicDir() . 'web.config'; $this->writeToFile($path, $content, true); }
php
public function createWebConfig() { $content = <<<TEXT <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <security> <requestFiltering> <hiddenSegments applyToWebDAV="false"> <add segment="silverstripe-cache" /> <add segment="composer.json" /> <add segment="composer.lock" /> </hiddenSegments> <fileExtensions allowUnlisted="true" > <add fileExtension=".ss" allowed="false"/> <add fileExtension=".yml" allowed="false"/> </fileExtensions> </requestFiltering> </security> <rewrite> <rules> <rule name="SilverStripe Clean URLs" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> </conditions> <action type="Rewrite" url="index.php" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> TEXT; $path = $this->getPublicDir() . 'web.config'; $this->writeToFile($path, $content, true); }
[ "public", "function", "createWebConfig", "(", ")", "{", "$", "content", "=", " <<<TEXT\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <system.webServer>\n <security>\n <requestFiltering>\n <hiddenSegments applyToWebDAV=\"false\">\n <add segment=\"silverstripe-cache\" />\n <add segment=\"composer.json\" />\n <add segment=\"composer.lock\" />\n </hiddenSegments>\n <fileExtensions allowUnlisted=\"true\" >\n <add fileExtension=\".ss\" allowed=\"false\"/>\n <add fileExtension=\".yml\" allowed=\"false\"/>\n </fileExtensions>\n </requestFiltering>\n </security>\n <rewrite>\n <rules>\n <rule name=\"SilverStripe Clean URLs\" stopProcessing=\"true\">\n <match url=\"^(.*)$\" />\n <conditions>\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" negate=\"true\" />\n </conditions>\n <action type=\"Rewrite\" url=\"index.php\" appendQueryString=\"true\" />\n </rule>\n </rules>\n </rewrite>\n </system.webServer>\n</configuration>\nTEXT", ";", "$", "path", "=", "$", "this", "->", "getPublicDir", "(", ")", ".", "'web.config'", ";", "$", "this", "->", "writeToFile", "(", "$", "path", ",", "$", "content", ",", "true", ")", ";", "}" ]
Writes basic configuration to the web.config for IIS so that rewriting capability can be use.
[ "Writes", "basic", "configuration", "to", "the", "web", ".", "config", "for", "IIS", "so", "that", "rewriting", "capability", "can", "be", "use", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/Installer.php#L561-L597
train
silverstripe/silverstripe-framework
src/View/GenericTemplateGlobalProvider.php
GenericTemplateGlobalProvider.ModulePath
public static function ModulePath($name) { // BC for a couple fo the key modules in the old syntax. Reduces merge brittleness but can // be removed before 4.0 stable $legacyMapping = [ 'framework' => 'silverstripe/framework', 'frameworkadmin' => 'silverstripe/admin', ]; if (isset($legacyMapping[$name])) { $name = $legacyMapping[$name]; } return ModuleLoader::getModule($name)->getRelativePath(); }
php
public static function ModulePath($name) { // BC for a couple fo the key modules in the old syntax. Reduces merge brittleness but can // be removed before 4.0 stable $legacyMapping = [ 'framework' => 'silverstripe/framework', 'frameworkadmin' => 'silverstripe/admin', ]; if (isset($legacyMapping[$name])) { $name = $legacyMapping[$name]; } return ModuleLoader::getModule($name)->getRelativePath(); }
[ "public", "static", "function", "ModulePath", "(", "$", "name", ")", "{", "// BC for a couple fo the key modules in the old syntax. Reduces merge brittleness but can", "// be removed before 4.0 stable", "$", "legacyMapping", "=", "[", "'framework'", "=>", "'silverstripe/framework'", ",", "'frameworkadmin'", "=>", "'silverstripe/admin'", ",", "]", ";", "if", "(", "isset", "(", "$", "legacyMapping", "[", "$", "name", "]", ")", ")", "{", "$", "name", "=", "$", "legacyMapping", "[", "$", "name", "]", ";", "}", "return", "ModuleLoader", "::", "getModule", "(", "$", "name", ")", "->", "getRelativePath", "(", ")", ";", "}" ]
Given some pre-defined modules, return the filesystem path of the module. @param string $name Name of module to find path of @return string
[ "Given", "some", "pre", "-", "defined", "modules", "return", "the", "filesystem", "path", "of", "the", "module", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/GenericTemplateGlobalProvider.php#L24-L37
train
silverstripe/silverstripe-framework
src/View/SSViewer_BasicIteratorSupport.php
SSViewer_BasicIteratorSupport.FirstLast
public function FirstLast() { if ($this->First() && $this->Last()) { return 'first last'; } if ($this->First()) { return 'first'; } if ($this->Last()) { return 'last'; } return null; }
php
public function FirstLast() { if ($this->First() && $this->Last()) { return 'first last'; } if ($this->First()) { return 'first'; } if ($this->Last()) { return 'last'; } return null; }
[ "public", "function", "FirstLast", "(", ")", "{", "if", "(", "$", "this", "->", "First", "(", ")", "&&", "$", "this", "->", "Last", "(", ")", ")", "{", "return", "'first last'", ";", "}", "if", "(", "$", "this", "->", "First", "(", ")", ")", "{", "return", "'first'", ";", "}", "if", "(", "$", "this", "->", "Last", "(", ")", ")", "{", "return", "'last'", ";", "}", "return", "null", ";", "}" ]
Returns 'first' or 'last' if this is the first or last object in the set. @return string|null
[ "Returns", "first", "or", "last", "if", "this", "is", "the", "first", "or", "last", "object", "in", "the", "set", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_BasicIteratorSupport.php#L80-L92
train
silverstripe/silverstripe-framework
src/Core/Manifest/Module.php
Module.getShortName
public function getShortName() { // If installed in the root directory we need to infer from composer if ($this->path === $this->basePath && $this->composerData) { // Sometimes we customise installer name if (isset($this->composerData['extra']['installer-name'])) { return $this->composerData['extra']['installer-name']; } // Strip from full composer name $composerName = $this->getComposerName(); if ($composerName) { list(, $name) = explode('/', $composerName); return $name; } } // Base name of directory return basename($this->path); }
php
public function getShortName() { // If installed in the root directory we need to infer from composer if ($this->path === $this->basePath && $this->composerData) { // Sometimes we customise installer name if (isset($this->composerData['extra']['installer-name'])) { return $this->composerData['extra']['installer-name']; } // Strip from full composer name $composerName = $this->getComposerName(); if ($composerName) { list(, $name) = explode('/', $composerName); return $name; } } // Base name of directory return basename($this->path); }
[ "public", "function", "getShortName", "(", ")", "{", "// If installed in the root directory we need to infer from composer", "if", "(", "$", "this", "->", "path", "===", "$", "this", "->", "basePath", "&&", "$", "this", "->", "composerData", ")", "{", "// Sometimes we customise installer name", "if", "(", "isset", "(", "$", "this", "->", "composerData", "[", "'extra'", "]", "[", "'installer-name'", "]", ")", ")", "{", "return", "$", "this", "->", "composerData", "[", "'extra'", "]", "[", "'installer-name'", "]", ";", "}", "// Strip from full composer name", "$", "composerName", "=", "$", "this", "->", "getComposerName", "(", ")", ";", "if", "(", "$", "composerName", ")", "{", "list", "(", ",", "$", "name", ")", "=", "explode", "(", "'/'", ",", "$", "composerName", ")", ";", "return", "$", "name", ";", "}", "}", "// Base name of directory", "return", "basename", "(", "$", "this", "->", "path", ")", ";", "}" ]
Gets "short" name of this module. This is the base directory this module is installed in. If installed in root, this will be generated from the composer name instead @return string
[ "Gets", "short", "name", "of", "this", "module", ".", "This", "is", "the", "base", "directory", "this", "module", "is", "installed", "in", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/Module.php#L110-L129
train
silverstripe/silverstripe-framework
src/Core/Manifest/Module.php
Module.getResource
public function getResource($path) { $path = Path::normalise($path, true); if (empty($path)) { throw new InvalidArgumentException('$path is required'); } if (isset($this->resources[$path])) { return $this->resources[$path]; } return $this->resources[$path] = new ModuleResource($this, $path); }
php
public function getResource($path) { $path = Path::normalise($path, true); if (empty($path)) { throw new InvalidArgumentException('$path is required'); } if (isset($this->resources[$path])) { return $this->resources[$path]; } return $this->resources[$path] = new ModuleResource($this, $path); }
[ "public", "function", "getResource", "(", "$", "path", ")", "{", "$", "path", "=", "Path", "::", "normalise", "(", "$", "path", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'$path is required'", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "resources", "[", "$", "path", "]", ")", ")", "{", "return", "$", "this", "->", "resources", "[", "$", "path", "]", ";", "}", "return", "$", "this", "->", "resources", "[", "$", "path", "]", "=", "new", "ModuleResource", "(", "$", "this", ",", "$", "path", ")", ";", "}" ]
Get resource for this module @param string $path @return ModuleResource
[ "Get", "resource", "for", "this", "module" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/Module.php#L215-L225
train
silverstripe/silverstripe-framework
src/ORM/Connect/Database.php
Database.setSchemaManager
public function setSchemaManager(DBSchemaManager $schemaManager) { $this->schemaManager = $schemaManager; if ($this->schemaManager) { $this->schemaManager->setDatabase($this); } }
php
public function setSchemaManager(DBSchemaManager $schemaManager) { $this->schemaManager = $schemaManager; if ($this->schemaManager) { $this->schemaManager->setDatabase($this); } }
[ "public", "function", "setSchemaManager", "(", "DBSchemaManager", "$", "schemaManager", ")", "{", "$", "this", "->", "schemaManager", "=", "$", "schemaManager", ";", "if", "(", "$", "this", "->", "schemaManager", ")", "{", "$", "this", "->", "schemaManager", "->", "setDatabase", "(", "$", "this", ")", ";", "}", "}" ]
Injector injection point for schema manager @param DBSchemaManager $schemaManager
[ "Injector", "injection", "point", "for", "schema", "manager" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L88-L95
train