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 currentTestEnablesDatabase() { $annotations = $this->getAnnotations(); return array_key_exists('useDatabase', $annotations['method'] ?? []) && $annotations['method']['useDatabase'][0] !== 'false'; }
Helper method to check, if the current test uses the database. This can be switched on with the annotation "@useDatabase" @return bool
currentTestEnablesDatabase
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function currentTestDisablesDatabase() { $annotations = $this->getAnnotations(); return array_key_exists('useDatabase', $annotations['method'] ?? []) && $annotations['method']['useDatabase'][0] === 'false'; }
Helper method to check, if the current test uses the database. This can be switched on with the annotation "@useDatabase false" @return bool
currentTestDisablesDatabase
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function idFromFixture($className, $identifier) { /** @var FixtureTestState $state */ $state = static::$state->getStateByName('fixtures'); $id = $state->getFixtureFactory(static::class)->getId($className, $identifier); if (!$id) { throw new InvalidArgumentException(sprintf( "Couldn't find object '%s' (class: %s)", $identifier, $className )); } return $id; }
Get the ID of an object from the fixture. @param string $className The data class or table name, as specified in your fixture file. Parent classes won't work @param string $identifier The identifier string, as provided in your fixture file @return int
idFromFixture
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function allFixtureIDs($className) { /** @var FixtureTestState $state */ $state = static::$state->getStateByName('fixtures'); return $state->getFixtureFactory(static::class)->getIds($className); }
Return all of the IDs in the fixture of a particular class name. Will collate all IDs form all fixtures if multiple fixtures are provided. @param string $className The data class or table name, as specified in your fixture file @return array A map of fixture-identifier => object-id
allFixtureIDs
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function objFromFixture($className, $identifier) { /** @var FixtureTestState $state */ $state = static::$state->getStateByName('fixtures'); $obj = $state->getFixtureFactory(static::class)->get($className, $identifier); if (!$obj) { throw new InvalidArgumentException(sprintf( "Couldn't find object '%s' (class: %s)", $identifier, $className )); } return $obj; }
Get an object from the fixture. @template T of DataObject @param class-string<T> $className The data class or table name, as specified in your fixture file. Parent classes won't work @param string $identifier The identifier string, as provided in your fixture file @return T
objFromFixture
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function getCurrentAbsolutePath() { $filename = ClassLoader::inst()->getItemPath(static::class); if (!$filename) { throw new LogicException('getItemPath returned null for ' . static::class . '. Try adding flush=1 to the test run.'); } return dirname($filename ?? ''); }
Useful for writing unit tests without hardcoding folder structures. @return string Absolute path to current class.
getCurrentAbsolutePath
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function findEmail($to, $from = null, $subject = null, $content = null) { $mailer = Injector::inst()->get(MailerInterface::class); if ($mailer instanceof TestMailer) { return $mailer->findEmail($to, $from, $subject, $content); } return null; }
Search for an email that was sent. All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression. @param string $to @param string $from @param string $subject @param string $content @return array|null Contains keys: 'Type', 'To', 'From', 'Subject', 'Content', 'PlainContent', 'AttachedFiles', 'HtmlContent'
findEmail
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function assertEmailSent($to, $from = null, $subject = null, $content = null) { $found = (bool)static::findEmail($to, $from, $subject, $content); $infoParts = ''; $withParts = []; if ($to) { $infoParts .= " to '$to'"; } if ($from) { $infoParts .= " from '$from'"; } if ($subject) { $withParts[] = "subject '$subject'"; } if ($content) { $withParts[] = "content '$content'"; } if ($withParts) { $infoParts .= ' with ' . implode(' and ', $withParts); } static::assertTrue( $found, "Failed asserting that an email was sent$infoParts." ); }
Assert that the matching email was sent since the last call to clearEmails() All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression. @param string $to @param string $from @param string $subject @param string $content
assertEmailSent
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected static function normaliseSQL($sql) { return trim(preg_replace('/\s+/m', ' ', $sql ?? '') ?? ''); }
Removes sequences of repeated whitespace characters from SQL queries making them suitable for string comparison @param string $sql @return string The cleaned and normalised SQL string
normaliseSQL
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function assertSQLEquals( $expectedSQL, $actualSQL, $message = '' ) { // Normalise SQL queries to remove patterns of repeating whitespace $expectedSQL = static::normaliseSQL($expectedSQL); $actualSQL = static::normaliseSQL($actualSQL); static::assertEquals($expectedSQL, $actualSQL, $message); }
Asserts that two SQL queries are equivalent @param string $expectedSQL @param string $actualSQL @param string $message
assertSQLEquals
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function assertSQLContains( $needleSQL, $haystackSQL, $message = '' ) { $needleSQL = static::normaliseSQL($needleSQL); $haystackSQL = static::normaliseSQL($haystackSQL); if (is_iterable($haystackSQL)) { /** @var iterable $iterableHaystackSQL */ $iterableHaystackSQL = $haystackSQL; static::assertContains($needleSQL, $iterableHaystackSQL, $message); } else { static::assertStringContainsString($needleSQL, $haystackSQL, $message); } }
Asserts that a SQL query contains a SQL fragment @param string $needleSQL @param string $haystackSQL @param string $message
assertSQLContains
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function resetDBSchema($includeExtraDataObjects = false, $forceCreate = false) { if (!static::$tempDB) { return; } // Check if DB is active before reset if (!static::$tempDB->isUsed()) { if (!$forceCreate) { return; } static::$tempDB->build(); } $extraDataObjects = $includeExtraDataObjects ? static::getExtraDataObjects() : []; static::$tempDB->resetDBSchema((array)$extraDataObjects); }
Reset the testing database's schema, but only if it is active @param bool $includeExtraDataObjects If true, the extraDataObjects tables will also be included @param bool $forceCreate Force DB to be created if it doesn't exist
resetDBSchema
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public function actWithPermission($permCode, $callback) { return Member::actAs($this->createMemberWithPermission($permCode), $callback); }
A wrapper for automatically performing callbacks as a user with a specific permission @param string|array $permCode @param callable $callback @return mixed
actWithPermission
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public function logInWithPermission($permCode = 'ADMIN') { $member = $this->createMemberWithPermission($permCode); $this->logInAs($member); return $member->ID; }
Create a member and group with the given permission code, and log in with it. Returns the member ID. @param string|array $permCode Either a permission, or list of permissions @return int Member ID
logInWithPermission
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function getFixturePaths() { $fixtureFile = static::get_fixture_file(); if (empty($fixtureFile)) { return []; } $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : [$fixtureFile]; return array_map(function ($fixtureFilePath) { return $this->resolveFixturePath($fixtureFilePath); }, $fixtureFiles ?? []); }
Get fixture paths for this test @return array List of paths
getFixturePaths
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function getExtraDataObjects() { return static::$extra_dataobjects; }
Return all extra objects to scaffold for this test @return array
getExtraDataObjects
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function getExtraControllers() { return static::$extra_controllers; }
Get additional controller classes to register routes for @return array
getExtraControllers
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
protected function resolveFixturePath($fixtureFilePath) { // support loading via composer name path. if (strpos($fixtureFilePath ?? '', ':') !== false) { return ModuleResourceLoader::singleton()->resolvePath($fixtureFilePath); } // Support fixture paths relative to the test class, rather than relative to webroot // String checking is faster than file_exists() calls. $resolvedPath = realpath($this->getCurrentAbsolutePath() . '/' . $fixtureFilePath); if ($resolvedPath) { return $resolvedPath; } // Check if file exists relative to base dir $resolvedPath = realpath(Director::baseFolder() . '/' . $fixtureFilePath); if ($resolvedPath) { return $resolvedPath; } return $fixtureFilePath; }
Map a fixture path to a physical file @param string $fixtureFilePath @return string
resolveFixturePath
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public static function createInvalidArgumentException($argument, $type, $value = null) { $stack = debug_backtrace(false); return new PHPUnitFrameworkException( sprintf( 'Argument #%d%sof %s::%s() must be a %s', $argument, $value !== null ? ' (' . gettype($value) . '#' . $value . ')' : ' (No Value) ', $stack[1]['class'], $stack[1]['function'], $type ) ); }
Reimplementation of phpunit5 PHPUnit_Util_InvalidArgumentHelper::factory() @param $argument @param $type @param $value
createInvalidArgumentException
php
silverstripe/silverstripe-framework
src/Dev/SapphireTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/SapphireTest.php
BSD-3-Clause
public function getBySelector($selector) { $xpath = $this->selector2xpath($selector); return $this->getByXpath($xpath); }
Returns a number of SimpleXML elements that match the given CSS selector. Currently the selector engine only supports querying by tag, id, and class. See {@link getByXpath()} for a more direct selector syntax. @param string $selector @return SimpleXMLElement[]
getBySelector
php
silverstripe/silverstripe-framework
src/Dev/CSSContentParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/CSSContentParser.php
BSD-3-Clause
public function getByXpath($xpath) { return $this->simpleXML->xpath($xpath); }
Allows querying the content through XPATH selectors. @param string $xpath SimpleXML compatible XPATH statement @return SimpleXMLElement[]
getByXpath
php
silverstripe/silverstripe-framework
src/Dev/CSSContentParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/CSSContentParser.php
BSD-3-Clause
public static function filtered_backtrace($ignoredFunctions = null) { return Backtrace::filter_backtrace(debug_backtrace(), $ignoredFunctions); }
Return debug_backtrace() results with functions filtered specific to the debugging system, and not the trace. @param null|array $ignoredFunctions If an array, filter these functions out of the trace @return array
filtered_backtrace
php
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Backtrace.php
BSD-3-Clause
public static function filter_backtrace($bt, $ignoredFunctions = null) { $defaultIgnoredFunctions = [ '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->renderTrace', 'SilverStripe\\Dev\\CliDebugView->renderTrace', '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(Backtrace::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($frame['class'])) { foreach ($ignoredArgs as $fnSpec) { if (is_array($fnSpec) && Backtrace::matchesFilterableClass($frame['class'], $fnSpec[0]) && $frame['function'] == $fnSpec[1] ) { $match = true; break; } } } else { if (in_array($frame['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_backtrace
php
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Backtrace.php
BSD-3-Clause
public static function backtrace($returnVal = false, $ignoreAjax = false, $ignoredFunctions = null) { $plainText = Director::is_cli() || (Director::is_ajax() && !$ignoreAjax); $result = Backtrace::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
backtrace
php
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Backtrace.php
BSD-3-Clause
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 = []; 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
full_func_name
php
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Backtrace.php
BSD-3-Clause
public static function get_rendered_backtrace($bt, $plainText = false, $ignoredFunctions = null) { if (empty($bt)) { return ''; } $bt = Backtrace::filter_backtrace($bt, $ignoredFunctions); $result = ($plainText) ? '' : '<ul>'; foreach ($bt as $item) { if ($plainText) { $result .= Backtrace::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 = Backtrace::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
get_rendered_backtrace
php
silverstripe/silverstripe-framework
src/Dev/Backtrace.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Backtrace.php
BSD-3-Clause
public function __construct(array $match) { Deprecation::noticeWithNoReplacment('5.4.0', 'Will be renamed to ModelDataContains', Deprecation::SCOPE_CLASS); if (!is_array($match)) { throw SapphireTest::createInvalidArgumentException( 1, 'array' ); } $this->match = $match; }
ViewableDataContains constructor.
__construct
php
silverstripe/silverstripe-framework
src/Dev/Constraint/ViewableDataContains.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Constraint/ViewableDataContains.php
BSD-3-Clause
protected function resolveFixturePath($fixtureFilePath, SapphireTest $test) { // Support fixture paths relative to the test class, rather than relative to webroot // String checking is faster than file_exists() calls. $resolvedPath = realpath($this->getTestAbsolutePath($test) . '/' . $fixtureFilePath); if ($resolvedPath) { return $resolvedPath; } // Check if file exists relative to base dir $resolvedPath = realpath(Director::baseFolder() . '/' . $fixtureFilePath); if ($resolvedPath) { return $resolvedPath; } return $fixtureFilePath; }
Map a fixture path to a physical file @param string $fixtureFilePath @param SapphireTest $test @return string
resolveFixturePath
php
silverstripe/silverstripe-framework
src/Dev/State/FixtureTestState.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/State/FixtureTestState.php
BSD-3-Clause
protected function getTestAbsolutePath(SapphireTest $test) { $class = get_class($test); $filename = ClassLoader::inst()->getItemPath($class); if (!$filename) { throw new LogicException('getItemPath returned null for ' . $class . '. Try adding flush=1 to the test run.'); } return dirname($filename ?? ''); }
Useful for writing unit tests without hardcoding folder structures. @param SapphireTest $test @return string Absolute path to current class.
getTestAbsolutePath
php
silverstripe/silverstripe-framework
src/Dev/State/FixtureTestState.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/State/FixtureTestState.php
BSD-3-Clause
protected function resetFixtureFactory($class) { $class = strtolower($class ?? ''); $this->fixtureFactories[$class] = Injector::inst()->create(FixtureFactory::class); $this->loaded[$class] = false; }
Bootstrap a clean fixture factory for the given class @param string $class
resetFixtureFactory
php
silverstripe/silverstripe-framework
src/Dev/State/FixtureTestState.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/State/FixtureTestState.php
BSD-3-Clause
protected function getIsLoaded($class) { return !empty($this->loaded[strtolower($class)]); }
Check if fixtures need to be loaded for this class @param string $class Name of test to check @return bool
getIsLoaded
php
silverstripe/silverstripe-framework
src/Dev/State/FixtureTestState.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/State/FixtureTestState.php
BSD-3-Clause
public static function register($config) { // Validate config $missing = array_diff(['title', 'class', 'helperClass', 'supported'], array_keys($config ?? [])); if ($missing) { throw new InvalidArgumentException( "Missing database helper config keys: '" . implode("', '", $missing) . "'" ); } // Guess missing module text if not given if (empty($config['missingModuleText'])) { if (empty($config['module'])) { $moduleText = 'Module for database connector ' . $config['title'] . 'is missing.'; } else { $moduleText = "The SilverStripe module '" . $config['module'] . "' is missing."; } $config['missingModuleText'] = $moduleText . ' Please install it via composer or from http://addons.silverstripe.org/.'; } // Set missing text if (empty($config['missingExtensionText'])) { $config['missingExtensionText'] = 'The PHP extension is missing, please enable or install it.'; } // set default fields if none are defined already if (!isset($config['fields'])) { $config['fields'] = DatabaseAdapterRegistry::$default_fields; } DatabaseAdapterRegistry::$adapters[$config['class']] = $config; }
Add new adapter to the registry @param array $config Associative array of configuration details. This must include: - title - class - helperClass - supported This SHOULD include: - fields - helperPath (if helperClass can't be autoloaded via psr-4/-0) - missingExtensionText - module OR missingModuleText
register
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
public static function unregister($class) { unset(DatabaseAdapterRegistry::$adapters[$class]); }
Unregisters a database connector by classname @param string $class
unregister
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
public static function autoconfigure(&$config = null) { $databaseConfig = $config; foreach (static::getConfigureDatabasePaths() as $configureDatabasePath) { include_once $configureDatabasePath; } // Update modified variable $config = $databaseConfig; }
Detects all _configure_database.php files and invokes them Called by ConfigureFromEnv.php. Searches through vendor/ folder only, does not support "legacy" folder location in webroot @param array $config Config to update. If not provided fall back to global $databaseConfig. In 5.0.0 this will be mandatory and the global will be removed.
autoconfigure
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
public static function get_adapters() { return DatabaseAdapterRegistry::$adapters; }
Return all registered adapters @return array
get_adapters
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
public static function get_adapter($class) { if (isset(DatabaseAdapterRegistry::$adapters[$class])) { return DatabaseAdapterRegistry::$adapters[$class]; } return null; }
Returns registry data for a class @param string $class @return array List of adapter properties
get_adapter
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
public static function get_default_fields() { return DatabaseAdapterRegistry::$default_fields; }
Retrieves default field configuration @return array
get_default_fields
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
public static function getDatabaseConfigurationHelper($databaseClass) { $adapters = static::get_adapters(); if (empty($adapters[$databaseClass]) || empty($adapters[$databaseClass]['helperClass'])) { return null; } // Load if path given if (isset($adapters[$databaseClass]['helperPath'])) { include_once $adapters[$databaseClass]['helperPath']; } // Construct $class = $adapters[$databaseClass]['helperClass']; return (class_exists($class ?? '')) ? new $class() : null; }
Build configuration helper for a given class @param string $databaseClass Name of class @return DatabaseConfigurationHelper|null Instance of helper, or null if cannot be loaded
getDatabaseConfigurationHelper
php
silverstripe/silverstripe-framework
src/Dev/Install/DatabaseAdapterRegistry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/DatabaseAdapterRegistry.php
BSD-3-Clause
protected function createConnection($databaseConfig, &$error) { $error = null; try { switch ($databaseConfig['type']) { case 'MySQLDatabase': $conn = mysqli_init(); // Set SSL parameters if they exist. // Must have both the SSL cert and key, or the common authority, or preferably all three. if ((array_key_exists('ssl_key', $databaseConfig) && array_key_exists('ssl_cert', $databaseConfig)) || array_key_exists('ssl_ca', $databaseConfig) ) { $conn->ssl_set( $databaseConfig['ssl_key'] ?? null, $databaseConfig['ssl_cert'] ?? null, $databaseConfig['ssl_ca'] ?? null, dirname($databaseConfig['ssl_ca']), array_key_exists('ssl_cipher', $databaseConfig) ? $databaseConfig['ssl_cipher'] : Config::inst()->get(MySQLiConnector::class, 'ssl_cipher_default') ); } @$conn->real_connect( $databaseConfig['server'], $databaseConfig['username'], $databaseConfig['password'] ); if ($conn && empty($conn->connect_errno)) { $conn->query("SET sql_mode = 'ANSI'"); return $conn; } else { $error = ($conn->connect_errno) ? $conn->connect_error : 'Unknown connection error'; return null; } default: $error = 'Invalid connection type: ' . $databaseConfig['type']; return null; } } catch (Exception $ex) { $error = $ex->getMessage(); return null; } }
Create a connection of the appropriate type @param array $databaseConfig @param string $error Error message passed by value @return mixed|null Either the connection object, or null if error
createConnection
php
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/MySQLDatabaseConfigurationHelper.php
BSD-3-Clause
protected function column($results) { $array = []; if ($results instanceof mysqli_result) { while ($row = $results->fetch_array()) { $array[] = $row[0]; } } else { foreach ($results as $row) { $array[] = $row[0]; } } return $array; }
Helper function to quickly extract a column from a mysqi_result @param mixed $results mysqli_result or enumerable list of rows @return array Resulting data
column
php
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/MySQLDatabaseConfigurationHelper.php
BSD-3-Clause
public function requireDatabaseVersion($databaseConfig) { $version = $this->getDatabaseVersion($databaseConfig); $success = false; $error = ''; if ($version) { $success = version_compare($version ?? '', '5.0', '>='); if (!$success) { $error = "Your MySQL server version is $version. It's recommended you use at least MySQL 5.0."; } } else { $error = "Could not determine your MySQL version."; } return [ 'success' => $success, 'error' => $error ]; }
Ensure that the MySQL server version is at least 5.0. @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc @return array Result - e.g. array('success' => true, 'error' => 'details of error')
requireDatabaseVersion
php
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/MySQLDatabaseConfigurationHelper.php
BSD-3-Clause
public function checkValidDatabaseName($database) { // Reject filename unsafe characters (cross platform) if (preg_match('/[\\\\\/\?%\*\:\|"\<\>\.]+/', $database ?? '')) { return false; } // Restricted to characters in the ASCII and Extended ASCII range // @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html return preg_match('/^[\x{0001}-\x{FFFF}]+$/u', $database ?? ''); }
Determines if a given database name is a valid Silverstripe name. @param string $database Candidate database name @return boolean
checkValidDatabaseName
php
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/MySQLDatabaseConfigurationHelper.php
BSD-3-Clause
public function checkDatabasePermissionGrant($database, $permission, $grant) { // Filter out invalid database names if (!$this->checkValidDatabaseName($database)) { return false; } // Escape all valid database patterns (permission must exist on all tables) $sqlDatabase = addcslashes($database ?? '', '_%'); // See http://dev.mysql.com/doc/refman/5.7/en/string-literals.html $dbPattern = sprintf( '((%s)|(%s)|(%s)|(%s))', preg_quote("\"$sqlDatabase\".*"), // Regexp escape sql-escaped db identifier preg_quote("\"$database\".*"), preg_quote('"%".*'), preg_quote('*.*') ); $expression = '/GRANT[ ,\w]+((ALL PRIVILEGES)|(' . $permission . '(?! ((VIEW)|(ROUTINE)))))[ ,\w]+ON ' . $dbPattern . '/i'; return preg_match($expression ?? '', $grant ?? ''); }
Checks if a specified grant proves that the current user has the specified permission on the specified database @param string $database Database name @param string $permission Permission to check for @param string $grant MySQL syntax grant to check within @return boolean
checkDatabasePermissionGrant
php
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/MySQLDatabaseConfigurationHelper.php
BSD-3-Clause
public function checkDatabasePermission($conn, $database, $permission) { $grants = $this->column($conn->query("SHOW GRANTS FOR CURRENT_USER")); foreach ($grants as $grant) { if ($this->checkDatabasePermissionGrant($database, $permission, $grant)) { return true; } } return false; }
Checks if the current user has the specified permission on the specified database @param mixed $conn Connection object @param string $database Database name @param string $permission Permission to check @return boolean
checkDatabasePermission
php
silverstripe/silverstripe-framework
src/Dev/Install/MySQLDatabaseConfigurationHelper.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Install/MySQLDatabaseConfigurationHelper.php
BSD-3-Clause
public function run($request) { Environment::increaseTimeLimitTo(); $collector = i18nTextCollector::create($request->getVar('locale')); $merge = $this->getIsMerge($request); // Custom writer $writerName = $request->getVar('writer'); if ($writerName) { $writer = Injector::inst()->get($writerName); $collector->setWriter($writer); } // Get restrictions $restrictModules = ($request->getVar('module')) ? explode(',', $request->getVar('module')) : null; $collector->run($restrictModules, $merge); Debug::message(__CLASS__ . " completed!", false); }
This is the main method to build the master string tables with the original strings. It will search for existent modules that use the i18n feature, parse the _t() calls and write the resultant files in the lang folder of each module. @uses DataObject::collectI18nStatics() @param HTTPRequest $request
run
php
silverstripe/silverstripe-framework
src/Dev/Tasks/i18nTextCollectorTask.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Tasks/i18nTextCollectorTask.php
BSD-3-Clause
function singleton($className) { if ($className === Config::class) { throw new InvalidArgumentException("Don't pass Config to singleton()"); } if (!isset($className)) { throw new InvalidArgumentException("singleton() Called without a class"); } if (!is_string($className)) { throw new InvalidArgumentException( "singleton() passed bad class_name: " . var_export($className, true) ); } return Injector::inst()->get($className); }
Creates a class instance by the "singleton" design pattern. It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling). @template T of object @param class-string<T> $className @return T|mixed
singleton
php
silverstripe/silverstripe-framework
src/includes/functions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/includes/functions.php
BSD-3-Clause
function _t($entity, $arg = null) { // Pass args directly to handle deprecation return call_user_func_array([i18n::class, '_t'], func_get_args()); }
This is the main translator function. Returns the string defined by $entity according to the currently set locale. Also supports pluralisation of strings. Pass in a `count` argument, as well as a default value with `|` pipe-delimited options for each plural form. @param string $entity Entity that identifies the string. It must be in the form "Namespace.Entity" where Namespace will be usually the class name where this string is used and Entity identifies the string inside the namespace. @param mixed $arg Additional arguments are parsed as such: - Next string argument is a default. Pass in a `|` pipe-delimeted value with `{count}` to do pluralisation. - Any other string argument after default is context for i18nTextCollector - Any array argument in any order is an injection parameter list. Pass in a `count` injection parameter to pluralise. @return string
_t
php
silverstripe/silverstripe-framework
src/includes/functions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/includes/functions.php
BSD-3-Clause
public function pushLogger(LoggerInterface $logger) { $this->loggers[] = $logger; return $this; }
Adds a PSR-3 logger to send messages to, to the end of the stack @param LoggerInterface $logger @return $this
pushLogger
php
silverstripe/silverstripe-framework
src/Logging/MonologErrorHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/MonologErrorHandler.php
BSD-3-Clause
public function getLoggers() { return $this->loggers; }
Returns the stack of PSR-3 loggers @return LoggerInterface[]
getLoggers
php
silverstripe/silverstripe-framework
src/Logging/MonologErrorHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/MonologErrorHandler.php
BSD-3-Clause
public function setLoggers(array $loggers) { $this->loggers = $loggers; return $this; }
Set the PSR-3 loggers (overwrites any previously configured values) @param LoggerInterface[] $loggers @return $this
setLoggers
php
silverstripe/silverstripe-framework
src/Logging/MonologErrorHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/MonologErrorHandler.php
BSD-3-Clause
protected function findInTrace(array $trace, $file, $line) { foreach ($trace as $i => $call) { if (isset($call['file']) && isset($call['line']) && $call['file'] == $file && $call['line'] == $line) { return $i; } } return null; }
Find a call on the given file & line in the trace @param array $trace The result of debug_backtrace() @param string $file The filename to look for @param string $line The line number to look for @return int|null The matching row number, if found, or null if not found
findInTrace
php
silverstripe/silverstripe-framework
src/Logging/DetailedErrorFormatter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/DetailedErrorFormatter.php
BSD-3-Clause
protected function output($errno, $errstr, $errfile, $errline, $errcontext) { $reporter = Debug::create_debug_view(); // Coupling alert: This relies on knowledge of how the director gets its URL, it could be improved. $httpRequest = null; if (isset($_SERVER['REQUEST_URI'])) { $httpRequest = $_SERVER['REQUEST_URI']; } if (isset($_SERVER['REQUEST_METHOD'])) { $httpRequest = $_SERVER['REQUEST_METHOD'] . ' ' . $httpRequest; } $output = $reporter->renderHeader(); $output .= $reporter->renderError($httpRequest, $errno, $errstr, $errfile, $errline); if (file_exists($errfile ?? '')) { $lines = file($errfile ?? ''); // Make the array 1-based array_unshift($lines, ""); unset($lines[0]); $offset = $errline-10; $lines = array_slice($lines ?? [], $offset ?? 0, 16, true); $output .= $reporter->renderSourceFragment($lines, $errline); } $output .= $reporter->renderTrace($errcontext); $output .= $reporter->renderFooter(); return $output; }
Render a developer facing error page, showing the stack trace and details of the code where the error occurred. @param int $errno @param string $errstr @param string $errfile @param int $errline @param array $errcontext @return string
output
php
silverstripe/silverstripe-framework
src/Logging/DetailedErrorFormatter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/DetailedErrorFormatter.php
BSD-3-Clause
public function output($statusCode) { if (Director::is_ajax()) { return $this->getTitle(); } $renderer = Debug::create_debug_view(); $output = $renderer->renderHeader(); $output .= $renderer->renderInfo("Website Error", $this->getTitle(), $this->getBody()); if (!is_null($contactInfo = $this->addContactAdministratorInfo())) { $output .= $renderer->renderParagraph($contactInfo); } $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
output
php
silverstripe/silverstripe-framework
src/Logging/DebugViewFriendlyErrorFormatter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/DebugViewFriendlyErrorFormatter.php
BSD-3-Clause
private function addContactAdministratorInfo() { if (!$adminEmail = Email::config()->admin_email) { return null; } if (is_string($adminEmail)) { return 'Contact an administrator: ' . Email::obfuscate($adminEmail); } if (!is_array($adminEmail) || !count($adminEmail ?? [])) { return null; } $email = array_keys($adminEmail)[0]; $name = array_values($adminEmail)[0]; return sprintf('Contact %s: %s', Convert::raw2xml($name), Email::obfuscate($email)); }
Generate the line with admin contact info @return string|null
addContactAdministratorInfo
php
silverstripe/silverstripe-framework
src/Logging/DebugViewFriendlyErrorFormatter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/DebugViewFriendlyErrorFormatter.php
BSD-3-Clause
public function setContentType($contentType) { $this->contentType = $contentType; return $this; }
Set the mime type to use when displaying this error. Default text/html @param string $contentType @return HTTPOutputHandler Return $this to allow chainable calls
setContentType
php
silverstripe/silverstripe-framework
src/Logging/HTTPOutputHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/HTTPOutputHandler.php
BSD-3-Clause
public function setStatusCode($statusCode) { $this->statusCode = $statusCode; return $this; }
Set the HTTP status code to use when displaying this error. Default 500 @param int $statusCode @return $this
setStatusCode
php
silverstripe/silverstripe-framework
src/Logging/HTTPOutputHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/HTTPOutputHandler.php
BSD-3-Clause
public function setCLIFormatter(FormatterInterface $cliFormatter) { $this->cliFormatter = $cliFormatter; return $this; }
Set a formatter to use if Director::is_cli() is true @param FormatterInterface $cliFormatter @return HTTPOutputHandler Return $this to allow chainable calls
setCLIFormatter
php
silverstripe/silverstripe-framework
src/Logging/HTTPOutputHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/HTTPOutputHandler.php
BSD-3-Clause
public function getCLIFormatter() { return $this->cliFormatter; }
Return the formatter use if Director::is_cli() is true If none has been set, null is returned, and the getFormatter() result will be used instead @return FormatterInterface
getCLIFormatter
php
silverstripe/silverstripe-framework
src/Logging/HTTPOutputHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Logging/HTTPOutputHandler.php
BSD-3-Clause
function checkenv($envs) { if ($envs) { foreach (explode(',', $envs ?? '') as $env) { if (!getenv($env)) { return false; } } } return true; }
Check if an env variable is set @param $envs @return bool
checkenv
php
silverstripe/silverstripe-framework
tests/behat/travis-upload-artifacts.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/travis-upload-artifacts.php
BSD-3-Clause
public function handleCmsLoadingAfterStep(AfterStepScope $event) { // Manually exclude @modal if ($this->stepHasTag($event, 'modal')) { return; } $timeoutMs = $this->getMainContext()->getAjaxTimeout(); $this->getSession()->wait( $timeoutMs, "(" . "document.getElementsByClassName('cms-content-loading-overlay').length +" . "document.getElementsByClassName('cms-loading-container').length" . ") == 0" ); }
Wait until CMS loading overlay isn't present. This is an addition to the "ajax steps" logic in SilverStripe\BehatExtension\Context\BasicContext which also waits for any ajax requests to finish before continuing. The check also applies in when not in the CMS, which is a structural issue: Every step could cause the CMS to be loaded, and we don't know if we're in the CMS UI until we run a check. Excluding scenarios with @modal tag is required, because modal dialogs stop any JS interaction @AfterStep @param AfterStepScope $event
handleCmsLoadingAfterStep
php
silverstripe/silverstripe-framework
tests/behat/src/CmsUiContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsUiContext.php
BSD-3-Clause
protected function interactWithElement($element, $action = 'click') { switch ($action) { case 'hover': $element->mouseOver(); break; case 'double click': $element->doubleClick(); break; case 'right click': $element->rightClick(); break; case 'left click': case 'click': default: $element->click(); break; } }
Applies a specific action to an element @param NodeElement $element Element to act on @param string $action Action, which may be one of 'hover', 'double click', 'right click', or 'left click' The default 'click' behaves the same as left click
interactWithElement
php
silverstripe/silverstripe-framework
tests/behat/src/CmsUiContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsUiContext.php
BSD-3-Clause
public function clickLinkInPreview($link) { $this->getSession()->switchToIFrame('cms-preview-iframe'); $link = $this->fixStepArgument($link); $this->getSession()->getPage()->clickLink($link); $this->getSession()->switchToWindow(); }
When I follow "my link" in preview @When /^(?:|I )follow "(?P<link>(?:[^"]|\\")*)" in preview$/
clickLinkInPreview
php
silverstripe/silverstripe-framework
tests/behat/src/CmsUiContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsUiContext.php
BSD-3-Clause
public function pressButtonInPreview($button) { // see https://groups.google.com/forum/#!topic/behat/QNhOuGHKEWI $this->getSession()->switchToIFrame('cms-preview-iframe'); $button = $this->fixStepArgument($button); $this->getSession()->getPage()->pressButton($button); $this->getSession()->switchToWindow(); }
When I press "submit" in preview @When /^(?:|I )press "(?P<button>(?:[^"]|\\")*)" in preview$/
pressButtonInPreview
php
silverstripe/silverstripe-framework
tests/behat/src/CmsUiContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsUiContext.php
BSD-3-Clause
protected function fixStepArgument($argument) { return str_replace('\\"', '"', $argument ?? ''); }
Returns fixed step argument (with \\" replaced back to "). @param string $argument @return string
fixStepArgument
php
silverstripe/silverstripe-framework
tests/behat/src/CmsUiContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsUiContext.php
BSD-3-Clause
protected function findParentByClass(NodeElement $el, $class) { $container = $el->getParent(); while ($container && $container->getTagName() != 'body') { if ($container->isVisible() && in_array($class, explode(' ', $container->getAttribute('class') ?? ''))) { return $container; } $container = $container->getParent(); } return null; }
Returns the closest parent element having a specific class attribute. @param NodeElement $el @param String $class @return Element|null
findParentByClass
php
silverstripe/silverstripe-framework
tests/behat/src/CmsUiContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsUiContext.php
BSD-3-Clause
public function __construct($configPath = null) { if (empty($configPath)) { throw new InvalidArgumentException("filesPath is required"); } $this->setConfigPath($configPath); }
Create new ConfigContext @param string $configPath Path to config files. E.g. `%paths.modules.framework%/tests/behat/features/configs/`
__construct
php
silverstripe/silverstripe-framework
tests/behat/src/ConfigContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/ConfigContext.php
BSD-3-Clause
public function afterResetAssets(AfterScenarioScope $event) { // No files to cleanup if (empty($this->activatedConfigFiles)) { return; } foreach ($this->activatedConfigFiles as $configFile) { if (file_exists($configFile ?? '')) { unlink($configFile ?? ''); } } $this->activatedConfigFiles = []; // Flush $this->stepIFlush(); }
Clean up all files after scenario @AfterScenario @param AfterScenarioScope $event
afterResetAssets
php
silverstripe/silverstripe-framework
tests/behat/src/ConfigContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/ConfigContext.php
BSD-3-Clause
public function stepIHaveConfigFile($filename) { // Ensure site is in dev mode /** @var Kernel $kernel */ $kernel = Injector::inst()->get(Kernel::class); Assert::assertEquals(Kernel::DEV, $kernel->getEnvironment(), "Site is in dev mode"); // Ensure file exists in specified fixture dir $sourceDir = $this->getConfigPath(); $sourcePath = "{$sourceDir}/{$filename}"; Assert::assertFileExists($sourcePath, "Config file {$filename} exists"); // Get destination $project = ModuleManifest::config()->get('project') ?: 'mysite'; $mysite = ModuleLoader::getModule($project); Assert::assertNotNull($mysite, 'Project exists'); $destPath = $mysite->getResource("_config/{$filename}")->getPath(); Assert::assertFileDoesNotExist($destPath, "Config file {$filename} hasn't already been loaded"); // Load $this->activatedConfigFiles[] = $destPath; copy($sourcePath ?? '', $destPath ?? ''); // Flush website $this->stepIFlush(); }
Setup a config file. The $filename should be a yml filename placed in the directory specified by configPaths argument to fixture constructor. @When /^(?:|I )have a config file "([^"]+)"$/ @param string $filename
stepIHaveConfigFile
php
silverstripe/silverstripe-framework
tests/behat/src/ConfigContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/ConfigContext.php
BSD-3-Clause
public function stepContentInHtmlFieldShouldHaveFormatting($text, $field, $negate, $formatting) { $inputField = $this->getHtmlField($field); $crawler = new Crawler($inputField->getValue()); $matchedNode = null; foreach($crawler->filterXPath('//*') as $node) { if( $node->firstChild && $node->firstChild->nodeType == XML_TEXT_NODE && stripos($node->firstChild->nodeValue ?? '', $text ?? '') !== FALSE ) { $matchedNode = $node; } } Assert::assertNotNull($matchedNode); if ($formatting == 'bold') { if ($negate) { Assert::assertNotEquals('strong', $matchedNode->nodeName); } else { Assert::assertEquals('strong', $matchedNode->nodeName); } } else if ($formatting == 'left aligned') { if ($matchedNode->getAttribute('class')) { if ($negate) { Assert::assertNotEquals('text-left', $matchedNode->getAttribute('class')); } else { Assert::assertEquals('text-left', $matchedNode->getAttribute('class')); } } } else if ($formatting == 'right aligned') { if ($negate) { Assert::assertNotEquals('text-right', $matchedNode->getAttribute('class')); } else { Assert::assertEquals('text-right', $matchedNode->getAttribute('class')); } } }
Checks formatting in the HTML field, by analyzing the HTML node surrounding the text for certain properties. Example: Given "my text" in the "Content" HTML field should be right aligned Example: Given "my text" in the "Content" HTML field should not be bold @Given /^"(?P<text>([^"]*))" in the "(?P<field>(?:[^"]|\\")*)" HTML field should(?P<negate>(?: not)?) be (?P<formatting>(.*))$/
stepContentInHtmlFieldShouldHaveFormatting
php
silverstripe/silverstripe-framework
tests/behat/src/CmsFormsContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsFormsContext.php
BSD-3-Clause
public function stepIHighlightTextInHtmlField($text, $field) { $inputField = $this->getHtmlField($field); $inputFieldId = $inputField->getAttribute('id'); $text = addcslashes($text ?? '', "'"); $js = <<<JS var editor = jQuery('#$inputFieldId').entwine('ss').getEditor(), doc = editor.getInstance().getDoc(), sel = editor.getInstance().selection, rng = document.createRange(), matched = false; editor.getInstance().focus(); jQuery(doc).find('body *').each(function() { if(!matched) { for(var i=0;i<this.childNodes.length;i++) { if(!matched && this.childNodes[i].nodeValue && this.childNodes[i].nodeValue.match('$text')) { rng.setStart(this.childNodes[i], this.childNodes[i].nodeValue.indexOf('$text')); rng.setEnd(this.childNodes[i], this.childNodes[i].nodeValue.indexOf('$text') + '$text'.length); sel.setRng(rng); editor.getInstance().nodeChanged(); matched = true; break; } } } }); JS; $this->getSession()->executeScript($js); }
Selects the first textual match in the HTML editor. Does not support selection across DOM node boundaries. @When /^I select "(?P<text>([^"]*))" in the "(?P<field>(?:[^"]|\\")*)" HTML field$/
stepIHighlightTextInHtmlField
php
silverstripe/silverstripe-framework
tests/behat/src/CmsFormsContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsFormsContext.php
BSD-3-Clause
public function iClickOnTheHtmlFieldButton($button) { $xpath = "//*[@aria-label='" . $button . "']"; $session = $this->getSession(); $element = $session->getPage()->find('xpath', $xpath); if (null === $element) { // If it can't find the exact name, find one that starts with the phrase // Helpful for "Insert link" which has a conditional label for keyboard shortcut $xpath = "//*[starts-with(@aria-label, '" . $button . "')]"; $element = $session->getPage()->find('xpath', $xpath); if (null === $element) { throw new \InvalidArgumentException(sprintf('Could not find element with xpath %s', $xpath)); }; } $element->click(); }
Click on the element with the provided CSS Selector @When /^I press the "([^"]*)" HTML field button$/
iClickOnTheHtmlFieldButton
php
silverstripe/silverstripe-framework
tests/behat/src/CmsFormsContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsFormsContext.php
BSD-3-Clause
protected function getGridFieldButton($gridFieldName, $rowName, $buttonLabel) { $page = $this->getSession()->getPage(); $gridField = $page->find('xpath', sprintf('//*[@data-name="%s"]', $gridFieldName)); Assert::assertNotNull($gridField, sprintf('Gridfield "%s" not found', $gridFieldName)); $name = $gridField->find('xpath', sprintf('//*[count(*)=0 and contains(.,"%s")]', $rowName)); if (!$name) { return null; } if ($dropdownButton = $name->getParent()->find('css', '.action-menu__toggle')) { $dropdownButton->click(); } $button = $name->getParent()->find('named', ['link_or_button', $buttonLabel]); return $button; }
Finds a button in the gridfield row @param $gridFieldName @param $rowName @param $buttonLabel @return $button
getGridFieldButton
php
silverstripe/silverstripe-framework
tests/behat/src/CmsFormsContext.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/behat/src/CmsFormsContext.php
BSD-3-Clause
protected function getStubFormWithWeirdValueFormat() { return new Form( Controller::curr(), 'Form', new FieldList( $dateField = DatetimeField::create('SomeDateTimeField') ->setHTML5(false) ->setDatetimeFormat("EEE, MMM d, ''yy HH:mm:ss"), $timeField = TimeField::create('SomeTimeField') ->setHTML5(false) ->setTimeFormat("hh 'o''clock' a mm ss") // Swatch Internet Time format ), new FieldList() ); }
Some fields handle submitted values differently from their internal values. This forms contains 2 such fields * a SomeDateTimeField that expect a date such as `Fri, Jun 15, '18 17:28:05`, * a SomeTimeField that expects it's time as `05 o'clock PM 28 05` @return Form
getStubFormWithWeirdValueFormat
php
silverstripe/silverstripe-framework
tests/php/Forms/FormTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/FormTest.php
BSD-3-Clause
protected function clean($input) { return str_replace( [ html_entity_decode('&nbsp;', 0, 'UTF-8'), html_entity_decode('&#8239;', 0, 'UTF-8'), // narrow non-breaking space ], ' ', trim($input ?? '') ); }
In some cases and locales, validation expects non-breaking spaces. This homogenises narrow and regular NBSPs to a regular space character @param string $input @return string The input value, with all non-breaking spaces replaced with spaces
clean
php
silverstripe/silverstripe-framework
tests/php/Forms/FormTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/FormTest.php
BSD-3-Clause
public function createDropdownField($emptyString = null, $value = '') { /* Set up source, with 0 and 1 integers as the values */ $source = [ 0 => 'No', 1 => 'Yes' ]; $field = new DropdownField('Field', null, $source, $value); if ($emptyString !== null) { $field->setEmptyString($emptyString); } return $field; }
Create a test dropdown field, with the option to set what source and blank value it should contain as optional parameters. @param string|null $emptyString The text to display for the empty value @param string|integer $value The default value of the field @return DropdownField object
createDropdownField
php
silverstripe/silverstripe-framework
tests/php/Forms/DropdownFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/DropdownFieldTest.php
BSD-3-Clause
public function findOptionElements($html) { $parser = new CSSContentParser($html); return $parser->getBySelector('option'); }
Find all the <OPTION> elements from a string of HTML. @param string $html HTML to scan for elements @return SimpleXMLElement
findOptionElements
php
silverstripe/silverstripe-framework
tests/php/Forms/DropdownFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/DropdownFieldTest.php
BSD-3-Clause
public function escapeHtmlDataProvider() { return [ ['<html>'], [['<html>']], [['<html>' => '<html>']] ]; }
Covering all potential inputs for Convert::raw2xml
escapeHtmlDataProvider
php
silverstripe/silverstripe-framework
tests/php/Forms/FormFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/FormFieldTest.php
BSD-3-Clause
protected function buildFormMock() { $form = $this->createMock(Form::class); $form->method('getTemplateHelper') ->willReturn(FormTemplateHelper::singleton()); $form->method('getHTMLID') ->willReturn($this->formId); return $form; }
Build a new mock object of a Form @return Form
buildFormMock
php
silverstripe/silverstripe-framework
tests/php/Forms/TreeMultiselectFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/TreeMultiselectFieldTest.php
BSD-3-Clause
protected function buildField(Form $form) { $field = new TreeMultiselectField($this->fieldName, 'Test tree', File::class); $field->setForm($form); return $field; }
Build a new instance of TreeMultiselectField @param Form $form The field form @return TreeMultiselectField
buildField
php
silverstripe/silverstripe-framework
tests/php/Forms/TreeMultiselectFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/TreeMultiselectFieldTest.php
BSD-3-Clause
protected function loadFolders() { $asdf = $this->objFromFixture(File::class, 'asdf'); $subfolderfile1 = $this->objFromFixture(File::class, 'subfolderfile1'); return [$asdf, $subfolderfile1]; }
Load several files from the fixtures and return them in an array @return File[]
loadFolders
php
silverstripe/silverstripe-framework
tests/php/Forms/TreeMultiselectFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/TreeMultiselectFieldTest.php
BSD-3-Clause
private function assertFieldAttributes(SudoModePasswordField $field, array $expected) { $keys = array_keys($expected); $actual = array_filter($field->getAttributes(), fn($key) => in_array($key, $keys), ARRAY_FILTER_USE_KEY); $this->assertSame($expected, $actual); }
Used to test a subset of attributes as things like 'disabled' and 'readonly' are not applicable
assertFieldAttributes
php
silverstripe/silverstripe-framework
tests/php/Forms/SudoModePasswordFieldTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/SudoModePasswordFieldTest.php
BSD-3-Clause
private function getHeaderlessGridField() { $this->gridField->setRequest(new HTTPRequest('GET', 'admin/pages/edit/show/9999')); $fieldList = FieldList::create(new TabSet('Root', new Tab('Main'))); $fieldList->addFieldToTab('Root.GridField', $this->gridField); Form::create(null, 'Form', $fieldList, FieldList::create()); return $this->gridField; }
This GridField will be lazy because it doesn't have a `X-Pjax` header. @return GridField
getHeaderlessGridField
php
silverstripe/silverstripe-framework
tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
BSD-3-Clause
private function getOutOfTabSetGridField() { $r = new HTTPRequest('POST', 'admin/pages/edit/EditForm/9999/field/testfield'); $r->addHeader('X-Pjax', 'CurrentField'); $this->gridField->setRequest($r); $fieldList = new FieldList($this->gridField); Form::create(null, 'Form', $fieldList, FieldList::create()); return $this->gridField; }
This GridField will not be lazy because it's in not in a tab set. @return GridField
getOutOfTabSetGridField
php
silverstripe/silverstripe-framework
tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
BSD-3-Clause
private function getNonLazyGridField() { $r = new HTTPRequest('POST', 'admin/pages/edit/EditForm/9999/field/testfield'); $r->addHeader('X-Pjax', 'CurrentField'); $this->gridField->setRequest($r); $fieldList = new FieldList(new TabSet('Root', new Tab('Main'))); $fieldList->addFieldToTab('Root', $this->gridField); Form::create(null, 'Form', $fieldList, FieldList::create()); return $this->gridField; }
This gridfield will not be lazy, because it has `X-Pjax` header equal to `CurrentField` @return GridField
getNonLazyGridField
php
silverstripe/silverstripe-framework
tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
BSD-3-Clause
private function makeGridFieldReadonly(GridField $gridField) { $form = $gridField->getForm()->makeReadonly(); $fields = $form->Fields()->dataFields(); foreach ($fields as $field) { if ($field->getName() === 'testfield') { return $field; } } }
Perform a readonly transformation on our GridField's Form and return the ReadOnly GridField. We need to make sure the LazyLoader component still works after our GridField has been made readonly. @param GridField $gridField @return GridField
makeGridFieldReadonly
php
silverstripe/silverstripe-framework
tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/GridField/GridFieldLazyLoaderTest.php
BSD-3-Clause
public function updateFormFields(FieldList &$fields, Controller $controller, $name, $context = []) { // Add preview link if (empty($context['Record'])) { return; } /** @var Versioned|DataObject $record */ $record = $context['Record']; if ($record->hasExtension(Versioned::class) && $record->hasStages()) { $link = $controller->Link('preview'); $fields->unshift( new LiteralField( "PreviewLink", sprintf('<a href="%s" rel="external" target="_blank">Preview</a>', Convert::raw2att($link)) ) ); } }
Adds extra fields to this form @param FieldList $fields @param Controller $controller @param string $name @param array $context
updateFormFields
php
silverstripe/silverstripe-framework
tests/php/Forms/FormFactoryTest/ControllerExtension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Forms/FormFactoryTest/ControllerExtension.php
BSD-3-Clause
protected function expectExceptionRedirect($url) { $this->expectedRedirect = $url; }
Expects this test to throw a HTTPResponse_Exception with the given redirect @param string $url
expectExceptionRedirect
php
silverstripe/silverstripe-framework
tests/php/Control/DirectorTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Control/DirectorTest.php
BSD-3-Clause
public function onBeforeHTTPError() { ControllerExtension::$called_error = true; }
Called whenever there is an HTTP error
onBeforeHTTPError
php
silverstripe/silverstripe-framework
tests/php/Control/RequestHandlingTest/ControllerExtension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Control/RequestHandlingTest/ControllerExtension.php
BSD-3-Clause
public function onBeforeHTTPError404() { ControllerExtension::$called_404_error = true; }
Called whenever there is an 404 error
onBeforeHTTPError404
php
silverstripe/silverstripe-framework
tests/php/Control/RequestHandlingTest/ControllerExtension.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Control/RequestHandlingTest/ControllerExtension.php
BSD-3-Clause
public function formaction($data, $form = null) { return 'formaction'; }
@param array $data @param Form $form Made optional to simulate error behaviour in "live" environment (missing arguments don't throw a fatal error there) (missing arguments don't throw a fatal error there) @return string
formaction
php
silverstripe/silverstripe-framework
tests/php/Control/RequestHandlingTest/FormActionController.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Control/RequestHandlingTest/FormActionController.php
BSD-3-Clause
protected function assertEqualsQuoted($expected, $actual) { $message = sprintf( 'Expected "%s" but given "%s"', addcslashes($expected ?? '', "\r\n"), addcslashes($actual ?? '', "\r\n") ); $this->assertEquals($expected, $actual, $message); }
Helper function for comparing characters with significant whitespaces @param string $expected @param string $actual
assertEqualsQuoted
php
silverstripe/silverstripe-framework
tests/php/Core/ConvertTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Core/ConvertTest.php
BSD-3-Clause
public function assertFinderFinds(ManifestFileFinder $finder, $base, $expect, $message = '') { if (!$base) { $base = $this->defaultBase; } $found = $finder->find($base); foreach ($expect as $k => $file) { $expect[$k] = "{$base}/$file"; } sort($expect); sort($found); $this->assertEquals($expect, $found, $message); }
Test that the finder can find the given files @param ManifestFileFinder $finder @param string $base @param array $expect @param string $message
assertFinderFinds
php
silverstripe/silverstripe-framework
tests/php/Core/Manifest/ManifestFileFinderTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Core/Manifest/ManifestFileFinderTest.php
BSD-3-Clause
protected function getConfigFixtureValue($name) { return $this->getTestConfig()->get(__CLASS__, $name); }
This is a helper method for getting a new manifest @param string $name @return mixed
getConfigFixtureValue
php
silverstripe/silverstripe-framework
tests/php/Core/Manifest/ConfigManifestTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Core/Manifest/ConfigManifestTest.php
BSD-3-Clause
public function getTestConfig() { $config = new MemoryConfigCollection(); $factory = new CoreConfigFactory(); $transformer = $factory->buildYamlTransformerForPath(dirname(__FILE__) . '/fixtures/configmanifest'); $config->transform([$transformer]); return $config; }
Build a new config based on YMl manifest @return MemoryConfigCollection
getTestConfig
php
silverstripe/silverstripe-framework
tests/php/Core/Manifest/ConfigManifestTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Core/Manifest/ConfigManifestTest.php
BSD-3-Clause
protected function getParsedAsMessage($path) { return sprintf('Reference path "%s" failed to parse correctly', $path); }
This is a helper method for displaying a relevant message about a parsing failure @param string $path @return string
getParsedAsMessage
php
silverstripe/silverstripe-framework
tests/php/Core/Manifest/ConfigManifestTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/Core/Manifest/ConfigManifestTest.php
BSD-3-Clause
public function render($templateString, $data = null, $cacheTemplate = false) { $t = SSViewer::fromString($templateString, $cacheTemplate); if (!$data) { $data = new SSViewerTest\TestFixture(); } return trim('' . $t->process($data)); }
Small helper to render templates from strings @param string $templateString @param null $data @param bool $cacheTemplate @return string
render
php
silverstripe/silverstripe-framework
tests/php/View/SSViewerTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/View/SSViewerTest.php
BSD-3-Clause
protected function setupCombinedRequirements($backend) { $this->setupRequirements($backend); // require files normally (e.g. called from a FormField instance) $backend->javascript('javascript/RequirementsTest_a.js'); $backend->javascript('javascript/RequirementsTest_b.js'); $backend->javascript('javascript/RequirementsTest_c.js'); // Public resources may or may not be specified with `public/` prefix $backend->javascript('javascript/RequirementsTest_d.js'); $backend->javascript('public/javascript/RequirementsTest_e.js'); // require two of those files as combined includes $backend->combineFiles( 'RequirementsTest_bc.js', [ 'javascript/RequirementsTest_b.js', 'javascript/RequirementsTest_c.js' ] ); }
Setup combined and non-combined js with the backend @param Requirements_Backend $backend
setupCombinedRequirements
php
silverstripe/silverstripe-framework
tests/php/View/RequirementsTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/View/RequirementsTest.php
BSD-3-Clause
protected function setupCombinedNonrequiredRequirements($backend) { $this->setupRequirements($backend); // require files as combined includes $backend->combineFiles( 'RequirementsTest_bc.js', [ 'javascript/RequirementsTest_b.js', 'javascript/RequirementsTest_c.js' ] ); }
Setup combined files with the backend @param Requirements_Backend $backend
setupCombinedNonrequiredRequirements
php
silverstripe/silverstripe-framework
tests/php/View/RequirementsTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/View/RequirementsTest.php
BSD-3-Clause
public function assertFileIncluded($backend, $type, $files) { $includedFiles = $this->getBackendFiles($backend, $type); if (is_array($files)) { $failedMatches = []; foreach ($files as $file) { if (!array_key_exists($file, $includedFiles ?? [])) { $failedMatches[] = $file; } } $this->assertCount( 0, $failedMatches, "Failed asserting the $type files '" . implode("', '", $failedMatches) . "' have exact matches in the required elements:\n'" . implode("'\n'", array_keys($includedFiles ?? [])) . "'" ); } else { $this->assertArrayHasKey( $files, $includedFiles, "Failed asserting the $type file '$files' has an exact match in the required elements:\n'" . implode("'\n'", array_keys($includedFiles ?? [])) . "'" ); } }
Verify that the given backend includes the given files @param Requirements_Backend $backend @param string $type js or css @param array|string $files Files or list of files to check
assertFileIncluded
php
silverstripe/silverstripe-framework
tests/php/View/RequirementsTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/View/RequirementsTest.php
BSD-3-Clause
protected function getBackendFiles($backend, $type) { $type = strtolower($type ?? ''); switch (strtolower($type ?? '')) { case 'css': return $backend->getCSS(); case 'js': case 'javascript': case 'script': return $backend->getJavascript(); } return []; }
Get files of the given type from the backend @param Requirements_Backend $backend @param string $type js or css @return array
getBackendFiles
php
silverstripe/silverstripe-framework
tests/php/View/RequirementsTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/tests/php/View/RequirementsTest.php
BSD-3-Clause