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/Dev/Install/InstallEnvironmentAware.php
InstallEnvironmentAware.getPublicDir
public function getPublicDir() { $base = $this->getBaseDir(); $public = Path::join($base, 'public') . DIRECTORY_SEPARATOR; if (file_exists($public)) { return $public; } return $base; }
php
public function getPublicDir() { $base = $this->getBaseDir(); $public = Path::join($base, 'public') . DIRECTORY_SEPARATOR; if (file_exists($public)) { return $public; } return $base; }
[ "public", "function", "getPublicDir", "(", ")", "{", "$", "base", "=", "$", "this", "->", "getBaseDir", "(", ")", ";", "$", "public", "=", "Path", "::", "join", "(", "$", "base", ",", "'public'", ")", ".", "DIRECTORY_SEPARATOR", ";", "if", "(", "file_exists", "(", "$", "public", ")", ")", "{", "return", "$", "public", ";", "}", "return", "$", "base", ";", "}" ]
Get path to public directory @return string
[ "Get", "path", "to", "public", "directory" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallEnvironmentAware.php#L62-L70
train
silverstripe/silverstripe-framework
src/Dev/Install/InstallEnvironmentAware.php
InstallEnvironmentAware.checkModuleExists
public function checkModuleExists($dirname) { // Mysite is base-only and doesn't need _config.php to be counted if (in_array($dirname, ['mysite', 'app'])) { return file_exists($this->getBaseDir() . $dirname); } $paths = [ "vendor/silverstripe/{$dirname}/", "{$dirname}/", ]; foreach ($paths as $path) { $checks = ['_config', '_config.php']; foreach ($checks as $check) { if (file_exists($this->getBaseDir() . $path . $check)) { return true; } } } return false; }
php
public function checkModuleExists($dirname) { // Mysite is base-only and doesn't need _config.php to be counted if (in_array($dirname, ['mysite', 'app'])) { return file_exists($this->getBaseDir() . $dirname); } $paths = [ "vendor/silverstripe/{$dirname}/", "{$dirname}/", ]; foreach ($paths as $path) { $checks = ['_config', '_config.php']; foreach ($checks as $check) { if (file_exists($this->getBaseDir() . $path . $check)) { return true; } } } return false; }
[ "public", "function", "checkModuleExists", "(", "$", "dirname", ")", "{", "// Mysite is base-only and doesn't need _config.php to be counted", "if", "(", "in_array", "(", "$", "dirname", ",", "[", "'mysite'", ",", "'app'", "]", ")", ")", "{", "return", "file_exists", "(", "$", "this", "->", "getBaseDir", "(", ")", ".", "$", "dirname", ")", ";", "}", "$", "paths", "=", "[", "\"vendor/silverstripe/{$dirname}/\"", ",", "\"{$dirname}/\"", ",", "]", ";", "foreach", "(", "$", "paths", "as", "$", "path", ")", "{", "$", "checks", "=", "[", "'_config'", ",", "'_config.php'", "]", ";", "foreach", "(", "$", "checks", "as", "$", "check", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "getBaseDir", "(", ")", ".", "$", "path", ".", "$", "check", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check that a module exists @param string $dirname @return bool
[ "Check", "that", "a", "module", "exists" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallEnvironmentAware.php#L78-L99
train
silverstripe/silverstripe-framework
src/Dev/Install/InstallEnvironmentAware.php
InstallEnvironmentAware.isIIS
public function isIIS($fromVersion = 7) { $webserver = $this->findWebserver(); if (preg_match('#.*IIS/(?<version>[.\\d]+)$#', $webserver, $matches)) { return version_compare($matches['version'], $fromVersion, '>='); } return false; }
php
public function isIIS($fromVersion = 7) { $webserver = $this->findWebserver(); if (preg_match('#.*IIS/(?<version>[.\\d]+)$#', $webserver, $matches)) { return version_compare($matches['version'], $fromVersion, '>='); } return false; }
[ "public", "function", "isIIS", "(", "$", "fromVersion", "=", "7", ")", "{", "$", "webserver", "=", "$", "this", "->", "findWebserver", "(", ")", ";", "if", "(", "preg_match", "(", "'#.*IIS/(?<version>[.\\\\d]+)$#'", ",", "$", "webserver", ",", "$", "matches", ")", ")", "{", "return", "version_compare", "(", "$", "matches", "[", "'version'", "]", ",", "$", "fromVersion", ",", "'>='", ")", ";", "}", "return", "false", ";", "}" ]
Check if the web server is IIS and version greater than the given version. @param int $fromVersion @return bool
[ "Check", "if", "the", "web", "server", "is", "IIS", "and", "version", "greater", "than", "the", "given", "version", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallEnvironmentAware.php#L141-L148
train
silverstripe/silverstripe-framework
src/Dev/Install/InstallEnvironmentAware.php
InstallEnvironmentAware.findWebserver
public function findWebserver() { // Try finding from SERVER_SIGNATURE or SERVER_SOFTWARE if (!empty($_SERVER['SERVER_SIGNATURE'])) { $webserver = $_SERVER['SERVER_SIGNATURE']; } elseif (!empty($_SERVER['SERVER_SOFTWARE'])) { $webserver = $_SERVER['SERVER_SOFTWARE']; } else { return false; } return strip_tags(trim($webserver)); }
php
public function findWebserver() { // Try finding from SERVER_SIGNATURE or SERVER_SOFTWARE if (!empty($_SERVER['SERVER_SIGNATURE'])) { $webserver = $_SERVER['SERVER_SIGNATURE']; } elseif (!empty($_SERVER['SERVER_SOFTWARE'])) { $webserver = $_SERVER['SERVER_SOFTWARE']; } else { return false; } return strip_tags(trim($webserver)); }
[ "public", "function", "findWebserver", "(", ")", "{", "// Try finding from SERVER_SIGNATURE or SERVER_SOFTWARE", "if", "(", "!", "empty", "(", "$", "_SERVER", "[", "'SERVER_SIGNATURE'", "]", ")", ")", "{", "$", "webserver", "=", "$", "_SERVER", "[", "'SERVER_SIGNATURE'", "]", ";", "}", "elseif", "(", "!", "empty", "(", "$", "_SERVER", "[", "'SERVER_SOFTWARE'", "]", ")", ")", "{", "$", "webserver", "=", "$", "_SERVER", "[", "'SERVER_SOFTWARE'", "]", ";", "}", "else", "{", "return", "false", ";", "}", "return", "strip_tags", "(", "trim", "(", "$", "webserver", ")", ")", ";", "}" ]
Find the webserver software running on the PHP host. @return string|false Server software or boolean FALSE
[ "Find", "the", "webserver", "software", "running", "on", "the", "PHP", "host", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallEnvironmentAware.php#L163-L175
train
silverstripe/silverstripe-framework
src/Core/Config/Configurable.php
Configurable.set_stat
public function set_stat($name, $value) { Deprecation::notice('5.0', 'Use ->config()->set()'); $this->config()->set($name, $value); return $this; }
php
public function set_stat($name, $value) { Deprecation::notice('5.0', 'Use ->config()->set()'); $this->config()->set($name, $value); return $this; }
[ "public", "function", "set_stat", "(", "$", "name", ",", "$", "value", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use ->config()->set()'", ")", ";", "$", "this", "->", "config", "(", ")", "->", "set", "(", "$", "name", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Update the config value for a given property @deprecated 5.0 Use ->config()->set() instead @param string $name @param mixed $value @return $this
[ "Update", "the", "config", "value", "for", "a", "given", "property" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/Configurable.php#L57-L62
train
silverstripe/silverstripe-framework
src/ORM/Connect/PDOStatementHandle.php
PDOStatementHandle.typeCorrectedFetchAll
public function typeCorrectedFetchAll() { if ($this->columnMeta === null) { $columnCount = $this->statement->columnCount(); $this->columnMeta = []; for ($i = 0; $i<$columnCount; $i++) { $this->columnMeta[$i] = $this->statement->getColumnMeta($i); } } // Re-map fetched data using columnMeta return array_map( function ($rowArray) { $row = []; foreach ($this->columnMeta as $i => $meta) { // Coerce any column types that aren't correctly retrieved from the database if (isset($meta['native_type']) && isset(self::$type_mapping[$meta['native_type']])) { settype($rowArray[$i], self::$type_mapping[$meta['native_type']]); } $row[$meta['name']] = $rowArray[$i]; } return $row; }, $this->statement->fetchAll(PDO::FETCH_NUM) ); }
php
public function typeCorrectedFetchAll() { if ($this->columnMeta === null) { $columnCount = $this->statement->columnCount(); $this->columnMeta = []; for ($i = 0; $i<$columnCount; $i++) { $this->columnMeta[$i] = $this->statement->getColumnMeta($i); } } // Re-map fetched data using columnMeta return array_map( function ($rowArray) { $row = []; foreach ($this->columnMeta as $i => $meta) { // Coerce any column types that aren't correctly retrieved from the database if (isset($meta['native_type']) && isset(self::$type_mapping[$meta['native_type']])) { settype($rowArray[$i], self::$type_mapping[$meta['native_type']]); } $row[$meta['name']] = $rowArray[$i]; } return $row; }, $this->statement->fetchAll(PDO::FETCH_NUM) ); }
[ "public", "function", "typeCorrectedFetchAll", "(", ")", "{", "if", "(", "$", "this", "->", "columnMeta", "===", "null", ")", "{", "$", "columnCount", "=", "$", "this", "->", "statement", "->", "columnCount", "(", ")", ";", "$", "this", "->", "columnMeta", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "columnCount", ";", "$", "i", "++", ")", "{", "$", "this", "->", "columnMeta", "[", "$", "i", "]", "=", "$", "this", "->", "statement", "->", "getColumnMeta", "(", "$", "i", ")", ";", "}", "}", "// Re-map fetched data using columnMeta", "return", "array_map", "(", "function", "(", "$", "rowArray", ")", "{", "$", "row", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "columnMeta", "as", "$", "i", "=>", "$", "meta", ")", "{", "// Coerce any column types that aren't correctly retrieved from the database", "if", "(", "isset", "(", "$", "meta", "[", "'native_type'", "]", ")", "&&", "isset", "(", "self", "::", "$", "type_mapping", "[", "$", "meta", "[", "'native_type'", "]", "]", ")", ")", "{", "settype", "(", "$", "rowArray", "[", "$", "i", "]", ",", "self", "::", "$", "type_mapping", "[", "$", "meta", "[", "'native_type'", "]", "]", ")", ";", "}", "$", "row", "[", "$", "meta", "[", "'name'", "]", "]", "=", "$", "rowArray", "[", "$", "i", "]", ";", "}", "return", "$", "row", ";", "}", ",", "$", "this", "->", "statement", "->", "fetchAll", "(", "PDO", "::", "FETCH_NUM", ")", ")", ";", "}" ]
Fetch a record form the statement with its type data corrected Returns data as an array of maps @return array
[ "Fetch", "a", "record", "form", "the", "statement", "with", "its", "type", "data", "corrected", "Returns", "data", "as", "an", "array", "of", "maps" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/PDOStatementHandle.php#L65-L90
train
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
Backtrace.filter_backtrace
public static function filter_backtrace($bt, $ignoredFunctions = null) { $defaultIgnoredFunctions = array( 'SilverStripe\\Logging\\Log::log', 'SilverStripe\\Dev\\Backtrace::backtrace', 'SilverStripe\\Dev\\Backtrace::filtered_backtrace', 'Zend_Log_Writer_Abstract->write', 'Zend_Log->log', 'Zend_Log->__call', 'Zend_Log->err', 'SilverStripe\\Dev\\DebugView->writeTrace', 'SilverStripe\\Dev\\CliDebugView->writeTrace', 'SilverStripe\\Dev\\Debug::emailError', 'SilverStripe\\Dev\\Debug::warningHandler', 'SilverStripe\\Dev\\Debug::noticeHandler', 'SilverStripe\\Dev\\Debug::fatalHandler', 'errorHandler', 'SilverStripe\\Dev\\Debug::showError', 'SilverStripe\\Dev\\Debug::backtrace', 'exceptionHandler' ); if ($ignoredFunctions) { foreach ($ignoredFunctions as $ignoredFunction) { $defaultIgnoredFunctions[] = $ignoredFunction; } } while ($bt && in_array(self::full_func_name($bt[0]), $defaultIgnoredFunctions)) { array_shift($bt); } $ignoredArgs = static::config()->get('ignore_function_args'); // Filter out arguments foreach ($bt as $i => $frame) { $match = false; if (!empty($bt[$i]['class'])) { foreach ($ignoredArgs as $fnSpec) { if (is_array($fnSpec) && ('*' == $fnSpec[0] || $bt[$i]['class'] == $fnSpec[0]) && $bt[$i]['function'] == $fnSpec[1] ) { $match = true; } } } else { if (in_array($bt[$i]['function'], $ignoredArgs)) { $match = true; } } if ($match) { foreach ($bt[$i]['args'] as $j => $arg) { $bt[$i]['args'][$j] = '<filtered>'; } } } return $bt; }
php
public static function filter_backtrace($bt, $ignoredFunctions = null) { $defaultIgnoredFunctions = array( 'SilverStripe\\Logging\\Log::log', 'SilverStripe\\Dev\\Backtrace::backtrace', 'SilverStripe\\Dev\\Backtrace::filtered_backtrace', 'Zend_Log_Writer_Abstract->write', 'Zend_Log->log', 'Zend_Log->__call', 'Zend_Log->err', 'SilverStripe\\Dev\\DebugView->writeTrace', 'SilverStripe\\Dev\\CliDebugView->writeTrace', 'SilverStripe\\Dev\\Debug::emailError', 'SilverStripe\\Dev\\Debug::warningHandler', 'SilverStripe\\Dev\\Debug::noticeHandler', 'SilverStripe\\Dev\\Debug::fatalHandler', 'errorHandler', 'SilverStripe\\Dev\\Debug::showError', 'SilverStripe\\Dev\\Debug::backtrace', 'exceptionHandler' ); if ($ignoredFunctions) { foreach ($ignoredFunctions as $ignoredFunction) { $defaultIgnoredFunctions[] = $ignoredFunction; } } while ($bt && in_array(self::full_func_name($bt[0]), $defaultIgnoredFunctions)) { array_shift($bt); } $ignoredArgs = static::config()->get('ignore_function_args'); // Filter out arguments foreach ($bt as $i => $frame) { $match = false; if (!empty($bt[$i]['class'])) { foreach ($ignoredArgs as $fnSpec) { if (is_array($fnSpec) && ('*' == $fnSpec[0] || $bt[$i]['class'] == $fnSpec[0]) && $bt[$i]['function'] == $fnSpec[1] ) { $match = true; } } } else { if (in_array($bt[$i]['function'], $ignoredArgs)) { $match = true; } } if ($match) { foreach ($bt[$i]['args'] as $j => $arg) { $bt[$i]['args'][$j] = '<filtered>'; } } } return $bt; }
[ "public", "static", "function", "filter_backtrace", "(", "$", "bt", ",", "$", "ignoredFunctions", "=", "null", ")", "{", "$", "defaultIgnoredFunctions", "=", "array", "(", "'SilverStripe\\\\Logging\\\\Log::log'", ",", "'SilverStripe\\\\Dev\\\\Backtrace::backtrace'", ",", "'SilverStripe\\\\Dev\\\\Backtrace::filtered_backtrace'", ",", "'Zend_Log_Writer_Abstract->write'", ",", "'Zend_Log->log'", ",", "'Zend_Log->__call'", ",", "'Zend_Log->err'", ",", "'SilverStripe\\\\Dev\\\\DebugView->writeTrace'", ",", "'SilverStripe\\\\Dev\\\\CliDebugView->writeTrace'", ",", "'SilverStripe\\\\Dev\\\\Debug::emailError'", ",", "'SilverStripe\\\\Dev\\\\Debug::warningHandler'", ",", "'SilverStripe\\\\Dev\\\\Debug::noticeHandler'", ",", "'SilverStripe\\\\Dev\\\\Debug::fatalHandler'", ",", "'errorHandler'", ",", "'SilverStripe\\\\Dev\\\\Debug::showError'", ",", "'SilverStripe\\\\Dev\\\\Debug::backtrace'", ",", "'exceptionHandler'", ")", ";", "if", "(", "$", "ignoredFunctions", ")", "{", "foreach", "(", "$", "ignoredFunctions", "as", "$", "ignoredFunction", ")", "{", "$", "defaultIgnoredFunctions", "[", "]", "=", "$", "ignoredFunction", ";", "}", "}", "while", "(", "$", "bt", "&&", "in_array", "(", "self", "::", "full_func_name", "(", "$", "bt", "[", "0", "]", ")", ",", "$", "defaultIgnoredFunctions", ")", ")", "{", "array_shift", "(", "$", "bt", ")", ";", "}", "$", "ignoredArgs", "=", "static", "::", "config", "(", ")", "->", "get", "(", "'ignore_function_args'", ")", ";", "// Filter out arguments", "foreach", "(", "$", "bt", "as", "$", "i", "=>", "$", "frame", ")", "{", "$", "match", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "bt", "[", "$", "i", "]", "[", "'class'", "]", ")", ")", "{", "foreach", "(", "$", "ignoredArgs", "as", "$", "fnSpec", ")", "{", "if", "(", "is_array", "(", "$", "fnSpec", ")", "&&", "(", "'*'", "==", "$", "fnSpec", "[", "0", "]", "||", "$", "bt", "[", "$", "i", "]", "[", "'class'", "]", "==", "$", "fnSpec", "[", "0", "]", ")", "&&", "$", "bt", "[", "$", "i", "]", "[", "'function'", "]", "==", "$", "fnSpec", "[", "1", "]", ")", "{", "$", "match", "=", "true", ";", "}", "}", "}", "else", "{", "if", "(", "in_array", "(", "$", "bt", "[", "$", "i", "]", "[", "'function'", "]", ",", "$", "ignoredArgs", ")", ")", "{", "$", "match", "=", "true", ";", "}", "}", "if", "(", "$", "match", ")", "{", "foreach", "(", "$", "bt", "[", "$", "i", "]", "[", "'args'", "]", "as", "$", "j", "=>", "$", "arg", ")", "{", "$", "bt", "[", "$", "i", "]", "[", "'args'", "]", "[", "$", "j", "]", "=", "'<filtered>'", ";", "}", "}", "}", "return", "$", "bt", ";", "}" ]
Filter a backtrace so that it doesn't show the calls to the debugging system, which is useless information. @param array $bt Backtrace to filter @param null|array $ignoredFunctions List of extra functions to filter out @return array
[ "Filter", "a", "backtrace", "so", "that", "it", "doesn", "t", "show", "the", "calls", "to", "the", "debugging", "system", "which", "is", "useless", "information", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Backtrace.php#L72-L131
train
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
Backtrace.backtrace
public static function backtrace($returnVal = false, $ignoreAjax = false, $ignoredFunctions = null) { $plainText = Director::is_cli() || (Director::is_ajax() && !$ignoreAjax); $result = self::get_rendered_backtrace(debug_backtrace(), $plainText, $ignoredFunctions); if ($returnVal) { return $result; } else { echo $result; return null; } }
php
public static function backtrace($returnVal = false, $ignoreAjax = false, $ignoredFunctions = null) { $plainText = Director::is_cli() || (Director::is_ajax() && !$ignoreAjax); $result = self::get_rendered_backtrace(debug_backtrace(), $plainText, $ignoredFunctions); if ($returnVal) { return $result; } else { echo $result; return null; } }
[ "public", "static", "function", "backtrace", "(", "$", "returnVal", "=", "false", ",", "$", "ignoreAjax", "=", "false", ",", "$", "ignoredFunctions", "=", "null", ")", "{", "$", "plainText", "=", "Director", "::", "is_cli", "(", ")", "||", "(", "Director", "::", "is_ajax", "(", ")", "&&", "!", "$", "ignoreAjax", ")", ";", "$", "result", "=", "self", "::", "get_rendered_backtrace", "(", "debug_backtrace", "(", ")", ",", "$", "plainText", ",", "$", "ignoredFunctions", ")", ";", "if", "(", "$", "returnVal", ")", "{", "return", "$", "result", ";", "}", "else", "{", "echo", "$", "result", ";", "return", "null", ";", "}", "}" ]
Render or return a backtrace from the given scope. @param mixed $returnVal @param bool $ignoreAjax @param array $ignoredFunctions @return mixed
[ "Render", "or", "return", "a", "backtrace", "from", "the", "given", "scope", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Backtrace.php#L141-L151
train
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
Backtrace.full_func_name
public static function full_func_name($item, $showArgs = false, $argCharLimit = 10000) { $funcName = ''; if (isset($item['class'])) { $funcName .= $item['class']; } if (isset($item['type'])) { $funcName .= $item['type']; } if (isset($item['function'])) { $funcName .= $item['function']; } if ($showArgs && isset($item['args'])) { $args = array(); foreach ($item['args'] as $arg) { if (!is_object($arg) || method_exists($arg, '__toString')) { $sarg = is_array($arg) ? 'Array' : strval($arg); $args[] = (strlen($sarg) > $argCharLimit) ? substr($sarg, 0, $argCharLimit) . '...' : $sarg; } else { $args[] = get_class($arg); } } $funcName .= "(" . implode(", ", $args) . ")"; } return $funcName; }
php
public static function full_func_name($item, $showArgs = false, $argCharLimit = 10000) { $funcName = ''; if (isset($item['class'])) { $funcName .= $item['class']; } if (isset($item['type'])) { $funcName .= $item['type']; } if (isset($item['function'])) { $funcName .= $item['function']; } if ($showArgs && isset($item['args'])) { $args = array(); foreach ($item['args'] as $arg) { if (!is_object($arg) || method_exists($arg, '__toString')) { $sarg = is_array($arg) ? 'Array' : strval($arg); $args[] = (strlen($sarg) > $argCharLimit) ? substr($sarg, 0, $argCharLimit) . '...' : $sarg; } else { $args[] = get_class($arg); } } $funcName .= "(" . implode(", ", $args) . ")"; } return $funcName; }
[ "public", "static", "function", "full_func_name", "(", "$", "item", ",", "$", "showArgs", "=", "false", ",", "$", "argCharLimit", "=", "10000", ")", "{", "$", "funcName", "=", "''", ";", "if", "(", "isset", "(", "$", "item", "[", "'class'", "]", ")", ")", "{", "$", "funcName", ".=", "$", "item", "[", "'class'", "]", ";", "}", "if", "(", "isset", "(", "$", "item", "[", "'type'", "]", ")", ")", "{", "$", "funcName", ".=", "$", "item", "[", "'type'", "]", ";", "}", "if", "(", "isset", "(", "$", "item", "[", "'function'", "]", ")", ")", "{", "$", "funcName", ".=", "$", "item", "[", "'function'", "]", ";", "}", "if", "(", "$", "showArgs", "&&", "isset", "(", "$", "item", "[", "'args'", "]", ")", ")", "{", "$", "args", "=", "array", "(", ")", ";", "foreach", "(", "$", "item", "[", "'args'", "]", "as", "$", "arg", ")", "{", "if", "(", "!", "is_object", "(", "$", "arg", ")", "||", "method_exists", "(", "$", "arg", ",", "'__toString'", ")", ")", "{", "$", "sarg", "=", "is_array", "(", "$", "arg", ")", "?", "'Array'", ":", "strval", "(", "$", "arg", ")", ";", "$", "args", "[", "]", "=", "(", "strlen", "(", "$", "sarg", ")", ">", "$", "argCharLimit", ")", "?", "substr", "(", "$", "sarg", ",", "0", ",", "$", "argCharLimit", ")", ".", "'...'", ":", "$", "sarg", ";", "}", "else", "{", "$", "args", "[", "]", "=", "get_class", "(", "$", "arg", ")", ";", "}", "}", "$", "funcName", ".=", "\"(\"", ".", "implode", "(", "\", \"", ",", "$", "args", ")", ".", "\")\"", ";", "}", "return", "$", "funcName", ";", "}" ]
Return the full function name. If showArgs is set to true, a string representation of the arguments will be shown @param Object $item @param bool $showArgs @param int $argCharLimit @return string
[ "Return", "the", "full", "function", "name", ".", "If", "showArgs", "is", "set", "to", "true", "a", "string", "representation", "of", "the", "arguments", "will", "be", "shown" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Backtrace.php#L162-L190
train
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
Backtrace.get_rendered_backtrace
public static function get_rendered_backtrace($bt, $plainText = false, $ignoredFunctions = null) { if (empty($bt)) { return ''; } $bt = self::filter_backtrace($bt, $ignoredFunctions); $result = ($plainText) ? '' : '<ul>'; foreach ($bt as $item) { if ($plainText) { $result .= self::full_func_name($item, true) . "\n"; if (isset($item['line']) && isset($item['file'])) { $result .= basename($item['file']) . ":$item[line]\n"; } $result .= "\n"; } else { if ($item['function'] == 'user_error') { $name = $item['args'][0]; } else { $name = self::full_func_name($item, true); } $result .= "<li><b>" . htmlentities($name, ENT_COMPAT, 'UTF-8') . "</b>\n<br />\n"; $result .= isset($item['file']) ? htmlentities(basename($item['file']), ENT_COMPAT, 'UTF-8') : ''; $result .= isset($item['line']) ? ":$item[line]" : ''; $result .= "</li>\n"; } } if (!$plainText) { $result .= '</ul>'; } return $result; }
php
public static function get_rendered_backtrace($bt, $plainText = false, $ignoredFunctions = null) { if (empty($bt)) { return ''; } $bt = self::filter_backtrace($bt, $ignoredFunctions); $result = ($plainText) ? '' : '<ul>'; foreach ($bt as $item) { if ($plainText) { $result .= self::full_func_name($item, true) . "\n"; if (isset($item['line']) && isset($item['file'])) { $result .= basename($item['file']) . ":$item[line]\n"; } $result .= "\n"; } else { if ($item['function'] == 'user_error') { $name = $item['args'][0]; } else { $name = self::full_func_name($item, true); } $result .= "<li><b>" . htmlentities($name, ENT_COMPAT, 'UTF-8') . "</b>\n<br />\n"; $result .= isset($item['file']) ? htmlentities(basename($item['file']), ENT_COMPAT, 'UTF-8') : ''; $result .= isset($item['line']) ? ":$item[line]" : ''; $result .= "</li>\n"; } } if (!$plainText) { $result .= '</ul>'; } return $result; }
[ "public", "static", "function", "get_rendered_backtrace", "(", "$", "bt", ",", "$", "plainText", "=", "false", ",", "$", "ignoredFunctions", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "bt", ")", ")", "{", "return", "''", ";", "}", "$", "bt", "=", "self", "::", "filter_backtrace", "(", "$", "bt", ",", "$", "ignoredFunctions", ")", ";", "$", "result", "=", "(", "$", "plainText", ")", "?", "''", ":", "'<ul>'", ";", "foreach", "(", "$", "bt", "as", "$", "item", ")", "{", "if", "(", "$", "plainText", ")", "{", "$", "result", ".=", "self", "::", "full_func_name", "(", "$", "item", ",", "true", ")", ".", "\"\\n\"", ";", "if", "(", "isset", "(", "$", "item", "[", "'line'", "]", ")", "&&", "isset", "(", "$", "item", "[", "'file'", "]", ")", ")", "{", "$", "result", ".=", "basename", "(", "$", "item", "[", "'file'", "]", ")", ".", "\":$item[line]\\n\"", ";", "}", "$", "result", ".=", "\"\\n\"", ";", "}", "else", "{", "if", "(", "$", "item", "[", "'function'", "]", "==", "'user_error'", ")", "{", "$", "name", "=", "$", "item", "[", "'args'", "]", "[", "0", "]", ";", "}", "else", "{", "$", "name", "=", "self", "::", "full_func_name", "(", "$", "item", ",", "true", ")", ";", "}", "$", "result", ".=", "\"<li><b>\"", ".", "htmlentities", "(", "$", "name", ",", "ENT_COMPAT", ",", "'UTF-8'", ")", ".", "\"</b>\\n<br />\\n\"", ";", "$", "result", ".=", "isset", "(", "$", "item", "[", "'file'", "]", ")", "?", "htmlentities", "(", "basename", "(", "$", "item", "[", "'file'", "]", ")", ",", "ENT_COMPAT", ",", "'UTF-8'", ")", ":", "''", ";", "$", "result", ".=", "isset", "(", "$", "item", "[", "'line'", "]", ")", "?", "\":$item[line]\"", ":", "''", ";", "$", "result", ".=", "\"</li>\\n\"", ";", "}", "}", "if", "(", "!", "$", "plainText", ")", "{", "$", "result", ".=", "'</ul>'", ";", "}", "return", "$", "result", ";", "}" ]
Render a backtrace array into an appropriate plain-text or HTML string. @param array $bt The trace array, as returned by debug_backtrace() or Exception::getTrace() @param boolean $plainText Set to false for HTML output, or true for plain-text output @param array $ignoredFunctions List of functions that should be ignored. If not set, a default is provided @return string The rendered backtrace
[ "Render", "a", "backtrace", "array", "into", "an", "appropriate", "plain", "-", "text", "or", "HTML", "string", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Backtrace.php#L200-L230
train
silverstripe/silverstripe-framework
src/Core/Config/CoreConfigFactory.php
CoreConfigFactory.createRoot
public function createRoot() { $instance = new CachedConfigCollection(); // Override nested config to use delta collection $instance->setNestFactory(function ($collection) { return DeltaConfigCollection::createFromCollection($collection, Config::NO_DELTAS); }); // Create config cache if ($this->cacheFactory) { $cache = $this->cacheFactory->create(CacheInterface::class . '.configcache', [ 'namespace' => 'configcache' ]); $instance->setCache($cache); } // Set collection creator $instance->setCollectionCreator(function () { return $this->createCore(); }); return $instance; }
php
public function createRoot() { $instance = new CachedConfigCollection(); // Override nested config to use delta collection $instance->setNestFactory(function ($collection) { return DeltaConfigCollection::createFromCollection($collection, Config::NO_DELTAS); }); // Create config cache if ($this->cacheFactory) { $cache = $this->cacheFactory->create(CacheInterface::class . '.configcache', [ 'namespace' => 'configcache' ]); $instance->setCache($cache); } // Set collection creator $instance->setCollectionCreator(function () { return $this->createCore(); }); return $instance; }
[ "public", "function", "createRoot", "(", ")", "{", "$", "instance", "=", "new", "CachedConfigCollection", "(", ")", ";", "// Override nested config to use delta collection", "$", "instance", "->", "setNestFactory", "(", "function", "(", "$", "collection", ")", "{", "return", "DeltaConfigCollection", "::", "createFromCollection", "(", "$", "collection", ",", "Config", "::", "NO_DELTAS", ")", ";", "}", ")", ";", "// Create config cache", "if", "(", "$", "this", "->", "cacheFactory", ")", "{", "$", "cache", "=", "$", "this", "->", "cacheFactory", "->", "create", "(", "CacheInterface", "::", "class", ".", "'.configcache'", ",", "[", "'namespace'", "=>", "'configcache'", "]", ")", ";", "$", "instance", "->", "setCache", "(", "$", "cache", ")", ";", "}", "// Set collection creator", "$", "instance", "->", "setCollectionCreator", "(", "function", "(", ")", "{", "return", "$", "this", "->", "createCore", "(", ")", ";", "}", ")", ";", "return", "$", "instance", ";", "}" ]
Create root application config. This will be an immutable cached config, which conditionally generates a nested "core" config. @return CachedConfigCollection
[ "Create", "root", "application", "config", ".", "This", "will", "be", "an", "immutable", "cached", "config", "which", "conditionally", "generates", "a", "nested", "core", "config", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/CoreConfigFactory.php#L48-L71
train
silverstripe/silverstripe-framework
src/Core/Config/CoreConfigFactory.php
CoreConfigFactory.createCore
public function createCore() { $config = new MemoryConfigCollection(); // Set default middleware $config->setMiddlewares([ new InheritanceMiddleware(Config::UNINHERITED), new ExtensionMiddleware(Config::EXCLUDE_EXTRA_SOURCES), ]); // Transform $config->transform([ $this->buildStaticTransformer(), $this->buildYamlTransformer() ]); return $config; }
php
public function createCore() { $config = new MemoryConfigCollection(); // Set default middleware $config->setMiddlewares([ new InheritanceMiddleware(Config::UNINHERITED), new ExtensionMiddleware(Config::EXCLUDE_EXTRA_SOURCES), ]); // Transform $config->transform([ $this->buildStaticTransformer(), $this->buildYamlTransformer() ]); return $config; }
[ "public", "function", "createCore", "(", ")", "{", "$", "config", "=", "new", "MemoryConfigCollection", "(", ")", ";", "// Set default middleware", "$", "config", "->", "setMiddlewares", "(", "[", "new", "InheritanceMiddleware", "(", "Config", "::", "UNINHERITED", ")", ",", "new", "ExtensionMiddleware", "(", "Config", "::", "EXCLUDE_EXTRA_SOURCES", ")", ",", "]", ")", ";", "// Transform", "$", "config", "->", "transform", "(", "[", "$", "this", "->", "buildStaticTransformer", "(", ")", ",", "$", "this", "->", "buildYamlTransformer", "(", ")", "]", ")", ";", "return", "$", "config", ";", "}" ]
Rebuild new uncached config, which is mutable @return MemoryConfigCollection
[ "Rebuild", "new", "uncached", "config", "which", "is", "mutable" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/CoreConfigFactory.php#L78-L95
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.reset
public function reset() { $this->tableNames = []; $this->databaseFields = []; $this->databaseIndexes = []; $this->defaultDatabaseIndexes = []; $this->compositeFields = []; }
php
public function reset() { $this->tableNames = []; $this->databaseFields = []; $this->databaseIndexes = []; $this->defaultDatabaseIndexes = []; $this->compositeFields = []; }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "tableNames", "=", "[", "]", ";", "$", "this", "->", "databaseFields", "=", "[", "]", ";", "$", "this", "->", "databaseIndexes", "=", "[", "]", ";", "$", "this", "->", "defaultDatabaseIndexes", "=", "[", "]", ";", "$", "this", "->", "compositeFields", "=", "[", "]", ";", "}" ]
Clear cached table names
[ "Clear", "cached", "table", "names" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L74-L81
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.tableName
public function tableName($class) { $tables = $this->getTableNames(); $class = ClassInfo::class_name($class); if (isset($tables[$class])) { return Convert::raw2sql($tables[$class]); } return null; }
php
public function tableName($class) { $tables = $this->getTableNames(); $class = ClassInfo::class_name($class); if (isset($tables[$class])) { return Convert::raw2sql($tables[$class]); } return null; }
[ "public", "function", "tableName", "(", "$", "class", ")", "{", "$", "tables", "=", "$", "this", "->", "getTableNames", "(", ")", ";", "$", "class", "=", "ClassInfo", "::", "class_name", "(", "$", "class", ")", ";", "if", "(", "isset", "(", "$", "tables", "[", "$", "class", "]", ")", ")", "{", "return", "Convert", "::", "raw2sql", "(", "$", "tables", "[", "$", "class", "]", ")", ";", "}", "return", "null", ";", "}" ]
Get table name for the given class. Note that this does not confirm a table actually exists (or should exist), but returns the name that would be used if this table did exist. @param string $class @return string Returns the table name, or null if there is no table
[ "Get", "table", "name", "for", "the", "given", "class", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L126-L134
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.fieldSpecs
public function fieldSpecs($classOrInstance, $options = 0) { $class = ClassInfo::class_name($classOrInstance); // Validate options if (!is_int($options)) { throw new InvalidArgumentException("Invalid options " . var_export($options, true)); } $uninherited = ($options & self::UNINHERITED) === self::UNINHERITED; $dbOnly = ($options & self::DB_ONLY) === self::DB_ONLY; $includeClass = ($options & self::INCLUDE_CLASS) === self::INCLUDE_CLASS; // Walk class hierarchy $db = []; $classes = $uninherited ? [$class] : ClassInfo::ancestry($class); foreach ($classes as $tableClass) { // Skip irrelevant parent classes if (!is_subclass_of($tableClass, DataObject::class)) { continue; } // Find all fields on this class $fields = $this->databaseFields($tableClass, false); // Merge with composite fields if (!$dbOnly) { $compositeFields = $this->compositeFields($tableClass, false); $fields = array_merge($fields, $compositeFields); } // Record specification foreach ($fields as $name => $specification) { $prefix = $includeClass ? "{$tableClass}." : ""; $db[$name] = $prefix . $specification; } } return $db; }
php
public function fieldSpecs($classOrInstance, $options = 0) { $class = ClassInfo::class_name($classOrInstance); // Validate options if (!is_int($options)) { throw new InvalidArgumentException("Invalid options " . var_export($options, true)); } $uninherited = ($options & self::UNINHERITED) === self::UNINHERITED; $dbOnly = ($options & self::DB_ONLY) === self::DB_ONLY; $includeClass = ($options & self::INCLUDE_CLASS) === self::INCLUDE_CLASS; // Walk class hierarchy $db = []; $classes = $uninherited ? [$class] : ClassInfo::ancestry($class); foreach ($classes as $tableClass) { // Skip irrelevant parent classes if (!is_subclass_of($tableClass, DataObject::class)) { continue; } // Find all fields on this class $fields = $this->databaseFields($tableClass, false); // Merge with composite fields if (!$dbOnly) { $compositeFields = $this->compositeFields($tableClass, false); $fields = array_merge($fields, $compositeFields); } // Record specification foreach ($fields as $name => $specification) { $prefix = $includeClass ? "{$tableClass}." : ""; $db[$name] = $prefix . $specification; } } return $db; }
[ "public", "function", "fieldSpecs", "(", "$", "classOrInstance", ",", "$", "options", "=", "0", ")", "{", "$", "class", "=", "ClassInfo", "::", "class_name", "(", "$", "classOrInstance", ")", ";", "// Validate options", "if", "(", "!", "is_int", "(", "$", "options", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid options \"", ".", "var_export", "(", "$", "options", ",", "true", ")", ")", ";", "}", "$", "uninherited", "=", "(", "$", "options", "&", "self", "::", "UNINHERITED", ")", "===", "self", "::", "UNINHERITED", ";", "$", "dbOnly", "=", "(", "$", "options", "&", "self", "::", "DB_ONLY", ")", "===", "self", "::", "DB_ONLY", ";", "$", "includeClass", "=", "(", "$", "options", "&", "self", "::", "INCLUDE_CLASS", ")", "===", "self", "::", "INCLUDE_CLASS", ";", "// Walk class hierarchy", "$", "db", "=", "[", "]", ";", "$", "classes", "=", "$", "uninherited", "?", "[", "$", "class", "]", ":", "ClassInfo", "::", "ancestry", "(", "$", "class", ")", ";", "foreach", "(", "$", "classes", "as", "$", "tableClass", ")", "{", "// Skip irrelevant parent classes", "if", "(", "!", "is_subclass_of", "(", "$", "tableClass", ",", "DataObject", "::", "class", ")", ")", "{", "continue", ";", "}", "// Find all fields on this class", "$", "fields", "=", "$", "this", "->", "databaseFields", "(", "$", "tableClass", ",", "false", ")", ";", "// Merge with composite fields", "if", "(", "!", "$", "dbOnly", ")", "{", "$", "compositeFields", "=", "$", "this", "->", "compositeFields", "(", "$", "tableClass", ",", "false", ")", ";", "$", "fields", "=", "array_merge", "(", "$", "fields", ",", "$", "compositeFields", ")", ";", "}", "// Record specification", "foreach", "(", "$", "fields", "as", "$", "name", "=>", "$", "specification", ")", "{", "$", "prefix", "=", "$", "includeClass", "?", "\"{$tableClass}.\"", ":", "\"\"", ";", "$", "db", "[", "$", "name", "]", "=", "$", "prefix", ".", "$", "specification", ";", "}", "}", "return", "$", "db", ";", "}" ]
Get all DB field specifications for a class, including ancestors and composite fields. @param string|DataObject $classOrInstance @param int $options Bitmask of options - UNINHERITED Limit to only this table - DB_ONLY Exclude virtual fields (such as composite fields), and only include fields with a db column. - INCLUDE_CLASS Prefix the field specification with the class name in RecordClass.Column(spec) format. @return array List of fields, where the key is the field name and the value is the field specification.
[ "Get", "all", "DB", "field", "specifications", "for", "a", "class", "including", "ancestors", "and", "composite", "fields", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L196-L232
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.fieldSpec
public function fieldSpec($classOrInstance, $fieldName, $options = 0) { $specs = $this->fieldSpecs($classOrInstance, $options); return isset($specs[$fieldName]) ? $specs[$fieldName] : null; }
php
public function fieldSpec($classOrInstance, $fieldName, $options = 0) { $specs = $this->fieldSpecs($classOrInstance, $options); return isset($specs[$fieldName]) ? $specs[$fieldName] : null; }
[ "public", "function", "fieldSpec", "(", "$", "classOrInstance", ",", "$", "fieldName", ",", "$", "options", "=", "0", ")", "{", "$", "specs", "=", "$", "this", "->", "fieldSpecs", "(", "$", "classOrInstance", ",", "$", "options", ")", ";", "return", "isset", "(", "$", "specs", "[", "$", "fieldName", "]", ")", "?", "$", "specs", "[", "$", "fieldName", "]", ":", "null", ";", "}" ]
Get specifications for a single class field @param string|DataObject $classOrInstance Name or instance of class @param string $fieldName Name of field to retrieve @param int $options Bitmask of options - UNINHERITED Limit to only this table - DB_ONLY Exclude virtual fields (such as composite fields), and only include fields with a db column. - INCLUDE_CLASS Prefix the field specification with the class name in RecordClass.Column(spec) format. @return string|null Field will be a string in FieldClass(args) format, or RecordClass.FieldClass(args) format if using INCLUDE_CLASS. Will be null if no field is found.
[ "Get", "specifications", "for", "a", "single", "class", "field" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L248-L252
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.tableClass
public function tableClass($table) { $tables = $this->getTableNames(); $class = array_search($table, $tables, true); if ($class) { return $class; } // If there is no class for this table, strip table modifiers (e.g. _Live / _Versions) // from the end and re-attempt a search. if (preg_match('/^(?<class>.+)(_[^_]+)$/i', $table, $matches)) { $table = $matches['class']; $class = array_search($table, $tables, true); if ($class) { return $class; } } return null; }
php
public function tableClass($table) { $tables = $this->getTableNames(); $class = array_search($table, $tables, true); if ($class) { return $class; } // If there is no class for this table, strip table modifiers (e.g. _Live / _Versions) // from the end and re-attempt a search. if (preg_match('/^(?<class>.+)(_[^_]+)$/i', $table, $matches)) { $table = $matches['class']; $class = array_search($table, $tables, true); if ($class) { return $class; } } return null; }
[ "public", "function", "tableClass", "(", "$", "table", ")", "{", "$", "tables", "=", "$", "this", "->", "getTableNames", "(", ")", ";", "$", "class", "=", "array_search", "(", "$", "table", ",", "$", "tables", ",", "true", ")", ";", "if", "(", "$", "class", ")", "{", "return", "$", "class", ";", "}", "// If there is no class for this table, strip table modifiers (e.g. _Live / _Versions)", "// from the end and re-attempt a search.", "if", "(", "preg_match", "(", "'/^(?<class>.+)(_[^_]+)$/i'", ",", "$", "table", ",", "$", "matches", ")", ")", "{", "$", "table", "=", "$", "matches", "[", "'class'", "]", ";", "$", "class", "=", "array_search", "(", "$", "table", ",", "$", "tables", ",", "true", ")", ";", "if", "(", "$", "class", ")", "{", "return", "$", "class", ";", "}", "}", "return", "null", ";", "}" ]
Find the class for the given table @param string $table @return string|null The FQN of the class, or null if not found
[ "Find", "the", "class", "for", "the", "given", "table" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L261-L279
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.cacheTableNames
protected function cacheTableNames() { if ($this->tableNames) { return; } $this->tableNames = []; foreach (ClassInfo::subclassesFor(DataObject::class) as $class) { if ($class === DataObject::class) { continue; } $table = $this->buildTableName($class); // Check for conflicts $conflict = array_search($table, $this->tableNames, true); if ($conflict) { throw new LogicException( "Multiple classes (\"{$class}\", \"{$conflict}\") map to the same table: \"{$table}\"" ); } $this->tableNames[$class] = $table; } }
php
protected function cacheTableNames() { if ($this->tableNames) { return; } $this->tableNames = []; foreach (ClassInfo::subclassesFor(DataObject::class) as $class) { if ($class === DataObject::class) { continue; } $table = $this->buildTableName($class); // Check for conflicts $conflict = array_search($table, $this->tableNames, true); if ($conflict) { throw new LogicException( "Multiple classes (\"{$class}\", \"{$conflict}\") map to the same table: \"{$table}\"" ); } $this->tableNames[$class] = $table; } }
[ "protected", "function", "cacheTableNames", "(", ")", "{", "if", "(", "$", "this", "->", "tableNames", ")", "{", "return", ";", "}", "$", "this", "->", "tableNames", "=", "[", "]", ";", "foreach", "(", "ClassInfo", "::", "subclassesFor", "(", "DataObject", "::", "class", ")", "as", "$", "class", ")", "{", "if", "(", "$", "class", "===", "DataObject", "::", "class", ")", "{", "continue", ";", "}", "$", "table", "=", "$", "this", "->", "buildTableName", "(", "$", "class", ")", ";", "// Check for conflicts", "$", "conflict", "=", "array_search", "(", "$", "table", ",", "$", "this", "->", "tableNames", ",", "true", ")", ";", "if", "(", "$", "conflict", ")", "{", "throw", "new", "LogicException", "(", "\"Multiple classes (\\\"{$class}\\\", \\\"{$conflict}\\\") map to the same table: \\\"{$table}\\\"\"", ")", ";", "}", "$", "this", "->", "tableNames", "[", "$", "class", "]", "=", "$", "table", ";", "}", "}" ]
Cache all table names if necessary
[ "Cache", "all", "table", "names", "if", "necessary" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L284-L305
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.buildTableName
protected function buildTableName($class) { $table = Config::inst()->get($class, 'table_name', Config::UNINHERITED); // Generate default table name if ($table) { return $table; } if (strpos($class, '\\') === false) { return $class; } $separator = DataObjectSchema::config()->uninherited('table_namespace_separator'); $table = str_replace('\\', $separator, trim($class, '\\')); if (!ClassInfo::classImplements($class, TestOnly::class) && $this->classHasTable($class)) { DBSchemaManager::showTableNameWarning($table, $class); } return $table; }
php
protected function buildTableName($class) { $table = Config::inst()->get($class, 'table_name', Config::UNINHERITED); // Generate default table name if ($table) { return $table; } if (strpos($class, '\\') === false) { return $class; } $separator = DataObjectSchema::config()->uninherited('table_namespace_separator'); $table = str_replace('\\', $separator, trim($class, '\\')); if (!ClassInfo::classImplements($class, TestOnly::class) && $this->classHasTable($class)) { DBSchemaManager::showTableNameWarning($table, $class); } return $table; }
[ "protected", "function", "buildTableName", "(", "$", "class", ")", "{", "$", "table", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'table_name'", ",", "Config", "::", "UNINHERITED", ")", ";", "// Generate default table name", "if", "(", "$", "table", ")", "{", "return", "$", "table", ";", "}", "if", "(", "strpos", "(", "$", "class", ",", "'\\\\'", ")", "===", "false", ")", "{", "return", "$", "class", ";", "}", "$", "separator", "=", "DataObjectSchema", "::", "config", "(", ")", "->", "uninherited", "(", "'table_namespace_separator'", ")", ";", "$", "table", "=", "str_replace", "(", "'\\\\'", ",", "$", "separator", ",", "trim", "(", "$", "class", ",", "'\\\\'", ")", ")", ";", "if", "(", "!", "ClassInfo", "::", "classImplements", "(", "$", "class", ",", "TestOnly", "::", "class", ")", "&&", "$", "this", "->", "classHasTable", "(", "$", "class", ")", ")", "{", "DBSchemaManager", "::", "showTableNameWarning", "(", "$", "table", ",", "$", "class", ")", ";", "}", "return", "$", "table", ";", "}" ]
Generate table name for a class. Note: some DB schema have a hard limit on table name length. This is not enforced by this method. See dev/build errors for details in case of table name violation. @param string $class @return string
[ "Generate", "table", "name", "for", "a", "class", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L317-L338
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.databaseFields
public function databaseFields($class, $aggregated = true) { $class = ClassInfo::class_name($class); if ($class === DataObject::class) { return []; } $this->cacheDatabaseFields($class); $fields = $this->databaseFields[$class]; if (!$aggregated) { return $fields; } // Recursively merge $parentFields = $this->databaseFields(get_parent_class($class)); return array_merge($fields, array_diff_key($parentFields, $fields)); }
php
public function databaseFields($class, $aggregated = true) { $class = ClassInfo::class_name($class); if ($class === DataObject::class) { return []; } $this->cacheDatabaseFields($class); $fields = $this->databaseFields[$class]; if (!$aggregated) { return $fields; } // Recursively merge $parentFields = $this->databaseFields(get_parent_class($class)); return array_merge($fields, array_diff_key($parentFields, $fields)); }
[ "public", "function", "databaseFields", "(", "$", "class", ",", "$", "aggregated", "=", "true", ")", "{", "$", "class", "=", "ClassInfo", "::", "class_name", "(", "$", "class", ")", ";", "if", "(", "$", "class", "===", "DataObject", "::", "class", ")", "{", "return", "[", "]", ";", "}", "$", "this", "->", "cacheDatabaseFields", "(", "$", "class", ")", ";", "$", "fields", "=", "$", "this", "->", "databaseFields", "[", "$", "class", "]", ";", "if", "(", "!", "$", "aggregated", ")", "{", "return", "$", "fields", ";", "}", "// Recursively merge", "$", "parentFields", "=", "$", "this", "->", "databaseFields", "(", "get_parent_class", "(", "$", "class", ")", ")", ";", "return", "array_merge", "(", "$", "fields", ",", "array_diff_key", "(", "$", "parentFields", ",", "$", "fields", ")", ")", ";", "}" ]
Return the complete map of fields to specification on this object, including fixed_fields. "ID" will be included on every table. @param string $class Class name to query from @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return array Map of fieldname to specification, similiar to {@link DataObject::$db}.
[ "Return", "the", "complete", "map", "of", "fields", "to", "specification", "on", "this", "object", "including", "fixed_fields", ".", "ID", "will", "be", "included", "on", "every", "table", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L349-L365
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.databaseField
public function databaseField($class, $field, $aggregated = true) { $fields = $this->databaseFields($class, $aggregated); return isset($fields[$field]) ? $fields[$field] : null; }
php
public function databaseField($class, $field, $aggregated = true) { $fields = $this->databaseFields($class, $aggregated); return isset($fields[$field]) ? $fields[$field] : null; }
[ "public", "function", "databaseField", "(", "$", "class", ",", "$", "field", ",", "$", "aggregated", "=", "true", ")", "{", "$", "fields", "=", "$", "this", "->", "databaseFields", "(", "$", "class", ",", "$", "aggregated", ")", ";", "return", "isset", "(", "$", "fields", "[", "$", "field", "]", ")", "?", "$", "fields", "[", "$", "field", "]", ":", "null", ";", "}" ]
Gets a single database field. @param string $class Class name to query from @param string $field Field name @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return string|null Field specification, or null if not a field
[ "Gets", "a", "single", "database", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L376-L380
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.classHasTable
public function classHasTable($class) { if (!is_subclass_of($class, DataObject::class)) { return false; } $fields = $this->databaseFields($class, false); return !empty($fields); }
php
public function classHasTable($class) { if (!is_subclass_of($class, DataObject::class)) { return false; } $fields = $this->databaseFields($class, false); return !empty($fields); }
[ "public", "function", "classHasTable", "(", "$", "class", ")", "{", "if", "(", "!", "is_subclass_of", "(", "$", "class", ",", "DataObject", "::", "class", ")", ")", "{", "return", "false", ";", "}", "$", "fields", "=", "$", "this", "->", "databaseFields", "(", "$", "class", ",", "false", ")", ";", "return", "!", "empty", "(", "$", "fields", ")", ";", "}" ]
Check if the given class has a table @param string $class @return bool
[ "Check", "if", "the", "given", "class", "has", "a", "table" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L409-L417
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.compositeFields
public function compositeFields($class, $aggregated = true) { $class = ClassInfo::class_name($class); if ($class === DataObject::class) { return []; } $this->cacheDatabaseFields($class); // Get fields for this class $compositeFields = $this->compositeFields[$class]; if (!$aggregated) { return $compositeFields; } // Recursively merge $parentFields = $this->compositeFields(get_parent_class($class)); return array_merge($compositeFields, array_diff_key($parentFields, $compositeFields)); }
php
public function compositeFields($class, $aggregated = true) { $class = ClassInfo::class_name($class); if ($class === DataObject::class) { return []; } $this->cacheDatabaseFields($class); // Get fields for this class $compositeFields = $this->compositeFields[$class]; if (!$aggregated) { return $compositeFields; } // Recursively merge $parentFields = $this->compositeFields(get_parent_class($class)); return array_merge($compositeFields, array_diff_key($parentFields, $compositeFields)); }
[ "public", "function", "compositeFields", "(", "$", "class", ",", "$", "aggregated", "=", "true", ")", "{", "$", "class", "=", "ClassInfo", "::", "class_name", "(", "$", "class", ")", ";", "if", "(", "$", "class", "===", "DataObject", "::", "class", ")", "{", "return", "[", "]", ";", "}", "$", "this", "->", "cacheDatabaseFields", "(", "$", "class", ")", ";", "// Get fields for this class", "$", "compositeFields", "=", "$", "this", "->", "compositeFields", "[", "$", "class", "]", ";", "if", "(", "!", "$", "aggregated", ")", "{", "return", "$", "compositeFields", ";", "}", "// Recursively merge", "$", "parentFields", "=", "$", "this", "->", "compositeFields", "(", "get_parent_class", "(", "$", "class", ")", ")", ";", "return", "array_merge", "(", "$", "compositeFields", ",", "array_diff_key", "(", "$", "parentFields", ",", "$", "compositeFields", ")", ")", ";", "}" ]
Returns a list of all the composite if the given db field on the class is a composite field. Will check all applicable ancestor classes and aggregate results. Can be called directly on an object. E.g. Member::composite_fields(), or Member::composite_fields(null, true) to aggregate. Includes composite has_one (Polymorphic) fields @param string $class Name of class to check @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return array List of composite fields and their class spec
[ "Returns", "a", "list", "of", "all", "the", "composite", "if", "the", "given", "db", "field", "on", "the", "class", "is", "a", "composite", "field", ".", "Will", "check", "all", "applicable", "ancestor", "classes", "and", "aggregate", "results", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L433-L450
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.compositeField
public function compositeField($class, $field, $aggregated = true) { $fields = $this->compositeFields($class, $aggregated); return isset($fields[$field]) ? $fields[$field] : null; }
php
public function compositeField($class, $field, $aggregated = true) { $fields = $this->compositeFields($class, $aggregated); return isset($fields[$field]) ? $fields[$field] : null; }
[ "public", "function", "compositeField", "(", "$", "class", ",", "$", "field", ",", "$", "aggregated", "=", "true", ")", "{", "$", "fields", "=", "$", "this", "->", "compositeFields", "(", "$", "class", ",", "$", "aggregated", ")", ";", "return", "isset", "(", "$", "fields", "[", "$", "field", "]", ")", "?", "$", "fields", "[", "$", "field", "]", ":", "null", ";", "}" ]
Get a composite field for a class @param string $class Class name to query from @param string $field Field name @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return string|null Field specification, or null if not a field
[ "Get", "a", "composite", "field", "for", "a", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L461-L465
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.cacheDatabaseFields
protected function cacheDatabaseFields($class) { // Skip if already cached if (isset($this->databaseFields[$class]) && isset($this->compositeFields[$class])) { return; } $compositeFields = array(); $dbFields = array(); // Ensure fixed fields appear at the start $fixedFields = DataObject::config()->uninherited('fixed_fields'); if (get_parent_class($class) === DataObject::class) { // Merge fixed with ClassName spec and custom db fields $dbFields = $fixedFields; } else { $dbFields['ID'] = $fixedFields['ID']; } // Check each DB value as either a field or composite field $db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: array(); foreach ($db as $fieldName => $fieldSpec) { $fieldClass = strtok($fieldSpec, '('); if (singleton($fieldClass) instanceof DBComposite) { $compositeFields[$fieldName] = $fieldSpec; } else { $dbFields[$fieldName] = $fieldSpec; } } // Add in all has_ones $hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED) ?: array(); foreach ($hasOne as $fieldName => $hasOneClass) { if ($hasOneClass === DataObject::class) { $compositeFields[$fieldName] = 'PolymorphicForeignKey'; } else { $dbFields["{$fieldName}ID"] = 'ForeignKey'; } } // Merge composite fields into DB foreach ($compositeFields as $fieldName => $fieldSpec) { $fieldObj = Injector::inst()->create($fieldSpec, $fieldName); $fieldObj->setTable($class); $nestedFields = $fieldObj->compositeDatabaseFields(); foreach ($nestedFields as $nestedName => $nestedSpec) { $dbFields["{$fieldName}{$nestedName}"] = $nestedSpec; } } // Prevent field-less tables with only 'ID' if (count($dbFields) < 2) { $dbFields = []; } // Return cached results $this->databaseFields[$class] = $dbFields; $this->compositeFields[$class] = $compositeFields; }
php
protected function cacheDatabaseFields($class) { // Skip if already cached if (isset($this->databaseFields[$class]) && isset($this->compositeFields[$class])) { return; } $compositeFields = array(); $dbFields = array(); // Ensure fixed fields appear at the start $fixedFields = DataObject::config()->uninherited('fixed_fields'); if (get_parent_class($class) === DataObject::class) { // Merge fixed with ClassName spec and custom db fields $dbFields = $fixedFields; } else { $dbFields['ID'] = $fixedFields['ID']; } // Check each DB value as either a field or composite field $db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: array(); foreach ($db as $fieldName => $fieldSpec) { $fieldClass = strtok($fieldSpec, '('); if (singleton($fieldClass) instanceof DBComposite) { $compositeFields[$fieldName] = $fieldSpec; } else { $dbFields[$fieldName] = $fieldSpec; } } // Add in all has_ones $hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED) ?: array(); foreach ($hasOne as $fieldName => $hasOneClass) { if ($hasOneClass === DataObject::class) { $compositeFields[$fieldName] = 'PolymorphicForeignKey'; } else { $dbFields["{$fieldName}ID"] = 'ForeignKey'; } } // Merge composite fields into DB foreach ($compositeFields as $fieldName => $fieldSpec) { $fieldObj = Injector::inst()->create($fieldSpec, $fieldName); $fieldObj->setTable($class); $nestedFields = $fieldObj->compositeDatabaseFields(); foreach ($nestedFields as $nestedName => $nestedSpec) { $dbFields["{$fieldName}{$nestedName}"] = $nestedSpec; } } // Prevent field-less tables with only 'ID' if (count($dbFields) < 2) { $dbFields = []; } // Return cached results $this->databaseFields[$class] = $dbFields; $this->compositeFields[$class] = $compositeFields; }
[ "protected", "function", "cacheDatabaseFields", "(", "$", "class", ")", "{", "// Skip if already cached", "if", "(", "isset", "(", "$", "this", "->", "databaseFields", "[", "$", "class", "]", ")", "&&", "isset", "(", "$", "this", "->", "compositeFields", "[", "$", "class", "]", ")", ")", "{", "return", ";", "}", "$", "compositeFields", "=", "array", "(", ")", ";", "$", "dbFields", "=", "array", "(", ")", ";", "// Ensure fixed fields appear at the start", "$", "fixedFields", "=", "DataObject", "::", "config", "(", ")", "->", "uninherited", "(", "'fixed_fields'", ")", ";", "if", "(", "get_parent_class", "(", "$", "class", ")", "===", "DataObject", "::", "class", ")", "{", "// Merge fixed with ClassName spec and custom db fields", "$", "dbFields", "=", "$", "fixedFields", ";", "}", "else", "{", "$", "dbFields", "[", "'ID'", "]", "=", "$", "fixedFields", "[", "'ID'", "]", ";", "}", "// Check each DB value as either a field or composite field", "$", "db", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'db'", ",", "Config", "::", "UNINHERITED", ")", "?", ":", "array", "(", ")", ";", "foreach", "(", "$", "db", "as", "$", "fieldName", "=>", "$", "fieldSpec", ")", "{", "$", "fieldClass", "=", "strtok", "(", "$", "fieldSpec", ",", "'('", ")", ";", "if", "(", "singleton", "(", "$", "fieldClass", ")", "instanceof", "DBComposite", ")", "{", "$", "compositeFields", "[", "$", "fieldName", "]", "=", "$", "fieldSpec", ";", "}", "else", "{", "$", "dbFields", "[", "$", "fieldName", "]", "=", "$", "fieldSpec", ";", "}", "}", "// Add in all has_ones", "$", "hasOne", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'has_one'", ",", "Config", "::", "UNINHERITED", ")", "?", ":", "array", "(", ")", ";", "foreach", "(", "$", "hasOne", "as", "$", "fieldName", "=>", "$", "hasOneClass", ")", "{", "if", "(", "$", "hasOneClass", "===", "DataObject", "::", "class", ")", "{", "$", "compositeFields", "[", "$", "fieldName", "]", "=", "'PolymorphicForeignKey'", ";", "}", "else", "{", "$", "dbFields", "[", "\"{$fieldName}ID\"", "]", "=", "'ForeignKey'", ";", "}", "}", "// Merge composite fields into DB", "foreach", "(", "$", "compositeFields", "as", "$", "fieldName", "=>", "$", "fieldSpec", ")", "{", "$", "fieldObj", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "fieldSpec", ",", "$", "fieldName", ")", ";", "$", "fieldObj", "->", "setTable", "(", "$", "class", ")", ";", "$", "nestedFields", "=", "$", "fieldObj", "->", "compositeDatabaseFields", "(", ")", ";", "foreach", "(", "$", "nestedFields", "as", "$", "nestedName", "=>", "$", "nestedSpec", ")", "{", "$", "dbFields", "[", "\"{$fieldName}{$nestedName}\"", "]", "=", "$", "nestedSpec", ";", "}", "}", "// Prevent field-less tables with only 'ID'", "if", "(", "count", "(", "$", "dbFields", ")", "<", "2", ")", "{", "$", "dbFields", "=", "[", "]", ";", "}", "// Return cached results", "$", "this", "->", "databaseFields", "[", "$", "class", "]", "=", "$", "dbFields", ";", "$", "this", "->", "compositeFields", "[", "$", "class", "]", "=", "$", "compositeFields", ";", "}" ]
Cache all database and composite fields for the given class. Will do nothing if already cached @param string $class Class name to cache
[ "Cache", "all", "database", "and", "composite", "fields", "for", "the", "given", "class", ".", "Will", "do", "nothing", "if", "already", "cached" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L473-L530
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.cacheDatabaseIndexes
protected function cacheDatabaseIndexes($class) { if (!array_key_exists($class, $this->databaseIndexes)) { $this->databaseIndexes[$class] = array_merge( $this->buildSortDatabaseIndexes($class), $this->cacheDefaultDatabaseIndexes($class), $this->buildCustomDatabaseIndexes($class) ); } }
php
protected function cacheDatabaseIndexes($class) { if (!array_key_exists($class, $this->databaseIndexes)) { $this->databaseIndexes[$class] = array_merge( $this->buildSortDatabaseIndexes($class), $this->cacheDefaultDatabaseIndexes($class), $this->buildCustomDatabaseIndexes($class) ); } }
[ "protected", "function", "cacheDatabaseIndexes", "(", "$", "class", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "class", ",", "$", "this", "->", "databaseIndexes", ")", ")", "{", "$", "this", "->", "databaseIndexes", "[", "$", "class", "]", "=", "array_merge", "(", "$", "this", "->", "buildSortDatabaseIndexes", "(", "$", "class", ")", ",", "$", "this", "->", "cacheDefaultDatabaseIndexes", "(", "$", "class", ")", ",", "$", "this", "->", "buildCustomDatabaseIndexes", "(", "$", "class", ")", ")", ";", "}", "}" ]
Cache all indexes for the given class. Will do nothing if already cached. @param $class
[ "Cache", "all", "indexes", "for", "the", "given", "class", ".", "Will", "do", "nothing", "if", "already", "cached", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L537-L546
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.cacheDefaultDatabaseIndexes
protected function cacheDefaultDatabaseIndexes($class) { if (array_key_exists($class, $this->defaultDatabaseIndexes)) { return $this->defaultDatabaseIndexes[$class]; } $this->defaultDatabaseIndexes[$class] = []; $fieldSpecs = $this->fieldSpecs($class, self::UNINHERITED); foreach ($fieldSpecs as $field => $spec) { /** @var DBField $fieldObj */ $fieldObj = Injector::inst()->create($spec, $field); if ($indexSpecs = $fieldObj->getIndexSpecs()) { $this->defaultDatabaseIndexes[$class][$field] = $indexSpecs; } } return $this->defaultDatabaseIndexes[$class]; }
php
protected function cacheDefaultDatabaseIndexes($class) { if (array_key_exists($class, $this->defaultDatabaseIndexes)) { return $this->defaultDatabaseIndexes[$class]; } $this->defaultDatabaseIndexes[$class] = []; $fieldSpecs = $this->fieldSpecs($class, self::UNINHERITED); foreach ($fieldSpecs as $field => $spec) { /** @var DBField $fieldObj */ $fieldObj = Injector::inst()->create($spec, $field); if ($indexSpecs = $fieldObj->getIndexSpecs()) { $this->defaultDatabaseIndexes[$class][$field] = $indexSpecs; } } return $this->defaultDatabaseIndexes[$class]; }
[ "protected", "function", "cacheDefaultDatabaseIndexes", "(", "$", "class", ")", "{", "if", "(", "array_key_exists", "(", "$", "class", ",", "$", "this", "->", "defaultDatabaseIndexes", ")", ")", "{", "return", "$", "this", "->", "defaultDatabaseIndexes", "[", "$", "class", "]", ";", "}", "$", "this", "->", "defaultDatabaseIndexes", "[", "$", "class", "]", "=", "[", "]", ";", "$", "fieldSpecs", "=", "$", "this", "->", "fieldSpecs", "(", "$", "class", ",", "self", "::", "UNINHERITED", ")", ";", "foreach", "(", "$", "fieldSpecs", "as", "$", "field", "=>", "$", "spec", ")", "{", "/** @var DBField $fieldObj */", "$", "fieldObj", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "spec", ",", "$", "field", ")", ";", "if", "(", "$", "indexSpecs", "=", "$", "fieldObj", "->", "getIndexSpecs", "(", ")", ")", "{", "$", "this", "->", "defaultDatabaseIndexes", "[", "$", "class", "]", "[", "$", "field", "]", "=", "$", "indexSpecs", ";", "}", "}", "return", "$", "this", "->", "defaultDatabaseIndexes", "[", "$", "class", "]", ";", "}" ]
Get "default" database indexable field types @param string $class @return array
[ "Get", "default", "database", "indexable", "field", "types" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L555-L571
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.buildCustomDatabaseIndexes
protected function buildCustomDatabaseIndexes($class) { $indexes = []; $classIndexes = Config::inst()->get($class, 'indexes', Config::UNINHERITED) ?: []; foreach ($classIndexes as $indexName => $indexSpec) { if (array_key_exists($indexName, $indexes)) { throw new InvalidArgumentException(sprintf( 'Index named "%s" already exists on class %s', $indexName, $class )); } if (is_array($indexSpec)) { if (!ArrayLib::is_associative($indexSpec)) { $indexSpec = [ 'columns' => $indexSpec, ]; } if (!isset($indexSpec['type'])) { $indexSpec['type'] = 'index'; } if (!isset($indexSpec['columns'])) { $indexSpec['columns'] = [$indexName]; } elseif (!is_array($indexSpec['columns'])) { throw new InvalidArgumentException(sprintf( 'Index %s on %s is not valid. columns should be an array %s given', var_export($indexName, true), var_export($class, true), var_export($indexSpec['columns'], true) )); } } else { $indexSpec = [ 'type' => 'index', 'columns' => [$indexName], ]; } $indexes[$indexName] = $indexSpec; } return $indexes; }
php
protected function buildCustomDatabaseIndexes($class) { $indexes = []; $classIndexes = Config::inst()->get($class, 'indexes', Config::UNINHERITED) ?: []; foreach ($classIndexes as $indexName => $indexSpec) { if (array_key_exists($indexName, $indexes)) { throw new InvalidArgumentException(sprintf( 'Index named "%s" already exists on class %s', $indexName, $class )); } if (is_array($indexSpec)) { if (!ArrayLib::is_associative($indexSpec)) { $indexSpec = [ 'columns' => $indexSpec, ]; } if (!isset($indexSpec['type'])) { $indexSpec['type'] = 'index'; } if (!isset($indexSpec['columns'])) { $indexSpec['columns'] = [$indexName]; } elseif (!is_array($indexSpec['columns'])) { throw new InvalidArgumentException(sprintf( 'Index %s on %s is not valid. columns should be an array %s given', var_export($indexName, true), var_export($class, true), var_export($indexSpec['columns'], true) )); } } else { $indexSpec = [ 'type' => 'index', 'columns' => [$indexName], ]; } $indexes[$indexName] = $indexSpec; } return $indexes; }
[ "protected", "function", "buildCustomDatabaseIndexes", "(", "$", "class", ")", "{", "$", "indexes", "=", "[", "]", ";", "$", "classIndexes", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'indexes'", ",", "Config", "::", "UNINHERITED", ")", "?", ":", "[", "]", ";", "foreach", "(", "$", "classIndexes", "as", "$", "indexName", "=>", "$", "indexSpec", ")", "{", "if", "(", "array_key_exists", "(", "$", "indexName", ",", "$", "indexes", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Index named \"%s\" already exists on class %s'", ",", "$", "indexName", ",", "$", "class", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "indexSpec", ")", ")", "{", "if", "(", "!", "ArrayLib", "::", "is_associative", "(", "$", "indexSpec", ")", ")", "{", "$", "indexSpec", "=", "[", "'columns'", "=>", "$", "indexSpec", ",", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "indexSpec", "[", "'type'", "]", ")", ")", "{", "$", "indexSpec", "[", "'type'", "]", "=", "'index'", ";", "}", "if", "(", "!", "isset", "(", "$", "indexSpec", "[", "'columns'", "]", ")", ")", "{", "$", "indexSpec", "[", "'columns'", "]", "=", "[", "$", "indexName", "]", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "indexSpec", "[", "'columns'", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Index %s on %s is not valid. columns should be an array %s given'", ",", "var_export", "(", "$", "indexName", ",", "true", ")", ",", "var_export", "(", "$", "class", ",", "true", ")", ",", "var_export", "(", "$", "indexSpec", "[", "'columns'", "]", ",", "true", ")", ")", ")", ";", "}", "}", "else", "{", "$", "indexSpec", "=", "[", "'type'", "=>", "'index'", ",", "'columns'", "=>", "[", "$", "indexName", "]", ",", "]", ";", "}", "$", "indexes", "[", "$", "indexName", "]", "=", "$", "indexSpec", ";", "}", "return", "$", "indexes", ";", "}" ]
Look for custom indexes declared on the class @param string $class @return array @throws InvalidArgumentException If an index already exists on the class @throws InvalidArgumentException If a custom index format is not valid
[ "Look", "for", "custom", "indexes", "declared", "on", "the", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L582-L622
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.manyManyComponent
public function manyManyComponent($class, $component) { $classes = ClassInfo::ancestry($class); foreach ($classes as $parentClass) { // Check if the component is defined in many_many on this class $otherManyMany = Config::inst()->get($parentClass, 'many_many', Config::UNINHERITED); if (isset($otherManyMany[$component])) { return $this->parseManyManyComponent($parentClass, $component, $otherManyMany[$component]); } // Check if the component is defined in belongs_many_many on this class $belongsManyMany = Config::inst()->get($parentClass, 'belongs_many_many', Config::UNINHERITED); if (!isset($belongsManyMany[$component])) { continue; } // Extract class and relation name from dot-notation $belongs = $this->parseBelongsManyManyComponent( $parentClass, $component, $belongsManyMany[$component] ); // Build inverse relationship from other many_many, and swap parent/child $otherManyMany = $this->manyManyComponent($belongs['childClass'], $belongs['relationName']); return [ 'relationClass' => $otherManyMany['relationClass'], 'parentClass' => $otherManyMany['childClass'], 'childClass' => $otherManyMany['parentClass'], 'parentField' => $otherManyMany['childField'], 'childField' => $otherManyMany['parentField'], 'join' => $otherManyMany['join'], ]; } return null; }
php
public function manyManyComponent($class, $component) { $classes = ClassInfo::ancestry($class); foreach ($classes as $parentClass) { // Check if the component is defined in many_many on this class $otherManyMany = Config::inst()->get($parentClass, 'many_many', Config::UNINHERITED); if (isset($otherManyMany[$component])) { return $this->parseManyManyComponent($parentClass, $component, $otherManyMany[$component]); } // Check if the component is defined in belongs_many_many on this class $belongsManyMany = Config::inst()->get($parentClass, 'belongs_many_many', Config::UNINHERITED); if (!isset($belongsManyMany[$component])) { continue; } // Extract class and relation name from dot-notation $belongs = $this->parseBelongsManyManyComponent( $parentClass, $component, $belongsManyMany[$component] ); // Build inverse relationship from other many_many, and swap parent/child $otherManyMany = $this->manyManyComponent($belongs['childClass'], $belongs['relationName']); return [ 'relationClass' => $otherManyMany['relationClass'], 'parentClass' => $otherManyMany['childClass'], 'childClass' => $otherManyMany['parentClass'], 'parentField' => $otherManyMany['childField'], 'childField' => $otherManyMany['parentField'], 'join' => $otherManyMany['join'], ]; } return null; }
[ "public", "function", "manyManyComponent", "(", "$", "class", ",", "$", "component", ")", "{", "$", "classes", "=", "ClassInfo", "::", "ancestry", "(", "$", "class", ")", ";", "foreach", "(", "$", "classes", "as", "$", "parentClass", ")", "{", "// Check if the component is defined in many_many on this class", "$", "otherManyMany", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "parentClass", ",", "'many_many'", ",", "Config", "::", "UNINHERITED", ")", ";", "if", "(", "isset", "(", "$", "otherManyMany", "[", "$", "component", "]", ")", ")", "{", "return", "$", "this", "->", "parseManyManyComponent", "(", "$", "parentClass", ",", "$", "component", ",", "$", "otherManyMany", "[", "$", "component", "]", ")", ";", "}", "// Check if the component is defined in belongs_many_many on this class", "$", "belongsManyMany", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "parentClass", ",", "'belongs_many_many'", ",", "Config", "::", "UNINHERITED", ")", ";", "if", "(", "!", "isset", "(", "$", "belongsManyMany", "[", "$", "component", "]", ")", ")", "{", "continue", ";", "}", "// Extract class and relation name from dot-notation", "$", "belongs", "=", "$", "this", "->", "parseBelongsManyManyComponent", "(", "$", "parentClass", ",", "$", "component", ",", "$", "belongsManyMany", "[", "$", "component", "]", ")", ";", "// Build inverse relationship from other many_many, and swap parent/child", "$", "otherManyMany", "=", "$", "this", "->", "manyManyComponent", "(", "$", "belongs", "[", "'childClass'", "]", ",", "$", "belongs", "[", "'relationName'", "]", ")", ";", "return", "[", "'relationClass'", "=>", "$", "otherManyMany", "[", "'relationClass'", "]", ",", "'parentClass'", "=>", "$", "otherManyMany", "[", "'childClass'", "]", ",", "'childClass'", "=>", "$", "otherManyMany", "[", "'parentClass'", "]", ",", "'parentField'", "=>", "$", "otherManyMany", "[", "'childField'", "]", ",", "'childField'", "=>", "$", "otherManyMany", "[", "'parentField'", "]", ",", "'join'", "=>", "$", "otherManyMany", "[", "'join'", "]", ",", "]", ";", "}", "return", "null", ";", "}" ]
Return information about a specific many_many component. Returns a numeric array. The first item in the array will be the class name of the relation. Standard many_many return type is: array( <manyManyClass>, Name of class for relation. E.g. "Categories" <classname>, The class that relation is defined in e.g. "Product" <candidateName>, The target class of the relation e.g. "Category" <parentField>, The field name pointing to <classname>'s table e.g. "ProductID". <childField>, The field name pointing to <candidatename>'s table e.g. "CategoryID". <joinTableOrRelation> The join table between the two classes e.g. "Product_Categories". If the class name is 'ManyManyThroughList' then this is the name of the has_many relation. ) @param string $class Name of class to get component for @param string $component The component name @return array|null
[ "Return", "information", "about", "a", "specific", "many_many", "component", ".", "Returns", "a", "numeric", "array", ".", "The", "first", "item", "in", "the", "array", "will", "be", "the", "class", "name", "of", "the", "relation", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L748-L783
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.parseBelongsManyManyComponent
protected function parseBelongsManyManyComponent($parentClass, $component, $specification) { $childClass = $specification; $relationName = null; if (strpos($specification, '.') !== false) { list($childClass, $relationName) = explode('.', $specification, 2); } // Check child class exists if (!class_exists($childClass)) { throw new LogicException( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$childClass} which does not exist" ); } // We need to find the inverse component name, if not explicitly given if (!$relationName) { $relationName = $this->getManyManyInverseRelationship($childClass, $parentClass); } // Check valid relation found if (!$relationName) { throw new LogicException( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$specification} without matching many_many" ); } // Return relatios return [ 'childClass' => $childClass, 'relationName' => $relationName, ]; }
php
protected function parseBelongsManyManyComponent($parentClass, $component, $specification) { $childClass = $specification; $relationName = null; if (strpos($specification, '.') !== false) { list($childClass, $relationName) = explode('.', $specification, 2); } // Check child class exists if (!class_exists($childClass)) { throw new LogicException( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$childClass} which does not exist" ); } // We need to find the inverse component name, if not explicitly given if (!$relationName) { $relationName = $this->getManyManyInverseRelationship($childClass, $parentClass); } // Check valid relation found if (!$relationName) { throw new LogicException( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$specification} without matching many_many" ); } // Return relatios return [ 'childClass' => $childClass, 'relationName' => $relationName, ]; }
[ "protected", "function", "parseBelongsManyManyComponent", "(", "$", "parentClass", ",", "$", "component", ",", "$", "specification", ")", "{", "$", "childClass", "=", "$", "specification", ";", "$", "relationName", "=", "null", ";", "if", "(", "strpos", "(", "$", "specification", ",", "'.'", ")", "!==", "false", ")", "{", "list", "(", "$", "childClass", ",", "$", "relationName", ")", "=", "explode", "(", "'.'", ",", "$", "specification", ",", "2", ")", ";", "}", "// Check child class exists", "if", "(", "!", "class_exists", "(", "$", "childClass", ")", ")", "{", "throw", "new", "LogicException", "(", "\"belongs_many_many relation {$parentClass}.{$component} points to \"", ".", "\"{$childClass} which does not exist\"", ")", ";", "}", "// We need to find the inverse component name, if not explicitly given", "if", "(", "!", "$", "relationName", ")", "{", "$", "relationName", "=", "$", "this", "->", "getManyManyInverseRelationship", "(", "$", "childClass", ",", "$", "parentClass", ")", ";", "}", "// Check valid relation found", "if", "(", "!", "$", "relationName", ")", "{", "throw", "new", "LogicException", "(", "\"belongs_many_many relation {$parentClass}.{$component} points to \"", ".", "\"{$specification} without matching many_many\"", ")", ";", "}", "// Return relatios", "return", "[", "'childClass'", "=>", "$", "childClass", ",", "'relationName'", "=>", "$", "relationName", ",", "]", ";", "}" ]
Parse a belongs_many_many component to extract class and relationship name @param string $parentClass Name of class @param string $component Name of relation on class @param string $specification specification for this belongs_many_many @return array Array with child class and relation name
[ "Parse", "a", "belongs_many_many", "component", "to", "extract", "class", "and", "relationship", "name" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L795-L829
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.manyManyExtraFieldsForComponent
public function manyManyExtraFieldsForComponent($class, $component) { // Get directly declared many_many_extraFields $extraFields = Config::inst()->get($class, 'many_many_extraFields'); if (isset($extraFields[$component])) { return $extraFields[$component]; } // If not belongs_many_many then there are no components while ($class && ($class !== DataObject::class)) { $belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED); if (isset($belongsManyMany[$component])) { // Reverse relationship and find extrafields from child class $belongs = $this->parseBelongsManyManyComponent( $class, $component, $belongsManyMany[$component] ); return $this->manyManyExtraFieldsForComponent($belongs['childClass'], $belongs['relationName']); } $class = get_parent_class($class); } return null; }
php
public function manyManyExtraFieldsForComponent($class, $component) { // Get directly declared many_many_extraFields $extraFields = Config::inst()->get($class, 'many_many_extraFields'); if (isset($extraFields[$component])) { return $extraFields[$component]; } // If not belongs_many_many then there are no components while ($class && ($class !== DataObject::class)) { $belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED); if (isset($belongsManyMany[$component])) { // Reverse relationship and find extrafields from child class $belongs = $this->parseBelongsManyManyComponent( $class, $component, $belongsManyMany[$component] ); return $this->manyManyExtraFieldsForComponent($belongs['childClass'], $belongs['relationName']); } $class = get_parent_class($class); } return null; }
[ "public", "function", "manyManyExtraFieldsForComponent", "(", "$", "class", ",", "$", "component", ")", "{", "// Get directly declared many_many_extraFields", "$", "extraFields", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'many_many_extraFields'", ")", ";", "if", "(", "isset", "(", "$", "extraFields", "[", "$", "component", "]", ")", ")", "{", "return", "$", "extraFields", "[", "$", "component", "]", ";", "}", "// If not belongs_many_many then there are no components", "while", "(", "$", "class", "&&", "(", "$", "class", "!==", "DataObject", "::", "class", ")", ")", "{", "$", "belongsManyMany", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'belongs_many_many'", ",", "Config", "::", "UNINHERITED", ")", ";", "if", "(", "isset", "(", "$", "belongsManyMany", "[", "$", "component", "]", ")", ")", "{", "// Reverse relationship and find extrafields from child class", "$", "belongs", "=", "$", "this", "->", "parseBelongsManyManyComponent", "(", "$", "class", ",", "$", "component", ",", "$", "belongsManyMany", "[", "$", "component", "]", ")", ";", "return", "$", "this", "->", "manyManyExtraFieldsForComponent", "(", "$", "belongs", "[", "'childClass'", "]", ",", "$", "belongs", "[", "'relationName'", "]", ")", ";", "}", "$", "class", "=", "get_parent_class", "(", "$", "class", ")", ";", "}", "return", "null", ";", "}" ]
Return the many-to-many extra fields specification for a specific component. @param string $class @param string $component @return array|null
[ "Return", "the", "many", "-", "to", "-", "many", "extra", "fields", "specification", "for", "a", "specific", "component", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L839-L862
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.hasManyComponent
public function hasManyComponent($class, $component, $classOnly = true) { $hasMany = (array)Config::inst()->get($class, 'has_many'); if (!isset($hasMany[$component])) { return null; } // Remove has_one specifier if given $hasMany = $hasMany[$component]; $hasManyClass = strtok($hasMany, '.'); // Validate $this->checkRelationClass($class, $component, $hasManyClass, 'has_many'); return $classOnly ? $hasManyClass : $hasMany; }
php
public function hasManyComponent($class, $component, $classOnly = true) { $hasMany = (array)Config::inst()->get($class, 'has_many'); if (!isset($hasMany[$component])) { return null; } // Remove has_one specifier if given $hasMany = $hasMany[$component]; $hasManyClass = strtok($hasMany, '.'); // Validate $this->checkRelationClass($class, $component, $hasManyClass, 'has_many'); return $classOnly ? $hasManyClass : $hasMany; }
[ "public", "function", "hasManyComponent", "(", "$", "class", ",", "$", "component", ",", "$", "classOnly", "=", "true", ")", "{", "$", "hasMany", "=", "(", "array", ")", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "class", ",", "'has_many'", ")", ";", "if", "(", "!", "isset", "(", "$", "hasMany", "[", "$", "component", "]", ")", ")", "{", "return", "null", ";", "}", "// Remove has_one specifier if given", "$", "hasMany", "=", "$", "hasMany", "[", "$", "component", "]", ";", "$", "hasManyClass", "=", "strtok", "(", "$", "hasMany", ",", "'.'", ")", ";", "// Validate", "$", "this", "->", "checkRelationClass", "(", "$", "class", ",", "$", "component", ",", "$", "hasManyClass", ",", "'has_many'", ")", ";", "return", "$", "classOnly", "?", "$", "hasManyClass", ":", "$", "hasMany", ";", "}" ]
Return data for a specific has_many component. @param string $class Parent class @param string $component @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE. @return string|null
[ "Return", "data", "for", "a", "specific", "has_many", "component", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L874-L888
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.hasOneComponent
public function hasOneComponent($class, $component) { $hasOnes = Config::forClass($class)->get('has_one'); if (!isset($hasOnes[$component])) { return null; } // Validate $relationClass = $hasOnes[$component]; $this->checkRelationClass($class, $component, $relationClass, 'has_one'); return $relationClass; }
php
public function hasOneComponent($class, $component) { $hasOnes = Config::forClass($class)->get('has_one'); if (!isset($hasOnes[$component])) { return null; } // Validate $relationClass = $hasOnes[$component]; $this->checkRelationClass($class, $component, $relationClass, 'has_one'); return $relationClass; }
[ "public", "function", "hasOneComponent", "(", "$", "class", ",", "$", "component", ")", "{", "$", "hasOnes", "=", "Config", "::", "forClass", "(", "$", "class", ")", "->", "get", "(", "'has_one'", ")", ";", "if", "(", "!", "isset", "(", "$", "hasOnes", "[", "$", "component", "]", ")", ")", "{", "return", "null", ";", "}", "// Validate", "$", "relationClass", "=", "$", "hasOnes", "[", "$", "component", "]", ";", "$", "this", "->", "checkRelationClass", "(", "$", "class", ",", "$", "component", ",", "$", "relationClass", ",", "'has_one'", ")", ";", "return", "$", "relationClass", ";", "}" ]
Return data for a specific has_one component. @param string $class @param string $component @return string|null
[ "Return", "data", "for", "a", "specific", "has_one", "component", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L898-L909
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.belongsToComponent
public function belongsToComponent($class, $component, $classOnly = true) { $belongsTo = (array)Config::forClass($class)->get('belongs_to'); if (!isset($belongsTo[$component])) { return null; } // Remove has_one specifier if given $belongsTo = $belongsTo[$component]; $belongsToClass = strtok($belongsTo, '.'); // Validate $this->checkRelationClass($class, $component, $belongsToClass, 'belongs_to'); return $classOnly ? $belongsToClass : $belongsTo; }
php
public function belongsToComponent($class, $component, $classOnly = true) { $belongsTo = (array)Config::forClass($class)->get('belongs_to'); if (!isset($belongsTo[$component])) { return null; } // Remove has_one specifier if given $belongsTo = $belongsTo[$component]; $belongsToClass = strtok($belongsTo, '.'); // Validate $this->checkRelationClass($class, $component, $belongsToClass, 'belongs_to'); return $classOnly ? $belongsToClass : $belongsTo; }
[ "public", "function", "belongsToComponent", "(", "$", "class", ",", "$", "component", ",", "$", "classOnly", "=", "true", ")", "{", "$", "belongsTo", "=", "(", "array", ")", "Config", "::", "forClass", "(", "$", "class", ")", "->", "get", "(", "'belongs_to'", ")", ";", "if", "(", "!", "isset", "(", "$", "belongsTo", "[", "$", "component", "]", ")", ")", "{", "return", "null", ";", "}", "// Remove has_one specifier if given", "$", "belongsTo", "=", "$", "belongsTo", "[", "$", "component", "]", ";", "$", "belongsToClass", "=", "strtok", "(", "$", "belongsTo", ",", "'.'", ")", ";", "// Validate", "$", "this", "->", "checkRelationClass", "(", "$", "class", ",", "$", "component", ",", "$", "belongsToClass", ",", "'belongs_to'", ")", ";", "return", "$", "classOnly", "?", "$", "belongsToClass", ":", "$", "belongsTo", ";", "}" ]
Return data for a specific belongs_to component. @param string $class @param string $component @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE. @return string|null
[ "Return", "data", "for", "a", "specific", "belongs_to", "component", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L921-L935
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.getManyManyInverseRelationship
protected function getManyManyInverseRelationship($childClass, $parentClass) { $otherManyMany = Config::inst()->get($childClass, 'many_many', Config::UNINHERITED); if (!$otherManyMany) { return null; } foreach ($otherManyMany as $inverseComponentName => $manyManySpec) { // Normal many-many if ($manyManySpec === $parentClass) { return $inverseComponentName; } // many-many through, inspect 'to' for the many_many if (is_array($manyManySpec)) { $toClass = $this->hasOneComponent($manyManySpec['through'], $manyManySpec['to']); if ($toClass === $parentClass) { return $inverseComponentName; } } } return null; }
php
protected function getManyManyInverseRelationship($childClass, $parentClass) { $otherManyMany = Config::inst()->get($childClass, 'many_many', Config::UNINHERITED); if (!$otherManyMany) { return null; } foreach ($otherManyMany as $inverseComponentName => $manyManySpec) { // Normal many-many if ($manyManySpec === $parentClass) { return $inverseComponentName; } // many-many through, inspect 'to' for the many_many if (is_array($manyManySpec)) { $toClass = $this->hasOneComponent($manyManySpec['through'], $manyManySpec['to']); if ($toClass === $parentClass) { return $inverseComponentName; } } } return null; }
[ "protected", "function", "getManyManyInverseRelationship", "(", "$", "childClass", ",", "$", "parentClass", ")", "{", "$", "otherManyMany", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "childClass", ",", "'many_many'", ",", "Config", "::", "UNINHERITED", ")", ";", "if", "(", "!", "$", "otherManyMany", ")", "{", "return", "null", ";", "}", "foreach", "(", "$", "otherManyMany", "as", "$", "inverseComponentName", "=>", "$", "manyManySpec", ")", "{", "// Normal many-many", "if", "(", "$", "manyManySpec", "===", "$", "parentClass", ")", "{", "return", "$", "inverseComponentName", ";", "}", "// many-many through, inspect 'to' for the many_many", "if", "(", "is_array", "(", "$", "manyManySpec", ")", ")", "{", "$", "toClass", "=", "$", "this", "->", "hasOneComponent", "(", "$", "manyManySpec", "[", "'through'", "]", ",", "$", "manyManySpec", "[", "'to'", "]", ")", ";", "if", "(", "$", "toClass", "===", "$", "parentClass", ")", "{", "return", "$", "inverseComponentName", ";", "}", "}", "}", "return", "null", ";", "}" ]
Find a many_many on the child class that points back to this many_many @param string $childClass @param string $parentClass @return string|null
[ "Find", "a", "many_many", "on", "the", "child", "class", "that", "points", "back", "to", "this", "many_many" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L1010-L1030
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.getRemoteJoinField
public function getRemoteJoinField($class, $component, $type = 'has_many', &$polymorphic = false) { // Extract relation from current object if ($type === 'has_many') { $remoteClass = $this->hasManyComponent($class, $component, false); } else { $remoteClass = $this->belongsToComponent($class, $component, false); } if (empty($remoteClass)) { throw new Exception("Unknown $type component '$component' on class '$class'"); } if (!ClassInfo::exists(strtok($remoteClass, '.'))) { throw new Exception( "Class '$remoteClass' not found, but used in $type component '$component' on class '$class'" ); } // If presented with an explicit field name (using dot notation) then extract field name $remoteField = null; if (strpos($remoteClass, '.') !== false) { list($remoteClass, $remoteField) = explode('.', $remoteClass); } // Reference remote has_one to check against $remoteRelations = Config::inst()->get($remoteClass, 'has_one'); // Without an explicit field name, attempt to match the first remote field // with the same type as the current class if (empty($remoteField)) { // look for remote has_one joins on this class or any parent classes $remoteRelationsMap = array_flip($remoteRelations); foreach (array_reverse(ClassInfo::ancestry($class)) as $ancestryClass) { if (array_key_exists($ancestryClass, $remoteRelationsMap)) { $remoteField = $remoteRelationsMap[$ancestryClass]; break; } } } // In case of an indeterminate remote field show an error if (empty($remoteField)) { $polymorphic = false; $message = "No has_one found on class '$remoteClass'"; if ($type == 'has_many') { // include a hint for has_many that is missing a has_one $message .= ", the has_many relation from '$class' to '$remoteClass'"; $message .= " requires a has_one on '$remoteClass'"; } throw new Exception($message); } // If given an explicit field name ensure the related class specifies this if (empty($remoteRelations[$remoteField])) { throw new Exception("Missing expected has_one named '$remoteField' on class '$remoteClass' referenced by $type named '$component' on class {$class}"); } // Inspect resulting found relation if ($remoteRelations[$remoteField] === DataObject::class) { $polymorphic = true; return $remoteField; // Composite polymorphic field does not include 'ID' suffix } else { $polymorphic = false; return $remoteField . 'ID'; } }
php
public function getRemoteJoinField($class, $component, $type = 'has_many', &$polymorphic = false) { // Extract relation from current object if ($type === 'has_many') { $remoteClass = $this->hasManyComponent($class, $component, false); } else { $remoteClass = $this->belongsToComponent($class, $component, false); } if (empty($remoteClass)) { throw new Exception("Unknown $type component '$component' on class '$class'"); } if (!ClassInfo::exists(strtok($remoteClass, '.'))) { throw new Exception( "Class '$remoteClass' not found, but used in $type component '$component' on class '$class'" ); } // If presented with an explicit field name (using dot notation) then extract field name $remoteField = null; if (strpos($remoteClass, '.') !== false) { list($remoteClass, $remoteField) = explode('.', $remoteClass); } // Reference remote has_one to check against $remoteRelations = Config::inst()->get($remoteClass, 'has_one'); // Without an explicit field name, attempt to match the first remote field // with the same type as the current class if (empty($remoteField)) { // look for remote has_one joins on this class or any parent classes $remoteRelationsMap = array_flip($remoteRelations); foreach (array_reverse(ClassInfo::ancestry($class)) as $ancestryClass) { if (array_key_exists($ancestryClass, $remoteRelationsMap)) { $remoteField = $remoteRelationsMap[$ancestryClass]; break; } } } // In case of an indeterminate remote field show an error if (empty($remoteField)) { $polymorphic = false; $message = "No has_one found on class '$remoteClass'"; if ($type == 'has_many') { // include a hint for has_many that is missing a has_one $message .= ", the has_many relation from '$class' to '$remoteClass'"; $message .= " requires a has_one on '$remoteClass'"; } throw new Exception($message); } // If given an explicit field name ensure the related class specifies this if (empty($remoteRelations[$remoteField])) { throw new Exception("Missing expected has_one named '$remoteField' on class '$remoteClass' referenced by $type named '$component' on class {$class}"); } // Inspect resulting found relation if ($remoteRelations[$remoteField] === DataObject::class) { $polymorphic = true; return $remoteField; // Composite polymorphic field does not include 'ID' suffix } else { $polymorphic = false; return $remoteField . 'ID'; } }
[ "public", "function", "getRemoteJoinField", "(", "$", "class", ",", "$", "component", ",", "$", "type", "=", "'has_many'", ",", "&", "$", "polymorphic", "=", "false", ")", "{", "// Extract relation from current object", "if", "(", "$", "type", "===", "'has_many'", ")", "{", "$", "remoteClass", "=", "$", "this", "->", "hasManyComponent", "(", "$", "class", ",", "$", "component", ",", "false", ")", ";", "}", "else", "{", "$", "remoteClass", "=", "$", "this", "->", "belongsToComponent", "(", "$", "class", ",", "$", "component", ",", "false", ")", ";", "}", "if", "(", "empty", "(", "$", "remoteClass", ")", ")", "{", "throw", "new", "Exception", "(", "\"Unknown $type component '$component' on class '$class'\"", ")", ";", "}", "if", "(", "!", "ClassInfo", "::", "exists", "(", "strtok", "(", "$", "remoteClass", ",", "'.'", ")", ")", ")", "{", "throw", "new", "Exception", "(", "\"Class '$remoteClass' not found, but used in $type component '$component' on class '$class'\"", ")", ";", "}", "// If presented with an explicit field name (using dot notation) then extract field name", "$", "remoteField", "=", "null", ";", "if", "(", "strpos", "(", "$", "remoteClass", ",", "'.'", ")", "!==", "false", ")", "{", "list", "(", "$", "remoteClass", ",", "$", "remoteField", ")", "=", "explode", "(", "'.'", ",", "$", "remoteClass", ")", ";", "}", "// Reference remote has_one to check against", "$", "remoteRelations", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "remoteClass", ",", "'has_one'", ")", ";", "// Without an explicit field name, attempt to match the first remote field", "// with the same type as the current class", "if", "(", "empty", "(", "$", "remoteField", ")", ")", "{", "// look for remote has_one joins on this class or any parent classes", "$", "remoteRelationsMap", "=", "array_flip", "(", "$", "remoteRelations", ")", ";", "foreach", "(", "array_reverse", "(", "ClassInfo", "::", "ancestry", "(", "$", "class", ")", ")", "as", "$", "ancestryClass", ")", "{", "if", "(", "array_key_exists", "(", "$", "ancestryClass", ",", "$", "remoteRelationsMap", ")", ")", "{", "$", "remoteField", "=", "$", "remoteRelationsMap", "[", "$", "ancestryClass", "]", ";", "break", ";", "}", "}", "}", "// In case of an indeterminate remote field show an error", "if", "(", "empty", "(", "$", "remoteField", ")", ")", "{", "$", "polymorphic", "=", "false", ";", "$", "message", "=", "\"No has_one found on class '$remoteClass'\"", ";", "if", "(", "$", "type", "==", "'has_many'", ")", "{", "// include a hint for has_many that is missing a has_one", "$", "message", ".=", "\", the has_many relation from '$class' to '$remoteClass'\"", ";", "$", "message", ".=", "\" requires a has_one on '$remoteClass'\"", ";", "}", "throw", "new", "Exception", "(", "$", "message", ")", ";", "}", "// If given an explicit field name ensure the related class specifies this", "if", "(", "empty", "(", "$", "remoteRelations", "[", "$", "remoteField", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Missing expected has_one named '$remoteField'\n\t\t\t\ton class '$remoteClass' referenced by $type named '$component'\n\t\t\t\ton class {$class}\"", ")", ";", "}", "// Inspect resulting found relation", "if", "(", "$", "remoteRelations", "[", "$", "remoteField", "]", "===", "DataObject", "::", "class", ")", "{", "$", "polymorphic", "=", "true", ";", "return", "$", "remoteField", ";", "// Composite polymorphic field does not include 'ID' suffix", "}", "else", "{", "$", "polymorphic", "=", "false", ";", "return", "$", "remoteField", ".", "'ID'", ";", "}", "}" ]
Tries to find the database key on another object that is used to store a relationship to this class. If no join field can be found it defaults to 'ParentID'. If the remote field is polymorphic then $polymorphic is set to true, and the return value is in the form 'Relation' instead of 'RelationID', referencing the composite DBField. @param string $class @param string $component Name of the relation on the current object pointing to the remote object. @param string $type the join type - either 'has_many' or 'belongs_to' @param boolean $polymorphic Flag set to true if the remote join field is polymorphic. @return string @throws Exception
[ "Tries", "to", "find", "the", "database", "key", "on", "another", "object", "that", "is", "used", "to", "store", "a", "relationship", "to", "this", "class", ".", "If", "no", "join", "field", "can", "be", "found", "it", "defaults", "to", "ParentID", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L1048-L1115
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.checkManyManyFieldClass
protected function checkManyManyFieldClass($parentClass, $component, $joinClass, $specification, $key) { // Ensure value for this key exists if (empty($specification[$key])) { throw new InvalidArgumentException( "many_many relation {$parentClass}.{$component} has missing {$key} which " . "should be a has_one on class {$joinClass}" ); } // Check that the field exists on the given object $relation = $specification[$key]; $relationClass = $this->hasOneComponent($joinClass, $relation); if (empty($relationClass)) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} which is not a has_one" ); } // Check for polymorphic /** @internal Polymorphic many_many is experimental */ if ($relationClass === DataObject::class) { // Currently polymorphic 'from' is supported. if ($key === 'from') { return $relationClass; } // @todo support polymorphic 'to' throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a polymorphic field " . "{$joinClass}::{$relation} which is not supported" ); } // Validate the join class isn't also the name of a field or relation on either side // of the relation $field = $this->fieldSpec($relationClass, $joinClass); if ($field) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} class {$relationClass} " . " cannot have a db field of the same name of the join class {$joinClass}" ); } // Validate bad types on parent relation if ($key === 'from' && $relationClass !== $parentClass) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} of type {$relationClass}; {$parentClass} expected" ); } return $relationClass; }
php
protected function checkManyManyFieldClass($parentClass, $component, $joinClass, $specification, $key) { // Ensure value for this key exists if (empty($specification[$key])) { throw new InvalidArgumentException( "many_many relation {$parentClass}.{$component} has missing {$key} which " . "should be a has_one on class {$joinClass}" ); } // Check that the field exists on the given object $relation = $specification[$key]; $relationClass = $this->hasOneComponent($joinClass, $relation); if (empty($relationClass)) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} which is not a has_one" ); } // Check for polymorphic /** @internal Polymorphic many_many is experimental */ if ($relationClass === DataObject::class) { // Currently polymorphic 'from' is supported. if ($key === 'from') { return $relationClass; } // @todo support polymorphic 'to' throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a polymorphic field " . "{$joinClass}::{$relation} which is not supported" ); } // Validate the join class isn't also the name of a field or relation on either side // of the relation $field = $this->fieldSpec($relationClass, $joinClass); if ($field) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} class {$relationClass} " . " cannot have a db field of the same name of the join class {$joinClass}" ); } // Validate bad types on parent relation if ($key === 'from' && $relationClass !== $parentClass) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} of type {$relationClass}; {$parentClass} expected" ); } return $relationClass; }
[ "protected", "function", "checkManyManyFieldClass", "(", "$", "parentClass", ",", "$", "component", ",", "$", "joinClass", ",", "$", "specification", ",", "$", "key", ")", "{", "// Ensure value for this key exists", "if", "(", "empty", "(", "$", "specification", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"many_many relation {$parentClass}.{$component} has missing {$key} which \"", ".", "\"should be a has_one on class {$joinClass}\"", ")", ";", "}", "// Check that the field exists on the given object", "$", "relation", "=", "$", "specification", "[", "$", "key", "]", ";", "$", "relationClass", "=", "$", "this", "->", "hasOneComponent", "(", "$", "joinClass", ",", "$", "relation", ")", ";", "if", "(", "empty", "(", "$", "relationClass", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"many_many through relation {$parentClass}.{$component} {$key} references a field name \"", ".", "\"{$joinClass}::{$relation} which is not a has_one\"", ")", ";", "}", "// Check for polymorphic", "/** @internal Polymorphic many_many is experimental */", "if", "(", "$", "relationClass", "===", "DataObject", "::", "class", ")", "{", "// Currently polymorphic 'from' is supported.", "if", "(", "$", "key", "===", "'from'", ")", "{", "return", "$", "relationClass", ";", "}", "// @todo support polymorphic 'to'", "throw", "new", "InvalidArgumentException", "(", "\"many_many through relation {$parentClass}.{$component} {$key} references a polymorphic field \"", ".", "\"{$joinClass}::{$relation} which is not supported\"", ")", ";", "}", "// Validate the join class isn't also the name of a field or relation on either side", "// of the relation", "$", "field", "=", "$", "this", "->", "fieldSpec", "(", "$", "relationClass", ",", "$", "joinClass", ")", ";", "if", "(", "$", "field", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"many_many through relation {$parentClass}.{$component} {$key} class {$relationClass} \"", ".", "\" cannot have a db field of the same name of the join class {$joinClass}\"", ")", ";", "}", "// Validate bad types on parent relation", "if", "(", "$", "key", "===", "'from'", "&&", "$", "relationClass", "!==", "$", "parentClass", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"many_many through relation {$parentClass}.{$component} {$key} references a field name \"", ".", "\"{$joinClass}::{$relation} of type {$relationClass}; {$parentClass} expected\"", ")", ";", "}", "return", "$", "relationClass", ";", "}" ]
Validate the to or from field on a has_many mapping class @param string $parentClass Name of parent class @param string $component Name of many_many component @param string $joinClass Class for the joined table @param array $specification Complete many_many specification @param string $key Name of key to check ('from' or 'to') @return string Class that matches the given relation @throws InvalidArgumentException
[ "Validate", "the", "to", "or", "from", "field", "on", "a", "has_many", "mapping", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L1129-L1181
train
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
DataObjectSchema.checkRelationClass
protected function checkRelationClass($class, $component, $relationClass, $type) { if (!is_string($component) || is_numeric($component)) { throw new InvalidArgumentException( "{$class} has invalid {$type} relation name" ); } if (!is_string($relationClass)) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} is not a class name" ); } if (!class_exists($relationClass)) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} references class {$relationClass} which doesn't exist" ); } // Support polymorphic has_one if ($type === 'has_one') { $valid = is_a($relationClass, DataObject::class, true); } else { $valid = is_subclass_of($relationClass, DataObject::class, true); } if (!$valid) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} references class {$relationClass} " . " which is not a subclass of " . DataObject::class ); } }
php
protected function checkRelationClass($class, $component, $relationClass, $type) { if (!is_string($component) || is_numeric($component)) { throw new InvalidArgumentException( "{$class} has invalid {$type} relation name" ); } if (!is_string($relationClass)) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} is not a class name" ); } if (!class_exists($relationClass)) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} references class {$relationClass} which doesn't exist" ); } // Support polymorphic has_one if ($type === 'has_one') { $valid = is_a($relationClass, DataObject::class, true); } else { $valid = is_subclass_of($relationClass, DataObject::class, true); } if (!$valid) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} references class {$relationClass} " . " which is not a subclass of " . DataObject::class ); } }
[ "protected", "function", "checkRelationClass", "(", "$", "class", ",", "$", "component", ",", "$", "relationClass", ",", "$", "type", ")", "{", "if", "(", "!", "is_string", "(", "$", "component", ")", "||", "is_numeric", "(", "$", "component", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"{$class} has invalid {$type} relation name\"", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "relationClass", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"{$type} relation {$class}.{$component} is not a class name\"", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "relationClass", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"{$type} relation {$class}.{$component} references class {$relationClass} which doesn't exist\"", ")", ";", "}", "// Support polymorphic has_one", "if", "(", "$", "type", "===", "'has_one'", ")", "{", "$", "valid", "=", "is_a", "(", "$", "relationClass", ",", "DataObject", "::", "class", ",", "true", ")", ";", "}", "else", "{", "$", "valid", "=", "is_subclass_of", "(", "$", "relationClass", ",", "DataObject", "::", "class", ",", "true", ")", ";", "}", "if", "(", "!", "$", "valid", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"{$type} relation {$class}.{$component} references class {$relationClass} \"", ".", "\" which is not a subclass of \"", ".", "DataObject", "::", "class", ")", ";", "}", "}" ]
Validate a given class is valid for a relation @param string $class Parent class @param string $component Component name @param string $relationClass Candidate class to check @param string $type Relation type (e.g. has_one)
[ "Validate", "a", "given", "class", "is", "valid", "for", "a", "relation" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObjectSchema.php#L1215-L1244
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.construct
function construct($matchrule, $name, $arguments = null) { $res = parent::construct($matchrule, $name, $arguments); if (!isset($res['php'])) { $res['php'] = ''; } return $res; }
php
function construct($matchrule, $name, $arguments = null) { $res = parent::construct($matchrule, $name, $arguments); if (!isset($res['php'])) { $res['php'] = ''; } return $res; }
[ "function", "construct", "(", "$", "matchrule", ",", "$", "name", ",", "$", "arguments", "=", "null", ")", "{", "$", "res", "=", "parent", "::", "construct", "(", "$", "matchrule", ",", "$", "name", ",", "$", "arguments", ")", ";", "if", "(", "!", "isset", "(", "$", "res", "[", "'php'", "]", ")", ")", "{", "$", "res", "[", "'php'", "]", "=", "''", ";", "}", "return", "$", "res", ";", "}" ]
Override the function that constructs the result arrays to also prepare a 'php' item in the array
[ "Override", "the", "function", "that", "constructs", "the", "result", "arrays", "to", "also", "prepare", "a", "php", "item", "in", "the", "array" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L99-L106
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.setClosedBlocks
public function setClosedBlocks($closedBlocks) { $this->closedBlocks = array(); foreach ((array) $closedBlocks as $name => $callable) { $this->addClosedBlock($name, $callable); } }
php
public function setClosedBlocks($closedBlocks) { $this->closedBlocks = array(); foreach ((array) $closedBlocks as $name => $callable) { $this->addClosedBlock($name, $callable); } }
[ "public", "function", "setClosedBlocks", "(", "$", "closedBlocks", ")", "{", "$", "this", "->", "closedBlocks", "=", "array", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "closedBlocks", "as", "$", "name", "=>", "$", "callable", ")", "{", "$", "this", "->", "addClosedBlock", "(", "$", "name", ",", "$", "callable", ")", ";", "}", "}" ]
Set the closed blocks that the template parser should use This method will delete any existing closed blocks, please use addClosedBlock if you don't want to overwrite @param array $closedBlocks @throws InvalidArgumentException
[ "Set", "the", "closed", "blocks", "that", "the", "template", "parser", "should", "use" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L116-L122
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.setOpenBlocks
public function setOpenBlocks($openBlocks) { $this->openBlocks = array(); foreach ((array) $openBlocks as $name => $callable) { $this->addOpenBlock($name, $callable); } }
php
public function setOpenBlocks($openBlocks) { $this->openBlocks = array(); foreach ((array) $openBlocks as $name => $callable) { $this->addOpenBlock($name, $callable); } }
[ "public", "function", "setOpenBlocks", "(", "$", "openBlocks", ")", "{", "$", "this", "->", "openBlocks", "=", "array", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "openBlocks", "as", "$", "name", "=>", "$", "callable", ")", "{", "$", "this", "->", "addOpenBlock", "(", "$", "name", ",", "$", "callable", ")", ";", "}", "}" ]
Set the open blocks that the template parser should use This method will delete any existing open blocks, please use addOpenBlock if you don't want to overwrite @param array $openBlocks @throws InvalidArgumentException
[ "Set", "the", "open", "blocks", "that", "the", "template", "parser", "should", "use" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L132-L138
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.validateExtensionBlock
protected function validateExtensionBlock($name, $callable, $type) { if (!is_string($name)) { throw new InvalidArgumentException( sprintf( "Name argument for %s must be a string", $type ) ); } elseif (!is_callable($callable)) { throw new InvalidArgumentException( sprintf( "Callable %s argument named '%s' is not callable", $type, $name ) ); } }
php
protected function validateExtensionBlock($name, $callable, $type) { if (!is_string($name)) { throw new InvalidArgumentException( sprintf( "Name argument for %s must be a string", $type ) ); } elseif (!is_callable($callable)) { throw new InvalidArgumentException( sprintf( "Callable %s argument named '%s' is not callable", $type, $name ) ); } }
[ "protected", "function", "validateExtensionBlock", "(", "$", "name", ",", "$", "callable", ",", "$", "type", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"Name argument for %s must be a string\"", ",", "$", "type", ")", ")", ";", "}", "elseif", "(", "!", "is_callable", "(", "$", "callable", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"Callable %s argument named '%s' is not callable\"", ",", "$", "type", ",", "$", "name", ")", ")", ";", "}", "}" ]
Ensures that the arguments to addOpenBlock and addClosedBlock are valid @param $name @param $callable @param $type @throws InvalidArgumentException
[ "Ensures", "that", "the", "arguments", "to", "addOpenBlock", "and", "addClosedBlock", "are", "valid" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L171-L189
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.CallArguments_Argument
function CallArguments_Argument(&$res, $sub) { if (!empty($res['php'])) { $res['php'] .= ', '; } $res['php'] .= ($sub['ArgumentMode'] == 'default') ? $sub['string_php'] : str_replace('$$FINAL', 'XML_val', $sub['php']); }
php
function CallArguments_Argument(&$res, $sub) { if (!empty($res['php'])) { $res['php'] .= ', '; } $res['php'] .= ($sub['ArgumentMode'] == 'default') ? $sub['string_php'] : str_replace('$$FINAL', 'XML_val', $sub['php']); }
[ "function", "CallArguments_Argument", "(", "&", "$", "res", ",", "$", "sub", ")", "{", "if", "(", "!", "empty", "(", "$", "res", "[", "'php'", "]", ")", ")", "{", "$", "res", "[", "'php'", "]", ".=", "', '", ";", "}", "$", "res", "[", "'php'", "]", ".=", "(", "$", "sub", "[", "'ArgumentMode'", "]", "==", "'default'", ")", "?", "$", "sub", "[", "'string_php'", "]", ":", "str_replace", "(", "'$$FINAL'", ",", "'XML_val'", ",", "$", "sub", "[", "'php'", "]", ")", ";", "}" ]
Values are bare words in templates, but strings in PHP. We rely on PHP's type conversion to back-convert strings to numbers when needed.
[ "Values", "are", "bare", "words", "in", "templates", "but", "strings", "in", "PHP", ".", "We", "rely", "on", "PHP", "s", "type", "conversion", "to", "back", "-", "convert", "strings", "to", "numbers", "when", "needed", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L550-L558
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.ClosedBlock_Handle_Loop
function ClosedBlock_Handle_Loop(&$res) { if ($res['ArgumentCount'] > 1) { throw new SSTemplateParseException('Either no or too many arguments in control block. Must be one ' . 'argument only.', $this); } //loop without arguments loops on the current scope if ($res['ArgumentCount'] == 0) { $on = '$scope->obj(\'Up\', null)->obj(\'Foo\', null)'; } else { //loop in the normal way $arg = $res['Arguments'][0]; if ($arg['ArgumentMode'] == 'string') { throw new SSTemplateParseException('Control block cant take string as argument.', $this); } $on = str_replace( '$$FINAL', 'obj', ($arg['ArgumentMode'] == 'default') ? $arg['lookup_php'] : $arg['php'] ); } return $on . '; $scope->pushScope(); while (($key = $scope->next()) !== false) {' . PHP_EOL . $res['Template']['php'] . PHP_EOL . '}; $scope->popScope(); '; }
php
function ClosedBlock_Handle_Loop(&$res) { if ($res['ArgumentCount'] > 1) { throw new SSTemplateParseException('Either no or too many arguments in control block. Must be one ' . 'argument only.', $this); } //loop without arguments loops on the current scope if ($res['ArgumentCount'] == 0) { $on = '$scope->obj(\'Up\', null)->obj(\'Foo\', null)'; } else { //loop in the normal way $arg = $res['Arguments'][0]; if ($arg['ArgumentMode'] == 'string') { throw new SSTemplateParseException('Control block cant take string as argument.', $this); } $on = str_replace( '$$FINAL', 'obj', ($arg['ArgumentMode'] == 'default') ? $arg['lookup_php'] : $arg['php'] ); } return $on . '; $scope->pushScope(); while (($key = $scope->next()) !== false) {' . PHP_EOL . $res['Template']['php'] . PHP_EOL . '}; $scope->popScope(); '; }
[ "function", "ClosedBlock_Handle_Loop", "(", "&", "$", "res", ")", "{", "if", "(", "$", "res", "[", "'ArgumentCount'", "]", ">", "1", ")", "{", "throw", "new", "SSTemplateParseException", "(", "'Either no or too many arguments in control block. Must be one '", ".", "'argument only.'", ",", "$", "this", ")", ";", "}", "//loop without arguments loops on the current scope", "if", "(", "$", "res", "[", "'ArgumentCount'", "]", "==", "0", ")", "{", "$", "on", "=", "'$scope->obj(\\'Up\\', null)->obj(\\'Foo\\', null)'", ";", "}", "else", "{", "//loop in the normal way", "$", "arg", "=", "$", "res", "[", "'Arguments'", "]", "[", "0", "]", ";", "if", "(", "$", "arg", "[", "'ArgumentMode'", "]", "==", "'string'", ")", "{", "throw", "new", "SSTemplateParseException", "(", "'Control block cant take string as argument.'", ",", "$", "this", ")", ";", "}", "$", "on", "=", "str_replace", "(", "'$$FINAL'", ",", "'obj'", ",", "(", "$", "arg", "[", "'ArgumentMode'", "]", "==", "'default'", ")", "?", "$", "arg", "[", "'lookup_php'", "]", ":", "$", "arg", "[", "'php'", "]", ")", ";", "}", "return", "$", "on", ".", "'; $scope->pushScope(); while (($key = $scope->next()) !== false) {'", ".", "PHP_EOL", ".", "$", "res", "[", "'Template'", "]", "[", "'php'", "]", ".", "PHP_EOL", ".", "'}; $scope->popScope(); '", ";", "}" ]
This is an example of a block handler function. This one handles the loop tag.
[ "This", "is", "an", "example", "of", "a", "block", "handler", "function", ".", "This", "one", "handles", "the", "loop", "tag", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L3862-L3888
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.ClosedBlock_Handle_With
function ClosedBlock_Handle_With(&$res) { if ($res['ArgumentCount'] != 1) { throw new SSTemplateParseException('Either no or too many arguments in with block. Must be one ' . 'argument only.', $this); } $arg = $res['Arguments'][0]; if ($arg['ArgumentMode'] == 'string') { throw new SSTemplateParseException('Control block cant take string as argument.', $this); } $on = str_replace('$$FINAL', 'obj', ($arg['ArgumentMode'] == 'default') ? $arg['lookup_php'] : $arg['php']); return $on . '; $scope->pushScope();' . PHP_EOL . $res['Template']['php'] . PHP_EOL . '; $scope->popScope(); '; }
php
function ClosedBlock_Handle_With(&$res) { if ($res['ArgumentCount'] != 1) { throw new SSTemplateParseException('Either no or too many arguments in with block. Must be one ' . 'argument only.', $this); } $arg = $res['Arguments'][0]; if ($arg['ArgumentMode'] == 'string') { throw new SSTemplateParseException('Control block cant take string as argument.', $this); } $on = str_replace('$$FINAL', 'obj', ($arg['ArgumentMode'] == 'default') ? $arg['lookup_php'] : $arg['php']); return $on . '; $scope->pushScope();' . PHP_EOL . $res['Template']['php'] . PHP_EOL . '; $scope->popScope(); '; }
[ "function", "ClosedBlock_Handle_With", "(", "&", "$", "res", ")", "{", "if", "(", "$", "res", "[", "'ArgumentCount'", "]", "!=", "1", ")", "{", "throw", "new", "SSTemplateParseException", "(", "'Either no or too many arguments in with block. Must be one '", ".", "'argument only.'", ",", "$", "this", ")", ";", "}", "$", "arg", "=", "$", "res", "[", "'Arguments'", "]", "[", "0", "]", ";", "if", "(", "$", "arg", "[", "'ArgumentMode'", "]", "==", "'string'", ")", "{", "throw", "new", "SSTemplateParseException", "(", "'Control block cant take string as argument.'", ",", "$", "this", ")", ";", "}", "$", "on", "=", "str_replace", "(", "'$$FINAL'", ",", "'obj'", ",", "(", "$", "arg", "[", "'ArgumentMode'", "]", "==", "'default'", ")", "?", "$", "arg", "[", "'lookup_php'", "]", ":", "$", "arg", "[", "'php'", "]", ")", ";", "return", "$", "on", ".", "'; $scope->pushScope();'", ".", "PHP_EOL", ".", "$", "res", "[", "'Template'", "]", "[", "'php'", "]", ".", "PHP_EOL", ".", "'; $scope->popScope(); '", ";", "}" ]
The closed block handler for with blocks
[ "The", "closed", "block", "handler", "for", "with", "blocks" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L3893-L3910
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.Text__finalise
function Text__finalise(&$res) { $text = $res['text']; // Unescape any escaped characters in the text, then put back escapes for any single quotes and backslashes $text = stripslashes($text); $text = addcslashes($text, '\'\\'); // TODO: This is pretty ugly & gets applied on all files not just html. I wonder if we can make this // non-dynamically calculated $code = <<<'EOC' (\SilverStripe\View\SSViewer::getRewriteHashLinksDefault() ? \SilverStripe\Core\Convert::raw2att( preg_replace("/^(\\/)+/", "/", $_SERVER['REQUEST_URI'] ) ) : "") EOC; // Because preg_replace replacement requires escaped slashes, addcslashes here $text = preg_replace( '/(<a[^>]+href *= *)"#/i', '\\1"\' . ' . addcslashes($code, '\\') . ' . \'#', $text ); $res['php'] .= '$val .= \'' . $text . '\';' . PHP_EOL; }
php
function Text__finalise(&$res) { $text = $res['text']; // Unescape any escaped characters in the text, then put back escapes for any single quotes and backslashes $text = stripslashes($text); $text = addcslashes($text, '\'\\'); // TODO: This is pretty ugly & gets applied on all files not just html. I wonder if we can make this // non-dynamically calculated $code = <<<'EOC' (\SilverStripe\View\SSViewer::getRewriteHashLinksDefault() ? \SilverStripe\Core\Convert::raw2att( preg_replace("/^(\\/)+/", "/", $_SERVER['REQUEST_URI'] ) ) : "") EOC; // Because preg_replace replacement requires escaped slashes, addcslashes here $text = preg_replace( '/(<a[^>]+href *= *)"#/i', '\\1"\' . ' . addcslashes($code, '\\') . ' . \'#', $text ); $res['php'] .= '$val .= \'' . $text . '\';' . PHP_EOL; }
[ "function", "Text__finalise", "(", "&", "$", "res", ")", "{", "$", "text", "=", "$", "res", "[", "'text'", "]", ";", "// Unescape any escaped characters in the text, then put back escapes for any single quotes and backslashes", "$", "text", "=", "stripslashes", "(", "$", "text", ")", ";", "$", "text", "=", "addcslashes", "(", "$", "text", ",", "'\\'\\\\'", ")", ";", "// TODO: This is pretty ugly & gets applied on all files not just html. I wonder if we can make this", "// non-dynamically calculated", "$", "code", "=", " <<<'EOC'\n(\\SilverStripe\\View\\SSViewer::getRewriteHashLinksDefault()\n ? \\SilverStripe\\Core\\Convert::raw2att( preg_replace(\"/^(\\\\/)+/\", \"/\", $_SERVER['REQUEST_URI'] ) )\n : \"\")\nEOC", ";", "// Because preg_replace replacement requires escaped slashes, addcslashes here", "$", "text", "=", "preg_replace", "(", "'/(<a[^>]+href *= *)\"#/i'", ",", "'\\\\1\"\\' . '", ".", "addcslashes", "(", "$", "code", ",", "'\\\\'", ")", ".", "' . \\'#'", ",", "$", "text", ")", ";", "$", "res", "[", "'php'", "]", ".=", "'$val .= \\''", ".", "$", "text", ".", "'\\';'", ".", "PHP_EOL", ";", "}" ]
We convert text
[ "We", "convert", "text" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L4826-L4849
train
silverstripe/silverstripe-framework
src/View/SSTemplateParser.php
SSTemplateParser.compileString
public function compileString($string, $templateName = "", $includeDebuggingComments = false, $topTemplate = true) { if (!trim($string)) { $code = ''; } else { parent::__construct($string); $this->includeDebuggingComments = $includeDebuggingComments; // Ignore UTF8 BOM at begining of string. TODO: Confirm this is needed, make sure SSViewer handles UTF // (and other encodings) properly if (substr($string, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) { $this->pos = 3; } // Match the source against the parser if ($topTemplate) { $result = $this->match_TopTemplate(); } else { $result = $this->match_Template(); } if (!$result) { throw new SSTemplateParseException('Unexpected problem parsing template', $this); } // Get the result $code = $result['php']; } // Include top level debugging comments if desired if ($includeDebuggingComments && $templateName && stripos($code, "<?xml") === false) { $code = $this->includeDebuggingComments($code, $templateName); } return $code; }
php
public function compileString($string, $templateName = "", $includeDebuggingComments = false, $topTemplate = true) { if (!trim($string)) { $code = ''; } else { parent::__construct($string); $this->includeDebuggingComments = $includeDebuggingComments; // Ignore UTF8 BOM at begining of string. TODO: Confirm this is needed, make sure SSViewer handles UTF // (and other encodings) properly if (substr($string, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) { $this->pos = 3; } // Match the source against the parser if ($topTemplate) { $result = $this->match_TopTemplate(); } else { $result = $this->match_Template(); } if (!$result) { throw new SSTemplateParseException('Unexpected problem parsing template', $this); } // Get the result $code = $result['php']; } // Include top level debugging comments if desired if ($includeDebuggingComments && $templateName && stripos($code, "<?xml") === false) { $code = $this->includeDebuggingComments($code, $templateName); } return $code; }
[ "public", "function", "compileString", "(", "$", "string", ",", "$", "templateName", "=", "\"\"", ",", "$", "includeDebuggingComments", "=", "false", ",", "$", "topTemplate", "=", "true", ")", "{", "if", "(", "!", "trim", "(", "$", "string", ")", ")", "{", "$", "code", "=", "''", ";", "}", "else", "{", "parent", "::", "__construct", "(", "$", "string", ")", ";", "$", "this", "->", "includeDebuggingComments", "=", "$", "includeDebuggingComments", ";", "// Ignore UTF8 BOM at begining of string. TODO: Confirm this is needed, make sure SSViewer handles UTF", "// (and other encodings) properly", "if", "(", "substr", "(", "$", "string", ",", "0", ",", "3", ")", "==", "pack", "(", "\"CCC\"", ",", "0xef", ",", "0xbb", ",", "0xbf", ")", ")", "{", "$", "this", "->", "pos", "=", "3", ";", "}", "// Match the source against the parser", "if", "(", "$", "topTemplate", ")", "{", "$", "result", "=", "$", "this", "->", "match_TopTemplate", "(", ")", ";", "}", "else", "{", "$", "result", "=", "$", "this", "->", "match_Template", "(", ")", ";", "}", "if", "(", "!", "$", "result", ")", "{", "throw", "new", "SSTemplateParseException", "(", "'Unexpected problem parsing template'", ",", "$", "this", ")", ";", "}", "// Get the result", "$", "code", "=", "$", "result", "[", "'php'", "]", ";", "}", "// Include top level debugging comments if desired", "if", "(", "$", "includeDebuggingComments", "&&", "$", "templateName", "&&", "stripos", "(", "$", "code", ",", "\"<?xml\"", ")", "===", "false", ")", "{", "$", "code", "=", "$", "this", "->", "includeDebuggingComments", "(", "$", "code", ",", "$", "templateName", ")", ";", "}", "return", "$", "code", ";", "}" ]
Compiles some passed template source code into the php code that will execute as per the template source. @throws SSTemplateParseException @param string $string The source of the template @param string $templateName The name of the template, normally the filename the template source was loaded from @param bool $includeDebuggingComments True is debugging comments should be included in the output @param bool $topTemplate True if this is a top template, false if it's just a template @return mixed|string The php that, when executed (via include or exec) will behave as per the template source
[ "Compiles", "some", "passed", "template", "source", "code", "into", "the", "php", "code", "that", "will", "execute", "as", "per", "the", "template", "source", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSTemplateParser.php#L4865-L4900
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.sessionEnvironment
protected function sessionEnvironment() { // Check isDev in querystring if (isset($_GET['isDev'])) { if (isset($_SESSION)) { unset($_SESSION['isTest']); // In case we are changing from test mode $_SESSION['isDev'] = $_GET['isDev']; } return self::DEV; } // Check isTest in querystring if (isset($_GET['isTest'])) { if (isset($_SESSION)) { unset($_SESSION['isDev']); // In case we are changing from dev mode $_SESSION['isTest'] = $_GET['isTest']; } return self::TEST; } // Check session if (!empty($_SESSION['isDev'])) { return self::DEV; } if (!empty($_SESSION['isTest'])) { return self::TEST; } // no session environment return null; }
php
protected function sessionEnvironment() { // Check isDev in querystring if (isset($_GET['isDev'])) { if (isset($_SESSION)) { unset($_SESSION['isTest']); // In case we are changing from test mode $_SESSION['isDev'] = $_GET['isDev']; } return self::DEV; } // Check isTest in querystring if (isset($_GET['isTest'])) { if (isset($_SESSION)) { unset($_SESSION['isDev']); // In case we are changing from dev mode $_SESSION['isTest'] = $_GET['isTest']; } return self::TEST; } // Check session if (!empty($_SESSION['isDev'])) { return self::DEV; } if (!empty($_SESSION['isTest'])) { return self::TEST; } // no session environment return null; }
[ "protected", "function", "sessionEnvironment", "(", ")", "{", "// Check isDev in querystring", "if", "(", "isset", "(", "$", "_GET", "[", "'isDev'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", ")", "{", "unset", "(", "$", "_SESSION", "[", "'isTest'", "]", ")", ";", "// In case we are changing from test mode", "$", "_SESSION", "[", "'isDev'", "]", "=", "$", "_GET", "[", "'isDev'", "]", ";", "}", "return", "self", "::", "DEV", ";", "}", "// Check isTest in querystring", "if", "(", "isset", "(", "$", "_GET", "[", "'isTest'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", ")", "{", "unset", "(", "$", "_SESSION", "[", "'isDev'", "]", ")", ";", "// In case we are changing from dev mode", "$", "_SESSION", "[", "'isTest'", "]", "=", "$", "_GET", "[", "'isTest'", "]", ";", "}", "return", "self", "::", "TEST", ";", "}", "// Check session", "if", "(", "!", "empty", "(", "$", "_SESSION", "[", "'isDev'", "]", ")", ")", "{", "return", "self", "::", "DEV", ";", "}", "if", "(", "!", "empty", "(", "$", "_SESSION", "[", "'isTest'", "]", ")", ")", "{", "return", "self", "::", "TEST", ";", "}", "// no session environment", "return", "null", ";", "}" ]
Check or update any temporary environment specified in the session. @return null|string
[ "Check", "or", "update", "any", "temporary", "environment", "specified", "in", "the", "session", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L155-L185
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.bootConfigs
protected function bootConfigs() { global $project; $projectBefore = $project; $config = ModuleManifest::config(); // After loading all other app manifests, include _config.php files $this->getModuleLoader()->getManifest()->activateConfig(); if ($project && $project !== $projectBefore) { Deprecation::notice('5.0', '$project global is deprecated'); $config->set('project', $project); } }
php
protected function bootConfigs() { global $project; $projectBefore = $project; $config = ModuleManifest::config(); // After loading all other app manifests, include _config.php files $this->getModuleLoader()->getManifest()->activateConfig(); if ($project && $project !== $projectBefore) { Deprecation::notice('5.0', '$project global is deprecated'); $config->set('project', $project); } }
[ "protected", "function", "bootConfigs", "(", ")", "{", "global", "$", "project", ";", "$", "projectBefore", "=", "$", "project", ";", "$", "config", "=", "ModuleManifest", "::", "config", "(", ")", ";", "// After loading all other app manifests, include _config.php files", "$", "this", "->", "getModuleLoader", "(", ")", "->", "getManifest", "(", ")", "->", "activateConfig", "(", ")", ";", "if", "(", "$", "project", "&&", "$", "project", "!==", "$", "projectBefore", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'$project global is deprecated'", ")", ";", "$", "config", "->", "set", "(", "'project'", ",", "$", "project", ")", ";", "}", "}" ]
Include all _config.php files
[ "Include", "all", "_config", ".", "php", "files" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L201-L212
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.bootDatabaseEnvVars
protected function bootDatabaseEnvVars() { // Set default database config $databaseConfig = $this->getDatabaseConfig(); $databaseConfig['database'] = $this->getDatabaseName(); DB::setConfig($databaseConfig); }
php
protected function bootDatabaseEnvVars() { // Set default database config $databaseConfig = $this->getDatabaseConfig(); $databaseConfig['database'] = $this->getDatabaseName(); DB::setConfig($databaseConfig); }
[ "protected", "function", "bootDatabaseEnvVars", "(", ")", "{", "// Set default database config", "$", "databaseConfig", "=", "$", "this", "->", "getDatabaseConfig", "(", ")", ";", "$", "databaseConfig", "[", "'database'", "]", "=", "$", "this", "->", "getDatabaseName", "(", ")", ";", "DB", "::", "setConfig", "(", "$", "databaseConfig", ")", ";", "}" ]
Load default database configuration from environment variable
[ "Load", "default", "database", "configuration", "from", "environment", "variable" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L249-L255
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.validateDatabase
protected function validateDatabase() { $databaseConfig = DB::getConfig(); // Gracefully fail if no DB is configured if (empty($databaseConfig['database'])) { $this->detectLegacyEnvironment(); $this->redirectToInstaller(); } }
php
protected function validateDatabase() { $databaseConfig = DB::getConfig(); // Gracefully fail if no DB is configured if (empty($databaseConfig['database'])) { $this->detectLegacyEnvironment(); $this->redirectToInstaller(); } }
[ "protected", "function", "validateDatabase", "(", ")", "{", "$", "databaseConfig", "=", "DB", "::", "getConfig", "(", ")", ";", "// Gracefully fail if no DB is configured", "if", "(", "empty", "(", "$", "databaseConfig", "[", "'database'", "]", ")", ")", "{", "$", "this", "->", "detectLegacyEnvironment", "(", ")", ";", "$", "this", "->", "redirectToInstaller", "(", ")", ";", "}", "}" ]
Check that the database configuration is valid, throwing an HTTPResponse_Exception if it's not @throws HTTPResponse_Exception
[ "Check", "that", "the", "database", "configuration", "is", "valid", "throwing", "an", "HTTPResponse_Exception", "if", "it", "s", "not" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L262-L270
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.detectLegacyEnvironment
protected function detectLegacyEnvironment() { // Is there an _ss_environment.php file? if (!file_exists($this->basePath . '/_ss_environment.php') && !file_exists(dirname($this->basePath) . '/_ss_environment.php') ) { return; } // Build error response $dv = new DebugView(); $body = $dv->renderHeader() . $dv->renderInfo( "Configuration Error", Director::absoluteBaseURL() ) . $dv->renderParagraph( 'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>' . 'See the <a href="https://docs.silverstripe.org/en/4/getting_started/environment_management/">' . 'Environment Management</a> docs for more information.' ) . $dv->renderFooter(); // Raise error $response = new HTTPResponse($body, 500); throw new HTTPResponse_Exception($response); }
php
protected function detectLegacyEnvironment() { // Is there an _ss_environment.php file? if (!file_exists($this->basePath . '/_ss_environment.php') && !file_exists(dirname($this->basePath) . '/_ss_environment.php') ) { return; } // Build error response $dv = new DebugView(); $body = $dv->renderHeader() . $dv->renderInfo( "Configuration Error", Director::absoluteBaseURL() ) . $dv->renderParagraph( 'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>' . 'See the <a href="https://docs.silverstripe.org/en/4/getting_started/environment_management/">' . 'Environment Management</a> docs for more information.' ) . $dv->renderFooter(); // Raise error $response = new HTTPResponse($body, 500); throw new HTTPResponse_Exception($response); }
[ "protected", "function", "detectLegacyEnvironment", "(", ")", "{", "// Is there an _ss_environment.php file?", "if", "(", "!", "file_exists", "(", "$", "this", "->", "basePath", ".", "'/_ss_environment.php'", ")", "&&", "!", "file_exists", "(", "dirname", "(", "$", "this", "->", "basePath", ")", ".", "'/_ss_environment.php'", ")", ")", "{", "return", ";", "}", "// Build error response", "$", "dv", "=", "new", "DebugView", "(", ")", ";", "$", "body", "=", "$", "dv", "->", "renderHeader", "(", ")", ".", "$", "dv", "->", "renderInfo", "(", "\"Configuration Error\"", ",", "Director", "::", "absoluteBaseURL", "(", ")", ")", ".", "$", "dv", "->", "renderParagraph", "(", "'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>'", ".", "'See the <a href=\"https://docs.silverstripe.org/en/4/getting_started/environment_management/\">'", ".", "'Environment Management</a> docs for more information.'", ")", ".", "$", "dv", "->", "renderFooter", "(", ")", ";", "// Raise error", "$", "response", "=", "new", "HTTPResponse", "(", "$", "body", ",", "500", ")", ";", "throw", "new", "HTTPResponse_Exception", "(", "$", "response", ")", ";", "}" ]
Check if there's a legacy _ss_environment.php file @throws HTTPResponse_Exception
[ "Check", "if", "there", "s", "a", "legacy", "_ss_environment", ".", "php", "file" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L277-L304
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.redirectToInstaller
protected function redirectToInstaller() { // Error if installer not available if (!file_exists(Director::publicFolder() . '/install.php')) { throw new HTTPResponse_Exception( 'SilverStripe Framework requires database configuration defined via .env', 500 ); } // Redirect to installer $response = new HTTPResponse(); $response->redirect(Director::absoluteURL('install.php')); throw new HTTPResponse_Exception($response); }
php
protected function redirectToInstaller() { // Error if installer not available if (!file_exists(Director::publicFolder() . '/install.php')) { throw new HTTPResponse_Exception( 'SilverStripe Framework requires database configuration defined via .env', 500 ); } // Redirect to installer $response = new HTTPResponse(); $response->redirect(Director::absoluteURL('install.php')); throw new HTTPResponse_Exception($response); }
[ "protected", "function", "redirectToInstaller", "(", ")", "{", "// Error if installer not available", "if", "(", "!", "file_exists", "(", "Director", "::", "publicFolder", "(", ")", ".", "'/install.php'", ")", ")", "{", "throw", "new", "HTTPResponse_Exception", "(", "'SilverStripe Framework requires database configuration defined via .env'", ",", "500", ")", ";", "}", "// Redirect to installer", "$", "response", "=", "new", "HTTPResponse", "(", ")", ";", "$", "response", "->", "redirect", "(", "Director", "::", "absoluteURL", "(", "'install.php'", ")", ")", ";", "throw", "new", "HTTPResponse_Exception", "(", "$", "response", ")", ";", "}" ]
If missing configuration, redirect to install.php
[ "If", "missing", "configuration", "redirect", "to", "install", ".", "php" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L309-L323
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.getDatabaseConfig
protected function getDatabaseConfig() { /** @skipUpgrade */ $databaseConfig = [ "type" => Environment::getEnv('SS_DATABASE_CLASS') ?: 'MySQLDatabase', "server" => Environment::getEnv('SS_DATABASE_SERVER') ?: 'localhost', "username" => Environment::getEnv('SS_DATABASE_USERNAME') ?: null, "password" => Environment::getEnv('SS_DATABASE_PASSWORD') ?: null, ]; // Set the port if called for $dbPort = Environment::getEnv('SS_DATABASE_PORT'); if ($dbPort) { $databaseConfig['port'] = $dbPort; } // Set the timezone if called for $dbTZ = Environment::getEnv('SS_DATABASE_TIMEZONE'); if ($dbTZ) { $databaseConfig['timezone'] = $dbTZ; } // For schema enabled drivers: $dbSchema = Environment::getEnv('SS_DATABASE_SCHEMA'); if ($dbSchema) { $databaseConfig["schema"] = $dbSchema; } // For SQlite3 memory databases (mainly for testing purposes) $dbMemory = Environment::getEnv('SS_DATABASE_MEMORY'); if ($dbMemory) { $databaseConfig["memory"] = $dbMemory; } // Allow database adapters to handle their own configuration DatabaseAdapterRegistry::autoconfigure($databaseConfig); return $databaseConfig; }
php
protected function getDatabaseConfig() { /** @skipUpgrade */ $databaseConfig = [ "type" => Environment::getEnv('SS_DATABASE_CLASS') ?: 'MySQLDatabase', "server" => Environment::getEnv('SS_DATABASE_SERVER') ?: 'localhost', "username" => Environment::getEnv('SS_DATABASE_USERNAME') ?: null, "password" => Environment::getEnv('SS_DATABASE_PASSWORD') ?: null, ]; // Set the port if called for $dbPort = Environment::getEnv('SS_DATABASE_PORT'); if ($dbPort) { $databaseConfig['port'] = $dbPort; } // Set the timezone if called for $dbTZ = Environment::getEnv('SS_DATABASE_TIMEZONE'); if ($dbTZ) { $databaseConfig['timezone'] = $dbTZ; } // For schema enabled drivers: $dbSchema = Environment::getEnv('SS_DATABASE_SCHEMA'); if ($dbSchema) { $databaseConfig["schema"] = $dbSchema; } // For SQlite3 memory databases (mainly for testing purposes) $dbMemory = Environment::getEnv('SS_DATABASE_MEMORY'); if ($dbMemory) { $databaseConfig["memory"] = $dbMemory; } // Allow database adapters to handle their own configuration DatabaseAdapterRegistry::autoconfigure($databaseConfig); return $databaseConfig; }
[ "protected", "function", "getDatabaseConfig", "(", ")", "{", "/** @skipUpgrade */", "$", "databaseConfig", "=", "[", "\"type\"", "=>", "Environment", "::", "getEnv", "(", "'SS_DATABASE_CLASS'", ")", "?", ":", "'MySQLDatabase'", ",", "\"server\"", "=>", "Environment", "::", "getEnv", "(", "'SS_DATABASE_SERVER'", ")", "?", ":", "'localhost'", ",", "\"username\"", "=>", "Environment", "::", "getEnv", "(", "'SS_DATABASE_USERNAME'", ")", "?", ":", "null", ",", "\"password\"", "=>", "Environment", "::", "getEnv", "(", "'SS_DATABASE_PASSWORD'", ")", "?", ":", "null", ",", "]", ";", "// Set the port if called for", "$", "dbPort", "=", "Environment", "::", "getEnv", "(", "'SS_DATABASE_PORT'", ")", ";", "if", "(", "$", "dbPort", ")", "{", "$", "databaseConfig", "[", "'port'", "]", "=", "$", "dbPort", ";", "}", "// Set the timezone if called for", "$", "dbTZ", "=", "Environment", "::", "getEnv", "(", "'SS_DATABASE_TIMEZONE'", ")", ";", "if", "(", "$", "dbTZ", ")", "{", "$", "databaseConfig", "[", "'timezone'", "]", "=", "$", "dbTZ", ";", "}", "// For schema enabled drivers:", "$", "dbSchema", "=", "Environment", "::", "getEnv", "(", "'SS_DATABASE_SCHEMA'", ")", ";", "if", "(", "$", "dbSchema", ")", "{", "$", "databaseConfig", "[", "\"schema\"", "]", "=", "$", "dbSchema", ";", "}", "// For SQlite3 memory databases (mainly for testing purposes)", "$", "dbMemory", "=", "Environment", "::", "getEnv", "(", "'SS_DATABASE_MEMORY'", ")", ";", "if", "(", "$", "dbMemory", ")", "{", "$", "databaseConfig", "[", "\"memory\"", "]", "=", "$", "dbMemory", ";", "}", "// Allow database adapters to handle their own configuration", "DatabaseAdapterRegistry", "::", "autoconfigure", "(", "$", "databaseConfig", ")", ";", "return", "$", "databaseConfig", ";", "}" ]
Load database config from environment @return array
[ "Load", "database", "config", "from", "environment" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L330-L367
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.getDatabaseName
protected function getDatabaseName() { // Check globals global $database; if (!empty($database)) { return $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix(); } global $databaseConfig; if (!empty($databaseConfig['database'])) { return $databaseConfig['database']; // Note: Already includes prefix } // Check environment $database = Environment::getEnv('SS_DATABASE_NAME'); if ($database) { return $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix(); } // Auto-detect name $chooseName = Environment::getEnv('SS_DATABASE_CHOOSE_NAME'); if ($chooseName) { // Find directory to build name from $loopCount = (int)$chooseName; $databaseDir = $this->basePath; for ($i = 0; $i < $loopCount-1; $i++) { $databaseDir = dirname($databaseDir); } // Build name $database = str_replace('.', '', basename($databaseDir)); $prefix = $this->getDatabasePrefix(); if ($prefix) { $prefix = 'SS_'; } else { // If no prefix, hard-code prefix into database global $prefix = ''; $database = 'SS_' . $database; } return $prefix . $database; } // no DB name (may be optional for some connectors) return null; }
php
protected function getDatabaseName() { // Check globals global $database; if (!empty($database)) { return $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix(); } global $databaseConfig; if (!empty($databaseConfig['database'])) { return $databaseConfig['database']; // Note: Already includes prefix } // Check environment $database = Environment::getEnv('SS_DATABASE_NAME'); if ($database) { return $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix(); } // Auto-detect name $chooseName = Environment::getEnv('SS_DATABASE_CHOOSE_NAME'); if ($chooseName) { // Find directory to build name from $loopCount = (int)$chooseName; $databaseDir = $this->basePath; for ($i = 0; $i < $loopCount-1; $i++) { $databaseDir = dirname($databaseDir); } // Build name $database = str_replace('.', '', basename($databaseDir)); $prefix = $this->getDatabasePrefix(); if ($prefix) { $prefix = 'SS_'; } else { // If no prefix, hard-code prefix into database global $prefix = ''; $database = 'SS_' . $database; } return $prefix . $database; } // no DB name (may be optional for some connectors) return null; }
[ "protected", "function", "getDatabaseName", "(", ")", "{", "// Check globals", "global", "$", "database", ";", "if", "(", "!", "empty", "(", "$", "database", ")", ")", "{", "return", "$", "this", "->", "getDatabasePrefix", "(", ")", ".", "$", "database", ".", "$", "this", "->", "getDatabaseSuffix", "(", ")", ";", "}", "global", "$", "databaseConfig", ";", "if", "(", "!", "empty", "(", "$", "databaseConfig", "[", "'database'", "]", ")", ")", "{", "return", "$", "databaseConfig", "[", "'database'", "]", ";", "// Note: Already includes prefix", "}", "// Check environment", "$", "database", "=", "Environment", "::", "getEnv", "(", "'SS_DATABASE_NAME'", ")", ";", "if", "(", "$", "database", ")", "{", "return", "$", "this", "->", "getDatabasePrefix", "(", ")", ".", "$", "database", ".", "$", "this", "->", "getDatabaseSuffix", "(", ")", ";", "}", "// Auto-detect name", "$", "chooseName", "=", "Environment", "::", "getEnv", "(", "'SS_DATABASE_CHOOSE_NAME'", ")", ";", "if", "(", "$", "chooseName", ")", "{", "// Find directory to build name from", "$", "loopCount", "=", "(", "int", ")", "$", "chooseName", ";", "$", "databaseDir", "=", "$", "this", "->", "basePath", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "loopCount", "-", "1", ";", "$", "i", "++", ")", "{", "$", "databaseDir", "=", "dirname", "(", "$", "databaseDir", ")", ";", "}", "// Build name", "$", "database", "=", "str_replace", "(", "'.'", ",", "''", ",", "basename", "(", "$", "databaseDir", ")", ")", ";", "$", "prefix", "=", "$", "this", "->", "getDatabasePrefix", "(", ")", ";", "if", "(", "$", "prefix", ")", "{", "$", "prefix", "=", "'SS_'", ";", "}", "else", "{", "// If no prefix, hard-code prefix into database global", "$", "prefix", "=", "''", ";", "$", "database", "=", "'SS_'", ".", "$", "database", ";", "}", "return", "$", "prefix", ".", "$", "database", ";", "}", "// no DB name (may be optional for some connectors)", "return", "null", ";", "}" ]
Get name of database @return string
[ "Get", "name", "of", "database" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L390-L440
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.bootPHP
protected function bootPHP() { if ($this->getEnvironment() === self::LIVE) { // limited to fatal errors and warnings in live mode error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE)); } else { // Report all errors in dev / test mode error_reporting(E_ALL | E_STRICT); } /** * Ensure we have enough memory */ Environment::increaseMemoryLimitTo('64M'); // Ensure we don't run into xdebug's fairly conservative infinite recursion protection limit if (function_exists('xdebug_enable')) { $current = ini_get('xdebug.max_nesting_level'); if ((int)$current < 200) { ini_set('xdebug.max_nesting_level', 200); } } /** * Set default encoding */ mb_http_output('UTF-8'); mb_internal_encoding('UTF-8'); mb_regex_encoding('UTF-8'); /** * Enable better garbage collection */ gc_enable(); }
php
protected function bootPHP() { if ($this->getEnvironment() === self::LIVE) { // limited to fatal errors and warnings in live mode error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE)); } else { // Report all errors in dev / test mode error_reporting(E_ALL | E_STRICT); } /** * Ensure we have enough memory */ Environment::increaseMemoryLimitTo('64M'); // Ensure we don't run into xdebug's fairly conservative infinite recursion protection limit if (function_exists('xdebug_enable')) { $current = ini_get('xdebug.max_nesting_level'); if ((int)$current < 200) { ini_set('xdebug.max_nesting_level', 200); } } /** * Set default encoding */ mb_http_output('UTF-8'); mb_internal_encoding('UTF-8'); mb_regex_encoding('UTF-8'); /** * Enable better garbage collection */ gc_enable(); }
[ "protected", "function", "bootPHP", "(", ")", "{", "if", "(", "$", "this", "->", "getEnvironment", "(", ")", "===", "self", "::", "LIVE", ")", "{", "// limited to fatal errors and warnings in live mode", "error_reporting", "(", "E_ALL", "&", "~", "(", "E_DEPRECATED", "|", "E_STRICT", "|", "E_NOTICE", ")", ")", ";", "}", "else", "{", "// Report all errors in dev / test mode", "error_reporting", "(", "E_ALL", "|", "E_STRICT", ")", ";", "}", "/**\n * Ensure we have enough memory\n */", "Environment", "::", "increaseMemoryLimitTo", "(", "'64M'", ")", ";", "// Ensure we don't run into xdebug's fairly conservative infinite recursion protection limit", "if", "(", "function_exists", "(", "'xdebug_enable'", ")", ")", "{", "$", "current", "=", "ini_get", "(", "'xdebug.max_nesting_level'", ")", ";", "if", "(", "(", "int", ")", "$", "current", "<", "200", ")", "{", "ini_set", "(", "'xdebug.max_nesting_level'", ",", "200", ")", ";", "}", "}", "/**\n * Set default encoding\n */", "mb_http_output", "(", "'UTF-8'", ")", ";", "mb_internal_encoding", "(", "'UTF-8'", ")", ";", "mb_regex_encoding", "(", "'UTF-8'", ")", ";", "/**\n * Enable better garbage collection\n */", "gc_enable", "(", ")", ";", "}" ]
Initialise PHP with default variables
[ "Initialise", "PHP", "with", "default", "variables" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L445-L479
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.bootManifests
protected function bootManifests($flush) { // Setup autoloader $this->getClassLoader()->init($this->getIncludeTests(), $flush); // Find modules $this->getModuleLoader()->init($this->getIncludeTests(), $flush); // Flush config if ($flush) { $config = $this->getConfigLoader()->getManifest(); if ($config instanceof CachedConfigCollection) { $config->setFlush(true); } } // tell modules to sort, now that config is available $this->getModuleLoader()->getManifest()->sort(); // Find default templates $defaultSet = $this->getThemeResourceLoader()->getSet('$default'); if ($defaultSet instanceof ThemeManifest) { $defaultSet->setProject( ModuleManifest::config()->get('project') ); $defaultSet->init($this->getIncludeTests(), $flush); } }
php
protected function bootManifests($flush) { // Setup autoloader $this->getClassLoader()->init($this->getIncludeTests(), $flush); // Find modules $this->getModuleLoader()->init($this->getIncludeTests(), $flush); // Flush config if ($flush) { $config = $this->getConfigLoader()->getManifest(); if ($config instanceof CachedConfigCollection) { $config->setFlush(true); } } // tell modules to sort, now that config is available $this->getModuleLoader()->getManifest()->sort(); // Find default templates $defaultSet = $this->getThemeResourceLoader()->getSet('$default'); if ($defaultSet instanceof ThemeManifest) { $defaultSet->setProject( ModuleManifest::config()->get('project') ); $defaultSet->init($this->getIncludeTests(), $flush); } }
[ "protected", "function", "bootManifests", "(", "$", "flush", ")", "{", "// Setup autoloader", "$", "this", "->", "getClassLoader", "(", ")", "->", "init", "(", "$", "this", "->", "getIncludeTests", "(", ")", ",", "$", "flush", ")", ";", "// Find modules", "$", "this", "->", "getModuleLoader", "(", ")", "->", "init", "(", "$", "this", "->", "getIncludeTests", "(", ")", ",", "$", "flush", ")", ";", "// Flush config", "if", "(", "$", "flush", ")", "{", "$", "config", "=", "$", "this", "->", "getConfigLoader", "(", ")", "->", "getManifest", "(", ")", ";", "if", "(", "$", "config", "instanceof", "CachedConfigCollection", ")", "{", "$", "config", "->", "setFlush", "(", "true", ")", ";", "}", "}", "// tell modules to sort, now that config is available", "$", "this", "->", "getModuleLoader", "(", ")", "->", "getManifest", "(", ")", "->", "sort", "(", ")", ";", "// Find default templates", "$", "defaultSet", "=", "$", "this", "->", "getThemeResourceLoader", "(", ")", "->", "getSet", "(", "'$default'", ")", ";", "if", "(", "$", "defaultSet", "instanceof", "ThemeManifest", ")", "{", "$", "defaultSet", "->", "setProject", "(", "ModuleManifest", "::", "config", "(", ")", "->", "get", "(", "'project'", ")", ")", ";", "$", "defaultSet", "->", "init", "(", "$", "this", "->", "getIncludeTests", "(", ")", ",", "$", "flush", ")", ";", "}", "}" ]
Boot all manifests @param bool $flush
[ "Boot", "all", "manifests" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L505-L531
train
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
CoreKernel.bootErrorHandling
protected function bootErrorHandling() { // Register error handler $errorHandler = Injector::inst()->get(ErrorHandler::class); $errorHandler->start(); // Register error log file $errorLog = Environment::getEnv('SS_ERROR_LOG'); if ($errorLog) { $logger = Injector::inst()->get(LoggerInterface::class); if ($logger instanceof Logger) { $logger->pushHandler(new StreamHandler($this->basePath . '/' . $errorLog, Logger::WARNING)); } else { user_error("SS_ERROR_LOG setting only works with Monolog, you are using another logger", E_USER_WARNING); } } }
php
protected function bootErrorHandling() { // Register error handler $errorHandler = Injector::inst()->get(ErrorHandler::class); $errorHandler->start(); // Register error log file $errorLog = Environment::getEnv('SS_ERROR_LOG'); if ($errorLog) { $logger = Injector::inst()->get(LoggerInterface::class); if ($logger instanceof Logger) { $logger->pushHandler(new StreamHandler($this->basePath . '/' . $errorLog, Logger::WARNING)); } else { user_error("SS_ERROR_LOG setting only works with Monolog, you are using another logger", E_USER_WARNING); } } }
[ "protected", "function", "bootErrorHandling", "(", ")", "{", "// Register error handler", "$", "errorHandler", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "ErrorHandler", "::", "class", ")", ";", "$", "errorHandler", "->", "start", "(", ")", ";", "// Register error log file", "$", "errorLog", "=", "Environment", "::", "getEnv", "(", "'SS_ERROR_LOG'", ")", ";", "if", "(", "$", "errorLog", ")", "{", "$", "logger", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "LoggerInterface", "::", "class", ")", ";", "if", "(", "$", "logger", "instanceof", "Logger", ")", "{", "$", "logger", "->", "pushHandler", "(", "new", "StreamHandler", "(", "$", "this", "->", "basePath", ".", "'/'", ".", "$", "errorLog", ",", "Logger", "::", "WARNING", ")", ")", ";", "}", "else", "{", "user_error", "(", "\"SS_ERROR_LOG setting only works with Monolog, you are using another logger\"", ",", "E_USER_WARNING", ")", ";", "}", "}", "}" ]
Turn on error handling
[ "Turn", "on", "error", "handling" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/CoreKernel.php#L536-L552
train
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
MySQLSchemaManager.renameTable
public function renameTable($oldTableName, $newTableName) { if (!$this->hasTable($oldTableName)) { throw new LogicException('Table ' . $oldTableName . ' does not exist.'); } return $this->query("ALTER TABLE \"$oldTableName\" RENAME \"$newTableName\""); }
php
public function renameTable($oldTableName, $newTableName) { if (!$this->hasTable($oldTableName)) { throw new LogicException('Table ' . $oldTableName . ' does not exist.'); } return $this->query("ALTER TABLE \"$oldTableName\" RENAME \"$newTableName\""); }
[ "public", "function", "renameTable", "(", "$", "oldTableName", ",", "$", "newTableName", ")", "{", "if", "(", "!", "$", "this", "->", "hasTable", "(", "$", "oldTableName", ")", ")", "{", "throw", "new", "LogicException", "(", "'Table '", ".", "$", "oldTableName", ".", "' does not exist.'", ")", ";", "}", "return", "$", "this", "->", "query", "(", "\"ALTER TABLE \\\"$oldTableName\\\" RENAME \\\"$newTableName\\\"\"", ")", ";", "}" ]
Renames a table @param string $oldTableName @param string $newTableName @throws LogicException @return Query
[ "Renames", "a", "table" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLSchemaManager.php#L151-L158
train
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
MySQLSchemaManager.runTableCheckCommand
protected function runTableCheckCommand($sql) { $testResults = $this->query($sql); foreach ($testResults as $testRecord) { if (strtolower($testRecord['Msg_text']) != 'ok') { return false; } } return true; }
php
protected function runTableCheckCommand($sql) { $testResults = $this->query($sql); foreach ($testResults as $testRecord) { if (strtolower($testRecord['Msg_text']) != 'ok') { return false; } } return true; }
[ "protected", "function", "runTableCheckCommand", "(", "$", "sql", ")", "{", "$", "testResults", "=", "$", "this", "->", "query", "(", "$", "sql", ")", ";", "foreach", "(", "$", "testResults", "as", "$", "testRecord", ")", "{", "if", "(", "strtolower", "(", "$", "testRecord", "[", "'Msg_text'", "]", ")", "!=", "'ok'", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Helper function used by checkAndRepairTable. @param string $sql Query to run. @return boolean Returns if the query returns a successful result.
[ "Helper", "function", "used", "by", "checkAndRepairTable", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLSchemaManager.php#L191-L200
train
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
MySQLSchemaManager.renameField
public function renameField($tableName, $oldName, $newName) { $fieldList = $this->fieldList($tableName); if (array_key_exists($oldName, $fieldList)) { $this->query("ALTER TABLE \"$tableName\" CHANGE \"$oldName\" \"$newName\" " . $fieldList[$oldName]); } }
php
public function renameField($tableName, $oldName, $newName) { $fieldList = $this->fieldList($tableName); if (array_key_exists($oldName, $fieldList)) { $this->query("ALTER TABLE \"$tableName\" CHANGE \"$oldName\" \"$newName\" " . $fieldList[$oldName]); } }
[ "public", "function", "renameField", "(", "$", "tableName", ",", "$", "oldName", ",", "$", "newName", ")", "{", "$", "fieldList", "=", "$", "this", "->", "fieldList", "(", "$", "tableName", ")", ";", "if", "(", "array_key_exists", "(", "$", "oldName", ",", "$", "fieldList", ")", ")", "{", "$", "this", "->", "query", "(", "\"ALTER TABLE \\\"$tableName\\\" CHANGE \\\"$oldName\\\" \\\"$newName\\\" \"", ".", "$", "fieldList", "[", "$", "oldName", "]", ")", ";", "}", "}" ]
Change the database column name of the given field. @param string $tableName The name of the tbale the field is in. @param string $oldName The name of the field to change. @param string $newName The new name of the field
[ "Change", "the", "database", "column", "name", "of", "the", "given", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLSchemaManager.php#L257-L263
train
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
MySQLSchemaManager.createIndex
public function createIndex($tableName, $indexName, $indexSpec) { $this->query("ALTER TABLE \"$tableName\" ADD " . $this->getIndexSqlDefinition($indexName, $indexSpec)); }
php
public function createIndex($tableName, $indexName, $indexSpec) { $this->query("ALTER TABLE \"$tableName\" ADD " . $this->getIndexSqlDefinition($indexName, $indexSpec)); }
[ "public", "function", "createIndex", "(", "$", "tableName", ",", "$", "indexName", ",", "$", "indexSpec", ")", "{", "$", "this", "->", "query", "(", "\"ALTER TABLE \\\"$tableName\\\" ADD \"", ".", "$", "this", "->", "getIndexSqlDefinition", "(", "$", "indexName", ",", "$", "indexSpec", ")", ")", ";", "}" ]
Create an index on a table. @param string $tableName The name of the table. @param string $indexName The name of the index. @param string $indexSpec The specification of the index, see {@link SS_Database::requireIndex()} for more details.
[ "Create", "an", "index", "on", "a", "table", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLSchemaManager.php#L307-L310
train
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
MySQLSchemaManager.getIndexSqlDefinition
protected function getIndexSqlDefinition($indexName, $indexSpec) { if ($indexSpec['type'] == 'using') { return sprintf('index "%s" using (%s)', $indexName, $this->implodeColumnList($indexSpec['columns'])); } else { return sprintf('%s "%s" (%s)', $indexSpec['type'], $indexName, $this->implodeColumnList($indexSpec['columns'])); } }
php
protected function getIndexSqlDefinition($indexName, $indexSpec) { if ($indexSpec['type'] == 'using') { return sprintf('index "%s" using (%s)', $indexName, $this->implodeColumnList($indexSpec['columns'])); } else { return sprintf('%s "%s" (%s)', $indexSpec['type'], $indexName, $this->implodeColumnList($indexSpec['columns'])); } }
[ "protected", "function", "getIndexSqlDefinition", "(", "$", "indexName", ",", "$", "indexSpec", ")", "{", "if", "(", "$", "indexSpec", "[", "'type'", "]", "==", "'using'", ")", "{", "return", "sprintf", "(", "'index \"%s\" using (%s)'", ",", "$", "indexName", ",", "$", "this", "->", "implodeColumnList", "(", "$", "indexSpec", "[", "'columns'", "]", ")", ")", ";", "}", "else", "{", "return", "sprintf", "(", "'%s \"%s\" (%s)'", ",", "$", "indexSpec", "[", "'type'", "]", ",", "$", "indexName", ",", "$", "this", "->", "implodeColumnList", "(", "$", "indexSpec", "[", "'columns'", "]", ")", ")", ";", "}", "}" ]
Generate SQL suitable for creating this index @param string $indexName @param string|array $indexSpec See {@link requireTable()} for details @return string MySQL compatible ALTER TABLE syntax
[ "Generate", "SQL", "suitable", "for", "creating", "this", "index" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLSchemaManager.php#L319-L326
train
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
MySQLSchemaManager.varchar
public function varchar($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'varchar', 'precision'=>$this->size, 'character set'=>'utf8', 'collate'=> //'utf8_general_ci'); //DB::requireField($this->tableName, $this->name, "varchar($this->size) character set utf8 collate // utf8_general_ci"); $default = $this->defaultClause($values); $charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset'); $collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation'); return "varchar({$values['precision']}) character set {$charset} collate {$collation}{$default}"; }
php
public function varchar($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'varchar', 'precision'=>$this->size, 'character set'=>'utf8', 'collate'=> //'utf8_general_ci'); //DB::requireField($this->tableName, $this->name, "varchar($this->size) character set utf8 collate // utf8_general_ci"); $default = $this->defaultClause($values); $charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset'); $collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation'); return "varchar({$values['precision']}) character set {$charset} collate {$collation}{$default}"; }
[ "public", "function", "varchar", "(", "$", "values", ")", "{", "//For reference, this is what typically gets passed to this function:", "//$parts=Array('datatype'=>'varchar', 'precision'=>$this->size, 'character set'=>'utf8', 'collate'=>", "//'utf8_general_ci');", "//DB::requireField($this->tableName, $this->name, \"varchar($this->size) character set utf8 collate", "// utf8_general_ci\");", "$", "default", "=", "$", "this", "->", "defaultClause", "(", "$", "values", ")", ";", "$", "charset", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "'SilverStripe\\ORM\\Connect\\MySQLDatabase'", ",", "'charset'", ")", ";", "$", "collation", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "'SilverStripe\\ORM\\Connect\\MySQLDatabase'", ",", "'collation'", ")", ";", "return", "\"varchar({$values['precision']}) character set {$charset} collate {$collation}{$default}\"", ";", "}" ]
Return a varchar type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
[ "Return", "a", "varchar", "type", "-", "formatted", "string" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLSchemaManager.php#L616-L627
train
silverstripe/silverstripe-framework
src/Core/Path.php
Path.join
public static function join(...$parts) { // In case $parts passed as an array in first parameter if (count($parts) === 1 && is_array($parts[0])) { $parts = $parts[0]; } // Cleanup and join all parts $parts = array_filter(array_map('trim', $parts)); $fullPath = static::normalise(implode(DIRECTORY_SEPARATOR, $parts)); // Protect against directory traversal vulnerability (OTG-AUTHZ-001) if (strpos($fullPath, '..') !== false) { throw new InvalidArgumentException('Can not collapse relative folders'); } return $fullPath ?: DIRECTORY_SEPARATOR; }
php
public static function join(...$parts) { // In case $parts passed as an array in first parameter if (count($parts) === 1 && is_array($parts[0])) { $parts = $parts[0]; } // Cleanup and join all parts $parts = array_filter(array_map('trim', $parts)); $fullPath = static::normalise(implode(DIRECTORY_SEPARATOR, $parts)); // Protect against directory traversal vulnerability (OTG-AUTHZ-001) if (strpos($fullPath, '..') !== false) { throw new InvalidArgumentException('Can not collapse relative folders'); } return $fullPath ?: DIRECTORY_SEPARATOR; }
[ "public", "static", "function", "join", "(", "...", "$", "parts", ")", "{", "// In case $parts passed as an array in first parameter", "if", "(", "count", "(", "$", "parts", ")", "===", "1", "&&", "is_array", "(", "$", "parts", "[", "0", "]", ")", ")", "{", "$", "parts", "=", "$", "parts", "[", "0", "]", ";", "}", "// Cleanup and join all parts", "$", "parts", "=", "array_filter", "(", "array_map", "(", "'trim'", ",", "$", "parts", ")", ")", ";", "$", "fullPath", "=", "static", "::", "normalise", "(", "implode", "(", "DIRECTORY_SEPARATOR", ",", "$", "parts", ")", ")", ";", "// Protect against directory traversal vulnerability (OTG-AUTHZ-001)", "if", "(", "strpos", "(", "$", "fullPath", ",", "'..'", ")", "!==", "false", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Can not collapse relative folders'", ")", ";", "}", "return", "$", "fullPath", "?", ":", "DIRECTORY_SEPARATOR", ";", "}" ]
Joins one or more paths, normalising all separators to DIRECTORY_SEPARATOR Note: Errors on collapsed `/../` for security reasons. Use realpath() if you need to join a trusted relative path. @link https://www.owasp.org/index.php/Testing_Directory_traversal/file_include_(OTG-AUTHZ-001) @see File::join_paths() for joining file identifiers @param array $parts @return string Combined path, not including trailing slash (unless it's a single slash)
[ "Joins", "one", "or", "more", "paths", "normalising", "all", "separators", "to", "DIRECTORY_SEPARATOR" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Path.php#L25-L42
train
silverstripe/silverstripe-framework
src/Security/Member_GroupSet.php
Member_GroupSet.foreignIDFilter
public function foreignIDFilter($id = null) { if ($id === null) { $id = $this->getForeignID(); } // Find directly applied groups $manyManyFilter = parent::foreignIDFilter($id); $query = SQLSelect::create('"Group_Members"."GroupID"', '"Group_Members"', $manyManyFilter); $groupIDs = $query->execute()->column(); // Get all ancestors, iteratively merging these into the master set $allGroupIDs = []; while ($groupIDs) { $allGroupIDs = array_merge($allGroupIDs, $groupIDs); $groupIDs = DataObject::get(Group::class)->byIDs($groupIDs)->column("ParentID"); $groupIDs = array_filter($groupIDs); } // Add a filter to this DataList if (!empty($allGroupIDs)) { $allGroupIDsPlaceholders = DB::placeholders($allGroupIDs); return ["\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $allGroupIDs]; } return ['"Group"."ID"' => 0]; }
php
public function foreignIDFilter($id = null) { if ($id === null) { $id = $this->getForeignID(); } // Find directly applied groups $manyManyFilter = parent::foreignIDFilter($id); $query = SQLSelect::create('"Group_Members"."GroupID"', '"Group_Members"', $manyManyFilter); $groupIDs = $query->execute()->column(); // Get all ancestors, iteratively merging these into the master set $allGroupIDs = []; while ($groupIDs) { $allGroupIDs = array_merge($allGroupIDs, $groupIDs); $groupIDs = DataObject::get(Group::class)->byIDs($groupIDs)->column("ParentID"); $groupIDs = array_filter($groupIDs); } // Add a filter to this DataList if (!empty($allGroupIDs)) { $allGroupIDsPlaceholders = DB::placeholders($allGroupIDs); return ["\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $allGroupIDs]; } return ['"Group"."ID"' => 0]; }
[ "public", "function", "foreignIDFilter", "(", "$", "id", "=", "null", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "$", "id", "=", "$", "this", "->", "getForeignID", "(", ")", ";", "}", "// Find directly applied groups", "$", "manyManyFilter", "=", "parent", "::", "foreignIDFilter", "(", "$", "id", ")", ";", "$", "query", "=", "SQLSelect", "::", "create", "(", "'\"Group_Members\".\"GroupID\"'", ",", "'\"Group_Members\"'", ",", "$", "manyManyFilter", ")", ";", "$", "groupIDs", "=", "$", "query", "->", "execute", "(", ")", "->", "column", "(", ")", ";", "// Get all ancestors, iteratively merging these into the master set", "$", "allGroupIDs", "=", "[", "]", ";", "while", "(", "$", "groupIDs", ")", "{", "$", "allGroupIDs", "=", "array_merge", "(", "$", "allGroupIDs", ",", "$", "groupIDs", ")", ";", "$", "groupIDs", "=", "DataObject", "::", "get", "(", "Group", "::", "class", ")", "->", "byIDs", "(", "$", "groupIDs", ")", "->", "column", "(", "\"ParentID\"", ")", ";", "$", "groupIDs", "=", "array_filter", "(", "$", "groupIDs", ")", ";", "}", "// Add a filter to this DataList", "if", "(", "!", "empty", "(", "$", "allGroupIDs", ")", ")", "{", "$", "allGroupIDsPlaceholders", "=", "DB", "::", "placeholders", "(", "$", "allGroupIDs", ")", ";", "return", "[", "\"\\\"Group\\\".\\\"ID\\\" IN ($allGroupIDsPlaceholders)\"", "=>", "$", "allGroupIDs", "]", ";", "}", "return", "[", "'\"Group\".\"ID\"'", "=>", "0", "]", ";", "}" ]
Link this group set to a specific member. Recursively selects all groups applied to this member, as well as any parent groups of any applied groups @param array|int|string|null $id (optional) An ID or an array of IDs - if not provided, will use the current ids as per getForeignID @return array Condition In array(SQL => parameters format)
[ "Link", "this", "group", "set", "to", "a", "specific", "member", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member_GroupSet.php#L36-L62
train
silverstripe/silverstripe-framework
src/Security/Member_GroupSet.php
Member_GroupSet.canAddGroups
protected function canAddGroups($itemIDs) { if (empty($itemIDs)) { return true; } $member = $this->getMember(); return empty($member) || $member->onChangeGroups($itemIDs); }
php
protected function canAddGroups($itemIDs) { if (empty($itemIDs)) { return true; } $member = $this->getMember(); return empty($member) || $member->onChangeGroups($itemIDs); }
[ "protected", "function", "canAddGroups", "(", "$", "itemIDs", ")", "{", "if", "(", "empty", "(", "$", "itemIDs", ")", ")", "{", "return", "true", ";", "}", "$", "member", "=", "$", "this", "->", "getMember", "(", ")", ";", "return", "empty", "(", "$", "member", ")", "||", "$", "member", "->", "onChangeGroups", "(", "$", "itemIDs", ")", ";", "}" ]
Determine if the following groups IDs can be added @param array $itemIDs @return boolean
[ "Determine", "if", "the", "following", "groups", "IDs", "can", "be", "added" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member_GroupSet.php#L125-L132
train
silverstripe/silverstripe-framework
src/Dev/CSSContentParser.php
CSSContentParser.selector2xpath
public function selector2xpath($selector) { $parts = preg_split('/\\s+/', $selector); $xpath = ""; foreach ($parts as $part) { if (preg_match('/^([A-Za-z][A-Za-z0-9]*)/', $part, $matches)) { $xpath .= "//$matches[1]"; } else { $xpath .= "//*"; } $xfilters = array(); if (preg_match('/#([^#.\[]+)/', $part, $matches)) { $xfilters[] = "@id='$matches[1]'"; } if (preg_match('/\.([^#.\[]+)/', $part, $matches)) { $xfilters[] = "contains(@class,'$matches[1]')"; } if ($xfilters) { $xpath .= '[' . implode(',', $xfilters) . ']'; } } return $xpath; }
php
public function selector2xpath($selector) { $parts = preg_split('/\\s+/', $selector); $xpath = ""; foreach ($parts as $part) { if (preg_match('/^([A-Za-z][A-Za-z0-9]*)/', $part, $matches)) { $xpath .= "//$matches[1]"; } else { $xpath .= "//*"; } $xfilters = array(); if (preg_match('/#([^#.\[]+)/', $part, $matches)) { $xfilters[] = "@id='$matches[1]'"; } if (preg_match('/\.([^#.\[]+)/', $part, $matches)) { $xfilters[] = "contains(@class,'$matches[1]')"; } if ($xfilters) { $xpath .= '[' . implode(',', $xfilters) . ']'; } } return $xpath; }
[ "public", "function", "selector2xpath", "(", "$", "selector", ")", "{", "$", "parts", "=", "preg_split", "(", "'/\\\\s+/'", ",", "$", "selector", ")", ";", "$", "xpath", "=", "\"\"", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "if", "(", "preg_match", "(", "'/^([A-Za-z][A-Za-z0-9]*)/'", ",", "$", "part", ",", "$", "matches", ")", ")", "{", "$", "xpath", ".=", "\"//$matches[1]\"", ";", "}", "else", "{", "$", "xpath", ".=", "\"//*\"", ";", "}", "$", "xfilters", "=", "array", "(", ")", ";", "if", "(", "preg_match", "(", "'/#([^#.\\[]+)/'", ",", "$", "part", ",", "$", "matches", ")", ")", "{", "$", "xfilters", "[", "]", "=", "\"@id='$matches[1]'\"", ";", "}", "if", "(", "preg_match", "(", "'/\\.([^#.\\[]+)/'", ",", "$", "part", ",", "$", "matches", ")", ")", "{", "$", "xfilters", "[", "]", "=", "\"contains(@class,'$matches[1]')\"", ";", "}", "if", "(", "$", "xfilters", ")", "{", "$", "xpath", ".=", "'['", ".", "implode", "(", "','", ",", "$", "xfilters", ")", ".", "']'", ";", "}", "}", "return", "$", "xpath", ";", "}" ]
Converts a CSS selector into an equivalent xpath expression. Currently the selector engine only supports querying by tag, id, and class. @param String $selector See {@link getBySelector()} @return String XPath expression
[ "Converts", "a", "CSS", "selector", "into", "an", "equivalent", "xpath", "expression", ".", "Currently", "the", "selector", "engine", "only", "supports", "querying", "by", "tag", "id", "and", "class", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CSSContentParser.php#L98-L120
train
silverstripe/silverstripe-framework
src/Forms/FormAction.php
FormAction.getSchemaDataDefaults
public function getSchemaDataDefaults() { $defaults = parent::getSchemaDataDefaults(); $defaults['attributes']['type'] = $this->getUseButtonTag() ? 'button' : 'submit'; $defaults['data']['icon'] = $this->getIcon(); return $defaults; }
php
public function getSchemaDataDefaults() { $defaults = parent::getSchemaDataDefaults(); $defaults['attributes']['type'] = $this->getUseButtonTag() ? 'button' : 'submit'; $defaults['data']['icon'] = $this->getIcon(); return $defaults; }
[ "public", "function", "getSchemaDataDefaults", "(", ")", "{", "$", "defaults", "=", "parent", "::", "getSchemaDataDefaults", "(", ")", ";", "$", "defaults", "[", "'attributes'", "]", "[", "'type'", "]", "=", "$", "this", "->", "getUseButtonTag", "(", ")", "?", "'button'", ":", "'submit'", ";", "$", "defaults", "[", "'data'", "]", "[", "'icon'", "]", "=", "$", "this", "->", "getIcon", "(", ")", ";", "return", "$", "defaults", ";", "}" ]
Add extra options to data
[ "Add", "extra", "options", "to", "data" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormAction.php#L91-L97
train
silverstripe/silverstripe-framework
src/i18n/i18n.php
i18n.get_closest_translation
public static function get_closest_translation($locale) { // Check if exact match $pool = self::getSources()->getKnownLocales(); if (isset($pool[$locale])) { return $locale; } // Fallback to best locale for common language $localesData = static::getData(); $lang = $localesData->langFromLocale($locale); $candidate = $localesData->localeFromLang($lang); if (isset($pool[$candidate])) { return $candidate; } return null; }
php
public static function get_closest_translation($locale) { // Check if exact match $pool = self::getSources()->getKnownLocales(); if (isset($pool[$locale])) { return $locale; } // Fallback to best locale for common language $localesData = static::getData(); $lang = $localesData->langFromLocale($locale); $candidate = $localesData->localeFromLang($lang); if (isset($pool[$candidate])) { return $candidate; } return null; }
[ "public", "static", "function", "get_closest_translation", "(", "$", "locale", ")", "{", "// Check if exact match", "$", "pool", "=", "self", "::", "getSources", "(", ")", "->", "getKnownLocales", "(", ")", ";", "if", "(", "isset", "(", "$", "pool", "[", "$", "locale", "]", ")", ")", "{", "return", "$", "locale", ";", "}", "// Fallback to best locale for common language", "$", "localesData", "=", "static", "::", "getData", "(", ")", ";", "$", "lang", "=", "$", "localesData", "->", "langFromLocale", "(", "$", "locale", ")", ";", "$", "candidate", "=", "$", "localesData", "->", "localeFromLang", "(", "$", "lang", ")", ";", "if", "(", "isset", "(", "$", "pool", "[", "$", "candidate", "]", ")", ")", "{", "return", "$", "candidate", ";", "}", "return", "null", ";", "}" ]
Matches a given locale with the closest translation available in the system @param string $locale locale code @return string Locale of closest available translation, if available
[ "Matches", "a", "given", "locale", "with", "the", "closest", "translation", "available", "in", "the", "system" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/i18n.php#L276-L292
train
silverstripe/silverstripe-framework
src/i18n/i18n.php
i18n.with_locale
public static function with_locale($locale, $callback) { $oldLocale = self::$current_locale; static::set_locale($locale); try { return $callback(); } finally { static::set_locale($oldLocale); } }
php
public static function with_locale($locale, $callback) { $oldLocale = self::$current_locale; static::set_locale($locale); try { return $callback(); } finally { static::set_locale($oldLocale); } }
[ "public", "static", "function", "with_locale", "(", "$", "locale", ",", "$", "callback", ")", "{", "$", "oldLocale", "=", "self", "::", "$", "current_locale", ";", "static", "::", "set_locale", "(", "$", "locale", ")", ";", "try", "{", "return", "$", "callback", "(", ")", ";", "}", "finally", "{", "static", "::", "set_locale", "(", "$", "oldLocale", ")", ";", "}", "}" ]
Temporarily set the locale while invoking a callback @param string $locale @param callable $callback @return mixed
[ "Temporarily", "set", "the", "locale", "while", "invoking", "a", "callback" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/i18n.php#L334-L343
train
silverstripe/silverstripe-framework
src/Forms/NullableField.php
NullableField.setValue
public function setValue($value, $data = null) { $id = $this->getIsNullId(); if (is_array($data) && array_key_exists($id, $data) && $data[$id]) { $value = null; } $this->valueField->setValue($value); parent::setValue($value); return $this; }
php
public function setValue($value, $data = null) { $id = $this->getIsNullId(); if (is_array($data) && array_key_exists($id, $data) && $data[$id]) { $value = null; } $this->valueField->setValue($value); parent::setValue($value); return $this; }
[ "public", "function", "setValue", "(", "$", "value", ",", "$", "data", "=", "null", ")", "{", "$", "id", "=", "$", "this", "->", "getIsNullId", "(", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", "&&", "array_key_exists", "(", "$", "id", ",", "$", "data", ")", "&&", "$", "data", "[", "$", "id", "]", ")", "{", "$", "value", "=", "null", ";", "}", "$", "this", "->", "valueField", "->", "setValue", "(", "$", "value", ")", ";", "parent", "::", "setValue", "(", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Value is sometimes an array, and sometimes a single value, so we need to handle both cases @param mixed $value @param null|array $data @return $this
[ "Value", "is", "sometimes", "an", "array", "and", "sometimes", "a", "single", "value", "so", "we", "need", "to", "handle", "both", "cases" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/NullableField.php#L137-L150
train
silverstripe/silverstripe-framework
src/View/HTML.php
HTML.createTag
public static function createTag($tag, $attributes, $content = null) { $tag = strtolower($tag); // Build list of arguments $preparedAttributes = ''; foreach ($attributes as $attributeKey => $attributeValue) { // Only set non-empty strings (ensures strlen(0) > 0) if (strlen($attributeValue) > 0) { $preparedAttributes .= sprintf( ' %s="%s"', $attributeKey, Convert::raw2att($attributeValue) ); } } // Check void element type if (in_array($tag, static::config()->get('void_elements'))) { if ($content) { throw new InvalidArgumentException("Void element \"{$tag}\" cannot have content"); } return "<{$tag}{$preparedAttributes} />"; } // Closed tag type return "<{$tag}{$preparedAttributes}>{$content}</{$tag}>"; }
php
public static function createTag($tag, $attributes, $content = null) { $tag = strtolower($tag); // Build list of arguments $preparedAttributes = ''; foreach ($attributes as $attributeKey => $attributeValue) { // Only set non-empty strings (ensures strlen(0) > 0) if (strlen($attributeValue) > 0) { $preparedAttributes .= sprintf( ' %s="%s"', $attributeKey, Convert::raw2att($attributeValue) ); } } // Check void element type if (in_array($tag, static::config()->get('void_elements'))) { if ($content) { throw new InvalidArgumentException("Void element \"{$tag}\" cannot have content"); } return "<{$tag}{$preparedAttributes} />"; } // Closed tag type return "<{$tag}{$preparedAttributes}>{$content}</{$tag}>"; }
[ "public", "static", "function", "createTag", "(", "$", "tag", ",", "$", "attributes", ",", "$", "content", "=", "null", ")", "{", "$", "tag", "=", "strtolower", "(", "$", "tag", ")", ";", "// Build list of arguments", "$", "preparedAttributes", "=", "''", ";", "foreach", "(", "$", "attributes", "as", "$", "attributeKey", "=>", "$", "attributeValue", ")", "{", "// Only set non-empty strings (ensures strlen(0) > 0)", "if", "(", "strlen", "(", "$", "attributeValue", ")", ">", "0", ")", "{", "$", "preparedAttributes", ".=", "sprintf", "(", "' %s=\"%s\"'", ",", "$", "attributeKey", ",", "Convert", "::", "raw2att", "(", "$", "attributeValue", ")", ")", ";", "}", "}", "// Check void element type", "if", "(", "in_array", "(", "$", "tag", ",", "static", "::", "config", "(", ")", "->", "get", "(", "'void_elements'", ")", ")", ")", "{", "if", "(", "$", "content", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Void element \\\"{$tag}\\\" cannot have content\"", ")", ";", "}", "return", "\"<{$tag}{$preparedAttributes} />\"", ";", "}", "// Closed tag type", "return", "\"<{$tag}{$preparedAttributes}>{$content}</{$tag}>\"", ";", "}" ]
Construct and return HTML tag. @param string $tag @param array $attributes @param string $content Content to use between two tags. Not valid for void elements (e.g. link) @return string
[ "Construct", "and", "return", "HTML", "tag", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/HTML.php#L50-L77
train
silverstripe/silverstripe-framework
src/Core/Config/Config_ForClass.php
Config_ForClass.merge
public function merge($name, $value) { Config::modify()->merge($this->class, $name, $value); return $this; }
php
public function merge($name, $value) { Config::modify()->merge($this->class, $name, $value); return $this; }
[ "public", "function", "merge", "(", "$", "name", ",", "$", "value", ")", "{", "Config", "::", "modify", "(", ")", "->", "merge", "(", "$", "this", "->", "class", ",", "$", "name", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Merge a given config @param string $name @param mixed $value @return $this
[ "Merge", "a", "given", "config" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/Config_ForClass.php#L60-L64
train
silverstripe/silverstripe-framework
src/Core/Config/Config_ForClass.php
Config_ForClass.set
public function set($name, $value) { Config::modify()->set($this->class, $name, $value); return $this; }
php
public function set($name, $value) { Config::modify()->set($this->class, $name, $value); return $this; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "value", ")", "{", "Config", "::", "modify", "(", ")", "->", "set", "(", "$", "this", "->", "class", ",", "$", "name", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Replace config value @param string $name @param mixed $value @return $this
[ "Replace", "config", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Config/Config_ForClass.php#L73-L77
train
silverstripe/silverstripe-framework
src/Logging/DebugViewFriendlyErrorFormatter.php
DebugViewFriendlyErrorFormatter.output
public function output($statusCode) { // TODO: Refactor into a content-type option if (Director::is_ajax()) { return $this->getTitle(); } $renderer = Debug::create_debug_view(); $output = $renderer->renderHeader(); $output .= $renderer->renderInfo("Website Error", $this->getTitle(), $this->getBody()); $adminEmail = Email::config()->get('admin_email'); if ($adminEmail) { $mailto = Email::obfuscate($adminEmail); $output .= $renderer->renderParagraph('Contact an administrator: ' . $mailto . ''); } $output .= $renderer->renderFooter(); return $output; }
php
public function output($statusCode) { // TODO: Refactor into a content-type option if (Director::is_ajax()) { return $this->getTitle(); } $renderer = Debug::create_debug_view(); $output = $renderer->renderHeader(); $output .= $renderer->renderInfo("Website Error", $this->getTitle(), $this->getBody()); $adminEmail = Email::config()->get('admin_email'); if ($adminEmail) { $mailto = Email::obfuscate($adminEmail); $output .= $renderer->renderParagraph('Contact an administrator: ' . $mailto . ''); } $output .= $renderer->renderFooter(); return $output; }
[ "public", "function", "output", "(", "$", "statusCode", ")", "{", "// TODO: Refactor into a content-type option", "if", "(", "Director", "::", "is_ajax", "(", ")", ")", "{", "return", "$", "this", "->", "getTitle", "(", ")", ";", "}", "$", "renderer", "=", "Debug", "::", "create_debug_view", "(", ")", ";", "$", "output", "=", "$", "renderer", "->", "renderHeader", "(", ")", ";", "$", "output", ".=", "$", "renderer", "->", "renderInfo", "(", "\"Website Error\"", ",", "$", "this", "->", "getTitle", "(", ")", ",", "$", "this", "->", "getBody", "(", ")", ")", ";", "$", "adminEmail", "=", "Email", "::", "config", "(", ")", "->", "get", "(", "'admin_email'", ")", ";", "if", "(", "$", "adminEmail", ")", "{", "$", "mailto", "=", "Email", "::", "obfuscate", "(", "$", "adminEmail", ")", ";", "$", "output", ".=", "$", "renderer", "->", "renderParagraph", "(", "'Contact an administrator: '", ".", "$", "mailto", ".", "''", ")", ";", "}", "$", "output", ".=", "$", "renderer", "->", "renderFooter", "(", ")", ";", "return", "$", "output", ";", "}" ]
Return the appropriate error content for the given status code @param int $statusCode @return string Content in an appropriate format for the current request
[ "Return", "the", "appropriate", "error", "content", "for", "the", "given", "status", "code" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Logging/DebugViewFriendlyErrorFormatter.php#L125-L144
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.getFormActions
protected function getFormActions() { $actions = new FieldList(); if ($this->record->ID !== 0) { // existing record if ($this->record->canEdit()) { $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save')) ->setUseButtonTag(true) ->addExtraClass('btn-primary font-icon-save')); } if ($this->record->canDelete()) { $actions->push(FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete')); } $gridState = $this->getRequest()->requestVar('gridState'); $this->gridField->getState(false)->setValue($gridState); $actions->push(HiddenField::create('gridState', null, $gridState)); $actions->push($this->getRightGroupField()); } else { // adding new record //Change the Save label to 'Create' $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create')) ->setUseButtonTag(true) ->addExtraClass('btn-primary font-icon-plus-thin')); // Add a Cancel link which is a button-like link and link back to one level up. $crumbs = $this->Breadcrumbs(); if ($crumbs && $crumbs->count() >= 2) { $oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2); $text = sprintf( "<a class=\"%s\" href=\"%s\">%s</a>", "crumb btn btn-secondary cms-panel-link", // CSS classes $oneLevelUp->Link, // url _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label ); $actions->push(new LiteralField('cancelbutton', $text)); } } $this->extend('updateFormActions', $actions); return $actions; }
php
protected function getFormActions() { $actions = new FieldList(); if ($this->record->ID !== 0) { // existing record if ($this->record->canEdit()) { $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save')) ->setUseButtonTag(true) ->addExtraClass('btn-primary font-icon-save')); } if ($this->record->canDelete()) { $actions->push(FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete')); } $gridState = $this->getRequest()->requestVar('gridState'); $this->gridField->getState(false)->setValue($gridState); $actions->push(HiddenField::create('gridState', null, $gridState)); $actions->push($this->getRightGroupField()); } else { // adding new record //Change the Save label to 'Create' $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create')) ->setUseButtonTag(true) ->addExtraClass('btn-primary font-icon-plus-thin')); // Add a Cancel link which is a button-like link and link back to one level up. $crumbs = $this->Breadcrumbs(); if ($crumbs && $crumbs->count() >= 2) { $oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2); $text = sprintf( "<a class=\"%s\" href=\"%s\">%s</a>", "crumb btn btn-secondary cms-panel-link", // CSS classes $oneLevelUp->Link, // url _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label ); $actions->push(new LiteralField('cancelbutton', $text)); } } $this->extend('updateFormActions', $actions); return $actions; }
[ "protected", "function", "getFormActions", "(", ")", "{", "$", "actions", "=", "new", "FieldList", "(", ")", ";", "if", "(", "$", "this", "->", "record", "->", "ID", "!==", "0", ")", "{", "// existing record", "if", "(", "$", "this", "->", "record", "->", "canEdit", "(", ")", ")", "{", "$", "actions", "->", "push", "(", "FormAction", "::", "create", "(", "'doSave'", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\GridField\\\\GridFieldDetailForm.Save'", ",", "'Save'", ")", ")", "->", "setUseButtonTag", "(", "true", ")", "->", "addExtraClass", "(", "'btn-primary font-icon-save'", ")", ")", ";", "}", "if", "(", "$", "this", "->", "record", "->", "canDelete", "(", ")", ")", "{", "$", "actions", "->", "push", "(", "FormAction", "::", "create", "(", "'doDelete'", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\GridField\\\\GridFieldDetailForm.Delete'", ",", "'Delete'", ")", ")", "->", "setUseButtonTag", "(", "true", ")", "->", "addExtraClass", "(", "'btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete'", ")", ")", ";", "}", "$", "gridState", "=", "$", "this", "->", "getRequest", "(", ")", "->", "requestVar", "(", "'gridState'", ")", ";", "$", "this", "->", "gridField", "->", "getState", "(", "false", ")", "->", "setValue", "(", "$", "gridState", ")", ";", "$", "actions", "->", "push", "(", "HiddenField", "::", "create", "(", "'gridState'", ",", "null", ",", "$", "gridState", ")", ")", ";", "$", "actions", "->", "push", "(", "$", "this", "->", "getRightGroupField", "(", ")", ")", ";", "}", "else", "{", "// adding new record", "//Change the Save label to 'Create'", "$", "actions", "->", "push", "(", "FormAction", "::", "create", "(", "'doSave'", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\GridField\\\\GridFieldDetailForm.Create'", ",", "'Create'", ")", ")", "->", "setUseButtonTag", "(", "true", ")", "->", "addExtraClass", "(", "'btn-primary font-icon-plus-thin'", ")", ")", ";", "// Add a Cancel link which is a button-like link and link back to one level up.", "$", "crumbs", "=", "$", "this", "->", "Breadcrumbs", "(", ")", ";", "if", "(", "$", "crumbs", "&&", "$", "crumbs", "->", "count", "(", ")", ">=", "2", ")", "{", "$", "oneLevelUp", "=", "$", "crumbs", "->", "offsetGet", "(", "$", "crumbs", "->", "count", "(", ")", "-", "2", ")", ";", "$", "text", "=", "sprintf", "(", "\"<a class=\\\"%s\\\" href=\\\"%s\\\">%s</a>\"", ",", "\"crumb btn btn-secondary cms-panel-link\"", ",", "// CSS classes", "$", "oneLevelUp", "->", "Link", ",", "// url", "_t", "(", "'SilverStripe\\\\Forms\\\\GridField\\\\GridFieldDetailForm.CancelBtn'", ",", "'Cancel'", ")", "// label", ")", ";", "$", "actions", "->", "push", "(", "new", "LiteralField", "(", "'cancelbutton'", ",", "$", "text", ")", ")", ";", "}", "}", "$", "this", "->", "extend", "(", "'updateFormActions'", ",", "$", "actions", ")", ";", "return", "$", "actions", ";", "}" ]
Build the set of form field actions for this DataObject @return FieldList
[ "Build", "the", "set", "of", "form", "field", "actions", "for", "this", "DataObject" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L322-L367
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.doPrevious
public function doPrevious($data, $form) { $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content'); $link = $this->getEditLink($this->getPreviousRecordID()); return $this->redirect($link); }
php
public function doPrevious($data, $form) { $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content'); $link = $this->getEditLink($this->getPreviousRecordID()); return $this->redirect($link); }
[ "public", "function", "doPrevious", "(", "$", "data", ",", "$", "form", ")", "{", "$", "this", "->", "getToplevelController", "(", ")", "->", "getResponse", "(", ")", "->", "addHeader", "(", "'X-Pjax'", ",", "'Content'", ")", ";", "$", "link", "=", "$", "this", "->", "getEditLink", "(", "$", "this", "->", "getPreviousRecordID", "(", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "link", ")", ";", "}" ]
Goes to the previous record @param array $data The form data @param Form $form The Form object @return HTTPResponse
[ "Goes", "to", "the", "previous", "record" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L472-L477
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.doNext
public function doNext($data, $form) { $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content'); $link = $this->getEditLink($this->getNextRecordID()); return $this->redirect($link); }
php
public function doNext($data, $form) { $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content'); $link = $this->getEditLink($this->getNextRecordID()); return $this->redirect($link); }
[ "public", "function", "doNext", "(", "$", "data", ",", "$", "form", ")", "{", "$", "this", "->", "getToplevelController", "(", ")", "->", "getResponse", "(", ")", "->", "addHeader", "(", "'X-Pjax'", ",", "'Content'", ")", ";", "$", "link", "=", "$", "this", "->", "getEditLink", "(", "$", "this", "->", "getNextRecordID", "(", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "link", ")", ";", "}" ]
Goes to the next record @param array $data The form data @param Form $form The Form object @return HTTPResponse
[ "Goes", "to", "the", "next", "record" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L485-L490
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.doNew
public function doNew($data, $form) { return $this->redirect(Controller::join_links($this->gridField->Link('item'), 'new')); }
php
public function doNew($data, $form) { return $this->redirect(Controller::join_links($this->gridField->Link('item'), 'new')); }
[ "public", "function", "doNew", "(", "$", "data", ",", "$", "form", ")", "{", "return", "$", "this", "->", "redirect", "(", "Controller", "::", "join_links", "(", "$", "this", "->", "gridField", "->", "Link", "(", "'item'", ")", ",", "'new'", ")", ")", ";", "}" ]
Creates a new record. If you're already creating a new record, this forces the URL to change. @param array $data The form data @param Form $form The Form object @return HTTPResponse
[ "Creates", "a", "new", "record", ".", "If", "you", "re", "already", "creating", "a", "new", "record", "this", "forces", "the", "URL", "to", "change", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L500-L503
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.getEditLink
public function getEditLink($id) { return Controller::join_links( $this->gridField->Link(), 'item', $id, '?gridState=' . urlencode($this->gridField->getState(false)->Value()) ); }
php
public function getEditLink($id) { return Controller::join_links( $this->gridField->Link(), 'item', $id, '?gridState=' . urlencode($this->gridField->getState(false)->Value()) ); }
[ "public", "function", "getEditLink", "(", "$", "id", ")", "{", "return", "Controller", "::", "join_links", "(", "$", "this", "->", "gridField", "->", "Link", "(", ")", ",", "'item'", ",", "$", "id", ",", "'?gridState='", ".", "urlencode", "(", "$", "this", "->", "gridField", "->", "getState", "(", "false", ")", "->", "Value", "(", ")", ")", ")", ";", "}" ]
Gets the edit link for a record @param int $id The ID of the record in the GridField @return string
[ "Gets", "the", "edit", "link", "for", "a", "record" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L511-L519
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.redirectAfterSave
protected function redirectAfterSave($isNewRecord) { $controller = $this->getToplevelController(); if ($isNewRecord) { return $controller->redirect($this->Link()); } elseif ($this->gridField->getList()->byID($this->record->ID)) { // Return new view, as we can't do a "virtual redirect" via the CMS Ajax // to the same URL (it assumes that its content is already current, and doesn't reload) return $this->edit($controller->getRequest()); } else { // Changes to the record properties might've excluded the record from // a filtered list, so return back to the main view if it can't be found $url = $controller->getRequest()->getURL(); $noActionURL = $controller->removeAction($url); $controller->getRequest()->addHeader('X-Pjax', 'Content'); return $controller->redirect($noActionURL, 302); } }
php
protected function redirectAfterSave($isNewRecord) { $controller = $this->getToplevelController(); if ($isNewRecord) { return $controller->redirect($this->Link()); } elseif ($this->gridField->getList()->byID($this->record->ID)) { // Return new view, as we can't do a "virtual redirect" via the CMS Ajax // to the same URL (it assumes that its content is already current, and doesn't reload) return $this->edit($controller->getRequest()); } else { // Changes to the record properties might've excluded the record from // a filtered list, so return back to the main view if it can't be found $url = $controller->getRequest()->getURL(); $noActionURL = $controller->removeAction($url); $controller->getRequest()->addHeader('X-Pjax', 'Content'); return $controller->redirect($noActionURL, 302); } }
[ "protected", "function", "redirectAfterSave", "(", "$", "isNewRecord", ")", "{", "$", "controller", "=", "$", "this", "->", "getToplevelController", "(", ")", ";", "if", "(", "$", "isNewRecord", ")", "{", "return", "$", "controller", "->", "redirect", "(", "$", "this", "->", "Link", "(", ")", ")", ";", "}", "elseif", "(", "$", "this", "->", "gridField", "->", "getList", "(", ")", "->", "byID", "(", "$", "this", "->", "record", "->", "ID", ")", ")", "{", "// Return new view, as we can't do a \"virtual redirect\" via the CMS Ajax", "// to the same URL (it assumes that its content is already current, and doesn't reload)", "return", "$", "this", "->", "edit", "(", "$", "controller", "->", "getRequest", "(", ")", ")", ";", "}", "else", "{", "// Changes to the record properties might've excluded the record from", "// a filtered list, so return back to the main view if it can't be found", "$", "url", "=", "$", "controller", "->", "getRequest", "(", ")", "->", "getURL", "(", ")", ";", "$", "noActionURL", "=", "$", "controller", "->", "removeAction", "(", "$", "url", ")", ";", "$", "controller", "->", "getRequest", "(", ")", "->", "addHeader", "(", "'X-Pjax'", ",", "'Content'", ")", ";", "return", "$", "controller", "->", "redirect", "(", "$", "noActionURL", ",", "302", ")", ";", "}", "}" ]
Response object for this request after a successful save @param bool $isNewRecord True if this record was just created @return HTTPResponse|DBHTMLText
[ "Response", "object", "for", "this", "request", "after", "a", "successful", "save" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L574-L591
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.saveFormIntoRecord
protected function saveFormIntoRecord($data, $form) { $list = $this->gridField->getList(); // Check object matches the correct classname if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) { $newClassName = $data['ClassName']; // The records originally saved attribute was overwritten by $form->saveInto($record) before. // This is necessary for newClassInstance() to work as expected, and trigger change detection // on the ClassName attribute $this->record->setClassName($this->record->ClassName); // Replace $record with a new instance $this->record = $this->record->newClassInstance($newClassName); } // Save form and any extra saved data into this dataobject $form->saveInto($this->record); $this->record->write(); $this->extend('onAfterSave', $this->record); $extraData = $this->getExtraSavedData($this->record, $list); $list->add($this->record, $extraData); return $this->record; }
php
protected function saveFormIntoRecord($data, $form) { $list = $this->gridField->getList(); // Check object matches the correct classname if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) { $newClassName = $data['ClassName']; // The records originally saved attribute was overwritten by $form->saveInto($record) before. // This is necessary for newClassInstance() to work as expected, and trigger change detection // on the ClassName attribute $this->record->setClassName($this->record->ClassName); // Replace $record with a new instance $this->record = $this->record->newClassInstance($newClassName); } // Save form and any extra saved data into this dataobject $form->saveInto($this->record); $this->record->write(); $this->extend('onAfterSave', $this->record); $extraData = $this->getExtraSavedData($this->record, $list); $list->add($this->record, $extraData); return $this->record; }
[ "protected", "function", "saveFormIntoRecord", "(", "$", "data", ",", "$", "form", ")", "{", "$", "list", "=", "$", "this", "->", "gridField", "->", "getList", "(", ")", ";", "// Check object matches the correct classname", "if", "(", "isset", "(", "$", "data", "[", "'ClassName'", "]", ")", "&&", "$", "data", "[", "'ClassName'", "]", "!=", "$", "this", "->", "record", "->", "ClassName", ")", "{", "$", "newClassName", "=", "$", "data", "[", "'ClassName'", "]", ";", "// The records originally saved attribute was overwritten by $form->saveInto($record) before.", "// This is necessary for newClassInstance() to work as expected, and trigger change detection", "// on the ClassName attribute", "$", "this", "->", "record", "->", "setClassName", "(", "$", "this", "->", "record", "->", "ClassName", ")", ";", "// Replace $record with a new instance", "$", "this", "->", "record", "=", "$", "this", "->", "record", "->", "newClassInstance", "(", "$", "newClassName", ")", ";", "}", "// Save form and any extra saved data into this dataobject", "$", "form", "->", "saveInto", "(", "$", "this", "->", "record", ")", ";", "$", "this", "->", "record", "->", "write", "(", ")", ";", "$", "this", "->", "extend", "(", "'onAfterSave'", ",", "$", "this", "->", "record", ")", ";", "$", "extraData", "=", "$", "this", "->", "getExtraSavedData", "(", "$", "this", "->", "record", ",", "$", "list", ")", ";", "$", "list", "->", "add", "(", "$", "this", "->", "record", ",", "$", "extraData", ")", ";", "return", "$", "this", "->", "record", ";", "}" ]
Loads the given form data into the underlying dataobject and relation @param array $data @param Form $form @throws ValidationException On error @return DataObject Saved record
[ "Loads", "the", "given", "form", "data", "into", "the", "underlying", "dataobject", "and", "relation" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L607-L631
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
GridFieldDetailForm_ItemRequest.getTemplates
public function getTemplates() { $templates = SSViewer::get_templates_by_class($this, '', __CLASS__); // Prefer any custom template if ($this->getTemplate()) { array_unshift($templates, $this->getTemplate()); } return $templates; }
php
public function getTemplates() { $templates = SSViewer::get_templates_by_class($this, '', __CLASS__); // Prefer any custom template if ($this->getTemplate()) { array_unshift($templates, $this->getTemplate()); } return $templates; }
[ "public", "function", "getTemplates", "(", ")", "{", "$", "templates", "=", "SSViewer", "::", "get_templates_by_class", "(", "$", "this", ",", "''", ",", "__CLASS__", ")", ";", "// Prefer any custom template", "if", "(", "$", "this", "->", "getTemplate", "(", ")", ")", "{", "array_unshift", "(", "$", "templates", ",", "$", "this", "->", "getTemplate", "(", ")", ")", ";", "}", "return", "$", "templates", ";", "}" ]
Get list of templates to use @return array
[ "Get", "list", "of", "templates", "to", "use" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php#L696-L704
train
silverstripe/silverstripe-framework
src/Dev/Deprecation.php
Deprecation.get_enabled
public static function get_enabled() { // Deprecation is only available on dev if (!Director::isDev()) { return false; } if (isset(self::$enabled)) { return self::$enabled; } return Environment::getEnv('SS_DEPRECATION_ENABLED') ?: true; }
php
public static function get_enabled() { // Deprecation is only available on dev if (!Director::isDev()) { return false; } if (isset(self::$enabled)) { return self::$enabled; } return Environment::getEnv('SS_DEPRECATION_ENABLED') ?: true; }
[ "public", "static", "function", "get_enabled", "(", ")", "{", "// Deprecation is only available on dev", "if", "(", "!", "Director", "::", "isDev", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "self", "::", "$", "enabled", ")", ")", "{", "return", "self", "::", "$", "enabled", ";", "}", "return", "Environment", "::", "getEnv", "(", "'SS_DEPRECATION_ENABLED'", ")", "?", ":", "true", ";", "}" ]
Determine if deprecation notices should be displayed @return bool
[ "Determine", "if", "deprecation", "notices", "should", "be", "displayed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Deprecation.php#L143-L153
train
silverstripe/silverstripe-framework
src/Dev/Deprecation.php
Deprecation.restore_settings
public static function restore_settings($settings) { self::$notice_level = $settings['level']; self::$version = $settings['version']; self::$module_version_overrides = $settings['moduleVersions']; self::$enabled = $settings['enabled']; }
php
public static function restore_settings($settings) { self::$notice_level = $settings['level']; self::$version = $settings['version']; self::$module_version_overrides = $settings['moduleVersions']; self::$enabled = $settings['enabled']; }
[ "public", "static", "function", "restore_settings", "(", "$", "settings", ")", "{", "self", "::", "$", "notice_level", "=", "$", "settings", "[", "'level'", "]", ";", "self", "::", "$", "version", "=", "$", "settings", "[", "'version'", "]", ";", "self", "::", "$", "module_version_overrides", "=", "$", "settings", "[", "'moduleVersions'", "]", ";", "self", "::", "$", "enabled", "=", "$", "settings", "[", "'enabled'", "]", ";", "}" ]
Method for when testing. Restore all the current version settings from a variable @param $settings array An array as returned by {@see Deprecation::dump_settings()}
[ "Method", "for", "when", "testing", ".", "Restore", "all", "the", "current", "version", "settings", "from", "a", "variable" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Deprecation.php#L264-L270
train
silverstripe/silverstripe-framework
src/View/ViewableData_Debugger.php
ViewableData_Debugger.forTemplate
public function forTemplate($field = null) { // debugging info for a specific field $class = get_class($this->object); if ($field) { return "<b>Debugging Information for {$class}->{$field}</b><br/>" . ($this->object->hasMethod($field) ? "Has method '$field'<br/>" : null) . ($this->object->hasField($field) ? "Has field '$field'<br/>" : null); } // debugging information for the entire class $reflector = new ReflectionObject($this->object); $debug = "<b>Debugging Information: all methods available in '{$class}'</b><br/><ul>"; foreach ($this->object->allMethodNames() as $method) { // check that the method is public if ($method[0] === strtoupper($method[0]) && $method[0] != '_') { if ($reflector->hasMethod($method) && $method = $reflector->getMethod($method)) { if ($method->isPublic()) { $debug .= "<li>\${$method->getName()}"; if (count($method->getParameters())) { $debug .= ' <small>(' . implode(', ', $method->getParameters()) . ')</small>'; } $debug .= '</li>'; } } else { $debug .= "<li>\$$method</li>"; } } } $debug .= '</ul>'; if ($this->object->hasMethod('toMap')) { $debug .= "<b>Debugging Information: all fields available in '{$class}'</b><br/><ul>"; foreach ($this->object->toMap() as $field => $value) { $debug .= "<li>\$$field</li>"; } $debug .= "</ul>"; } // check for an extra attached data if ($this->object->hasMethod('data') && $this->object->data() != $this->object) { $debug .= ViewableData_Debugger::create($this->object->data())->forTemplate(); } return $debug; }
php
public function forTemplate($field = null) { // debugging info for a specific field $class = get_class($this->object); if ($field) { return "<b>Debugging Information for {$class}->{$field}</b><br/>" . ($this->object->hasMethod($field) ? "Has method '$field'<br/>" : null) . ($this->object->hasField($field) ? "Has field '$field'<br/>" : null); } // debugging information for the entire class $reflector = new ReflectionObject($this->object); $debug = "<b>Debugging Information: all methods available in '{$class}'</b><br/><ul>"; foreach ($this->object->allMethodNames() as $method) { // check that the method is public if ($method[0] === strtoupper($method[0]) && $method[0] != '_') { if ($reflector->hasMethod($method) && $method = $reflector->getMethod($method)) { if ($method->isPublic()) { $debug .= "<li>\${$method->getName()}"; if (count($method->getParameters())) { $debug .= ' <small>(' . implode(', ', $method->getParameters()) . ')</small>'; } $debug .= '</li>'; } } else { $debug .= "<li>\$$method</li>"; } } } $debug .= '</ul>'; if ($this->object->hasMethod('toMap')) { $debug .= "<b>Debugging Information: all fields available in '{$class}'</b><br/><ul>"; foreach ($this->object->toMap() as $field => $value) { $debug .= "<li>\$$field</li>"; } $debug .= "</ul>"; } // check for an extra attached data if ($this->object->hasMethod('data') && $this->object->data() != $this->object) { $debug .= ViewableData_Debugger::create($this->object->data())->forTemplate(); } return $debug; }
[ "public", "function", "forTemplate", "(", "$", "field", "=", "null", ")", "{", "// debugging info for a specific field", "$", "class", "=", "get_class", "(", "$", "this", "->", "object", ")", ";", "if", "(", "$", "field", ")", "{", "return", "\"<b>Debugging Information for {$class}->{$field}</b><br/>\"", ".", "(", "$", "this", "->", "object", "->", "hasMethod", "(", "$", "field", ")", "?", "\"Has method '$field'<br/>\"", ":", "null", ")", ".", "(", "$", "this", "->", "object", "->", "hasField", "(", "$", "field", ")", "?", "\"Has field '$field'<br/>\"", ":", "null", ")", ";", "}", "// debugging information for the entire class", "$", "reflector", "=", "new", "ReflectionObject", "(", "$", "this", "->", "object", ")", ";", "$", "debug", "=", "\"<b>Debugging Information: all methods available in '{$class}'</b><br/><ul>\"", ";", "foreach", "(", "$", "this", "->", "object", "->", "allMethodNames", "(", ")", "as", "$", "method", ")", "{", "// check that the method is public", "if", "(", "$", "method", "[", "0", "]", "===", "strtoupper", "(", "$", "method", "[", "0", "]", ")", "&&", "$", "method", "[", "0", "]", "!=", "'_'", ")", "{", "if", "(", "$", "reflector", "->", "hasMethod", "(", "$", "method", ")", "&&", "$", "method", "=", "$", "reflector", "->", "getMethod", "(", "$", "method", ")", ")", "{", "if", "(", "$", "method", "->", "isPublic", "(", ")", ")", "{", "$", "debug", ".=", "\"<li>\\${$method->getName()}\"", ";", "if", "(", "count", "(", "$", "method", "->", "getParameters", "(", ")", ")", ")", "{", "$", "debug", ".=", "' <small>('", ".", "implode", "(", "', '", ",", "$", "method", "->", "getParameters", "(", ")", ")", ".", "')</small>'", ";", "}", "$", "debug", ".=", "'</li>'", ";", "}", "}", "else", "{", "$", "debug", ".=", "\"<li>\\$$method</li>\"", ";", "}", "}", "}", "$", "debug", ".=", "'</ul>'", ";", "if", "(", "$", "this", "->", "object", "->", "hasMethod", "(", "'toMap'", ")", ")", "{", "$", "debug", ".=", "\"<b>Debugging Information: all fields available in '{$class}'</b><br/><ul>\"", ";", "foreach", "(", "$", "this", "->", "object", "->", "toMap", "(", ")", "as", "$", "field", "=>", "$", "value", ")", "{", "$", "debug", ".=", "\"<li>\\$$field</li>\"", ";", "}", "$", "debug", ".=", "\"</ul>\"", ";", "}", "// check for an extra attached data", "if", "(", "$", "this", "->", "object", "->", "hasMethod", "(", "'data'", ")", "&&", "$", "this", "->", "object", "->", "data", "(", ")", "!=", "$", "this", "->", "object", ")", "{", "$", "debug", ".=", "ViewableData_Debugger", "::", "create", "(", "$", "this", "->", "object", "->", "data", "(", ")", ")", "->", "forTemplate", "(", ")", ";", "}", "return", "$", "debug", ";", "}" ]
Return debugging information, as XHTML. If a field name is passed, it will show debugging information on that field, otherwise it will show information on all methods and fields. @param string $field the field name @return string
[ "Return", "debugging", "information", "as", "XHTML", ".", "If", "a", "field", "name", "is", "passed", "it", "will", "show", "debugging", "information", "on", "that", "field", "otherwise", "it", "will", "show", "information", "on", "all", "methods", "and", "fields", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/ViewableData_Debugger.php#L42-L91
train
silverstripe/silverstripe-framework
src/Forms/TimeField.php
TimeField.getTimeFormat
public function getTimeFormat() { if ($this->getHTML5()) { // Browsers expect ISO 8601 times, localisation is handled on the client $this->setTimeFormat(DBTime::ISO_TIME); } if ($this->timeFormat) { return $this->timeFormat; } // Get from locale return $this->getFrontendFormatter()->getPattern(); }
php
public function getTimeFormat() { if ($this->getHTML5()) { // Browsers expect ISO 8601 times, localisation is handled on the client $this->setTimeFormat(DBTime::ISO_TIME); } if ($this->timeFormat) { return $this->timeFormat; } // Get from locale return $this->getFrontendFormatter()->getPattern(); }
[ "public", "function", "getTimeFormat", "(", ")", "{", "if", "(", "$", "this", "->", "getHTML5", "(", ")", ")", "{", "// Browsers expect ISO 8601 times, localisation is handled on the client", "$", "this", "->", "setTimeFormat", "(", "DBTime", "::", "ISO_TIME", ")", ";", "}", "if", "(", "$", "this", "->", "timeFormat", ")", "{", "return", "$", "this", "->", "timeFormat", ";", "}", "// Get from locale", "return", "$", "this", "->", "getFrontendFormatter", "(", ")", "->", "getPattern", "(", ")", ";", "}" ]
Get time format in CLDR standard format This can be set explicitly. If not, this will be generated from the current locale with the current time length. @see http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Field-Symbol-Table
[ "Get", "time", "format", "in", "CLDR", "standard", "format" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TimeField.php#L96-L109
train
silverstripe/silverstripe-framework
src/Forms/TimeField.php
TimeField.getInternalFormatter
protected function getInternalFormatter() { $formatter = IntlDateFormatter::create( i18n::config()->uninherited('default_locale'), IntlDateFormatter::NONE, IntlDateFormatter::MEDIUM, date_default_timezone_get() // Default to server timezone ); $formatter->setLenient(false); // Note we omit timezone from this format, and we assume server TZ always. $formatter->setPattern(DBTime::ISO_TIME); return $formatter; }
php
protected function getInternalFormatter() { $formatter = IntlDateFormatter::create( i18n::config()->uninherited('default_locale'), IntlDateFormatter::NONE, IntlDateFormatter::MEDIUM, date_default_timezone_get() // Default to server timezone ); $formatter->setLenient(false); // Note we omit timezone from this format, and we assume server TZ always. $formatter->setPattern(DBTime::ISO_TIME); return $formatter; }
[ "protected", "function", "getInternalFormatter", "(", ")", "{", "$", "formatter", "=", "IntlDateFormatter", "::", "create", "(", "i18n", "::", "config", "(", ")", "->", "uninherited", "(", "'default_locale'", ")", ",", "IntlDateFormatter", "::", "NONE", ",", "IntlDateFormatter", "::", "MEDIUM", ",", "date_default_timezone_get", "(", ")", "// Default to server timezone", ")", ";", "$", "formatter", "->", "setLenient", "(", "false", ")", ";", "// Note we omit timezone from this format, and we assume server TZ always.", "$", "formatter", "->", "setPattern", "(", "DBTime", "::", "ISO_TIME", ")", ";", "return", "$", "formatter", ";", "}" ]
Get a time formatter for the ISO 8601 format @return IntlDateFormatter
[ "Get", "a", "time", "formatter", "for", "the", "ISO", "8601", "format" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TimeField.php#L209-L223
train
silverstripe/silverstripe-framework
src/Forms/TimeField.php
TimeField.withTimezone
protected function withTimezone($timezone, $callback) { $currentTimezone = date_default_timezone_get(); try { if ($timezone) { date_default_timezone_set($timezone); } return $callback(); } finally { // Restore timezone if ($timezone) { date_default_timezone_set($currentTimezone); } } }
php
protected function withTimezone($timezone, $callback) { $currentTimezone = date_default_timezone_get(); try { if ($timezone) { date_default_timezone_set($timezone); } return $callback(); } finally { // Restore timezone if ($timezone) { date_default_timezone_set($currentTimezone); } } }
[ "protected", "function", "withTimezone", "(", "$", "timezone", ",", "$", "callback", ")", "{", "$", "currentTimezone", "=", "date_default_timezone_get", "(", ")", ";", "try", "{", "if", "(", "$", "timezone", ")", "{", "date_default_timezone_set", "(", "$", "timezone", ")", ";", "}", "return", "$", "callback", "(", ")", ";", "}", "finally", "{", "// Restore timezone", "if", "(", "$", "timezone", ")", "{", "date_default_timezone_set", "(", "$", "currentTimezone", ")", ";", "}", "}", "}" ]
Run a callback within a specific timezone @param string $timezone @param callable $callback
[ "Run", "a", "callback", "within", "a", "specific", "timezone" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TimeField.php#L488-L502
train
silverstripe/silverstripe-framework
src/Forms/EmailField.php
EmailField.validate
public function validate($validator) { $this->value = trim($this->value); $pattern = '^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'; // Escape delimiter characters. $safePattern = str_replace('/', '\\/', $pattern); if ($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) { $validator->validationError( $this->name, _t('SilverStripe\\Forms\\EmailField.VALIDATION', 'Please enter an email address'), 'validation' ); return false; } return true; }
php
public function validate($validator) { $this->value = trim($this->value); $pattern = '^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'; // Escape delimiter characters. $safePattern = str_replace('/', '\\/', $pattern); if ($this->value && !preg_match('/' . $safePattern . '/i', $this->value)) { $validator->validationError( $this->name, _t('SilverStripe\\Forms\\EmailField.VALIDATION', 'Please enter an email address'), 'validation' ); return false; } return true; }
[ "public", "function", "validate", "(", "$", "validator", ")", "{", "$", "this", "->", "value", "=", "trim", "(", "$", "this", "->", "value", ")", ";", "$", "pattern", "=", "'^[a-z0-9!#$%&\\'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&\\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'", ";", "// Escape delimiter characters.", "$", "safePattern", "=", "str_replace", "(", "'/'", ",", "'\\\\/'", ",", "$", "pattern", ")", ";", "if", "(", "$", "this", "->", "value", "&&", "!", "preg_match", "(", "'/'", ".", "$", "safePattern", ".", "'/i'", ",", "$", "this", "->", "value", ")", ")", "{", "$", "validator", "->", "validationError", "(", "$", "this", "->", "name", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\EmailField.VALIDATION'", ",", "'Please enter an email address'", ")", ",", "'validation'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validates for RFC 2822 compliant email addresses. @see http://www.regular-expressions.info/email.html @see http://www.ietf.org/rfc/rfc2822.txt @param Validator $validator @return string
[ "Validates", "for", "RFC", "2822", "compliant", "email", "addresses", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/EmailField.php#L30-L50
train
silverstripe/silverstripe-framework
src/Dev/DevelopmentAdmin.php
DevelopmentAdmin.generatesecuretoken
public function generatesecuretoken() { $generator = Injector::inst()->create('SilverStripe\\Security\\RandomGenerator'); $token = $generator->randomToken('sha1'); $body = <<<TXT Generated new token. Please add the following code to your YAML configuration: Security: token: $token TXT; $response = new HTTPResponse($body); return $response->addHeader('Content-Type', 'text/plain'); }
php
public function generatesecuretoken() { $generator = Injector::inst()->create('SilverStripe\\Security\\RandomGenerator'); $token = $generator->randomToken('sha1'); $body = <<<TXT Generated new token. Please add the following code to your YAML configuration: Security: token: $token TXT; $response = new HTTPResponse($body); return $response->addHeader('Content-Type', 'text/plain'); }
[ "public", "function", "generatesecuretoken", "(", ")", "{", "$", "generator", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "'SilverStripe\\\\Security\\\\RandomGenerator'", ")", ";", "$", "token", "=", "$", "generator", "->", "randomToken", "(", "'sha1'", ")", ";", "$", "body", "=", " <<<TXT\nGenerated new token. Please add the following code to your YAML configuration:\n\nSecurity:\n token: $token\n\nTXT", ";", "$", "response", "=", "new", "HTTPResponse", "(", "$", "body", ")", ";", "return", "$", "response", "->", "addHeader", "(", "'Content-Type'", ",", "'text/plain'", ")", ";", "}" ]
Generate a secure token which can be used as a crypto key. Returns the token and suggests PHP configuration to set it.
[ "Generate", "a", "secure", "token", "which", "can", "be", "used", "as", "a", "crypto", "key", ".", "Returns", "the", "token", "and", "suggests", "PHP", "configuration", "to", "set", "it", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DevelopmentAdmin.php#L213-L226
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
GridFieldDataColumns.getDisplayFields
public function getDisplayFields($gridField) { if (!$this->displayFields) { return singleton($gridField->getModelClass())->summaryFields(); } return $this->displayFields; }
php
public function getDisplayFields($gridField) { if (!$this->displayFields) { return singleton($gridField->getModelClass())->summaryFields(); } return $this->displayFields; }
[ "public", "function", "getDisplayFields", "(", "$", "gridField", ")", "{", "if", "(", "!", "$", "this", "->", "displayFields", ")", "{", "return", "singleton", "(", "$", "gridField", "->", "getModelClass", "(", ")", ")", "->", "summaryFields", "(", ")", ";", "}", "return", "$", "this", "->", "displayFields", ";", "}" ]
Get the DisplayFields @param GridField $gridField @return array @see GridFieldDataColumns::setDisplayFields
[ "Get", "the", "DisplayFields" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDataColumns.php#L87-L93
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
GridFieldDataColumns.castValue
protected function castValue($gridField, $fieldName, $value) { // If a fieldCasting is specified, we assume the result is safe if (array_key_exists($fieldName, $this->fieldCasting)) { $value = $gridField->getCastedValue($value, $this->fieldCasting[$fieldName]); } elseif (is_object($value)) { // If the value is an object, we do one of two things if (method_exists($value, 'Nice')) { // If it has a "Nice" method, call that & make sure the result is safe $value = Convert::raw2xml($value->Nice()); } else { // Otherwise call forTemplate - the result of this should already be safe $value = $value->forTemplate(); } } else { // Otherwise, just treat as a text string & make sure the result is safe $value = Convert::raw2xml($value); } return $value; }
php
protected function castValue($gridField, $fieldName, $value) { // If a fieldCasting is specified, we assume the result is safe if (array_key_exists($fieldName, $this->fieldCasting)) { $value = $gridField->getCastedValue($value, $this->fieldCasting[$fieldName]); } elseif (is_object($value)) { // If the value is an object, we do one of two things if (method_exists($value, 'Nice')) { // If it has a "Nice" method, call that & make sure the result is safe $value = Convert::raw2xml($value->Nice()); } else { // Otherwise call forTemplate - the result of this should already be safe $value = $value->forTemplate(); } } else { // Otherwise, just treat as a text string & make sure the result is safe $value = Convert::raw2xml($value); } return $value; }
[ "protected", "function", "castValue", "(", "$", "gridField", ",", "$", "fieldName", ",", "$", "value", ")", "{", "// If a fieldCasting is specified, we assume the result is safe", "if", "(", "array_key_exists", "(", "$", "fieldName", ",", "$", "this", "->", "fieldCasting", ")", ")", "{", "$", "value", "=", "$", "gridField", "->", "getCastedValue", "(", "$", "value", ",", "$", "this", "->", "fieldCasting", "[", "$", "fieldName", "]", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "value", ")", ")", "{", "// If the value is an object, we do one of two things", "if", "(", "method_exists", "(", "$", "value", ",", "'Nice'", ")", ")", "{", "// If it has a \"Nice\" method, call that & make sure the result is safe", "$", "value", "=", "Convert", "::", "raw2xml", "(", "$", "value", "->", "Nice", "(", ")", ")", ";", "}", "else", "{", "// Otherwise call forTemplate - the result of this should already be safe", "$", "value", "=", "$", "value", "->", "forTemplate", "(", ")", ";", "}", "}", "else", "{", "// Otherwise, just treat as a text string & make sure the result is safe", "$", "value", "=", "Convert", "::", "raw2xml", "(", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Casts a field to a string which is safe to insert into HTML @param GridField $gridField @param string $fieldName @param string $value @return string
[ "Casts", "a", "field", "to", "a", "string", "which", "is", "safe", "to", "insert", "into", "HTML" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDataColumns.php#L247-L267
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
GridFieldDataColumns.escapeValue
protected function escapeValue($gridField, $value) { if (!$escape = $gridField->FieldEscape) { return $value; } foreach ($escape as $search => $replace) { $value = str_replace($search, $replace, $value); } return $value; }
php
protected function escapeValue($gridField, $value) { if (!$escape = $gridField->FieldEscape) { return $value; } foreach ($escape as $search => $replace) { $value = str_replace($search, $replace, $value); } return $value; }
[ "protected", "function", "escapeValue", "(", "$", "gridField", ",", "$", "value", ")", "{", "if", "(", "!", "$", "escape", "=", "$", "gridField", "->", "FieldEscape", ")", "{", "return", "$", "value", ";", "}", "foreach", "(", "$", "escape", "as", "$", "search", "=>", "$", "replace", ")", "{", "$", "value", "=", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Remove values from a value using FieldEscape setter @param GridField $gridField @param string $value @return string
[ "Remove", "values", "from", "a", "value", "using", "FieldEscape", "setter" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDataColumns.php#L302-L312
train
silverstripe/silverstripe-framework
src/Core/Extension.php
Extension.withOwner
public function withOwner($owner, callable $callback, $args = []) { try { $this->setOwner($owner); return $callback(...$args); } finally { $this->clearOwner(); } }
php
public function withOwner($owner, callable $callback, $args = []) { try { $this->setOwner($owner); return $callback(...$args); } finally { $this->clearOwner(); } }
[ "public", "function", "withOwner", "(", "$", "owner", ",", "callable", "$", "callback", ",", "$", "args", "=", "[", "]", ")", "{", "try", "{", "$", "this", "->", "setOwner", "(", "$", "owner", ")", ";", "return", "$", "callback", "(", "...", "$", "args", ")", ";", "}", "finally", "{", "$", "this", "->", "clearOwner", "(", ")", ";", "}", "}" ]
Temporarily modify the owner. The original owner is ensured to be restored @param mixed $owner Owner to set @param callable $callback Callback to invoke @param array $args Args to pass to callback @return mixed
[ "Temporarily", "modify", "the", "owner", ".", "The", "original", "owner", "is", "ensured", "to", "be", "restored" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Extension.php#L74-L82
train
silverstripe/silverstripe-framework
src/Security/LoginForm.php
LoginForm.setAuthenticatorClass
public function setAuthenticatorClass($class) { $this->authenticatorClass = $class; /** @var FieldList|null $fields */ $fields = $this->Fields(); if (!$fields) { return $this; } $authenticatorField = $fields->dataFieldByName('AuthenticationMethod'); if ($authenticatorField) { $authenticatorField->setValue($class); } return $this; }
php
public function setAuthenticatorClass($class) { $this->authenticatorClass = $class; /** @var FieldList|null $fields */ $fields = $this->Fields(); if (!$fields) { return $this; } $authenticatorField = $fields->dataFieldByName('AuthenticationMethod'); if ($authenticatorField) { $authenticatorField->setValue($class); } return $this; }
[ "public", "function", "setAuthenticatorClass", "(", "$", "class", ")", "{", "$", "this", "->", "authenticatorClass", "=", "$", "class", ";", "/** @var FieldList|null $fields */", "$", "fields", "=", "$", "this", "->", "Fields", "(", ")", ";", "if", "(", "!", "$", "fields", ")", "{", "return", "$", "this", ";", "}", "$", "authenticatorField", "=", "$", "fields", "->", "dataFieldByName", "(", "'AuthenticationMethod'", ")", ";", "if", "(", "$", "authenticatorField", ")", "{", "$", "authenticatorField", "->", "setValue", "(", "$", "class", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set the authenticator class name to use @param string $class @return $this
[ "Set", "the", "authenticator", "class", "name", "to", "use" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/LoginForm.php#L39-L55
train
silverstripe/silverstripe-framework
src/Core/Cache/RateLimiter.php
RateLimiter.hit
public function hit() { if (!$this->getCache()->has($this->getIdentifier())) { $ttl = $this->getDecay() * 60; $expiry = DBDatetime::now()->getTimestamp() + $ttl; $this->getCache()->set($this->getIdentifier() . '-timer', $expiry, $ttl); } else { $expiry = $this->getCache()->get($this->getIdentifier() . '-timer'); $ttl = $expiry - DBDatetime::now()->getTimestamp(); } $this->getCache()->set($this->getIdentifier(), $this->getNumAttempts() + 1, $ttl); return $this; }
php
public function hit() { if (!$this->getCache()->has($this->getIdentifier())) { $ttl = $this->getDecay() * 60; $expiry = DBDatetime::now()->getTimestamp() + $ttl; $this->getCache()->set($this->getIdentifier() . '-timer', $expiry, $ttl); } else { $expiry = $this->getCache()->get($this->getIdentifier() . '-timer'); $ttl = $expiry - DBDatetime::now()->getTimestamp(); } $this->getCache()->set($this->getIdentifier(), $this->getNumAttempts() + 1, $ttl); return $this; }
[ "public", "function", "hit", "(", ")", "{", "if", "(", "!", "$", "this", "->", "getCache", "(", ")", "->", "has", "(", "$", "this", "->", "getIdentifier", "(", ")", ")", ")", "{", "$", "ttl", "=", "$", "this", "->", "getDecay", "(", ")", "*", "60", ";", "$", "expiry", "=", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", "+", "$", "ttl", ";", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "this", "->", "getIdentifier", "(", ")", ".", "'-timer'", ",", "$", "expiry", ",", "$", "ttl", ")", ";", "}", "else", "{", "$", "expiry", "=", "$", "this", "->", "getCache", "(", ")", "->", "get", "(", "$", "this", "->", "getIdentifier", "(", ")", ".", "'-timer'", ")", ";", "$", "ttl", "=", "$", "expiry", "-", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", ";", "}", "$", "this", "->", "getCache", "(", ")", "->", "set", "(", "$", "this", "->", "getIdentifier", "(", ")", ",", "$", "this", "->", "getNumAttempts", "(", ")", "+", "1", ",", "$", "ttl", ")", ";", "return", "$", "this", ";", "}" ]
Store a hit in the rate limit cache @return $this
[ "Store", "a", "hit", "in", "the", "rate", "limit", "cache" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Cache/RateLimiter.php#L164-L176
train
silverstripe/silverstripe-framework
src/Dev/BulkLoader.php
BulkLoader.getImportSpec
public function getImportSpec() { $singleton = DataObject::singleton($this->objectClass); // get database columns (fieldlabels include fieldname as a key) // using $$includerelations flag as false, so that it only contain $db fields $fields = (array)$singleton->fieldLabels(false); // Merge relations $relations = array_merge( $singleton->hasOne(), $singleton->hasMany(), $singleton->manyMany() ); // Ensure description is string (e.g. many_many through) foreach ($relations as $name => $desc) { if (!is_string($desc)) { $relations[$name] = $name; } } return [ 'fields' => $fields, 'relations' => $relations, ]; }
php
public function getImportSpec() { $singleton = DataObject::singleton($this->objectClass); // get database columns (fieldlabels include fieldname as a key) // using $$includerelations flag as false, so that it only contain $db fields $fields = (array)$singleton->fieldLabels(false); // Merge relations $relations = array_merge( $singleton->hasOne(), $singleton->hasMany(), $singleton->manyMany() ); // Ensure description is string (e.g. many_many through) foreach ($relations as $name => $desc) { if (!is_string($desc)) { $relations[$name] = $name; } } return [ 'fields' => $fields, 'relations' => $relations, ]; }
[ "public", "function", "getImportSpec", "(", ")", "{", "$", "singleton", "=", "DataObject", "::", "singleton", "(", "$", "this", "->", "objectClass", ")", ";", "// get database columns (fieldlabels include fieldname as a key)", "// using $$includerelations flag as false, so that it only contain $db fields", "$", "fields", "=", "(", "array", ")", "$", "singleton", "->", "fieldLabels", "(", "false", ")", ";", "// Merge relations", "$", "relations", "=", "array_merge", "(", "$", "singleton", "->", "hasOne", "(", ")", ",", "$", "singleton", "->", "hasMany", "(", ")", ",", "$", "singleton", "->", "manyMany", "(", ")", ")", ";", "// Ensure description is string (e.g. many_many through)", "foreach", "(", "$", "relations", "as", "$", "name", "=>", "$", "desc", ")", "{", "if", "(", "!", "is_string", "(", "$", "desc", ")", ")", "{", "$", "relations", "[", "$", "name", "]", "=", "$", "name", ";", "}", "}", "return", "[", "'fields'", "=>", "$", "fields", ",", "'relations'", "=>", "$", "relations", ",", "]", ";", "}" ]
Get a specification of all available columns and relations on the used model. Useful for generation of spec documents for technical end users. Return Format: <code> array( 'fields' => array('myFieldName'=>'myDescription'), 'relations' => array('myRelationName'=>'myDescription'), ) </code> @todo Mix in custom column mappings @return array
[ "Get", "a", "specification", "of", "all", "available", "columns", "and", "relations", "on", "the", "used", "model", ".", "Useful", "for", "generation", "of", "spec", "documents", "for", "technical", "end", "users", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/BulkLoader.php#L224-L250
train
silverstripe/silverstripe-framework
src/ORM/DataQuery.php
DataQuery.removeFilterOn
public function removeFilterOn($fieldExpression) { $matched = false; // If given a parameterised condition extract only the condition if (is_array($fieldExpression)) { reset($fieldExpression); $fieldExpression = key($fieldExpression); } $where = $this->query->getWhere(); // Iterate through each condition foreach ($where as $i => $condition) { // Rewrite condition groups as plain conditions before comparison if ($condition instanceof SQLConditionGroup) { $predicate = $condition->conditionSQL($parameters); $condition = array($predicate => $parameters); } // As each condition is a single length array, do a single // iteration to extract the predicate and parameters foreach ($condition as $predicate => $parameters) { // @see SQLSelect::addWhere for why this is required here if (strpos($predicate, $fieldExpression) !== false) { unset($where[$i]); $matched = true; } // Enforce single-item condition predicate => parameters structure break; } } // set the entire where clause back, but clear the original one first if ($matched) { $this->query->setWhere($where); } else { throw new InvalidArgumentException("Couldn't find $fieldExpression in the query filter."); } return $this; }
php
public function removeFilterOn($fieldExpression) { $matched = false; // If given a parameterised condition extract only the condition if (is_array($fieldExpression)) { reset($fieldExpression); $fieldExpression = key($fieldExpression); } $where = $this->query->getWhere(); // Iterate through each condition foreach ($where as $i => $condition) { // Rewrite condition groups as plain conditions before comparison if ($condition instanceof SQLConditionGroup) { $predicate = $condition->conditionSQL($parameters); $condition = array($predicate => $parameters); } // As each condition is a single length array, do a single // iteration to extract the predicate and parameters foreach ($condition as $predicate => $parameters) { // @see SQLSelect::addWhere for why this is required here if (strpos($predicate, $fieldExpression) !== false) { unset($where[$i]); $matched = true; } // Enforce single-item condition predicate => parameters structure break; } } // set the entire where clause back, but clear the original one first if ($matched) { $this->query->setWhere($where); } else { throw new InvalidArgumentException("Couldn't find $fieldExpression in the query filter."); } return $this; }
[ "public", "function", "removeFilterOn", "(", "$", "fieldExpression", ")", "{", "$", "matched", "=", "false", ";", "// If given a parameterised condition extract only the condition", "if", "(", "is_array", "(", "$", "fieldExpression", ")", ")", "{", "reset", "(", "$", "fieldExpression", ")", ";", "$", "fieldExpression", "=", "key", "(", "$", "fieldExpression", ")", ";", "}", "$", "where", "=", "$", "this", "->", "query", "->", "getWhere", "(", ")", ";", "// Iterate through each condition", "foreach", "(", "$", "where", "as", "$", "i", "=>", "$", "condition", ")", "{", "// Rewrite condition groups as plain conditions before comparison", "if", "(", "$", "condition", "instanceof", "SQLConditionGroup", ")", "{", "$", "predicate", "=", "$", "condition", "->", "conditionSQL", "(", "$", "parameters", ")", ";", "$", "condition", "=", "array", "(", "$", "predicate", "=>", "$", "parameters", ")", ";", "}", "// As each condition is a single length array, do a single", "// iteration to extract the predicate and parameters", "foreach", "(", "$", "condition", "as", "$", "predicate", "=>", "$", "parameters", ")", "{", "// @see SQLSelect::addWhere for why this is required here", "if", "(", "strpos", "(", "$", "predicate", ",", "$", "fieldExpression", ")", "!==", "false", ")", "{", "unset", "(", "$", "where", "[", "$", "i", "]", ")", ";", "$", "matched", "=", "true", ";", "}", "// Enforce single-item condition predicate => parameters structure", "break", ";", "}", "}", "// set the entire where clause back, but clear the original one first", "if", "(", "$", "matched", ")", "{", "$", "this", "->", "query", "->", "setWhere", "(", "$", "where", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "\"Couldn't find $fieldExpression in the query filter.\"", ")", ";", "}", "return", "$", "this", ";", "}" ]
Remove a filter from the query @param string|array $fieldExpression The predicate of the condition to remove (ignoring parameters). The expression will be considered a match if it's contained within any other predicate. @return $this
[ "Remove", "a", "filter", "from", "the", "query" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataQuery.php#L117-L157
train