code
stringlengths
17
296k
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
public static function text($val, HTTPRequest $request = null) { return static::create_debug_view($request) ->debugVariableText($val); }
Get debug text for this object @param mixed $val @param HTTPRequest $request @return string
text
php
silverstripe/silverstripe-framework
src/Dev/Debug.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Debug.php
BSD-3-Clause
public static function message($message, $showHeader = true, HTTPRequest $request = null) { // Don't show on live if (Director::isLive()) { return; } echo static::create_debug_view($request) ->renderMessage($message, static::caller(), $showHeader); }
Show a debugging message. Does not work on live mode @param string $message @param bool $showHeader @param HTTPRequest|null $request
message
php
silverstripe/silverstripe-framework
src/Dev/Debug.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Debug.php
BSD-3-Clause
public static function create_debug_view(HTTPRequest $request = null) { $service = static::supportsHTML($request) ? DebugView::class : CliDebugView::class; return Injector::inst()->get($service); }
Create an instance of an appropriate DebugView object. @param HTTPRequest $request Optional request to target this view for @return DebugView
create_debug_view
php
silverstripe/silverstripe-framework
src/Dev/Debug.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Debug.php
BSD-3-Clause
public static function require_developer_login() { Deprecation::noticeWithNoReplacment('5.4.0'); // Don't require login for dev mode if (Director::isDev()) { return; } if (isset($_SESSION['loggedInAs'])) { // We have to do some raw SQL here, because this method is called in Object::defineMethods(). // This means we have to be careful about what objects we create, as we don't want Object::defineMethods() // being called again. // This basically calls Permission::checkMember($_SESSION['loggedInAs'], 'ADMIN'); $memberID = $_SESSION['loggedInAs']; $permission = DB::prepared_query( ' SELECT "ID" FROM "Permission" INNER JOIN "Group_Members" ON "Permission"."GroupID" = "Group_Members"."GroupID" WHERE "Permission"."Code" = ? AND "Permission"."Type" = ? AND "Group_Members"."MemberID" = ?', [ 'ADMIN', // Code Permission::GRANT_PERMISSION, // Type $memberID // MemberID ] )->value(); if ($permission) { return; } } // This basically does the same as // Security::permissionFailure(null, "You need to login with developer access to make use of debugging tools.") // We have to do this because of how early this method is called in execution. $_SESSION['SilverStripe\\Security\\Security']['Message']['message'] = "You need to login with developer access to make use of debugging tools."; $_SESSION['SilverStripe\\Security\\Security']['Message']['type'] = 'warning'; $_SESSION['BackURL'] = $_SERVER['REQUEST_URI']; header($_SERVER['SERVER_PROTOCOL'] . " 302 Found"); header("Location: " . Director::baseURL() . Security::login_url()); die(); }
Check if the user has permissions to run URL debug tools, else redirect them to log in. @deprecated 5.4.0 Will be removed without equivalent functionality.
require_developer_login
php
silverstripe/silverstripe-framework
src/Dev/Debug.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Debug.php
BSD-3-Clause
public function Breadcrumbs() { $basePath = str_replace(Director::protocolAndHost() ?? '', '', Director::absoluteBaseURL() ?? ''); $relPath = parse_url( substr($_SERVER['REQUEST_URI'] ?? '', strlen($basePath ?? ''), strlen($_SERVER['REQUEST_URI'] ?? '')), PHP_URL_PATH ); $parts = explode('/', $relPath ?? ''); $base = Director::absoluteBaseURL(); $pathPart = ""; $pathLinks = []; foreach ($parts as $part) { if ($part != '') { $pathPart = Controller::join_links($pathPart, $part); $href = Controller::join_links($base, $pathPart); $pathLinks[] = "<a href=\"$href\">$part</a>"; } } return implode('&nbsp;&rarr;&nbsp;', $pathLinks); }
Generate breadcrumb links to the URL path being displayed @return string
Breadcrumbs
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function renderHeader($httpRequest = null) { $url = htmlentities( $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'], ENT_COMPAT, 'UTF-8' ); $debugCSS = ModuleResourceLoader::singleton() ->resolveURL('silverstripe/framework:client/styles/debug.css'); $output = '<!DOCTYPE html><html><head><title>' . $url . '</title>'; $output .= '<link rel="stylesheet" type="text/css" href="' . $debugCSS . '" />'; $output .= '<meta name="robots" content="noindex">'; $output .= '</head>'; $output .= '<body>'; return $output; }
Render HTML header for development views @param HTTPRequest $httpRequest @return string
renderHeader
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function renderInfo($title, $subtitle, $description = false) { $output = '<div class="info header">'; $output .= "<h1>" . Convert::raw2xml($title) . "</h1>"; if ($subtitle) { $output .= "<h3>" . Convert::raw2xml($subtitle) . "</h3>"; } if ($description) { $output .= "<p>$description</p>"; } else { $output .= $this->Breadcrumbs(); } $output .= '</div>'; return $output; }
Render the information header for the view @param string $title The main title @param string $subtitle The subtitle @param string|bool $description The description to show @return string
renderInfo
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function renderFooter() { return "</body></html>"; }
Render HTML footer for development views @return string
renderFooter
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function renderParagraph($text) { return '<div class="info"><p>' . $text . '</p></div>'; }
Render an arbitrary paragraph. @param string $text The HTML-escaped text to render @return string
renderParagraph
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
protected function formatCaller($caller) { $return = basename($caller['file'] ?? '') . ":" . $caller['line']; if (!empty($caller['class']) && !empty($caller['function'])) { $return .= " - {$caller['class']}::{$caller['function']}()"; } return $return; }
Formats the caller of a method @param array $caller @return string
formatCaller
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function renderVariable($val, $caller) { $output = '<pre style="background-color:#ccc;padding:5px;font-size:14px;line-height:18px;">'; $output .= "<span style=\"font-size: 12px;color:#666;\">" . $this->formatCaller($caller) . " - </span>\n"; if (is_string($val)) { $output .= wordwrap($val ?? '', static::config()->columns ?? 0); } else { $output .= var_export($val, true); } $output .= '</pre>'; return $output; }
Outputs a variable in a user presentable way @param object $val @param array $caller Caller information @return string
renderVariable
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function debugVariable($val, $caller, $showHeader = true) { $text = $this->debugVariableText($val); if ($showHeader) { $callerFormatted = $this->formatCaller($caller); return "<div style=\"background-color: white; text-align: left;\">\n<hr>\n" . "<h3>Debug <span style=\"font-size: 65%\">($callerFormatted)</span>\n</h3>\n" . $text . "</div>"; } else { return $text; } }
Similar to renderVariable() but respects debug() method on object if available @param mixed $val @param array $caller @param bool $showHeader @return string
debugVariable
php
silverstripe/silverstripe-framework
src/Dev/DebugView.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/DebugView.php
BSD-3-Clause
public function writeInto(FixtureFactory $factory) { $parser = new Parser(); if (isset($this->fixtureString)) { $fixtureContent = $parser->parse($this->fixtureString); } else { if (!file_exists($this->fixtureFile ?? '') || is_dir($this->fixtureFile ?? '')) { return; } $contents = file_get_contents($this->fixtureFile ?? ''); $fixtureContent = $parser->parse($contents); if (!$fixtureContent) { return; } } foreach ($fixtureContent as $class => $items) { foreach ($items as $identifier => $data) { if (ClassInfo::exists($class)) { $factory->createObject($class, $identifier, $data); } else { $factory->createRaw($class, $identifier, $data); } } } }
Persists the YAML data in a FixtureFactory, which in turn saves them into the database. Please use the passed in factory to access the fixtures afterwards. @param FixtureFactory $factory
writeInto
php
silverstripe/silverstripe-framework
src/Dev/YamlFixture.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/YamlFixture.php
BSD-3-Clause
public function followRedirection() { if ($this->lastResponse->getHeader('Location')) { $url = Director::makeRelative($this->lastResponse->getHeader('Location')); $url = strtok($url ?? '', '#'); return $this->get($url); } }
If the last request was a 3xx response, then follow the redirection @return HTTPResponse The response given, or null if no redirect occurred
followRedirection
php
silverstripe/silverstripe-framework
src/Dev/TestSession.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/TestSession.php
BSD-3-Clause
public function wasRedirected() { $code = $this->lastResponse->getStatusCode(); return $code >= 300 && $code < 400; }
Returns true if the last response was a 3xx redirection @return bool
wasRedirected
php
silverstripe/silverstripe-framework
src/Dev/TestSession.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/TestSession.php
BSD-3-Clause
public function lastUrl() { return $this->lastUrl; }
Return the fake HTTP_REFERER; set each time get() or post() is called. @return string
lastUrl
php
silverstripe/silverstripe-framework
src/Dev/TestSession.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/TestSession.php
BSD-3-Clause
public function lastContent() { if (is_string($this->lastResponse)) { return $this->lastResponse; } else { return $this->lastResponse->getBody(); } }
Get the most recent response's content @return string
lastContent
php
silverstripe/silverstripe-framework
src/Dev/TestSession.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/TestSession.php
BSD-3-Clause
public function cssParser() { return new CSSContentParser($this->lastContent()); }
Return a CSSContentParser containing the most recent response @return CSSContentParser
cssParser
php
silverstripe/silverstripe-framework
src/Dev/TestSession.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/TestSession.php
BSD-3-Clause
public function session() { return $this->session; }
Get the current session, as a Session object @return Session
session
php
silverstripe/silverstripe-framework
src/Dev/TestSession.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/TestSession.php
BSD-3-Clause
public function Created() { return $this->mapToArrayList($this->created); }
Returns all created objects. Each object might contain specific importer feedback in the "_BulkLoaderMessage" property. @return ArrayList
Created
php
silverstripe/silverstripe-framework
src/Dev/BulkLoader_Result.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/BulkLoader_Result.php
BSD-3-Clause
public function LastChange() { return $this->lastChange; }
Returns the last change. It is in the same format as {@link $created} but with an additional key, "ChangeType", which will be set to one of 3 strings: "created", "updated", or "deleted"
LastChange
php
silverstripe/silverstripe-framework
src/Dev/BulkLoader_Result.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/BulkLoader_Result.php
BSD-3-Clause
public function merge(BulkLoader_Result $other) { $this->created = array_merge($this->created, $other->created); $this->updated = array_merge($this->updated, $other->updated); $this->deleted = array_merge($this->deleted, $other->deleted); }
Merges another BulkLoader_Result into this one. @param BulkLoader_Result $other
merge
php
silverstripe/silverstripe-framework
src/Dev/BulkLoader_Result.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/BulkLoader_Result.php
BSD-3-Clause
public static function withNoReplacement(callable $func) { Deprecation::notice('5.4.0', 'Use withSuppressedNotice() instead'); return Deprecation::withSuppressedNotice($func); }
Used to wrap deprecated methods and deprecated config get()/set() called from the vendor dir that projects have no ability to change. @return mixed @deprecated 5.4.0 Use withSuppressedNotice() instead
withNoReplacement
php
silverstripe/silverstripe-framework
src/Dev/Deprecation.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/Deprecation.php
BSD-3-Clause
protected function withBaseURL($url, $callback) { $oldBase = Config::inst()->get(Director::class, 'alternate_base_url'); Config::modify()->set(Director::class, 'alternate_base_url', $url); $callback($this); Config::modify()->set(Director::class, 'alternate_base_url', $oldBase); }
Run a test while mocking the base url with the provided value @param string $url The base URL to use for this test @param callable $callback The test to run
withBaseURL
php
silverstripe/silverstripe-framework
src/Dev/FunctionalTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/FunctionalTest.php
BSD-3-Clause
protected function withBaseFolder($folder, $callback) { $oldFolder = Config::inst()->get(Director::class, 'alternate_base_folder'); Config::modify()->set(Director::class, 'alternate_base_folder', $folder); $callback($this); Config::modify()->set(Director::class, 'alternate_base_folder', $oldFolder); }
Run a test while mocking the base folder with the provided value @param string $folder The base folder to use for this test @param callable $callback The test to run
withBaseFolder
php
silverstripe/silverstripe-framework
src/Dev/FunctionalTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/FunctionalTest.php
BSD-3-Clause
public function content() { return $this->mainSession->lastContent(); }
Return the most recent content @return string
content
php
silverstripe/silverstripe-framework
src/Dev/FunctionalTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/FunctionalTest.php
BSD-3-Clause
public function findAttribute($object, $attribute) { $found = false; foreach ($object->attributes() as $a => $b) { if ($a == $attribute) { $found = $b; } } return $found; }
Find an attribute in a SimpleXMLElement object by name. @param SimpleXMLElement $object @param string $attribute Name of attribute to find @return SimpleXMLElement object of the attribute
findAttribute
php
silverstripe/silverstripe-framework
src/Dev/FunctionalTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/FunctionalTest.php
BSD-3-Clause
public function cssParser() { if (!$this->cssParser) { $this->cssParser = new CSSContentParser($this->mainSession->lastContent()); } return $this->cssParser; }
Return a CSSContentParser for the most recent content. @return CSSContentParser
cssParser
php
silverstripe/silverstripe-framework
src/Dev/FunctionalTest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/FunctionalTest.php
BSD-3-Clause
public function hasHeaderRow() { return ($this->hasHeaderRow || isset($this->columnMap)); }
Determine whether any loaded files should be parsed with a header-row (otherwise we rely on {@link CsvBulkLoader::$columnMap}. @return boolean
hasHeaderRow
php
silverstripe/silverstripe-framework
src/Dev/CsvBulkLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Dev/CsvBulkLoader.php
BSD-3-Clause
public static function getIllegalExtensions() { return static::$illegal_extensions; }
Gets illegal extensions for this class @return array
getIllegalExtensions
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 getRequiredExtensions() { return static::$required_extensions; }
Gets required extensions for this class @return array
getRequiredExtensions
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 is_running_test() { return SapphireTest::$is_running_test; }
Check if test bootstrapping has been performed. Must not be relied on outside of unit tests. @return bool
is_running_test
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 shouldSetupDatabaseForCurrentTest($fixtureFiles) { $databaseEnabledByDefault = $fixtureFiles || $this->usesDatabase; return ($databaseEnabledByDefault && !$this->currentTestDisablesDatabase()) || $this->currentTestEnablesDatabase(); }
Helper method to determine if the current test should enable a test database @param $fixtureFiles @return bool
shouldSetupDatabaseForCurrentTest
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 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 assertSQLNotContains( $needleSQL, $haystackSQL, $message = '' ) { $needleSQL = static::normaliseSQL($needleSQL); $haystackSQL = static::normaliseSQL($haystackSQL); if (is_iterable($haystackSQL)) { /** @var iterable $iterableHaystackSQL */ $iterableHaystackSQL = $haystackSQL; static::assertNotContains($needleSQL, $iterableHaystackSQL, $message); } else { static::assertStringNotContainsString($needleSQL, $haystackSQL, $message); } }
Asserts that a SQL query contains a SQL fragment @param string $needleSQL @param string $haystackSQL @param string $message
assertSQLNotContains
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 getContentType() { return $this->contentType; }
Get the mime type to use when displaying this error. @return string
getContentType
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 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 getStatusCode() { return $this->statusCode; }
Get the HTTP status code to use when displaying this error. @return int
getStatusCode
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 getSession($name = null) { return $this->getMainContext()->getSession($name); }
Get Mink session from MinkContext @param string $name @return Session
getSession
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 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