code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
protected function checkPath($path) { $targetPath = $this->getPath(); return strncmp($this->normalisePath($path) ?? '', $targetPath ?? '', strlen($targetPath ?? '')) === 0; }
Checks the given path by the rules and returns whether it should be protected @param string $path Path to be checked @return bool
checkPath
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
BSD-3-Clause
public function checkRequestForBypass(HTTPRequest $request) { return $request->isAjax(); }
Returns true for AJAX requests @param HTTPRequest $request @return bool
checkRequestForBypass
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/AjaxBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/AjaxBypass.php
BSD-3-Clause
public function checkRequestForBypass(HTTPRequest $request) { return Director::is_cli(); }
Returns true if the current process is running in CLI mode @param HTTPRequest $request @return bool
checkRequestForBypass
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/CliBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/CliBypass.php
BSD-3-Clause
protected function buildConfirmationItem($token, $value) { return new Confirmation\Item( $token, _t(__CLASS__ . '.CONFIRMATION_NAME', '"{key}" GET parameter', ['key' => $this->name]), sprintf('%s = "%s"', $this->name, $value) ); }
Generates the confirmation item @param string $token @param string $value @return Confirmation\Item
buildConfirmationItem
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/GetParameter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/GetParameter.php
BSD-3-Clause
protected function generateToken($path, $value) { return sprintf('%s::%s?%s=%s', static::class, $path, $this->name, $value); }
Generates the unique token depending on the path and the parameter @param string $path URL path @param string $value The parameter value @return string
generateToken
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/GetParameter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/GetParameter.php
BSD-3-Clause
protected function checkRequestHasParameter(HTTPRequest $request) { return array_key_exists($this->name, $request->getVars() ?? []); }
Check request contains the GET parameter @param HTTPRequest $request @return bool
checkRequestHasParameter
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/GetParameter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/GetParameter.php
BSD-3-Clause
protected function normalisePath($path) { if (substr($path ?? '', -1) !== '/') { return $path . '/'; } else { return $path; } }
Returns the normalised version of the given path @param string $path Path to normalise @return string normalised version of the path
normalisePath
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/PathAware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/PathAware.php
BSD-3-Clause
public function __construct(...$methods) { $this->addMethods(...$methods); }
Initialize the bypass with HTTP methods @param string[] ...$methods
__construct
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/HttpMethodBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/HttpMethodBypass.php
BSD-3-Clause
public function addMethods(...$methods) { // uppercase and exclude empties $methods = array_reduce( $methods ?? [], function ($result, $method) { $method = strtoupper(trim($method ?? '')); if (strlen($method ?? '')) { $result[] = $method; } return $result; }, [] ); foreach ($methods as $method) { if (!in_array($method, $this->methods ?? [], true)) { $this->methods[] = $method; } } return $this; }
Add new HTTP methods to the list @param string[] ...$methods return $this
addMethods
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/HttpMethodBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/HttpMethodBypass.php
BSD-3-Clause
public function addHttpMethods(...$methods) { $this->httpMethods->addMethods(...$methods); return $this; }
Add HTTP methods to check against @param string[] ...$methods @return $this
addHttpMethods
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/Url.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/Url.php
BSD-3-Clause
public function getHttpMethods() { return $this->httpMethods->getMethods(); }
Returns HTTP methods to be checked @return string[]
getHttpMethods
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/Url.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/Url.php
BSD-3-Clause
public function setParams($params = null) { $this->params = $params; return $this; }
Set the GET parameters null to skip parameter check If an array of parameters provided, then URL should contain ALL of them and ONLY them to match. If the values in the list contain strings, those will be checked against parameter values accordingly. Null as a value in the array matches any parameter values. @param string|null $params @return $this
setParams
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/Url.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/Url.php
BSD-3-Clause
public function checkRequest(HTTPRequest $request) { $httpMethods = $this->getHttpMethods(); if (count($httpMethods ?? []) && !in_array($request->httpMethod(), $httpMethods ?? [], true)) { return false; } if (!$this->checkPath($request->getURL())) { return false; } if (!is_null($this->params)) { $getVars = $request->getVars(); // compare the request parameters with the declared ones foreach ($this->params as $key => $val) { if (is_null($val)) { $cmp = array_key_exists($key, $getVars ?? []); } else { $cmp = isset($getVars[$key]) && $getVars[$key] === strval($val); } if (!$cmp) { return false; } } // check only declared parameters exist in the request foreach ($getVars as $key => $val) { if (!array_key_exists($key, $this->params ?? [])) { return false; } } } return true; }
Match the request against the rules @param HTTPRequest $request @return bool
checkRequest
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/Url.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/Url.php
BSD-3-Clause
protected function checkPath($path) { return $this->getPath() === $this->normalisePath($path); }
Checks the given path by the rules and returns true if it is matching @param string $path Path to be checked @return bool
checkPath
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/Url.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/Url.php
BSD-3-Clause
protected function generateToken($httpMethod, $path) { return sprintf('%s::%s|%s', static::class, $httpMethod, $path); }
Generates the unique token depending on the path @param string $httpMethod HTTP method @param string $path URL path @return string
generateToken
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/Url.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/Url.php
BSD-3-Clause
public function __construct(...$environments) { $this->environments = $environments; }
Initialize the bypass with the list of environment types @param string[] ...$environments
__construct
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/EnvironmentBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/EnvironmentBypass.php
BSD-3-Clause
public function setEnvironments($environments) { $this->environments = $environments; return $this; }
Set the list of environments allowing a bypass @param string[] $environments List of environment types @return $this
setEnvironments
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/EnvironmentBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/EnvironmentBypass.php
BSD-3-Clause
public function checkRequestForBypass(HTTPRequest $request) { return in_array(Director::get_environment_type(), $this->environments ?? [], true); }
Checks whether the current environment type in the list of allowed ones @param HTTPRequest $request @return bool
checkRequestForBypass
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/EnvironmentBypass.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/EnvironmentBypass.php
BSD-3-Clause
public function scheduleFlush(HTTPRequest $request) { $flush = array_key_exists('flush', $request->getVars() ?? []) || ($request->getURL() === 'dev/build'); $kernel = Injector::inst()->get(Kernel::class); if (!$flush || (method_exists($kernel, 'isFlushed') && $kernel->isFlushed())) { return false; } ScheduledFlushDiscoverer::scheduleFlush($kernel); return true; }
Schedules the manifest flush operation for a following request WARNING! Does not perform flush, but schedules it for another request @param HTTPRequest $request @return bool true if flush has been scheduled, false otherwise
scheduleFlush
php
silverstripe/silverstripe-framework
src/Control/Middleware/URLSpecialsMiddleware/FlushScheduler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/URLSpecialsMiddleware/FlushScheduler.php
BSD-3-Clause
public static function raw2att($val) { return Convert::raw2xml($val); }
Convert a value to be suitable for an XML attribute. Warning: Does not escape array keys @param array|string $val String to escape, or array of strings @return array|string
raw2att
php
silverstripe/silverstripe-framework
src/Core/Convert.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Convert.php
BSD-3-Clause
public static function raw2htmlatt($val) { return Convert::raw2att($val); }
Convert a value to be suitable for an HTML attribute. Warning: Does not escape array keys @param string|array $val String to escape, or array of strings @return array|string
raw2htmlatt
php
silverstripe/silverstripe-framework
src/Core/Convert.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Convert.php
BSD-3-Clause
public static function symbol2sql($identifier, $separator = '.') { return DB::get_conn()->escapeIdentifier($identifier, $separator); }
Safely encodes a SQL symbolic identifier (or list of identifiers), such as a database, table, or column name. Supports encoding of multi identfiers separated by a delimiter (e.g. ".") @param string|array $identifier The identifier to escape. E.g. 'SiteTree.Title' or list of identifiers to be joined via the separator. @param string $separator The string that delimits subsequent identifiers @return string The escaped identifier. E.g. '"SiteTree"."Title"'
symbol2sql
php
silverstripe/silverstripe-framework
src/Core/Convert.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Convert.php
BSD-3-Clause
public static function linkIfMatch($string) { if (preg_match('/^[a-z+]+\:\/\/[a-zA-Z0-9$-_.+?&=!*\'()%]+$/', $string ?? '')) { return "<a style=\"white-space: nowrap\" href=\"$string\">$string</a>"; } return $string; }
Create a link if the string is a valid URL @param string $string The string to linkify @return string A link to the URL if string is a URL
linkIfMatch
php
silverstripe/silverstripe-framework
src/Core/Convert.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Convert.php
BSD-3-Clause
public function __construct($basePath) { $this->basePath = $basePath; // Initialise the dependency injector as soon as possible, as it is // subsequently used by some of the following code $injectorLoader = InjectorLoader::inst(); $injector = new Injector(['locator' => SilverStripeServiceConfigurationLocator::class]); $injectorLoader->pushManifest($injector); $this->setInjectorLoader($injectorLoader); // Manifest cache factory $manifestCacheFactory = $this->buildManifestCacheFactory(); // Class loader $classLoader = ClassLoader::inst(); $classLoader->pushManifest(new ClassManifest($basePath, $manifestCacheFactory)); $this->setClassLoader($classLoader); // Module loader $moduleLoader = ModuleLoader::inst(); $moduleManifest = new ModuleManifest($basePath, $manifestCacheFactory); $moduleLoader->pushManifest($moduleManifest); $this->setModuleLoader($moduleLoader); // Config loader $configLoader = ConfigLoader::inst(); // If nesting kernels, don't create a new config manifest as that will reset config deltas if (!$configLoader->hasManifest()) { $configFactory = new CoreConfigFactory($manifestCacheFactory); $configManifest = $configFactory->createRoot(); $configLoader->pushManifest($configManifest); } $this->setConfigLoader($configLoader); // Load template manifest $themeResourceLoader = ThemeResourceLoader::inst(); $themeResourceLoader->addSet(SSViewer::PUBLIC_THEME, new PublicThemes()); $themeResourceLoader->addSet(SSViewer::DEFAULT_THEME, new ThemeManifest( $basePath, null, // project is defined in config, and this argument is deprecated $manifestCacheFactory )); $this->setThemeResourceLoader($themeResourceLoader); }
Create a new kernel for this application @param string $basePath Path to base dir for this application
__construct
php
silverstripe/silverstripe-framework
src/Core/BaseKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/BaseKernel.php
BSD-3-Clause
protected function bootPHP() { if ($this->getEnvironment() === BaseKernel::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(); }
Initialise PHP with default variables
bootPHP
php
silverstripe/silverstripe-framework
src/Core/BaseKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/BaseKernel.php
BSD-3-Clause
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 = implode([ $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
detectLegacyEnvironment
php
silverstripe/silverstripe-framework
src/Core/BaseKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/BaseKernel.php
BSD-3-Clause
protected function redirectToInstaller($msg = '') { Deprecation::notice('5.3.0', 'Will be removed without equivalent functionality'); // Error if installer not available if (!file_exists(Director::publicFolder() . '/install.php')) { throw new HTTPResponse_Exception( $msg, 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 it exists. Otherwise show a server error to the user. @deprecated 5.3.0 Will be removed without equivalent functionality @param string $msg Optional message to show to the user on an installed project (install.php missing).
redirectToInstaller
php
silverstripe/silverstripe-framework
src/Core/BaseKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/BaseKernel.php
BSD-3-Clause
protected function beforeExtending($method, $callback) { if (empty($this->beforeExtendCallbacks[$method])) { $this->beforeExtendCallbacks[$method] = []; } $this->beforeExtendCallbacks[$method][] = $callback; }
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called. @param string $method The name of the method to hook into @param callable $callback The callback to execute
beforeExtending
php
silverstripe/silverstripe-framework
src/Core/Extensible.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extensible.php
BSD-3-Clause
protected function afterExtending($method, $callback) { if (empty($this->afterExtendCallbacks[$method])) { $this->afterExtendCallbacks[$method] = []; } $this->afterExtendCallbacks[$method][] = $callback; }
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called. @param string $method The name of the method to hook into @param callable $callback The callback to execute
afterExtending
php
silverstripe/silverstripe-framework
src/Core/Extensible.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extensible.php
BSD-3-Clause
public function invokeWithExtensions($method, &...$arguments) { $result = []; if (method_exists($this, $method ?? '')) { $thisResult = $this->$method(...$arguments); if ($thisResult !== null) { $result[] = $thisResult; } } $extras = $this->extend($method, ...$arguments); return $extras ? array_merge($result, $extras) : $result; }
Calls a method if available on both this object and all applied {@link Extensions}, and then attempts to merge all results into an array @param string $method the method name to call @param mixed ...$arguments List of arguments @return array List of results with nulls filtered out
invokeWithExtensions
php
silverstripe/silverstripe-framework
src/Core/Extensible.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extensible.php
BSD-3-Clause
public function getExtensionInstance($extension) { $instances = $this->getExtensionInstances(); if (array_key_exists($extension, $instances ?? [])) { return $instances[$extension]; } // in case Injector has been used to replace an extension foreach ($instances as $instance) { if (is_a($instance, $extension ?? '')) { return $instance; } } return null; }
Get an extension instance attached to this object by name. @param string $extension @return Extension|null
getExtensionInstance
php
silverstripe/silverstripe-framework
src/Core/Extensible.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extensible.php
BSD-3-Clause
public static function setVariables(array $vars) { foreach ($vars as $varName => $varValue) { if ($varName === 'env') { continue; } $GLOBALS[$varName] = $varValue; } if (array_key_exists('env', $vars ?? [])) { static::$env = $vars['env']; } }
Restore a backed up or modified list of vars to $globals @param array $vars
setVariables
php
silverstripe/silverstripe-framework
src/Core/Environment.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Environment.php
BSD-3-Clause
static function setMemoryLimitMax($memoryLimit) { if (isset($memoryLimit) && !is_numeric($memoryLimit)) { $memoryLimit = Convert::memstring2bytes($memoryLimit); } static::$memoryLimitMax = $memoryLimit; }
Set the maximum allowed value for {@link increaseMemoryLimitTo()}. The same result can also be achieved through 'suhosin.memory_limit' if PHP is running with the Suhosin system. @param string|float $memoryLimit Memory limit string or float value
setMemoryLimitMax
php
silverstripe/silverstripe-framework
src/Core/Environment.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Environment.php
BSD-3-Clause
public static function increaseTimeLimitTo($timeLimit = null) { // Check vs max limit $max = static::getTimeLimitMax(); if ($max > 0 && $timeLimit > $max) { return false; } if (!$timeLimit) { set_time_limit(0); } else { $currTimeLimit = ini_get('max_execution_time'); // Only increase if its smaller if ($currTimeLimit > 0 && $currTimeLimit < $timeLimit) { set_time_limit($timeLimit ?? 0); } } return true; }
Increase the time limit of this script. By default, the time will be unlimited. Only works if 'safe_mode' is off in the PHP configuration. Only values up to {@link getTimeLimitMax()} are allowed. @param int $timeLimit The time limit in seconds. If omitted, no time limit will be set. @return Boolean TRUE indicates a successful change, FALSE a denied change.
increaseTimeLimitTo
php
silverstripe/silverstripe-framework
src/Core/Environment.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Environment.php
BSD-3-Clause
public static function getEnv($name) { if (array_key_exists($name, static::$env)) { return static::$env[$name]; } // isset() is used for $_ENV and $_SERVER instead of array_key_exists() to fix a very strange issue that // occured in CI running silverstripe/recipe-kitchen-sink where PHP would timeout due apparently due to an // excessively high number of array method calls. isset() is not used for static::$env above because // values there may be null, and isset() will return false for null values // Symfony also uses isset() for reading $_ENV and $_SERVER values // https://github.com/symfony/dependency-injection/blob/6.2/EnvVarProcessor.php#L148 if (isset($_ENV[$name])) { return $_ENV[$name]; } if (isset($_SERVER[$name])) { return $_SERVER[$name]; } return getenv($name); }
Get value of environment variable. If the value is false, you should check Environment::hasEnv() to see if the value is an actual environment variable value or if the variable simply hasn't been set. @param string $name @return mixed Value of the environment variable, or false if not set
getEnv
php
silverstripe/silverstripe-framework
src/Core/Environment.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Environment.php
BSD-3-Clause
public static function setEnv($name, $value) { static::$env[$name] = $value; }
Set environment variable via $name / $value pair @param string $name @param string $value
setEnv
php
silverstripe/silverstripe-framework
src/Core/Environment.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Environment.php
BSD-3-Clause
public static function isCli() { if (Environment::$isCliOverride !== null) { return Environment::$isCliOverride; } return in_array(strtolower(php_sapi_name() ?? ''), ['cli', 'phpdbg']); }
Returns true if this script is being run from the command line rather than the web server @return bool
isCli
php
silverstripe/silverstripe-framework
src/Core/Environment.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Environment.php
BSD-3-Clause
protected function registerExtraMethodCallback($name, $callback) { if (!isset($this->extra_method_registers[$name])) { $this->extra_method_registers[$name] = $callback; } }
Register an callback to invoke that defines extra methods @param string $name @param callable $callback
registerExtraMethodCallback
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
public function hasMethod($method) { return method_exists($this, $method ?? '') || $this->hasCustomMethod($method); }
Return TRUE if a method exists on this object This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions @param string $method @return bool
hasMethod
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
protected function getExtraMethodConfig($method) { if (empty($method)) { return null; } // Lazy define methods $lowerClass = strtolower(static::class); if (!isset(self::class::$extra_methods[$lowerClass])) { $this->defineMethods(); } return self::class::$extra_methods[$lowerClass][strtolower($method)] ?? null; }
Get meta-data details on a named method @param string $method @return array List of custom method details, if defined for this method
getExtraMethodConfig
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
public function allMethodNames($custom = false) { $methods = static::findBuiltInMethods(); // Query extra methods $lowerClass = strtolower(static::class); if ($custom && isset(self::class::$extra_methods[$lowerClass])) { $methods = array_merge(self::class::$extra_methods[$lowerClass], $methods); } return $methods; }
Return the names of all the methods available on this object @param bool $custom include methods added dynamically at runtime @return array Map of method names with lowercase keys
allMethodNames
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
protected function addMethodsFrom($property, $index = null) { $class = static::class; $object = ($index !== null) ? $this->{$property}[$index] : $this->$property; if (!$object) { throw new InvalidArgumentException( "Object->addMethodsFrom(): could not add methods from {$class}->{$property}[$index]" ); } $methods = $this->findMethodsFrom($object); if (!$methods) { return; } $methodInfo = [ 'property' => $property, 'index' => $index, ]; $newMethods = array_fill_keys(array_keys($methods), $methodInfo); // Merge with extra_methods $lowerClass = strtolower($class); if (isset(self::class::$extra_methods[$lowerClass])) { self::class::$extra_methods[$lowerClass] = array_merge(self::class::$extra_methods[$lowerClass], $newMethods); } else { self::class::$extra_methods[$lowerClass] = $newMethods; } }
Add all the methods from an object property. @param string $property the property name @param string|int $index an index to use if the property is an array @throws InvalidArgumentException
addMethodsFrom
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
protected function addWrapperMethod($method, $wrap) { self::class::$extra_methods[strtolower(static::class)][strtolower($method)] = [ 'wrap' => $wrap, 'method' => $method ]; }
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x) @param string $method the method name to wrap @param string $wrap the method name to wrap to
addWrapperMethod
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
protected function addCallbackMethod($method, $callback) { self::class::$extra_methods[strtolower(static::class)][strtolower($method)] = [ 'callback' => $callback, ]; }
Add callback as a method. @param string $method Name of method @param callable $callback Callback to invoke. Note: $this is passed as first parameter to this callback and then $args as array
addCallbackMethod
php
silverstripe/silverstripe-framework
src/Core/CustomMethods.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CustomMethods.php
BSD-3-Clause
public static function getTempFolder($base) { $parent = static::getTempParentFolder($base); // The actual temp folder is a subfolder of getTempParentFolder(), named by username $subfolder = Path::join($parent, static::getTempFolderUsername()); if (!@file_exists($subfolder ?? '')) { mkdir($subfolder ?? ''); } return $subfolder; }
Returns the temporary folder path that silverstripe should use for its cache files. @param string $base The base path to use for determining the temporary path @return string Path to temp
getTempFolder
php
silverstripe/silverstripe-framework
src/Core/TempFolder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/TempFolder.php
BSD-3-Clause
public static function getTempFolderUsername() { $user = ''; if (function_exists('posix_getpwuid') && function_exists('posix_getuid')) { $userDetails = posix_getpwuid(posix_getuid()); $user = $userDetails['name'] ?? false; } if (!$user) { $user = Environment::getEnv('APACHE_RUN_USER'); } if (!$user) { $user = Environment::getEnv('USER'); } if (!$user) { $user = Environment::getEnv('USERNAME'); } if (!$user) { $user = 'unknown'; } $user = preg_replace('/[^A-Za-z0-9_\-]/', '', $user ?? ''); return $user; }
Returns as best a representation of the current username as we can glean. @return string
getTempFolderUsername
php
silverstripe/silverstripe-framework
src/Core/TempFolder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/TempFolder.php
BSD-3-Clause
protected static function getTempParentFolder($base) { // first, try finding a silverstripe-cache dir built off the base path $localPath = Path::join($base, 'silverstripe-cache'); if (@file_exists($localPath ?? '')) { if ((fileperms($localPath ?? '') & 0777) != 0777) { @chmod($localPath ?? '', 0777); } return $localPath; } // failing the above, try finding a namespaced silverstripe-cache dir in the system temp $tempPath = Path::join( sys_get_temp_dir(), 'silverstripe-cache-php' . preg_replace('/[^\w\-\.+]+/', '-', PHP_VERSION) . str_replace([' ', '/', ':', '\\'], '-', $base ?? '') ); if (!@file_exists($tempPath ?? '')) { $oldUMask = umask(0); @mkdir($tempPath ?? '', 0777); umask($oldUMask); // if the folder already exists, correct perms } else { if ((fileperms($tempPath ?? '') & 0777) != 0777) { @chmod($tempPath ?? '', 0777); } } $worked = @file_exists($tempPath ?? '') && @is_writable($tempPath ?? ''); // failing to use the system path, attempt to create a local silverstripe-cache dir if (!$worked) { $tempPath = $localPath; if (!@file_exists($tempPath ?? '')) { $oldUMask = umask(0); @mkdir($tempPath ?? '', 0777); umask($oldUMask); } $worked = @file_exists($tempPath ?? '') && @is_writable($tempPath ?? ''); } if (!$worked) { throw new Exception( 'Permission problem gaining access to a temp folder. ' . 'Please create a folder named silverstripe-cache in the base folder ' . 'of the installation and ensure it has the correct permissions' ); } return $tempPath; }
Return the parent folder of the temp folder. The temp folder will be a subfolder of this, named by username. This structure prevents permission problems. @param string $base @return string @throws Exception
getTempParentFolder
php
silverstripe/silverstripe-framework
src/Core/TempFolder.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/TempFolder.php
BSD-3-Clause
public static function exists($class) { return class_exists($class ?? '', false) || interface_exists($class ?? '', false) || ClassLoader::inst()->getItemPath($class); }
Returns true if a class or interface name exists. @param string $class @return bool
exists
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function hasTable($tableName) { $cache = ClassInfo::getCache(); $configData = serialize(DB::getConfig()); $cacheKey = 'tableList_' . md5($configData); $tableList = $cache->get($cacheKey) ?? []; if (empty($tableList) && DB::is_active()) { $tableList = DB::get_schema()->tableList(); // Cache the list of all table names to reduce on DB traffic $cache->set($cacheKey, $tableList); } return !empty($tableList[strtolower($tableName)]); }
Cached call to see if the table exists in the DB. For live queries, use DBSchemaManager::hasTable. @param string $tableName @return bool
hasTable
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function getValidSubClasses($class = SiteTree::class, $includeUnbacked = false) { if (is_string($class) && !class_exists($class ?? '')) { return []; } $class = ClassInfo::class_name($class); if ($includeUnbacked) { $table = DataObject::getSchema()->tableName($class); $classes = DB::get_schema()->enumValuesForField($table, 'ClassName'); } else { $classes = static::subclassesFor($class); } return $classes; }
Returns the manifest of all classes which are present in the database. @param string $class Class name to check enum values for ClassName field @param boolean $includeUnbacked Flag indicating whether or not to include types that don't exist as implemented classes. By default these are excluded. @return array List of subclasses
getValidSubClasses
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function dataClassesFor($nameOrObject) { if (is_string($nameOrObject) && !class_exists($nameOrObject ?? '')) { return []; } // Get all classes $class = ClassInfo::class_name($nameOrObject); $classes = array_merge( ClassInfo::ancestry($class), ClassInfo::subclassesFor($class) ); // Filter by table return array_filter($classes ?? [], function ($next) { return DataObject::getSchema()->classHasTable($next); }); }
Returns an array of the current class and all its ancestors and children which require a DB table. @param string|object $nameOrObject Class or object instance @return array
dataClassesFor
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function class_name($nameOrObject) { if (is_object($nameOrObject)) { return get_class($nameOrObject); } $key = strtolower($nameOrObject ?? ''); if (!isset(static::$_cache_class_names[$key])) { // Get manifest name $name = ClassLoader::inst()->getManifest()->getItemName($nameOrObject); // Use reflection for non-manifest classes if (!$name) { $reflection = new ReflectionClass($nameOrObject); $name = $reflection->getName(); } static::$_cache_class_names[$key] = $name; } return static::$_cache_class_names[$key]; }
Convert a class name in any case and return it as it was defined in PHP eg: ClassInfo::class_name('dataobJEct'); //returns 'DataObject' @param string|object $nameOrObject The classname or object you want to normalise @throws \ReflectionException @return string The normalised class name
class_name
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function classImplements($className, $interfaceName) { $lowerClassName = strtolower($className ?? ''); $implementors = ClassInfo::implementorsOf($interfaceName); return isset($implementors[$lowerClassName]); }
Returns true if the given class implements the given interface @param string $className @param string $interfaceName @return bool
classImplements
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function classes_for_file($filePath) { $absFilePath = Convert::slashes(Director::getAbsFile($filePath)); $classManifest = ClassLoader::inst()->getManifest(); $classes = $classManifest->getClasses(); $classNames = $classManifest->getClassNames(); $matchedClasses = []; foreach ($classes as $lowerClass => $compareFilePath) { if (strcasecmp($absFilePath, Convert::slashes($compareFilePath ?? '')) === 0) { $matchedClasses[$lowerClass] = $classNames[$lowerClass]; } } return $matchedClasses; }
Get all classes contained in a file. @param string $filePath Path to a PHP file (absolute or relative to webroot) @return array Map of lowercase class names to correct class name
classes_for_file
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function classes_for_folder($folderPath) { $absFolderPath = Convert::slashes(Director::getAbsFile($folderPath)); $classManifest = ClassLoader::inst()->getManifest(); $classes = $classManifest->getClasses(); $classNames = $classManifest->getClassNames(); $matchedClasses = []; foreach ($classes as $lowerClass => $compareFilePath) { if (stripos(Convert::slashes($compareFilePath ?? ''), $absFolderPath) === 0) { $matchedClasses[$lowerClass] = $classNames[$lowerClass]; } } return $matchedClasses; }
Returns all classes contained in a certain folder. @param string $folderPath Relative or absolute folder path @return array Map of lowercase class names to correct class name
classes_for_folder
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function has_method_from($class, $method, $compclass) { $lClass = strtolower($class ?? ''); $lMethod = strtolower($method ?? ''); $lCompclass = strtolower($compclass ?? ''); if (!isset(ClassInfo::$_cache_methods[$lClass])) { ClassInfo::$_cache_methods[$lClass] = []; } if (!array_key_exists($lMethod, ClassInfo::$_cache_methods[$lClass] ?? [])) { ClassInfo::$_cache_methods[$lClass][$lMethod] = false; $classRef = new ReflectionClass($class); if ($classRef->hasMethod($method)) { $methodRef = $classRef->getMethod($method); ClassInfo::$_cache_methods[$lClass][$lMethod] = $methodRef->getDeclaringClass()->getName(); } } return strtolower(ClassInfo::$_cache_methods[$lClass][$lMethod] ?? '') === $lCompclass; }
Determine if the given class method is implemented at the given comparison class @param string $class Class to get methods from @param string $method Method name to lookup @param string $compclass Parent class to test if this is the implementor @return bool True if $class::$method is declared in $compclass
has_method_from
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
public static function hasMethod($object, $method) { if (empty($object) || (!is_object($object) && !is_string($object))) { return false; } if (method_exists($object, $method ?? '')) { return true; } return method_exists($object, 'hasMethod') && $object->hasMethod($method); }
Helper to determine if the given object has a method @param object $object @param string $method @return bool
hasMethod
php
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/ClassInfo.php
BSD-3-Clause
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', array_filter($parts ?? []))); $fullPath = static::normalise(implode(DIRECTORY_SEPARATOR, $parts)); // Protect against directory traversal vulnerability (OTG-AUTHZ-001) if ($fullPath === '..' || str_ends_with($fullPath, '/..') || str_contains($fullPath, '../')) { 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)
join
php
silverstripe/silverstripe-framework
src/Core/Path.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Path.php
BSD-3-Clause
public static function normalise($path, $relative = false) { $path = trim(Convert::slashes($path) ?? ''); if ($relative) { return trim($path ?? '', Path::TRIM_CHARS ?? ''); } else { return rtrim($path ?? '', Path::TRIM_CHARS ?? ''); } }
Normalise absolute or relative filesystem path. Important: Single slashes are converted to empty strings (empty relative paths) @param string $path Input path @param bool $relative @return string Path with no trailing slash. If $relative is true, also trim leading slashes
normalise
php
silverstripe/silverstripe-framework
src/Core/Path.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Path.php
BSD-3-Clause
public static function add_to_class($class, $extensionClass, $args = null) { // NOP }
Called when this extension is added to a particular class @param string $class @param string $extensionClass @param mixed $args
add_to_class
php
silverstripe/silverstripe-framework
src/Core/Extension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extension.php
BSD-3-Clause
public function setOwner($owner) { $this->ownerStack[] = $this->owner; $this->owner = $owner; }
Set the owner of this extension. @param object $owner The owner object
setOwner
php
silverstripe/silverstripe-framework
src/Core/Extension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extension.php
BSD-3-Clause
public function clearOwner() { if (empty($this->ownerStack)) { throw new BadMethodCallException("clearOwner() called more than setOwner()"); } $this->owner = array_pop($this->ownerStack); }
Clear the current owner, and restore extension to the state prior to the last setOwner()
clearOwner
php
silverstripe/silverstripe-framework
src/Core/Extension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extension.php
BSD-3-Clause
public static function get_classname_without_arguments($extensionStr) { // Split out both args and service name return strtok(strtok($extensionStr ?? '', '(') ?? '', '.'); }
Helper method to strip eval'ed arguments from a string that's passed to {@link DataObject::$extensions} or {@link Object::add_extension()}. @param string $extensionStr E.g. "Versioned('Stage','Live')" @return string Extension classname, e.g. "Versioned"
get_classname_without_arguments
php
silverstripe/silverstripe-framework
src/Core/Extension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Extension.php
BSD-3-Clause
protected function validateDatabase() { if (!$this->bootDatabase) { return; } $databaseConfig = DB::getConfig(); // Gracefully fail if no DB is configured if (empty($databaseConfig['database'])) { $msg = 'Silverstripe Framework requires a "database" key in DB::getConfig(). ' . 'Did you forget to set SS_DATABASE_NAME or SS_DATABASE_CHOOSE_NAME in your environment?'; $this->detectLegacyEnvironment(); Deprecation::withSuppressedNotice(fn() => $this->redirectToInstaller($msg)); } }
Check that the database configuration is valid, throwing an HTTPResponse_Exception if it's not @throws HTTPResponse_Exception
validateDatabase
php
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CoreKernel.php
BSD-3-Clause
protected function bootDatabaseGlobals() { if (!$this->bootDatabase) { return; } // Now that configs have been loaded, we can check global for database config global $databaseConfig; global $database; // Case 1: $databaseConfig global exists. Merge $database in as needed if (!empty($databaseConfig)) { if (!empty($database)) { $databaseConfig['database'] = $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix(); } // Only set it if its valid, otherwise ignore $databaseConfig entirely if (!empty($databaseConfig['database'])) { DB::setConfig($databaseConfig); return; } } // Case 2: $database merged into existing config if (!empty($database)) { $existing = DB::getConfig(); $existing['database'] = $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix(); DB::setConfig($existing); } }
Load default database configuration from the $database and $databaseConfig globals
bootDatabaseGlobals
php
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CoreKernel.php
BSD-3-Clause
protected function bootDatabaseEnvVars() { if (!$this->bootDatabase) { return; } // Set default database config $databaseConfig = $this->getDatabaseConfig(); $databaseConfig['database'] = $this->getDatabaseName(); DB::setConfig($databaseConfig); }
Load default database configuration from environment variable
bootDatabaseEnvVars
php
silverstripe/silverstripe-framework
src/Core/CoreKernel.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/CoreKernel.php
BSD-3-Clause
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
createRoot
php
silverstripe/silverstripe-framework
src/Core/Config/CoreConfigFactory.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/CoreConfigFactory.php
BSD-3-Clause
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
createCore
php
silverstripe/silverstripe-framework
src/Core/Config/CoreConfigFactory.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/CoreConfigFactory.php
BSD-3-Clause
public function getManifest() { if ($this !== ConfigLoader::$instance) { throw new BadMethodCallException( "Non-current config manifest cannot be accessed. Please call ->activate() first" ); } if (empty($this->manifests)) { throw new BadMethodCallException("No config manifests available"); } return $this->manifests[count($this->manifests) - 1]; }
Returns the currently active class manifest instance that is used for loading classes. @return ConfigCollectionInterface
getManifest
php
silverstripe/silverstripe-framework
src/Core/Config/ConfigLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/ConfigLoader.php
BSD-3-Clause
public function hasManifest() { return (bool)$this->manifests; }
Returns true if this class loader has a manifest. @return bool
hasManifest
php
silverstripe/silverstripe-framework
src/Core/Config/ConfigLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/ConfigLoader.php
BSD-3-Clause
public function pushManifest(ConfigCollectionInterface $manifest) { $this->manifests[] = $manifest; }
Pushes a class manifest instance onto the top of the stack. @param ConfigCollectionInterface $manifest
pushManifest
php
silverstripe/silverstripe-framework
src/Core/Config/ConfigLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/ConfigLoader.php
BSD-3-Clause
public function nest() { // Nest config $manifest = clone $this->getManifest(); // Create new blank loader with new stack (top level nesting) $newLoader = new static; $newLoader->pushManifest($manifest); // Activate new loader return $newLoader->activate(); }
Nest the config loader and activates it @return static
nest
php
silverstripe/silverstripe-framework
src/Core/Config/ConfigLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/ConfigLoader.php
BSD-3-Clause
public function activate() { static::$instance = $this; return $this; }
Mark this instance as the current instance @return $this
activate
php
silverstripe/silverstripe-framework
src/Core/Config/ConfigLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/ConfigLoader.php
BSD-3-Clause
public static function inst() { return ConfigLoader::inst()->getManifest(); }
Get the current active Config instance. In general use you will use this method to obtain the current Config instance. It assumes the config instance has already been set. @return ConfigCollectionInterface
inst
php
silverstripe/silverstripe-framework
src/Core/Config/Config.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Config.php
BSD-3-Clause
public static function modify() { $instance = static::inst(); if ($instance instanceof MutableConfigCollectionInterface) { return $instance; } // By default nested configs should become mutable $instance = static::nest(); if ($instance instanceof MutableConfigCollectionInterface) { return $instance; } throw new InvalidArgumentException("Nested config could not be made mutable"); }
Make this config available to be modified @return MutableConfigCollectionInterface
modify
php
silverstripe/silverstripe-framework
src/Core/Config/Config.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Config.php
BSD-3-Clause
public static function nest() { // Clone current config and nest $new = Config::inst()->nest(); ConfigLoader::inst()->pushManifest($new); return $new; }
Make the newly active {@link Config} be a copy of the current active {@link Config} instance. You can then make changes to the configuration by calling update and remove on the new value returned by {@link Config::inst()}, and then discard those changes later by calling unnest. @return ConfigCollectionInterface Active config
nest
php
silverstripe/silverstripe-framework
src/Core/Config/Config.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Config.php
BSD-3-Clause
public static function unnest() { // Unnest unless we would be left at 0 manifests $loader = ConfigLoader::inst(); if ($loader->countManifests() <= 1) { user_error( "Unable to unnest root Config, please make sure you don't have mis-matched nest/unnest", E_USER_WARNING ); } else { $loader->popManifest(); } return static::inst(); }
Change the active Config back to the Config instance the current active Config object was copied from. @return ConfigCollectionInterface
unnest
php
silverstripe/silverstripe-framework
src/Core/Config/Config.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Config.php
BSD-3-Clause
public static function forClass($class) { return new Config_ForClass($class); }
Get an accessor that returns results by class by default. Shouldn't be overridden, since there might be many Config_ForClass instances already held in the wild. Each Config_ForClass instance asks the current_instance of Config for the actual result, so override that instead @param string $class @return Config_ForClass
forClass
php
silverstripe/silverstripe-framework
src/Core/Config/Config.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Config.php
BSD-3-Clause
public static function config() { return Config::forClass(get_called_class()); }
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....). @return Config_ForClass
config
php
silverstripe/silverstripe-framework
src/Core/Config/Configurable.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Configurable.php
BSD-3-Clause
public function uninherited($name) { return $this->config()->uninherited($name); }
Gets the uninherited value for the given config option @param string $name @return mixed
uninherited
php
silverstripe/silverstripe-framework
src/Core/Config/Configurable.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Config/Configurable.php
BSD-3-Clause
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
hit
php
silverstripe/silverstripe-framework
src/Core/Cache/RateLimiter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Cache/RateLimiter.php
BSD-3-Clause
public function create($service, array $params = []) { // Override default cache generation with SS_MANIFESTCACHE $cacheClass = Environment::getEnv('SS_MANIFESTCACHE'); $params['useInjector'] = false; if (!$cacheClass) { return parent::create($service, $params); } // Check if SS_MANIFESTCACHE is a factory if (is_a($cacheClass, CacheFactory::class, true)) { /** @var CacheFactory $factory */ $factory = new $cacheClass; return $factory->create($service, $params); } // Check if SS_MANIFESTCACHE is a PSR-6 or PSR-16 class if (is_a($cacheClass, CacheItemPoolInterface::class, true) || is_a($cacheClass, CacheInterface::class, true) ) { $args = array_merge($this->args, $params); $namespace = isset($args['namespace']) ? $args['namespace'] : ''; return $this->createCache($cacheClass, [$namespace], false); } // Validate type throw new BadMethodCallException( 'SS_MANIFESTCACHE is not a valid CacheInterface, CacheItemPoolInterface or CacheFactory class name' ); }
Note: While the returned object is used as a singleton (by the originating Injector->get() call), this cache object shouldn't be a singleton itself - it has varying constructor args for the same service name. @param string $service The class name of the service. @param array $params The constructor parameters. @return CacheInterface
create
php
silverstripe/silverstripe-framework
src/Core/Cache/ManifestCacheFactory.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Cache/ManifestCacheFactory.php
BSD-3-Clause
protected function isAPCUSupported() { Deprecation::noticeWithNoReplacment('5.4.0'); static $apcuSupported = null; if (null === $apcuSupported) { // Need to check for CLI because Symfony won't: https://github.com/symfony/symfony/pull/25080 $apcuSupported = Director::is_cli() ? filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOL) && ApcuAdapter::isSupported() : ApcuAdapter::isSupported(); } return $apcuSupported; }
Determine if apcu is supported @return bool @deprecated 5.4.0 Will be removed without equivalent functionality to replace it.
isAPCUSupported
php
silverstripe/silverstripe-framework
src/Core/Cache/DefaultCacheFactory.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Cache/DefaultCacheFactory.php
BSD-3-Clause
protected function isPHPFilesSupported() { static $phpFilesSupported = null; if (null === $phpFilesSupported) { $phpFilesSupported = PhpFilesAdapter::isSupported(); } return $phpFilesSupported; }
Determine if PHP files is supported @return bool
isPHPFilesSupported
php
silverstripe/silverstripe-framework
src/Core/Cache/DefaultCacheFactory.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Cache/DefaultCacheFactory.php
BSD-3-Clause
protected function getCacheTimestamp() { $classLoader = $this->kernel->getClassLoader(); $classManifest = $classLoader->getManifest(); $cacheTimestamp = $classManifest->getManifestTimestamp(); return $cacheTimestamp; }
Returns the timestamp of the manifest generation or null if no cache has been found (or couldn't read the cache) @return int|null unix timestamp
getCacheTimestamp
php
silverstripe/silverstripe-framework
src/Core/Startup/DeployFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/DeployFlushDiscoverer.php
BSD-3-Clause
protected function getDeployResource() { $resource = Environment::getEnv('SS_FLUSH_ON_DEPLOY'); if ($resource === false) { return null; } if ($resource === true) { $path = __FILE__; } else { $path = sprintf("%s/%s", BASE_PATH, $resource); } return $path; }
Returns the resource to be checked for deployment - if the environment variable SS_FLUSH_ON_DEPLOY undefined or false, then returns null - if SS_FLUSH_ON_DEPLOY is true, then takes __FILE__ as the resource to check - otherwise takes {BASE_PATH/SS_FLUSH_ON_DEPLOY} as the resource to check @return string|null returns the resource path or null if not set
getDeployResource
php
silverstripe/silverstripe-framework
src/Core/Startup/DeployFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/DeployFlushDiscoverer.php
BSD-3-Clause
protected function getDeployTimestamp($resource) { if (!file_exists($resource ?? '')) { return 0; } return max(filemtime($resource ?? ''), filectime($resource ?? '')); }
Returns the resource modification timestamp @param string $resource Path to the filesystem @return int
getDeployTimestamp
php
silverstripe/silverstripe-framework
src/Core/Startup/DeployFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/DeployFlushDiscoverer.php
BSD-3-Clause
public function __construct(HTTPRequest $request, $env) { $this->env = $env; $this->request = $request; }
Initialize it with active Request and Kernel @param HTTPRequest $request instance of the request (session is not initialized yet!) @param string $env Environment type (dev, test or live)
__construct
php
silverstripe/silverstripe-framework
src/Core/Startup/RequestFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/RequestFlushDiscoverer.php
BSD-3-Clause
protected function lookupRequest() { $request = $this->request; $getVar = array_key_exists('flush', $request->getVars() ?? []); $devBuild = $request->getURL() === 'dev/build'; // WARNING! // We specifically return `null` and not `false` here so that // it does not override other FlushDiscoverers return ($getVar || $devBuild) ? true : null; }
Checks whether the request contains any flush indicators @return null|bool flush or don't care
lookupRequest
php
silverstripe/silverstripe-framework
src/Core/Startup/RequestFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/RequestFlushDiscoverer.php
BSD-3-Clause
protected function isAllowed() { // WARNING! // We specifically return `null` and not `false` here so that // it does not override other FlushDiscoverers return (Environment::isCli() || $this->env === Kernel::DEV) ? true : null; }
Checks for permission to flush Startup flush through a request is only allowed to CLI or DEV modes for security reasons @return bool|null true for allow, false for denying, or null if don't care
isAllowed
php
silverstripe/silverstripe-framework
src/Core/Startup/RequestFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/RequestFlushDiscoverer.php
BSD-3-Clause
protected function getFlush() { $classLoader = $this->kernel->getClassLoader(); $classManifest = $classLoader->getManifest(); return (bool) $classManifest->isFlushScheduled(); }
Returns the flag whether the manifest flush has been scheduled in previous requests @return bool unix timestamp
getFlush
php
silverstripe/silverstripe-framework
src/Core/Startup/ScheduledFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/ScheduledFlushDiscoverer.php
BSD-3-Clause
public static function scheduleFlush(Kernel $kernel) { $classLoader = $kernel->getClassLoader(); $classManifest = $classLoader->getManifest(); if (!$classManifest->isFlushScheduled()) { $classManifest->scheduleFlush(); return true; } return false; }
@internal This method is not a part of public API and will be deleted without a deprecation warning This method is here so that scheduleFlush functionality implementation is kept close to the check implementation.
scheduleFlush
php
silverstripe/silverstripe-framework
src/Core/Startup/ScheduledFlushDiscoverer.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Startup/ScheduledFlushDiscoverer.php
BSD-3-Clause
public static function getModule($module) { return static::inst()->getManifest()->getModule($module); }
Get module by name from the current manifest. Alias for ::inst()->getManifest()->getModule() @param string $module @return Module
getModule
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleLoader.php
BSD-3-Clause
public function getManifest() { return $this->manifests[count($this->manifests) - 1]; }
Returns the currently active class manifest instance that is used for loading classes. @return ModuleManifest
getManifest
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleLoader.php
BSD-3-Clause
public function pushManifest(ModuleManifest $manifest) { $this->manifests[] = $manifest; }
Pushes a module manifest instance onto the top of the stack. @param ModuleManifest $manifest
pushManifest
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleLoader.php
BSD-3-Clause
public function resolvePath($resource) { // Skip blank resources if (empty($resource)) { return null; } $resourceObj = $this->resolveResource($resource); if ($resourceObj instanceof ModuleResource) { return $resourceObj->getRelativePath(); } return $resource; }
Convert a file of the form "vendor/package:resource" into a BASE_PATH-relative file or folder For other files, return original value @param string $resource @return string|null
resolvePath
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleResourceLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleResourceLoader.php
BSD-3-Clause
public function resolveURL($resource) { // Skip blank resources if (empty($resource)) { return null; } // Resolve resource to reference $resource = $this->resolveResource($resource); // Resolve resource to url $generator = Injector::inst()->get(ResourceURLGenerator::class); return $generator->urlForResource($resource); }
Resolves resource specifier to the given url. @param string $resource @return string|null
resolveURL
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleResourceLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleResourceLoader.php
BSD-3-Clause
public static function resourcePath($resource) { return static::singleton()->resolvePath($resource); }
Template wrapper for resolvePath @param string $resource @return string|null
resourcePath
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleResourceLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleResourceLoader.php
BSD-3-Clause
public static function resourceURL($resource) { return static::singleton()->resolveURL($resource); }
Template wrapper for resolveURL @param string $resource @return string|null
resourceURL
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleResourceLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleResourceLoader.php
BSD-3-Clause
public function resolveResource($resource) { // String of the form vendor/package:resource. Excludes "http://bla" as that's an absolute URL if (!preg_match('#^ *(?<module>[^/: ]+/[^/: ]+) *: *(?<resource>[^ ]*)$#', $resource ?? '', $matches)) { return $resource; } $module = $matches['module']; $resource = $matches['resource']; $moduleObj = ModuleLoader::getModule($module); if (!$moduleObj) { throw new InvalidArgumentException("Can't find module '$module', the composer.json file may be missing from the modules installation directory"); } $resourceObj = $moduleObj->getResource($resource); return $resourceObj; }
Return module resource for the given path, if specified as one. Returns the original resource otherwise. @param string $resource @return ModuleResource|string The resource (or directory), or input string if not a module resource
resolveResource
php
silverstripe/silverstripe-framework
src/Core/Manifest/ModuleResourceLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Core/Manifest/ModuleResourceLoader.php
BSD-3-Clause