Fixing string concat CS issues

This commit is contained in:
Daniel Hensby 2018-01-16 18:39:30 +00:00
parent ff05a7265e
commit db610aaf3b
No known key found for this signature in database
GPG Key ID: B00D1E9767F0B06E
126 changed files with 397 additions and 513 deletions

View File

@ -205,14 +205,14 @@ class HTTP
} }
$host = (isset($parts['host'])) ? $parts['host'] : ''; $host = (isset($parts['host'])) ? $parts['host'] : '';
$port = (isset($parts['port']) && $parts['port'] != '') ? ':'.$parts['port'] : ''; $port = (isset($parts['port']) && $parts['port'] != '') ? ':' . $parts['port'] : '';
$path = (isset($parts['path']) && $parts['path'] != '') ? $parts['path'] : ''; $path = (isset($parts['path']) && $parts['path'] != '') ? $parts['path'] : '';
// handle URL params which are existing / new // handle URL params which are existing / new
$params = ($params) ? '?' . http_build_query($params, null, $separator) : ''; $params = ($params) ? '?' . http_build_query($params, null, $separator) : '';
// keep fragments (anchors) intact. // keep fragments (anchors) intact.
$fragment = (isset($parts['fragment']) && $parts['fragment'] != '') ? '#'.$parts['fragment'] : ''; $fragment = (isset($parts['fragment']) && $parts['fragment'] != '') ? '#' . $parts['fragment'] : '';
// Recompile URI segments // Recompile URI segments
$newUri = $scheme . '://' . $user . $host . $port . $path . $params . $fragment; $newUri = $scheme . '://' . $user . $host . $port . $path . $params . $fragment;
@ -465,7 +465,7 @@ class HTTP
} elseif ((is_bool($value) && $value) || $value === "true") { } elseif ((is_bool($value) && $value) || $value === "true") {
$cacheControlHeaders[$header] = $header; $cacheControlHeaders[$header] = $header;
} else { } else {
$cacheControlHeaders[$header] = $header."=".$value; $cacheControlHeaders[$header] = $header . "=" . $value;
} }
} }

View File

@ -157,8 +157,7 @@ class RSSFeed extends ViewableData
{ {
$title = Convert::raw2xml($title); $title = Convert::raw2xml($title);
Requirements::insertHeadTags( Requirements::insertHeadTags(
'<link rel="alternate" type="application/rss+xml" title="' . $title . '<link rel="alternate" type="application/rss+xml" title="' . $title . '" href="' . $url . '" />'
'" href="' . $url . '" />'
); );
} }

View File

@ -130,9 +130,7 @@ class RSSFeed_Entry extends ViewableData
} }
throw new BadMethodCallException( throw new BadMethodCallException(
get_class($this->failover) . get_class($this->failover) . " object has neither an AbsoluteLink nor a Link method." . " Can't put a link in the RSS feed",
" object has neither an AbsoluteLink nor a Link method." .
" Can't put a link in the RSS feed",
E_USER_WARNING E_USER_WARNING
); );
} }

View File

@ -189,7 +189,7 @@ class RequestHandler extends ViewableData
user_error("Non-string method name: " . var_export($action, true), E_USER_ERROR); user_error("Non-string method name: " . var_export($action, true), E_USER_ERROR);
} }
$classMessage = Director::isLive() ? 'on this handler' : 'on class '.static::class; $classMessage = Director::isLive() ? 'on this handler' : 'on class ' . static::class;
try { try {
if (!$this->hasAction($action)) { if (!$this->hasAction($action)) {
@ -266,8 +266,7 @@ class RequestHandler extends ViewableData
$class = static::class; $class = static::class;
$latestParams = var_export($request->latestParams(), true); $latestParams = var_export($request->latestParams(), true);
Debug::message( Debug::message(
"Rule '{$rule}' matched to action '{$action}' on {$class}. ". "Rule '{$rule}' matched to action '{$action}' on {$class}. " . "Latest request params: {$latestParams}"
"Latest request params: {$latestParams}"
); );
} }
@ -306,7 +305,7 @@ class RequestHandler extends ViewableData
*/ */
protected function handleAction($request, $action) protected function handleAction($request, $action)
{ {
$classMessage = Director::isLive() ? 'on this handler' : 'on class '.static::class; $classMessage = Director::isLive() ? 'on this handler' : 'on class ' . static::class;
if (!$this->hasMethod($action)) { if (!$this->hasMethod($action)) {
return new HTTPResponse("Action '$action' isn't available $classMessage.", 404); return new HTTPResponse("Action '$action' isn't available $classMessage.", 404);
@ -566,8 +565,7 @@ class RequestHandler extends ViewableData
// no link defined by default // no link defined by default
trigger_error( trigger_error(
'Request handler '.static::class. ' does not have a url_segment defined. '. 'Request handler ' . static::class . ' does not have a url_segment defined. ' . 'Relying on this link may be an application error',
'Relying on this link may be an application error',
E_USER_WARNING E_USER_WARNING
); );
return null; return null;

View File

@ -59,7 +59,7 @@ class RequestProcessor implements HTTPMiddleware
foreach ($this->filters as $filter) { foreach ($this->filters as $filter) {
$res = $filter->preRequest($request); $res = $filter->preRequest($request);
if ($res === false) { if ($res === false) {
return new HTTPResponse(_t(__CLASS__.'.INVALID_REQUEST', 'Invalid request'), 400); return new HTTPResponse(_t(__CLASS__ . '.INVALID_REQUEST', 'Invalid request'), 400);
} }
} }

View File

@ -251,7 +251,7 @@ trait Extensible
foreach ($config as $key => $candidate) { foreach ($config as $key => $candidate) {
// extensions with parameters will be stored in config as ExtensionName("Param"). // extensions with parameters will be stored in config as ExtensionName("Param").
if (strcasecmp($candidate, $extension) === 0 || if (strcasecmp($candidate, $extension) === 0 ||
stripos($candidate, $extension.'(') === 0 stripos($candidate, $extension . '(') === 0
) { ) {
$found = true; $found = true;
unset($config[$key]); unset($config[$key]);

View File

@ -789,8 +789,8 @@ class Injector implements ContainerInterface
*/ */
protected function setObjectProperty($object, $name, $value) protected function setObjectProperty($object, $name, $value)
{ {
if (ClassInfo::hasMethod($object, 'set'.$name)) { if (ClassInfo::hasMethod($object, 'set' . $name)) {
$object->{'set'.$name}($value); $object->{'set' . $name}($value);
} else { } else {
$object->$name = $value; $object->$name = $value;
} }

View File

@ -37,7 +37,7 @@ class VersionProvider
foreach ($modules as $module => $title) { foreach ($modules as $module => $title) {
$version = isset($lockModules[$module]) $version = isset($lockModules[$module])
? $lockModules[$module] ? $lockModules[$module]
: _t(__CLASS__.'.VERSIONUNKNOWN', 'Unknown'); : _t(__CLASS__ . '.VERSIONUNKNOWN', 'Unknown');
$output[] = $title . ': ' . $version; $output[] = $title . ': ' . $version;
} }
return implode(', ', $output); return implode(', ', $output);

View File

@ -98,7 +98,7 @@ class ErrorControlChainMiddleware implements HTTPMiddleware
// Fail and redirect the user to the login page // Fail and redirect the user to the login page
$params = array_merge($request->getVars(), $reloadToken->params(false)); $params = array_merge($request->getVars(), $reloadToken->params(false));
$backURL = $request->getURL(). '?' . http_build_query($params); $backURL = $request->getURL() . '?' . http_build_query($params);
$loginPage = Director::absoluteURL(Security::config()->get('login_url')); $loginPage = Director::absoluteURL(Security::config()->get('login_url'));
$loginPage .= "?BackURL=" . urlencode($backURL); $loginPage .= "?BackURL=" . urlencode($backURL);
$result = new HTTPResponse(); $result = new HTTPResponse();

View File

@ -56,7 +56,7 @@ class ParameterConfirmationToken
protected function pathForToken($token) protected function pathForToken($token)
{ {
return TEMP_PATH . DIRECTORY_SEPARATOR . 'token_'.preg_replace('/[^a-z0-9]+/', '', $token); return TEMP_PATH . DIRECTORY_SEPARATOR . 'token_' . preg_replace('/[^a-z0-9]+/', '', $token);
} }
/** /**
@ -116,7 +116,7 @@ class ParameterConfirmationToken
$this->parameterBackURL = $this->backURLToken($request); $this->parameterBackURL = $this->backURLToken($request);
// If the token provided is valid, mark it as such // If the token provided is valid, mark it as such
$token = $request->getVar($parameterName.'token'); $token = $request->getVar($parameterName . 'token');
if ($this->checkToken($token)) { if ($this->checkToken($token)) {
$this->token = $token; $this->token = $token;
} }

View File

@ -76,9 +76,7 @@ class TempFolder
} }
// failing the above, try finding a namespaced silverstripe-cache dir in the system temp // failing the above, try finding a namespaced silverstripe-cache dir in the system temp
$tempPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'silverstripe-cache-php' . preg_replace('/[^\w-\.+]+/', '-', PHP_VERSION) . str_replace(array(' ', '/', ':', '\\'), '-', $base);
'silverstripe-cache-php' . preg_replace('/[^\w-\.+]+/', '-', PHP_VERSION) .
str_replace(array(' ', '/', ':', '\\'), '-', $base);
if (!@file_exists($tempPath)) { if (!@file_exists($tempPath)) {
$oldUMask = umask(0); $oldUMask = umask(0);
@mkdir($tempPath, 0777); @mkdir($tempPath, 0777);
@ -107,9 +105,7 @@ class TempFolder
if (!$worked) { if (!$worked) {
throw new Exception( throw new Exception(
'Permission problem gaining access to a temp folder. ' . 'Permission problem gaining access to a temp folder. ' . 'Please create a folder named silverstripe-cache in the base folder ' . 'of the installation and ensure it has the correct permissions'
'Please create a folder named silverstripe-cache in the base folder ' .
'of the installation and ensure it has the correct permissions'
); );
} }

View File

@ -178,7 +178,7 @@ class Backtrace
} }
} }
$funcName .= "(" . implode(", ", $args) .")"; $funcName .= "(" . implode(", ", $args) . ")";
} }
return $funcName; return $funcName;

View File

@ -256,7 +256,7 @@ class CSVParser implements Iterator
foreach ($srcRow as $i => $value) { foreach ($srcRow as $i => $value) {
// Allow escaping of quotes and commas in the data // Allow escaping of quotes and commas in the data
$value = str_replace( $value = str_replace(
array('\\'.$this->enclosure,'\\'.$this->delimiter), array('\\' . $this->enclosure,'\\' . $this->delimiter),
array($this->enclosure, $this->delimiter), array($this->enclosure, $this->delimiter),
$value $value
); );

View File

@ -119,7 +119,7 @@ class CliDebugView extends DebugView
$output .= CLI::text(str_repeat('=', self::config()->columns), 'green'); $output .= CLI::text(str_repeat('=', self::config()->columns), 'green');
$output .= PHP_EOL; $output .= PHP_EOL;
$output .= CLI::text($this->formatCaller($caller), 'blue', null, true); $output .= CLI::text($this->formatCaller($caller), 'blue', null, true);
$output .= PHP_EOL.PHP_EOL; $output .= PHP_EOL . PHP_EOL;
if (is_string($val)) { if (is_string($val)) {
$output .= wordwrap($val, self::config()->columns); $output .= wordwrap($val, self::config()->columns);
} else { } else {

View File

@ -222,7 +222,7 @@ class DebugView
$debugCSS = ModuleResourceLoader::singleton() $debugCSS = ModuleResourceLoader::singleton()
->resolveURL('silverstripe/framework:client/styles/debug.css'); ->resolveURL('silverstripe/framework:client/styles/debug.css');
$output = '<!DOCTYPE html><html><head><title>' . $url . '</title>'; $output = '<!DOCTYPE html><html><head><title>' . $url . '</title>';
$output .= '<link rel="stylesheet" type="text/css" href="'. $debugCSS .'" />'; $output .= '<link rel="stylesheet" type="text/css" href="' . $debugCSS . '" />';
$output .= '</head>'; $output .= '</head>';
$output .= '<body>'; $output .= '<body>';
@ -367,7 +367,7 @@ class DebugView
public function renderVariable($val, $caller) public function renderVariable($val, $caller)
{ {
$output = '<pre style="background-color:#ccc;padding:5px;font-size:14px;line-height:18px;">'; $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"; $output .= "<span style=\"font-size: 12px;color:#666;\">" . $this->formatCaller($caller) . " - </span>\n";
if (is_string($val)) { if (is_string($val)) {
$output .= wordwrap($val, self::config()->columns); $output .= wordwrap($val, self::config()->columns);
} else { } else {

View File

@ -234,7 +234,7 @@ class Deprecation
$string .= " Called from " . self::get_called_method_from_trace($backtrace, 2) . '.'; $string .= " Called from " . self::get_called_method_from_trace($backtrace, 2) . '.';
if ($caller) { if ($caller) {
user_error($caller.' is deprecated.'.($string ? ' '.$string : ''), $level); user_error($caller . ' is deprecated.' . ($string ? ' ' . $string : ''), $level);
} else { } else {
user_error($string, $level); user_error($string, $level);
} }

View File

@ -127,7 +127,7 @@ class DevelopmentAdmin extends Controller
return $controllerClass::create(); return $controllerClass::create();
} }
$msg = 'Error: no controller registered in '.__CLASS__.' for: '.$request->param('Action'); $msg = 'Error: no controller registered in ' . __CLASS__ . ' for: ' . $request->param('Action');
if (Director::is_cli()) { if (Director::is_cli()) {
// in CLI we cant use httpError because of a bug with stuff being in the output already, see DevAdminControllerTest // in CLI we cant use httpError because of a bug with stuff being in the output already, see DevAdminControllerTest
throw new Exception($msg); throw new Exception($msg);

View File

@ -44,7 +44,7 @@ class FixtureBlueprint
/** @config */ /** @config */
private static $dependencies = array( private static $dependencies = array(
'factory' => '%$'.FixtureFactory::class, 'factory' => '%$' . FixtureFactory::class,
); );
/** /**
@ -221,10 +221,10 @@ class FixtureBlueprint
} else { } else {
$hasOneField = preg_replace('/ID$/', '', $fieldName); $hasOneField = preg_replace('/ID$/', '', $fieldName);
if ($className = $schema->hasOneComponent($class, $hasOneField)) { if ($className = $schema->hasOneComponent($class, $hasOneField)) {
$obj->{$hasOneField.'ID'} = $this->parseValue($fieldVal, $fixtures, $fieldClass); $obj->{$hasOneField . 'ID'} = $this->parseValue($fieldVal, $fixtures, $fieldClass);
// Inject class for polymorphic relation // Inject class for polymorphic relation
if ($className === 'SilverStripe\\ORM\\DataObject') { if ($className === 'SilverStripe\\ORM\\DataObject') {
$obj->{$hasOneField.'Class'} = $fieldClass; $obj->{$hasOneField . 'Class'} = $fieldClass;
} }
} }
} }

View File

@ -282,7 +282,7 @@ PHP;
]; ];
ksort($vars); ksort($vars);
foreach ($vars as $key => $value) { foreach ($vars as $key => $value) {
$lines[] = $key.'="'.addcslashes($value, '"').'"'; $lines[] = $key . '="' . addcslashes($value, '"') . '"';
} }
$this->writeToFile('.env', implode("\n", $lines)); $this->writeToFile('.env', implode("\n", $lines));

View File

@ -88,7 +88,7 @@ class MySQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
} }
$conn = @new PDO( $conn = @new PDO(
'mysql:host='.$databaseConfig['server'], 'mysql:host=' . $databaseConfig['server'],
$databaseConfig['username'], $databaseConfig['username'],
$databaseConfig['password'], $databaseConfig['password'],
$ssl $ssl
@ -247,8 +247,7 @@ class MySQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
preg_quote('"%".*'), preg_quote('"%".*'),
preg_quote('*.*') preg_quote('*.*')
); );
$expression = '/GRANT[ ,\w]+((ALL PRIVILEGES)|('.$permission.'(?! ((VIEW)|(ROUTINE)))))[ ,\w]+ON '. $expression = '/GRANT[ ,\w]+((ALL PRIVILEGES)|(' . $permission . '(?! ((VIEW)|(ROUTINE)))))[ ,\w]+ON ' . $dbPattern . '/i';
$dbPattern.'/i';
return preg_match($expression, $grant); return preg_match($expression, $grant);
} }

View File

@ -97,7 +97,7 @@ class SapphireREPL extends Controller
} catch (Exception $__repl_exception) { } catch (Exception $__repl_exception) {
echo CLI::start_colour("red"); echo CLI::start_colour("red");
printf( printf(
'%s (code: %d) got thrown'.PHP_EOL, '%s (code: %d) got thrown' . PHP_EOL,
get_class($__repl_exception), get_class($__repl_exception),
$__repl_exception->getCode() $__repl_exception->getCode()
); );

View File

@ -1114,7 +1114,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly
$themeBaseDir = substr($themeBaseDir, strlen(BASE_PATH)); $themeBaseDir = substr($themeBaseDir, strlen(BASE_PATH));
} }
SSViewer::config()->update('theme_enabled', true); SSViewer::config()->update('theme_enabled', true);
SSViewer::set_themes([$themeBaseDir.'/themes/'.$theme, '$default']); SSViewer::set_themes([$themeBaseDir . '/themes/' . $theme, '$default']);
try { try {
$callback(); $callback();

View File

@ -95,7 +95,7 @@ class YamlFixture
$this->fixtureString = $fixture; $this->fixtureString = $fixture;
} else { } else {
if (!Director::is_absolute($fixture)) { if (!Director::is_absolute($fixture)) {
$fixture = Director::baseFolder().'/'. $fixture; $fixture = Director::baseFolder() . '/' . $fixture;
} }
if (!file_exists($fixture)) { if (!file_exists($fixture)) {

View File

@ -60,7 +60,7 @@ class CurrencyField extends TextField
public function validate($validator) public function validate($validator)
{ {
$currencySymbol = preg_quote(DBCurrency::config()->uninherited('currency_symbol')); $currencySymbol = preg_quote(DBCurrency::config()->uninherited('currency_symbol'));
$regex = '/^\s*(\-?'.$currencySymbol.'?|'.$currencySymbol.'\-?)?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?\s*$/'; $regex = '/^\s*(\-?' . $currencySymbol . '?|' . $currencySymbol . '\-?)?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?\s*$/';
if (!empty($this->value) && !preg_match($regex, $this->value)) { if (!empty($this->value) && !preg_match($regex, $this->value)) {
$validator->validationError( $validator->validationError(
$this->name, $this->name,

View File

@ -572,7 +572,7 @@ class DatetimeField extends TextField
$validator->validationError( $validator->validationError(
$this->name, $this->name,
_t( _t(
__CLASS__.'.VALIDDATETIMEFORMAT', __CLASS__ . '.VALIDDATETIMEFORMAT',
"Please enter a valid date and time format ({format})", "Please enter a valid date and time format ({format})",
['format' => $this->getDatetimeFormat()] ['format' => $this->getDatetimeFormat()]
) )
@ -588,7 +588,7 @@ class DatetimeField extends TextField
$validator->validationError( $validator->validationError(
$this->name, $this->name,
_t( _t(
__CLASS__.'.VALIDDATETIMEMINDATE', __CLASS__ . '.VALIDDATETIMEMINDATE',
"Your date has to be newer or matching the minimum allowed date and time ({datetime})", "Your date has to be newer or matching the minimum allowed date and time ({datetime})",
[ [
'datetime' => sprintf( 'datetime' => sprintf(
@ -613,7 +613,7 @@ class DatetimeField extends TextField
$validator->validationError( $validator->validationError(
$this->name, $this->name,
_t( _t(
__CLASS__.'.VALIDDATEMAXDATETIME', __CLASS__ . '.VALIDDATEMAXDATETIME',
"Your date has to be older or matching the maximum allowed date and time ({datetime})", "Your date has to be older or matching the maximum allowed date and time ({datetime})",
[ [
'datetime' => sprintf( 'datetime' => sprintf(

View File

@ -1771,7 +1771,7 @@ class Form extends ViewableData implements HasRequestHandler
if ($this->validator) { if ($this->validator) {
/** @skipUpgrade */ /** @skipUpgrade */
$result .= '<h3>'._t(__CLASS__.'.VALIDATOR', 'Validator').'</h3>' . $this->validator->debug(); $result .= '<h3>' . _t(__CLASS__ . '.VALIDATOR', 'Validator') . '</h3>' . $this->validator->debug();
} }
return $result; return $result;

View File

@ -144,8 +144,7 @@ class FormRequestHandler extends RequestHandler
if (empty($vars[$securityID])) { if (empty($vars[$securityID])) {
$this->httpError(400, _t( $this->httpError(400, _t(
"SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE", "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE",
"There seems to have been a technical problem. Please click the back button, ". "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again."
"refresh your browser, and try again."
)); ));
} else { } else {
// Clear invalid token on refresh // Clear invalid token on refresh
@ -258,8 +257,7 @@ class FormRequestHandler extends RequestHandler
$legacyActions = $this->form->config()->get('allowed_actions'); $legacyActions = $this->form->config()->get('allowed_actions');
if ($legacyActions) { if ($legacyActions) {
throw new BadMethodCallException( throw new BadMethodCallException(
"allowed_actions are not valid on Form class " . get_class($this->form) . "allowed_actions are not valid on Form class " . get_class($this->form) . ". Implement these in subclasses of " . static::class . " instead"
". Implement these in subclasses of " . static::class . " instead"
); );
} }

View File

@ -77,7 +77,7 @@ class FormScaffolder
// tabbed or untabbed // tabbed or untabbed
if ($this->tabbed) { if ($this->tabbed) {
$fields->push(new TabSet("Root", $mainTab = new Tab("Main"))); $fields->push(new TabSet("Root", $mainTab = new Tab("Main")));
$mainTab->setTitle(_t(__CLASS__.'.TABMAIN', 'Main')); $mainTab->setTitle(_t(__CLASS__ . '.TABMAIN', 'Main'));
} }
// Add logical fields directly specified in db config // Add logical fields directly specified in db config

View File

@ -897,8 +897,7 @@ class GridField extends FormField
if (!$token->checkRequest($request)) { if (!$token->checkRequest($request)) {
$this->httpError(400, _t( $this->httpError(400, _t(
"SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE", "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE",
"There seems to have been a technical problem. Please click the back button, ". "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again."
"refresh your browser, and try again."
)); ));
} }

View File

@ -119,11 +119,11 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
if (!$record->canEdit()) { if (!$record->canEdit()) {
return null; return null;
} }
$title = _t(__CLASS__.'.UnlinkRelation', "Unlink"); $title = _t(__CLASS__ . '.UnlinkRelation', "Unlink");
$field = GridField_FormAction::create( $field = GridField_FormAction::create(
$gridField, $gridField,
'UnlinkRelation'.$record->ID, 'UnlinkRelation' . $record->ID,
false, false,
"unlinkrelation", "unlinkrelation",
array('RecordID' => $record->ID) array('RecordID' => $record->ID)
@ -138,14 +138,14 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
$field = GridField_FormAction::create( $field = GridField_FormAction::create(
$gridField, $gridField,
'DeleteRecord'.$record->ID, 'DeleteRecord' . $record->ID,
false, false,
"deleterecord", "deleterecord",
array('RecordID' => $record->ID) array('RecordID' => $record->ID)
) )
->addExtraClass('gridfield-button-delete btn--icon-md font-icon-trash-bin btn--no-text grid-field__icon-action') ->addExtraClass('gridfield-button-delete btn--icon-md font-icon-trash-bin btn--no-text grid-field__icon-action')
->setAttribute('title', _t(__CLASS__.'.Delete', "Delete")) ->setAttribute('title', _t(__CLASS__ . '.Delete', "Delete"))
->setDescription(_t(__CLASS__.'.DELETE_DESCRIPTION', 'Delete')); ->setDescription(_t(__CLASS__ . '.DELETE_DESCRIPTION', 'Delete'));
} }
return $field->Field(); return $field->Field();
} }
@ -171,7 +171,7 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
if ($actionName == 'deleterecord') { if ($actionName == 'deleterecord') {
if (!$item->canDelete()) { if (!$item->canDelete()) {
throw new ValidationException( throw new ValidationException(
_t(__CLASS__.'.DeletePermissionsFailure', "No delete permissions") _t(__CLASS__ . '.DeletePermissionsFailure', "No delete permissions")
); );
} }
@ -179,7 +179,7 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
} else { } else {
if (!$item->canEdit()) { if (!$item->canEdit()) {
throw new ValidationException( throw new ValidationException(
_t(__CLASS__.'.EditPermissionsFailure', "No permission to unlink record") _t(__CLASS__ . '.EditPermissionsFailure', "No permission to unlink record")
); );
} }

View File

@ -128,7 +128,7 @@ class GridFieldFilterHeader implements GridField_HTMLProvider, GridField_DataMan
$dataListClone = clone($dataList); $dataListClone = clone($dataList);
foreach ($filterArguments as $columnName => $value) { foreach ($filterArguments as $columnName => $value) {
if ($dataList->canFilterBy($columnName) && $value) { if ($dataList->canFilterBy($columnName) && $value) {
$dataListClone = $dataListClone->filter($columnName.':PartialMatch', $value); $dataListClone = $dataListClone->filter($columnName . ':PartialMatch', $value);
} }
} }
return $dataListClone; return $dataListClone;
@ -196,7 +196,7 @@ class GridFieldFilterHeader implements GridField_HTMLProvider, GridField_DataMan
$field->setAttribute( $field->setAttribute(
'placeholder', 'placeholder',
_t('SilverStripe\\Forms\\GridField\\GridField.FilterBy', "Filter by ") . _t('SilverStripe\\Forms\\GridField\\GridField.'.$metadata['title'], $metadata['title']) _t('SilverStripe\\Forms\\GridField\\GridField.FilterBy', "Filter by ") . _t('SilverStripe\\Forms\\GridField\\GridField.' . $metadata['title'], $metadata['title'])
); );
$fields->push($field); $fields->push($field);

View File

@ -51,8 +51,7 @@ class GridFieldPageCount implements GridField_HTMLProvider
if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) { if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) {
throw new LogicException( throw new LogicException(
static::class . " relies on a GridFieldPaginator to be added " . static::class . " relies on a GridFieldPaginator to be added " . "to the same GridField, but none are present."
"to the same GridField, but none are present."
); );
} }

View File

@ -133,7 +133,7 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
$this->extend('updatePrintData', $data); $this->extend('updatePrintData', $data);
if ($data) { if ($data) {
return $data->renderWith(get_class($gridField)."_print"); return $data->renderWith(get_class($gridField) . "_print");
} }
return null; return null;

View File

@ -171,7 +171,7 @@ class GridFieldSortableHeader implements GridField_HTMLProvider, GridField_DataM
$field = GridField_FormAction::create( $field = GridField_FormAction::create(
$gridField, $gridField,
'SetOrder'.$fieldName, 'SetOrder' . $fieldName,
$title, $title,
"sort$dir", "sort$dir",
array('SortColumn' => $columnField) array('SortColumn' => $columnField)

View File

@ -149,23 +149,23 @@ class GridFieldVersionedState implements GridField_ColumnProvider
if ($record->isOnLiveOnly()) { if ($record->isOnLiveOnly()) {
$flags['removedfromdraft'] = array( $flags['removedfromdraft'] = array(
'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'), 'text' => _t(__CLASS__ . '.ONLIVEONLYSHORT', 'On live only'),
'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Item is published, but has been deleted from draft'), 'title' => _t(__CLASS__ . '.ONLIVEONLYSHORTHELP', 'Item is published, but has been deleted from draft'),
); );
} elseif ($record->isArchived()) { } elseif ($record->isArchived()) {
$flags['archived'] = array( $flags['archived'] = array(
'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'), 'text' => _t(__CLASS__ . '.ARCHIVEDPAGESHORT', 'Archived'),
'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Item is removed from draft and live'), 'title' => _t(__CLASS__ . '.ARCHIVEDPAGEHELP', 'Item is removed from draft and live'),
); );
} elseif ($record->isOnDraftOnly()) { } elseif ($record->isOnDraftOnly()) {
$flags['addedtodraft'] = array( $flags['addedtodraft'] = array(
'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'), 'text' => _t(__CLASS__ . '.ADDEDTODRAFTSHORT', 'Draft'),
'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Item has not been published yet") 'title' => _t(__CLASS__ . '.ADDEDTODRAFTHELP', "Item has not been published yet")
); );
} elseif ($record->isModifiedOnDraft()) { } elseif ($record->isModifiedOnDraft()) {
$flags['modified'] = array( $flags['modified'] = array(
'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'), 'text' => _t(__CLASS__ . '.MODIFIEDONDRAFTSHORT', 'Modified'),
'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Item has unpublished changes'), 'title' => _t(__CLASS__ . '.MODIFIEDONDRAFTHELP', 'Item has unpublished changes'),
); );
} }

View File

@ -168,8 +168,7 @@ SCRIPT;
// Join list of paths // Join list of paths
$filesList = Convert::raw2js(implode(',', $fileURLS)); $filesList = Convert::raw2js(implode(',', $fileURLS));
// Mark all themes, plugins and languages as done // Mark all themes, plugins and languages as done
$buffer[] = "window.tinymce.each('$filesList'.split(',')," . $buffer[] = "window.tinymce.each('$filesList'.split(',')," . "function(f){tinymce.ScriptLoader.markDone(baseURL+f);});";
"function(f){tinymce.ScriptLoader.markDone(baseURL+f);});";
$buffer[] = '})();'; $buffer[] = '})();';
return implode("\n", $buffer) . "\n"; return implode("\n", $buffer) . "\n";

View File

@ -54,7 +54,7 @@ class LookupField extends MultiSelectField
$attrValue = implode(', ', array_values($mapped)); $attrValue = implode(', ', array_values($mapped));
$inputValue = implode(', ', array_values($values)); $inputValue = implode(', ', array_values($values));
} else { } else {
$attrValue = '<i>('._t('SilverStripe\\Forms\\FormField.NONE', 'none').')</i>'; $attrValue = '<i>(' . _t('SilverStripe\\Forms\\FormField.NONE', 'none') . ')</i>';
$inputValue = ''; $inputValue = '';
} }

View File

@ -330,7 +330,7 @@ class MoneyField extends FormField
$validator->validationError( $validator->validationError(
$this->getName(), $this->getName(),
_t( _t(
__CLASS__.'.INVALID_CURRENCY', __CLASS__ . '.INVALID_CURRENCY',
'Currency {currency} is not in the list of allowed currencies', 'Currency {currency} is not in the list of allowed currencies',
['currency' => $currency] ['currency' => $currency]
) )

View File

@ -290,7 +290,7 @@ class NumericField extends TextField
if ($scale === 0) { if ($scale === 0) {
return '1'; return '1';
} }
return '0.'.str_repeat('0', $scale - 1).'1'; return '0.' . str_repeat('0', $scale - 1) . '1';
} }
/** /**

View File

@ -700,7 +700,7 @@ class TreeDropdownField extends FormField
$grandChildren = $child['children']; $grandChildren = $child['children'];
$contextString = implode('/', $parentTitles); $contextString = implode('/', $parentTitles);
$child['contextString'] = ($contextString !== '') ? $contextString .'/' : ''; $child['contextString'] = ($contextString !== '') ? $contextString . '/' : '';
unset($child['children']); unset($child['children']);
if (!$this->search || in_array($child['id'], $this->realSearchIds)) { if (!$this->search || in_array($child['id'], $this->realSearchIds)) {
@ -847,7 +847,7 @@ class TreeDropdownField extends FormField
foreach ($ancestors as $parent) { foreach ($ancestors as $parent) {
$title = $parent->obj($this->getTitleField())->getValue(); $title = $parent->obj($this->getTitleField())->getValue();
$titlePath .= $title .'/'; $titlePath .= $title . '/';
} }
} }
$data['data']['valueObject'] = [ $data['data']['valueObject'] = [

View File

@ -191,7 +191,7 @@ class TreeMultiselectField extends TreeDropdownField
if ($this->form) { if ($this->form) {
$dataUrlTree = $this->Link('tree'); $dataUrlTree = $this->Link('tree');
if (!empty($idArray)) { if (!empty($idArray)) {
$dataUrlTree = Controller::join_links($dataUrlTree, '?forceValue='.implode(',', $idArray)); $dataUrlTree = Controller::join_links($dataUrlTree, '?forceValue=' . implode(',', $idArray));
} }
} }
$properties = array_merge( $properties = array_merge(

View File

@ -357,7 +357,7 @@ class DBQueryBuilder
// Assert that the array version provides the 'limit' key // Assert that the array version provides the 'limit' key
if (!isset($limit['limit']) || !is_numeric($limit['limit'])) { if (!isset($limit['limit']) || !is_numeric($limit['limit'])) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: '. var_export($limit, true) 'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: ' . var_export($limit, true)
); );
} }

View File

@ -285,7 +285,7 @@ abstract class Database
} }
// Implode quoted column // Implode quoted column
return '"' . implode('"'.$separator.'"', $value) . '"'; return '"' . implode('"' . $separator . '"', $value) . '"';
} }
/** /**

View File

@ -42,7 +42,7 @@ class MySQLQueryBuilder extends DBQueryBuilder
// Assert that the array version provides the 'limit' key // Assert that the array version provides the 'limit' key
if (!array_key_exists('limit', $limit) || ($limit['limit'] !== null && ! is_numeric($limit['limit']))) { if (!array_key_exists('limit', $limit) || ($limit['limit'] !== null && ! is_numeric($limit['limit']))) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
'MySQLQueryBuilder::buildLimitSQL(): Wrong format for $limit: '. var_export($limit, true) 'MySQLQueryBuilder::buildLimitSQL(): Wrong format for $limit: ' . var_export($limit, true)
); );
} }

View File

@ -199,7 +199,7 @@ class PDOConnector extends DBConnector
// May throw a PDOException if fails // May throw a PDOException if fails
$this->pdoConnection = new PDO( $this->pdoConnection = new PDO(
$driver.implode(';', $dsn), $driver . implode(';', $dsn),
empty($parameters['username']) ? '' : $parameters['username'], empty($parameters['username']) ? '' : $parameters['username'],
empty($parameters['password']) ? '' : $parameters['password'], empty($parameters['password']) ? '' : $parameters['password'],
$options $options

View File

@ -517,7 +517,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
// Simple fields without relations are mapped directly // Simple fields without relations are mapped directly
if (strpos($field, '.') === false) { if (strpos($field, '.') === false) {
$columnName = '"'.$field.'"'; $columnName = '"' . $field . '"';
return $this; return $this;
} }

View File

@ -321,7 +321,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if (!is_array($record)) { if (!is_array($record)) {
if (is_object($record)) { if (is_object($record)) {
$passed = "an object of type '".get_class($record)."'"; $passed = "an object of type '" . get_class($record) . "'";
} else { } else {
$passed = "The value '$record'"; $passed = "The value '$record'";
} }
@ -359,7 +359,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
foreach ($fields as $field => $fieldSpec) { foreach ($fields as $field => $fieldSpec) {
$fieldClass = strtok($fieldSpec, "."); $fieldClass = strtok($fieldSpec, ".");
if (!array_key_exists($field, $record)) { if (!array_key_exists($field, $record)) {
$this->record[$field.'_Lazy'] = $fieldClass; $this->record[$field . '_Lazy'] = $fieldClass;
} }
} }
} }
@ -636,7 +636,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
{ {
$default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name(); $default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
return i18n::_t( return i18n::_t(
static::class.'.PLURALS', static::class . '.PLURALS',
$default, $default,
[ 'count' => $count ] [ 'count' => $count ]
); );
@ -675,7 +675,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
*/ */
public function i18n_singular_name() public function i18n_singular_name()
{ {
return _t(static::class.'.SINGULARNAME', $this->singular_name()); return _t(static::class . '.SINGULARNAME', $this->singular_name());
} }
/** /**
@ -710,7 +710,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
*/ */
public function i18n_plural_name() public function i18n_plural_name()
{ {
return _t(static::class.'.PLURALNAME', $this->plural_name()); return _t(static::class . '.PLURALNAME', $this->plural_name());
} }
/** /**
@ -809,7 +809,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// If the intermediate relationship objects haven't been created, then write them // If the intermediate relationship objects haven't been created, then write them
if ($i<sizeof($relations)-1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) { if ($i<sizeof($relations)-1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) {
$relObj->write(); $relObj->write();
$relatedFieldName = $relation."ID"; $relatedFieldName = $relation . "ID";
$parentObj->$relatedFieldName = $relObj->ID; $parentObj->$relatedFieldName = $relObj->ID;
$parentObj->write(); $parentObj->write();
} }
@ -828,7 +828,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if ($relObj) { if ($relObj) {
$relObj->$fieldName = $value; $relObj->$fieldName = $value;
$relObj->write(); $relObj->write();
$relatedFieldName = $relation."ID"; $relatedFieldName = $relation . "ID";
$this->$relatedFieldName = $relObj->ID; $this->$relatedFieldName = $relObj->ID;
$relObj->flushCache(); $relObj->flushCache();
} else { } else {
@ -1151,7 +1151,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
{ {
if ($this->ObsoleteClassName) { if ($this->ObsoleteClassName) {
return new ValidationException( return new ValidationException(
"Object is of class '{$this->ObsoleteClassName}' which doesn't exist - ". "Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
"you need to change the ClassName before you can write it" "you need to change the ClassName before you can write it"
); );
} }
@ -1281,7 +1281,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
} }
// Perform an insert on the base table // Perform an insert on the base table
$insert = new SQLInsert('"'.$baseTable.'"'); $insert = new SQLInsert('"' . $baseTable . '"');
$insert $insert
->assign('"Created"', $now) ->assign('"Created"', $now)
->execute(); ->execute();
@ -1565,8 +1565,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if (empty($component)) { if (empty($component)) {
$component = Injector::inst()->create($class); $component = Injector::inst()->create($class);
if ($polymorphic) { if ($polymorphic) {
$component->{$joinField.'ID'} = $this->ID; $component->{$joinField . 'ID'} = $this->ID;
$component->{$joinField.'Class'} = static::class; $component->{$joinField . 'Class'} = static::class;
} else { } else {
$component->$joinField = $this->ID; $component->$joinField = $this->ID;
} }
@ -2167,8 +2167,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
} }
// Do we have a field that needs to be lazy loaded? // Do we have a field that needs to be lazy loaded?
if (isset($this->record[$field.'_Lazy'])) { if (isset($this->record[$field . '_Lazy'])) {
$tableClass = $this->record[$field.'_Lazy']; $tableClass = $this->record[$field . '_Lazy'];
$this->loadLazyFields($tableClass); $this->loadLazyFields($tableClass);
} }
@ -2368,8 +2368,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
} }
// If we've just lazy-loaded the column, then we need to populate the $original array // If we've just lazy-loaded the column, then we need to populate the $original array
if (isset($this->record[$fieldName.'_Lazy'])) { if (isset($this->record[$fieldName . '_Lazy'])) {
$tableClass = $this->record[$fieldName.'_Lazy']; $tableClass = $this->record[$fieldName . '_Lazy'];
$this->loadLazyFields($tableClass); $this->loadLazyFields($tableClass);
} }
@ -2751,7 +2751,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Select db object // Select db object
$component = $dbObject; $component = $dbObject;
} else { } else {
user_error("$relation is not a relation/field on ".get_class($component), E_USER_ERROR); user_error("$relation is not a relation/field on " . get_class($component), E_USER_ERROR);
} }
} }
} }
@ -3659,9 +3659,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
$singularName = $this->singular_name(); $singularName = $this->singular_name();
$conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A '; $conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A ';
return [ return [
static::class.'.SINGULARNAME' => $this->singular_name(), static::class . '.SINGULARNAME' => $this->singular_name(),
static::class.'.PLURALNAME' => $pluralName, static::class . '.PLURALNAME' => $pluralName,
static::class.'.PLURALS' => [ static::class . '.PLURALS' => [
'one' => $conjunction . $singularName, 'one' => $conjunction . $singularName,
'other' => '{count} ' . $pluralName 'other' => '{count} ' . $pluralName
] ]

View File

@ -324,7 +324,7 @@ class DataQuery
$query->selectField( $query->selectField(
" "
CASE WHEN {$baseClassColumn} IS NOT NULL THEN {$baseClassColumn} CASE WHEN {$baseClassColumn} IS NOT NULL THEN {$baseClassColumn}
ELSE ".Convert::raw2sql($baseDataClass, true)." END", ELSE " . Convert::raw2sql($baseDataClass, true) . " END",
"RecordClassName" "RecordClassName"
); );
@ -939,7 +939,7 @@ class DataQuery
foreach ($ancestry as $ancestor) { foreach ($ancestry as $ancestor) {
$ancestorTable = $schema->tableName($ancestor); $ancestorTable = $schema->tableName($ancestor);
if ($ancestorTable !== $foreignTable) { if ($ancestorTable !== $foreignTable) {
$ancestorTableAliased = $foreignPrefix.$ancestorTable; $ancestorTableAliased = $foreignPrefix . $ancestorTable;
$this->query->addLeftJoin( $this->query->addLeftJoin(
$ancestorTable, $ancestorTable,
"\"{$foreignTableAliased}\".\"ID\" = \"{$ancestorTableAliased}\".\"ID\"", "\"{$foreignTableAliased}\".\"ID\" = \"{$ancestorTableAliased}\".\"ID\"",
@ -979,7 +979,7 @@ class DataQuery
// Skip if already joined // Skip if already joined
$foreignBaseClass = $schema->baseDataClass($foreignClass); $foreignBaseClass = $schema->baseDataClass($foreignClass);
$foreignBaseTable = $schema->tableName($foreignBaseClass); $foreignBaseTable = $schema->tableName($foreignBaseClass);
if ($this->query->isJoinedTo($foreignPrefix.$foreignBaseTable)) { if ($this->query->isJoinedTo($foreignPrefix . $foreignBaseTable)) {
return; return;
} }
@ -989,7 +989,7 @@ class DataQuery
$this->query->addLeftJoin( $this->query->addLeftJoin(
$foreignBaseTable, $foreignBaseTable,
"{$foreignIDColumn} = {$localColumn}", "{$foreignIDColumn} = {$localColumn}",
$foreignPrefix.$foreignBaseTable $foreignPrefix . $foreignBaseTable
); );
// Add join clause to the component's ancestry classes so that the search filter could search on // Add join clause to the component's ancestry classes so that the search filter could search on
@ -1000,7 +1000,7 @@ class DataQuery
foreach ($ancestry as $ancestor) { foreach ($ancestry as $ancestor) {
$ancestorTable = $schema->tableName($ancestor); $ancestorTable = $schema->tableName($ancestor);
if ($ancestorTable !== $foreignBaseTable) { if ($ancestorTable !== $foreignBaseTable) {
$ancestorTableAliased = $foreignPrefix.$ancestorTable; $ancestorTableAliased = $foreignPrefix . $ancestorTable;
$this->query->addLeftJoin( $this->query->addLeftJoin(
$ancestorTable, $ancestorTable,
"{$foreignIDColumn} = \"{$ancestorTableAliased}\".\"ID\"", "{$foreignIDColumn} = \"{$ancestorTableAliased}\".\"ID\"",
@ -1048,7 +1048,7 @@ class DataQuery
} }
// Join parent class to join table // Join parent class to join table
$relationAliasedTable = $componentPrefix.$relationClassOrTable; $relationAliasedTable = $componentPrefix . $relationClassOrTable;
$parentIDColumn = $schema->sqlColumnForField($parentClass, 'ID', $parentPrefix); $parentIDColumn = $schema->sqlColumnForField($parentClass, 'ID', $parentPrefix);
$this->query->addLeftJoin( $this->query->addLeftJoin(
$relationClassOrTable, $relationClassOrTable,
@ -1071,7 +1071,7 @@ class DataQuery
foreach ($ancestry as $ancestor) { foreach ($ancestry as $ancestor) {
$ancestorTable = $schema->tableName($ancestor); $ancestorTable = $schema->tableName($ancestor);
if ($ancestorTable !== $componentBaseTable) { if ($ancestorTable !== $componentBaseTable) {
$ancestorTableAliased = $componentPrefix.$ancestorTable; $ancestorTableAliased = $componentPrefix . $ancestorTable;
$this->query->addLeftJoin( $this->query->addLeftJoin(
$ancestorTable, $ancestorTable,
"{$componentIDColumn} = \"{$ancestorTableAliased}\".\"ID\"", "{$componentIDColumn} = \"{$ancestorTableAliased}\".\"ID\"",
@ -1096,7 +1096,7 @@ class DataQuery
$subSelect->selectField($fieldExpression, $field); $subSelect->selectField($fieldExpression, $field);
$subSelect->setOrderBy(null); $subSelect->setOrderBy(null);
$subSelectSQL = $subSelect->sql($subSelectParameters); $subSelectSQL = $subSelect->sql($subSelectParameters);
$this->where(array($this->expressionForField($field)." NOT IN ($subSelectSQL)" => $subSelectParameters)); $this->where(array($this->expressionForField($field) . " NOT IN ($subSelectSQL)" => $subSelectParameters));
return $this; return $this;
} }

View File

@ -211,7 +211,7 @@ abstract class DBComposite extends DBField
// Check bound object // Check bound object
if ($this->record instanceof DataObject) { if ($this->record instanceof DataObject) {
$key = $this->getName().$field; $key = $this->getName() . $field;
return $this->record->getField($key); return $this->record->getField($key);
} }

View File

@ -329,7 +329,7 @@ class DBDate extends DBField
$matches = array(); $matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $this->getTimestamp()), $matches)) { if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $this->getTimestamp()), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3]; $date .= $matches[1] . $matches[2] . ':' . $matches[3];
} else { } else {
$date .= 'Z'; $date .= 'Z';
} }
@ -419,7 +419,7 @@ class DBDate extends DBField
case "seconds": case "seconds":
$span = $ago; $span = $ago;
return _t( return _t(
__CLASS__.'.SECONDS_SHORT_PLURALS', __CLASS__ . '.SECONDS_SHORT_PLURALS',
'{count} sec|{count} secs', '{count} sec|{count} secs',
['count' => $span] ['count' => $span]
); );
@ -427,7 +427,7 @@ class DBDate extends DBField
case "minutes": case "minutes":
$span = round($ago/60); $span = round($ago/60);
return _t( return _t(
__CLASS__.'.MINUTES_SHORT_PLURALS', __CLASS__ . '.MINUTES_SHORT_PLURALS',
'{count} min|{count} mins', '{count} min|{count} mins',
['count' => $span] ['count' => $span]
); );
@ -435,7 +435,7 @@ class DBDate extends DBField
case "hours": case "hours":
$span = round($ago/3600); $span = round($ago/3600);
return _t( return _t(
__CLASS__.'.HOURS_SHORT_PLURALS', __CLASS__ . '.HOURS_SHORT_PLURALS',
'{count} hour|{count} hours', '{count} hour|{count} hours',
['count' => $span] ['count' => $span]
); );
@ -443,7 +443,7 @@ class DBDate extends DBField
case "days": case "days":
$span = round($ago/86400); $span = round($ago/86400);
return _t( return _t(
__CLASS__.'.DAYS_SHORT_PLURALS', __CLASS__ . '.DAYS_SHORT_PLURALS',
'{count} day|{count} days', '{count} day|{count} days',
['count' => $span] ['count' => $span]
); );
@ -451,7 +451,7 @@ class DBDate extends DBField
case "months": case "months":
$span = round($ago/86400/30); $span = round($ago/86400/30);
return _t( return _t(
__CLASS__.'.MONTHS_SHORT_PLURALS', __CLASS__ . '.MONTHS_SHORT_PLURALS',
'{count} month|{count} months', '{count} month|{count} months',
['count' => $span] ['count' => $span]
); );
@ -459,7 +459,7 @@ class DBDate extends DBField
case "years": case "years":
$span = round($ago/86400/365); $span = round($ago/86400/365);
return _t( return _t(
__CLASS__.'.YEARS_SHORT_PLURALS', __CLASS__ . '.YEARS_SHORT_PLURALS',
'{count} year|{count} years', '{count} year|{count} years',
['count' => $span] ['count' => $span]
); );

View File

@ -186,11 +186,11 @@ class DBHTMLText extends DBText
if ($tag === 'text()') { if ($tag === 'text()') {
$textFilter = ''; // Disable text filter if allowed $textFilter = ''; // Disable text filter if allowed
} else { } else {
$query[] = 'not(self::'.$tag.')'; $query[] = 'not(self::' . $tag . ')';
} }
} }
foreach ($dom->query('//body//*['.implode(' and ', $query).']'.$textFilter) as $el) { foreach ($dom->query('//body//*[' . implode(' and ', $query) . ']' . $textFilter) as $el) {
if ($el->parentNode) { if ($el->parentNode) {
$el->parentNode->removeChild($el); $el->parentNode->removeChild($el);
} }

View File

@ -54,7 +54,7 @@ class HasManyList extends RelationList
// Apply relation filter // Apply relation filter
$key = DataObject::getSchema()->sqlColumnForField($this->dataClass(), $this->getForeignKey()); $key = DataObject::getSchema()->sqlColumnForField($this->dataClass(), $this->getForeignKey());
if (is_array($id)) { if (is_array($id)) {
return array("$key IN (".DB::placeholders($id).")" => $id); return array("$key IN (" . DB::placeholders($id) . ")" => $id);
} elseif ($id !== null) { } elseif ($id !== null) {
return array($key => $id); return array($key => $id);
} }

View File

@ -178,7 +178,7 @@ class ManyManyList extends RelationList
// Apply relation filter // Apply relation filter
$key = "\"{$this->joinTable}\".\"{$this->foreignKey}\""; $key = "\"{$this->joinTable}\".\"{$this->foreignKey}\"";
if (is_array($id)) { if (is_array($id)) {
return array("$key IN (".DB::placeholders($id).")" => $id); return array("$key IN (" . DB::placeholders($id) . ")" => $id);
} elseif ($id !== null) { } elseif ($id !== null) {
return array($key => $id); return array($key => $id);
} }

View File

@ -76,7 +76,7 @@ class SQLAssignmentRow
throw new InvalidArgumentException( throw new InvalidArgumentException(
"Nested field assignments should be given as a single parameterised item array in " "Nested field assignments should be given as a single parameterised item array in "
. "array('?' => array('value')) format)" . "array('?' => array('value')) format)"
); );
} }

View File

@ -227,7 +227,7 @@ abstract class SQLConditionalExpression extends SQLExpression
foreach ($this->from as $key => $tableClause) { foreach ($this->from as $key => $tableClause) {
if (is_array($tableClause)) { if (is_array($tableClause)) {
$table = '"'.$tableClause['table'].'"'; $table = '"' . $tableClause['table'] . '"';
} elseif (is_string($tableClause) && preg_match('/JOIN +("[^"]+") +(AS|ON) +/i', $tableClause, $matches)) { } elseif (is_string($tableClause) && preg_match('/JOIN +("[^"]+") +(AS|ON) +/i', $tableClause, $matches)) {
$table = $matches[1]; $table = $matches[1];
} else { } else {
@ -526,7 +526,7 @@ abstract class SQLConditionalExpression extends SQLExpression
$filters = $this->normalisePredicates(func_get_args()); $filters = $this->normalisePredicates(func_get_args());
$this->splitQueryParameters($filters, $predicates, $parameters); $this->splitQueryParameters($filters, $predicates, $parameters);
$clause = "(".implode(") OR (", $predicates).")"; $clause = "(" . implode(") OR (", $predicates) . ")";
return $this->addWhere(array($clause => $parameters)); return $this->addWhere(array($clause => $parameters));
} }
@ -595,7 +595,7 @@ abstract class SQLConditionalExpression extends SQLExpression
// then run a quick check over the contents and recursively parse // then run a quick check over the contents and recursively parse
if (count($value) != 1) { if (count($value) != 1) {
user_error('Nested predicates should be given as a single item array in ' user_error('Nested predicates should be given as a single item array in '
. 'array($predicate => array($prameters)) format)', E_USER_ERROR); . 'array($predicate => array($prameters)) format)', E_USER_ERROR);
} }
foreach ($value as $key => $pairValue) { foreach ($value as $key => $pairValue) {
return $this->parsePredicate($key, $pairValue); return $this->parsePredicate($key, $pairValue);

View File

@ -95,7 +95,7 @@ class CMSSecurity extends Security
// Format // Format
return _t( return _t(
__CLASS__.'.LOGIN_MESSAGE', __CLASS__ . '.LOGIN_MESSAGE',
'<p>Your session has timed out due to inactivity</p>' '<p>Your session has timed out due to inactivity</p>'
); );
} }
@ -121,7 +121,7 @@ class CMSSecurity extends Security
$loginURLATT = Convert::raw2att($loginURL); $loginURLATT = Convert::raw2att($loginURL);
$loginURLJS = Convert::raw2js($loginURL); $loginURLJS = Convert::raw2js($loginURL);
$message = _t( $message = _t(
__CLASS__.'.INVALIDUSER', __CLASS__ . '.INVALIDUSER',
'<p>Invalid user. <a target="_top" href="{link}">Please re-authenticate here</a> to continue.</p>', '<p>Invalid user. <a target="_top" href="{link}">Please re-authenticate here</a> to continue.</p>',
'Message displayed to user if their session cannot be restored', 'Message displayed to user if their session cannot be restored',
array('link' => $loginURLATT) array('link' => $loginURLATT)
@ -181,7 +181,7 @@ PHP
} }
// Get redirect url // Get redirect url
$controller = $this->getResponseController(_t(__CLASS__.'.SUCCESS', 'Success')); $controller = $this->getResponseController(_t(__CLASS__ . '.SUCCESS', 'Success'));
$backURLs = array( $backURLs = array(
$this->getRequest()->requestVar('BackURL'), $this->getRequest()->requestVar('BackURL'),
$this->getRequest()->getSession()->get('BackURL'), $this->getRequest()->getSession()->get('BackURL'),
@ -197,9 +197,8 @@ PHP
// Show login // Show login
$controller = $controller->customise(array( $controller = $controller->customise(array(
'Content' => DBField::create_field(DBHTMLText::class, _t( 'Content' => DBField::create_field(DBHTMLText::class, _t(
__CLASS__.'.SUCCESSCONTENT', __CLASS__ . '.SUCCESSCONTENT',
'<p>Login success. If you are not automatically redirected ' . '<p>Login success. If you are not automatically redirected ' . '<a target="_top" href="{link}">click here</a></p>',
'<a target="_top" href="{link}">click here</a></p>',
'Login message displayed in the cms popup once a user has re-authenticated themselves', 'Login message displayed in the cms popup once a user has re-authenticated themselves',
array('link' => Convert::raw2att($backURL)) array('link' => Convert::raw2att($backURL))
)) ))

View File

@ -88,7 +88,7 @@ class Group extends DataObject
parent::populateDefaults(); parent::populateDefaults();
if (!$this->Title) { if (!$this->Title) {
$this->Title = _t(__CLASS__.'.NEWGROUP', "New Group"); $this->Title = _t(__CLASS__ . '.NEWGROUP', "New Group");
} }
} }
@ -120,7 +120,7 @@ class Group extends DataObject
"Root", "Root",
new Tab( new Tab(
'Members', 'Members',
_t(__CLASS__.'.MEMBERS', 'Members'), _t(__CLASS__ . '.MEMBERS', 'Members'),
new TextField("Title", $this->fieldLabel('Title')), new TextField("Title", $this->fieldLabel('Title')),
$parentidfield = DropdownField::create( $parentidfield = DropdownField::create(
'ParentID', 'ParentID',
@ -131,7 +131,7 @@ class Group extends DataObject
), ),
$permissionsTab = new Tab( $permissionsTab = new Tab(
'Permissions', 'Permissions',
_t(__CLASS__.'.PERMISSIONS', 'Permissions'), _t(__CLASS__ . '.PERMISSIONS', 'Permissions'),
$permissionsField = new PermissionCheckboxSetField( $permissionsField = new PermissionCheckboxSetField(
'Permissions', 'Permissions',
false, false,
@ -217,14 +217,14 @@ class Group extends DataObject
PermissionRole::get()->count() && PermissionRole::get()->count() &&
class_exists(SecurityAdmin::class) class_exists(SecurityAdmin::class)
) { ) {
$fields->findOrMakeTab('Root.Roles', _t(__CLASS__.'.ROLES', 'Roles')); $fields->findOrMakeTab('Root.Roles', _t(__CLASS__ . '.ROLES', 'Roles'));
$fields->addFieldToTab( $fields->addFieldToTab(
'Root.Roles', 'Root.Roles',
new LiteralField( new LiteralField(
"", "",
"<p>" . "<p>" .
_t( _t(
__CLASS__.'.ROLESDESCRIPTION', __CLASS__ . '.ROLESDESCRIPTION',
"Roles are predefined sets of permissions, and can be assigned to groups.<br />" "Roles are predefined sets of permissions, and can be assigned to groups.<br />"
. "They are inherited from parent groups if required." . "They are inherited from parent groups if required."
) . '<br />' . ) . '<br />' .
@ -286,7 +286,7 @@ class Group extends DataObject
public function fieldLabels($includerelations = true) public function fieldLabels($includerelations = true)
{ {
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['Title'] = _t(__CLASS__.'.GROUPNAME', 'Group name'); $labels['Title'] = _t(__CLASS__ . '.GROUPNAME', 'Group name');
$labels['Description'] = _t('SilverStripe\\Security\\Group.Description', 'Description'); $labels['Description'] = _t('SilverStripe\\Security\\Group.Description', 'Description');
$labels['Code'] = _t('SilverStripe\\Security\\Group.Code', 'Group Code', 'Programmatical code identifying a group'); $labels['Code'] = _t('SilverStripe\\Security\\Group.Code', 'Group Code', 'Programmatical code identifying a group');
$labels['Locked'] = _t('SilverStripe\\Security\\Group.Locked', 'Locked?', 'Group is locked in the security administration area'); $labels['Locked'] = _t('SilverStripe\\Security\\Group.Locked', 'Locked?', 'Group is locked in the security administration area');
@ -514,7 +514,7 @@ class Group extends DataObject
// Only set code property when the group has a custom title, and no code exists. // Only set code property when the group has a custom title, and no code exists.
// The "Code" attribute is usually treated as a more permanent identifier than database IDs // The "Code" attribute is usually treated as a more permanent identifier than database IDs
// in custom application logic, so can't be changed after its first set. // in custom application logic, so can't be changed after its first set.
if (!$this->Code && $this->Title != _t(__CLASS__.'.NEWGROUP', "New Group")) { if (!$this->Code && $this->Title != _t(__CLASS__ . '.NEWGROUP', "New Group")) {
$this->setCode($this->Title); $this->setCode($this->Title);
} }
} }

View File

@ -306,8 +306,7 @@ class InheritedPermissions implements PermissionChecker
$baseTable = DataObject::getSchema()->baseDataTable($this->getBaseClass()); $baseTable = DataObject::getSchema()->baseDataTable($this->getBaseClass());
$uninheritedPermissions = $stageRecords $uninheritedPermissions = $stageRecords
->where([ ->where([
"(\"$typeField\" IN (?, ?) OR " . "(\"$typeField\" IN (?, ?) OR " . "(\"$typeField\" = ? AND \"$groupJoinTable\".\"{$baseTable}ID\" IS NOT NULL))"
"(\"$typeField\" = ? AND \"$groupJoinTable\".\"{$baseTable}ID\" IS NOT NULL))"
=> [ => [
self::ANYONE, self::ANYONE,
self::LOGGED_IN_USERS, self::LOGGED_IN_USERS,
@ -316,8 +315,7 @@ class InheritedPermissions implements PermissionChecker
]) ])
->leftJoin( ->leftJoin(
$groupJoinTable, $groupJoinTable,
"\"$groupJoinTable\".\"{$baseTable}ID\" = \"{$baseTable}\".\"ID\" AND " . "\"$groupJoinTable\".\"{$baseTable}ID\" = \"{$baseTable}\".\"ID\" AND " . "\"$groupJoinTable\".\"GroupID\" IN ($groupIDsSQLList)"
"\"$groupJoinTable\".\"GroupID\" IN ($groupIDsSQLList)"
)->column('ID'); )->column('ID');
} else { } else {
// Only view pages with ViewType = Anyone if not logged in // Only view pages with ViewType = Anyone if not logged in

View File

@ -56,10 +56,10 @@ class LoginAttempt extends DataObject
public function fieldLabels($includerelations = true) public function fieldLabels($includerelations = true)
{ {
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['Email'] = _t(__CLASS__.'.Email', 'Email Address'); $labels['Email'] = _t(__CLASS__ . '.Email', 'Email Address');
$labels['EmailHashed'] = _t(__CLASS__.'.EmailHashed', 'Email Address (hashed)'); $labels['EmailHashed'] = _t(__CLASS__ . '.EmailHashed', 'Email Address (hashed)');
$labels['Status'] = _t(__CLASS__.'.Status', 'Status'); $labels['Status'] = _t(__CLASS__ . '.Status', 'Status');
$labels['IP'] = _t(__CLASS__.'.IP', 'IP Address'); $labels['IP'] = _t(__CLASS__ . '.IP', 'IP Address');
return $labels; return $labels;
} }

View File

@ -351,8 +351,7 @@ class Member extends DataObject
$result->addError( $result->addError(
_t( _t(
__CLASS__ . '.ERRORLOCKEDOUT2', __CLASS__ . '.ERRORLOCKEDOUT2',
'Your account has been temporarily disabled because of too many failed attempts at ' . 'Your account has been temporarily disabled because of too many failed attempts at ' . 'logging in. Please try again in {count} minutes.',
'logging in. Please try again in {count} minutes.',
null, null,
array('count' => static::config()->get('lock_out_delay_mins')) array('count' => static::config()->get('lock_out_delay_mins'))
) )

View File

@ -86,14 +86,14 @@ class CMSMemberLoginForm extends MemberLoginForm
// Make actions // Make actions
$actions = FieldList::create([ $actions = FieldList::create([
FormAction::create('doLogin', _t(__CLASS__.'.BUTTONLOGIN', "Let me back in")) FormAction::create('doLogin', _t(__CLASS__ . '.BUTTONLOGIN', "Let me back in"))
->addExtraClass('btn-primary'), ->addExtraClass('btn-primary'),
LiteralField::create( LiteralField::create(
'doLogout', 'doLogout',
sprintf( sprintf(
'<a class="btn btn-secondary" href="%s" target="_top">%s</a>', '<a class="btn btn-secondary" href="%s" target="_top">%s</a>',
Convert::raw2att($logoutLink), Convert::raw2att($logoutLink),
_t(__CLASS__.'.BUTTONLOGOUT', "Log out") _t(__CLASS__ . '.BUTTONLOGOUT', "Log out")
) )
), ),
LiteralField::create( LiteralField::create(
@ -101,7 +101,7 @@ class CMSMemberLoginForm extends MemberLoginForm
sprintf( sprintf(
'<a href="%s" class="cms-security__container__form__forgotPassword btn btn-secondary" target="_top">%s</a>', '<a href="%s" class="cms-security__container__form__forgotPassword btn btn-secondary" target="_top">%s</a>',
$this->getExternalLink('lostpassword'), $this->getExternalLink('lostpassword'),
_t(__CLASS__.'.BUTTONFORGOTPASSWORD', "Forgot password") _t(__CLASS__ . '.BUTTONFORGOTPASSWORD', "Forgot password")
) )
) )
]); ]);
@ -125,6 +125,6 @@ class CMSMemberLoginForm extends MemberLoginForm
*/ */
public function getAuthenticatorName() public function getAuthenticatorName()
{ {
return _t(__CLASS__.'.AUTHENTICATORNAME', 'CMS Member Login Form'); return _t(__CLASS__ . '.AUTHENTICATORNAME', 'CMS Member Login Form');
} }
} }

View File

@ -532,9 +532,9 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl
$classes = ClassInfo::implementorsOf('SilverStripe\\Security\\PermissionProvider'); $classes = ClassInfo::implementorsOf('SilverStripe\\Security\\PermissionProvider');
$allCodes = array(); $allCodes = array();
$adminCategory = _t(__CLASS__.'.AdminGroup', 'Administrator'); $adminCategory = _t(__CLASS__ . '.AdminGroup', 'Administrator');
$allCodes[$adminCategory]['ADMIN'] = array( $allCodes[$adminCategory]['ADMIN'] = array(
'name' => _t(__CLASS__.'.FULLADMINRIGHTS', 'Full administrative rights'), 'name' => _t(__CLASS__ . '.FULLADMINRIGHTS', 'Full administrative rights'),
'help' => _t( 'help' => _t(
'SilverStripe\\Security\\Permission.FULLADMINRIGHTS_HELP', 'SilverStripe\\Security\\Permission.FULLADMINRIGHTS_HELP',
'Implies and overrules all other assigned permissions.' 'Implies and overrules all other assigned permissions.'
@ -727,10 +727,10 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl
$keys = parent::provideI18nEntities(); // TODO: Change the autogenerated stub $keys = parent::provideI18nEntities(); // TODO: Change the autogenerated stub
// Localise all permission categories // Localise all permission categories
$keys[__CLASS__.'.AdminGroup'] = 'Administrator'; $keys[__CLASS__ . '.AdminGroup'] = 'Administrator';
$keys[__CLASS__.'.CMS_ACCESS_CATEGORY'] = 'CMS Access'; $keys[__CLASS__ . '.CMS_ACCESS_CATEGORY'] = 'CMS Access';
$keys[__CLASS__.'.CONTENT_CATEGORY'] = 'Content permissions'; $keys[__CLASS__ . '.CONTENT_CATEGORY'] = 'Content permissions';
$keys[__CLASS__.'.PERMISSIONS_CATEGORY'] = 'Roles and access permissions'; $keys[__CLASS__ . '.PERMISSIONS_CATEGORY'] = 'Roles and access permissions';
return $keys; return $keys;
} }
} }

View File

@ -225,7 +225,7 @@ class PermissionCheckboxSetField extends FormField
} elseif ($this->records && $this->records->Count() > 1 && isset($uninheritedCodes[$code])) { } elseif ($this->records && $this->records->Count() > 1 && isset($uninheritedCodes[$code])) {
// If code assignments are collected from more than one "source group", // If code assignments are collected from more than one "source group",
// show its origin automatically // show its origin automatically
$inheritMessage = ' (' . join(', ', $uninheritedCodes[$code]).')'; $inheritMessage = ' (' . join(', ', $uninheritedCodes[$code]) . ')';
} }
// Disallow modification of "privileged" permissions unless currently logged-in user is an admin // Disallow modification of "privileged" permissions unless currently logged-in user is an admin

View File

@ -145,7 +145,7 @@ class RememberLoginHash extends DataObject
$now = DBDatetime::now(); $now = DBDatetime::now();
$expiryDate = new DateTime($now->Rfc2822()); $expiryDate = new DateTime($now->Rfc2822());
$tokenExpiryDays = static::config()->token_expiry_days; $tokenExpiryDays = static::config()->token_expiry_days;
$expiryDate->add(new DateInterval('P'.$tokenExpiryDays.'D')); $expiryDate->add(new DateInterval('P' . $tokenExpiryDays . 'D'));
$rememberLoginHash->ExpiryDate = $expiryDate->format('Y-m-d H:i:s'); $rememberLoginHash->ExpiryDate = $expiryDate->format('Y-m-d H:i:s');
$rememberLoginHash->extend('onAfterGenerateToken'); $rememberLoginHash->extend('onAfterGenerateToken');
$rememberLoginHash->write(); $rememberLoginHash->write();

View File

@ -675,7 +675,7 @@ class Security extends Controller implements TemplateGlobalProvider
return $this->delegateToMultipleHandlers( return $this->delegateToMultipleHandlers(
$handlers, $handlers,
_t(__CLASS__.'.LOGIN', 'Log in'), _t(__CLASS__ . '.LOGIN', 'Log in'),
$this->getTemplatesFor('login'), $this->getTemplatesFor('login'),
[$this, 'aggregateTabbedForms'] [$this, 'aggregateTabbedForms']
); );
@ -712,7 +712,7 @@ class Security extends Controller implements TemplateGlobalProvider
return $this->delegateToMultipleHandlers( return $this->delegateToMultipleHandlers(
$handlers, $handlers,
_t(__CLASS__.'.LOGOUT', 'Log out'), _t(__CLASS__ . '.LOGOUT', 'Log out'),
$this->getTemplatesFor('logout'), $this->getTemplatesFor('logout'),
[$this, 'aggregateAuthenticatorResponses'] [$this, 'aggregateAuthenticatorResponses']
); );

View File

@ -22,8 +22,7 @@ class HTML4Value extends HTMLValue
$errorState = libxml_use_internal_errors(true); $errorState = libxml_use_internal_errors(true);
$result = $this->getDocument()->loadHTML( $result = $this->getDocument()->loadHTML(
'<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head>' . '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head>' . "<body>$content</body></html>"
"<body>$content</body></html>"
); );
libxml_clear_errors(); libxml_clear_errors();
libxml_use_internal_errors($errorState); libxml_use_internal_errors($errorState);

View File

@ -49,7 +49,7 @@ abstract class HTMLValue extends ViewableData
$i = 0; $i = 0;
foreach ($xp->query('//body//@*') as $attr) { foreach ($xp->query('//body//@*') as $attr) {
$key = "__HTMLVALUE_".($i++); $key = "__HTMLVALUE_" . ($i++);
$attrs[$key] = $attr->value; $attrs[$key] = $attr->value;
$attr->value = $key; $attr->value = $key;
} }

View File

@ -30,7 +30,7 @@ class ShortcodeParser
public function img_shortcode($attrs) public function img_shortcode($attrs)
{ {
return "<img src='".$attrs['src']."'>"; return "<img src='" . $attrs['src'] . "'>";
} }
protected static $instances = array(); protected static $instances = array();
@ -191,9 +191,9 @@ class ShortcodeParser
// Missing tag // Missing tag
if ($content === false) { if ($content === false) {
if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) { if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) {
user_error('Unknown shortcode tag '.$tag['open'], E_USER_ERROR); user_error('Unknown shortcode tag ' . $tag['open'], E_USER_ERROR);
} elseif (self::$error_behavior == self::WARN && $isHTMLAllowed) { } elseif (self::$error_behavior == self::WARN && $isHTMLAllowed) {
$content = '<strong class="warning">'.$tag['text'].'</strong>'; $content = '<strong class="warning">' . $tag['text'] . '</strong>';
} elseif (ShortcodeParser::$error_behavior == ShortcodeParser::STRIP) { } elseif (ShortcodeParser::$error_behavior == ShortcodeParser::STRIP) {
return ''; return '';
} else { } else {
@ -271,7 +271,7 @@ class ShortcodeParser
protected static function attrrx() protected static function attrrx()
{ {
return '/'.self::$attrrx.'/xS'; return '/' . self::$attrrx . '/xS';
} }
protected static $tagrx = ' protected static $tagrx = '
@ -296,7 +296,7 @@ class ShortcodeParser
protected static function tagrx() protected static function tagrx()
{ {
return '/'.sprintf(self::$tagrx, self::$attrrx).'/xS'; return '/' . sprintf(self::$tagrx, self::$attrrx) . '/xS';
} }
const WARN = 'warn'; const WARN = 'warn';
@ -372,13 +372,11 @@ class ShortcodeParser
$err = null; $err = null;
if ($i == 0) { if ($i == 0) {
$err = 'Close tag "'.$tags[$i]['close'].'" is the first found tag, so has no related open tag'; $err = 'Close tag "' . $tags[$i]['close'] . '" is the first found tag, so has no related open tag';
} elseif (!$tags[$i-1]['open']) { } elseif (!$tags[$i-1]['open']) {
$err = 'Close tag "'.$tags[$i]['close'].'" preceded by another close tag "'. $err = 'Close tag "' . $tags[$i]['close'] . '" preceded by another close tag "' . $tags[$i-1]['close'] . '"';
$tags[$i-1]['close'].'"';
} elseif ($tags[$i]['close'] != $tags[$i-1]['open']) { } elseif ($tags[$i]['close'] != $tags[$i-1]['open']) {
$err = 'Close tag "'.$tags[$i]['close'].'" doesn\'t match preceding open tag "'. $err = 'Close tag "' . $tags[$i]['close'] . '" doesn\'t match preceding open tag "' . $tags[$i-1]['open'] . '"';
$tags[$i-1]['open'].'"';
} }
if ($err) { if ($err) {
@ -502,7 +500,7 @@ class ShortcodeParser
$markerClass = self::$marker_class; $markerClass = self::$marker_class;
$content = $this->replaceTagsWithText($content, $tags, function ($idx, $tag) use ($markerClass) { $content = $this->replaceTagsWithText($content, $tags, function ($idx, $tag) use ($markerClass) {
return '<img class="'.$markerClass.'" data-tagid="'.$idx.'" />'; return '<img class="' . $markerClass . '" data-tagid="' . $idx . '" />';
}); });
} }
@ -599,14 +597,13 @@ class ShortcodeParser
elseif ($location == self::INLINE) { elseif ($location == self::INLINE) {
if (in_array(strtolower($node->tagName), self::$block_level_elements)) { if (in_array(strtolower($node->tagName), self::$block_level_elements)) {
user_error( user_error(
'Requested to insert block tag '.$node->tagName. 'Requested to insert block tag ' . $node->tagName . ' inline - probably this will break HTML compliance',
' inline - probably this will break HTML compliance',
E_USER_WARNING E_USER_WARNING
); );
} }
// NOP // NOP
} else { } else {
user_error('Unknown value for $location argument '.$location, E_USER_ERROR); user_error('Unknown value for $location argument ' . $location, E_USER_ERROR);
} }
} }
@ -680,7 +677,7 @@ class ShortcodeParser
$this->replaceAttributeTagsWithContent($htmlvalue); $this->replaceAttributeTagsWithContent($htmlvalue);
// Find all the element scoped shortcode markers // Find all the element scoped shortcode markers
$shortcodes = $htmlvalue->query('//img[@class="'.self::$marker_class.'"]'); $shortcodes = $htmlvalue->query('//img[@class="' . self::$marker_class . '"]');
// Find the parents. Do this before DOM modification, since SPLIT might cause parents to move otherwise // Find the parents. Do this before DOM modification, since SPLIT might cause parents to move otherwise
$parents = $this->findParentsForMarkers($shortcodes); $parents = $this->findParentsForMarkers($shortcodes);
@ -729,7 +726,7 @@ class ShortcodeParser
$content = preg_replace_callback( $content = preg_replace_callback(
// Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers() // Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers()
// hasn't been heavily modified // hasn't been heavily modified
'/<img[^>]+class="'.preg_quote(self::$marker_class).'"[^>]+data-tagid="([^"]+)"[^>]+>/i', '/<img[^>]+class="' . preg_quote(self::$marker_class) . '"[^>]+data-tagid="([^"]+)"[^>]+>/i',
function ($matches) use ($tags, $parser) { function ($matches) use ($tags, $parser) {
$tag = $tags[$matches[1]]; $tag = $tags[$matches[1]];
return $parser->getShortcodeReplacementText($tag); return $parser->getShortcodeReplacementText($tag);

View File

@ -79,7 +79,7 @@ class ThemeManifest implements ThemeList
// build cache from factory // build cache from factory
if ($this->cacheFactory) { if ($this->cacheFactory) {
$this->cache = $this->cacheFactory->create( $this->cache = $this->cacheFactory->create(
CacheInterface::class.'.thememanifest', CacheInterface::class . '.thememanifest',
[ 'namespace' => 'thememanifest' . ($includeTests ? '_tests' : '') ] [ 'namespace' => 'thememanifest' . ($includeTests ? '_tests' : '') ]
); );
} }
@ -165,7 +165,7 @@ class ThemeManifest implements ThemeList
return; return;
} }
$dir = trim(substr(dirname($pathname), strlen($this->base)), '/\\'); $dir = trim(substr(dirname($pathname), strlen($this->base)), '/\\');
$this->themes[] = "/".$dir; $this->themes[] = "/" . $dir;
} }
/** /**

View File

@ -108,7 +108,7 @@ class ThemeResourceLoader
// If there is no slash / colon it's a legacy theme // If there is no slash / colon it's a legacy theme
if ($slashPos === false && count($parts) === 1) { if ($slashPos === false && count($parts) === 1) {
return THEMES_DIR.'/'.$identifier; return THEMES_DIR . '/' . $identifier;
} }
// Extract from <vendor>/<module>:<theme> format. // Extract from <vendor>/<module>:<theme> format.

View File

@ -398,7 +398,7 @@ class ViewableData implements IteratorAggregate
} }
throw new UnexpectedValueException( throw new UnexpectedValueException(
"ViewableData::renderWith(): unexpected ".get_class($template)." object, expected an SSViewer instance" "ViewableData::renderWith(): unexpected " . get_class($template) . " object, expected an SSViewer instance"
); );
} }

View File

@ -44,9 +44,7 @@ class ViewableData_Debugger extends ViewableData
// debugging info for a specific field // debugging info for a specific field
$class = get_class($this->object); $class = get_class($this->object);
if ($field) { if ($field) {
return "<b>Debugging Information for {$class}->{$field}</b><br/>" . return "<b>Debugging Information for {$class}->{$field}</b><br/>" . ($this->object->hasMethod($field) ? "Has method '$field'<br/>" : null) . ($this->object->hasField($field) ? "Has field '$field'<br/>" : null);
($this->object->hasMethod($field) ? "Has method '$field'<br/>" : null) .
($this->object->hasField($field) ? "Has field '$field'<br/>" : null);
} }
// debugging information for the entire class // debugging information for the entire class

View File

@ -343,7 +343,7 @@ class i18nTextCollector
// Find FQN that ends with $class // Find FQN that ends with $class
$classes = preg_grep( $classes = preg_grep(
'/'.preg_quote("\\{$class}", '\/').'$/i', '/' . preg_quote("\\{$class}", '\/') . '$/i',
ClassLoader::inst()->getManifest()->getClassNames() ClassLoader::inst()->getManifest()->getClassNames()
); );
@ -662,7 +662,7 @@ class i18nTextCollector
$matches['text'] $matches['text']
); );
} else { } else {
throw new LogicException("Invalid string escape: " .$text); throw new LogicException("Invalid string escape: " . $text);
} }
} elseif ($id === T_CLASS_C) { } elseif ($id === T_CLASS_C) {
// Evaluate __CLASS__ . '.KEY' and self::class concatenation // Evaluate __CLASS__ . '.KEY' and self::class concatenation
@ -907,7 +907,7 @@ class i18nTextCollector
return $fileList; return $fileList;
} }
foreach (glob($folder.'/*') as $path) { foreach (glob($folder . '/*') as $path) {
// Recurse if directory // Recurse if directory
if (is_dir($path)) { if (is_dir($path)) {
$fileList = array_merge( $fileList = array_merge(

View File

@ -135,7 +135,7 @@ if (!defined('ASSETS_PATH')) {
// Custom include path - deprecated // Custom include path - deprecated
if (defined('CUSTOM_INCLUDE_PATH')) { if (defined('CUSTOM_INCLUDE_PATH')) {
set_include_path(CUSTOM_INCLUDE_PATH . PATH_SEPARATOR . get_include_path()); set_include_path(CUSTOM_INCLUDE_PATH . PATH_SEPARATOR . get_include_path());
} }
// Define the temporary folder if it wasn't defined yet // Define the temporary folder if it wasn't defined yet

View File

@ -1,9 +1,7 @@
<?php <?php
if (!defined('BASE_PATH')) { if (!defined('BASE_PATH')) {
echo "BASE_PATH hasn't been defined. This probably means that framework/Core/Constants.php hasn't been " . echo "BASE_PATH hasn't been defined. This probably means that framework/Core/Constants.php hasn't been " . "included by Composer's autoloader.\n" . "Make sure the you are running your tests via vendor/bin/phpunit and your autoloader is up to date.\n";
"included by Composer's autoloader.\n" .
"Make sure the you are running your tests via vendor/bin/phpunit and your autoloader is up to date.\n";
exit(1); exit(1);
} }

View File

@ -108,40 +108,35 @@ class ControllerTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted on index action without $allowed_actions on defining controller, ' . 'Access granted on index action without $allowed_actions on defining controller, ' . 'when called without an action in the URL'
'when called without an action in the URL'
); );
$response = $this->get("UnsecuredController/index"); $response = $this->get("UnsecuredController/index");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on index action without $allowed_actions on defining controller, ' . 'Access denied on index action without $allowed_actions on defining controller, ' . 'when called with an action in the URL'
'when called with an action in the URL'
); );
$response = $this->get("UnsecuredController/method1"); $response = $this->get("UnsecuredController/method1");
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action without $allowed_actions on defining controller, ' . 'Access denied on action without $allowed_actions on defining controller, ' . 'when called without an action in the URL'
'when called without an action in the URL'
); );
$response = $this->get("AccessBaseController/"); $response = $this->get("AccessBaseController/");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted on index with empty $allowed_actions on defining controller, ' . 'Access granted on index with empty $allowed_actions on defining controller, ' . 'when called without an action in the URL'
'when called without an action in the URL'
); );
$response = $this->get("AccessBaseController/index"); $response = $this->get("AccessBaseController/index");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted on index with empty $allowed_actions on defining controller, ' . 'Access granted on index with empty $allowed_actions on defining controller, ' . 'when called with an action in the URL'
'when called with an action in the URL'
); );
$response = $this->get("AccessBaseController/method1"); $response = $this->get("AccessBaseController/method1");
@ -155,48 +150,42 @@ class ControllerTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action with empty $allowed_actions on defining controller, ' . 'Access denied on action with empty $allowed_actions on defining controller, ' . 'even when action is allowed in subclasses (allowed_actions don\'t inherit)'
'even when action is allowed in subclasses (allowed_actions don\'t inherit)'
); );
$response = $this->get("AccessSecuredController/"); $response = $this->get("AccessSecuredController/");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted on index with non-empty $allowed_actions on defining controller, ' . 'Access granted on index with non-empty $allowed_actions on defining controller, ' . 'even when index isn\'t specifically mentioned in there'
'even when index isn\'t specifically mentioned in there'
); );
$response = $this->get("AccessSecuredController/method1"); $response = $this->get("AccessSecuredController/method1");
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action which is only defined in parent controller, ' . 'Access denied on action which is only defined in parent controller, ' . 'even when action is allowed in currently called class (allowed_actions don\'t inherit)'
'even when action is allowed in currently called class (allowed_actions don\'t inherit)'
); );
$response = $this->get("AccessSecuredController/method2"); $response = $this->get("AccessSecuredController/method2");
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted on action originally defined with empty $allowed_actions on parent controller, ' . 'Access granted on action originally defined with empty $allowed_actions on parent controller, ' . 'because it has been redefined in the subclass'
'because it has been redefined in the subclass'
); );
$response = $this->get("AccessSecuredController/templateaction"); $response = $this->get("AccessSecuredController/templateaction");
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action with $allowed_actions on defining controller, ' . 'Access denied on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention'
'if action is not a method but rather a template discovered by naming convention'
); );
$response = $this->get("AccessSecuredController/templateaction"); $response = $this->get("AccessSecuredController/templateaction");
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action with $allowed_actions on defining controller, ' . 'Access denied on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention'
'if action is not a method but rather a template discovered by naming convention'
); );
Security::setCurrentUser($adminUser); Security::setCurrentUser($adminUser);
@ -204,8 +193,7 @@ class ControllerTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
'Access granted for logged in admin on action with $allowed_actions on defining controller, ' . 'Access granted for logged in admin on action with $allowed_actions on defining controller, ' . 'if action is not a method but rather a template discovered by naming convention'
'if action is not a method but rather a template discovered by naming convention'
); );
Security::setCurrentUser(null); Security::setCurrentUser(null);
@ -213,16 +201,14 @@ class ControllerTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action with $allowed_actions on defining controller, ' . 'Access denied on action with $allowed_actions on defining controller, ' . 'when restricted by unmatched permission code'
'when restricted by unmatched permission code'
); );
$response = $this->get("AccessSecuredController/aDmiNOnlY"); $response = $this->get("AccessSecuredController/aDmiNOnlY");
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Access denied on action with $allowed_actions on defining controller, ' . 'Access denied on action with $allowed_actions on defining controller, ' . 'regardless of capitalization'
'regardless of capitalization'
); );
$response = $this->get('AccessSecuredController/protectedmethod'); $response = $this->get('AccessSecuredController/protectedmethod');
@ -245,40 +231,35 @@ class ControllerTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
"Access granted to method defined in allowed_actions on extension, " . "Access granted to method defined in allowed_actions on extension, " . "where method is also defined on extension"
"where method is also defined on extension"
); );
$response = $this->get('AccessSecuredController/extensionmethod1'); $response = $this->get('AccessSecuredController/extensionmethod1');
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
"Access granted to method defined in allowed_actions on extension, " . "Access granted to method defined in allowed_actions on extension, " . "where method is also defined on extension, even when called in a subclass"
"where method is also defined on extension, even when called in a subclass"
); );
$response = $this->get('AccessBaseController/extensionmethod2'); $response = $this->get('AccessBaseController/extensionmethod2');
$this->assertEquals( $this->assertEquals(
404, 404,
$response->getStatusCode(), $response->getStatusCode(),
"Access denied to method not defined in allowed_actions on extension, " . "Access denied to method not defined in allowed_actions on extension, " . "where method is also defined on extension"
"where method is also defined on extension"
); );
$response = $this->get('IndexSecuredController/'); $response = $this->get('IndexSecuredController/');
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
"Access denied when index action is limited through allowed_actions, " . "Access denied when index action is limited through allowed_actions, " . "and doesn't satisfy checks, and action is empty"
"and doesn't satisfy checks, and action is empty"
); );
$response = $this->get('IndexSecuredController/index'); $response = $this->get('IndexSecuredController/index');
$this->assertEquals( $this->assertEquals(
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
"Access denied when index action is limited through allowed_actions, " . "Access denied when index action is limited through allowed_actions, " . "and doesn't satisfy checks"
"and doesn't satisfy checks"
); );
Security::setCurrentUser($adminUser); Security::setCurrentUser($adminUser);
@ -286,8 +267,7 @@ class ControllerTest extends FunctionalTest
$this->assertEquals( $this->assertEquals(
200, 200,
$response->getStatusCode(), $response->getStatusCode(),
"Access granted when index action is limited through allowed_actions, " . "Access granted when index action is limited through allowed_actions, " . "and does satisfy checks"
"and does satisfy checks"
); );
Security::setCurrentUser(null); Security::setCurrentUser(null);
} }
@ -433,8 +413,7 @@ class ControllerTest extends FunctionalTest
$this->assertFalse( $this->assertFalse(
$securedController->hasAction('protectedextensionmethod'), $securedController->hasAction('protectedextensionmethod'),
'Method is not visible when defined on an extension, part of allowed_actions, ' . 'Method is not visible when defined on an extension, part of allowed_actions, ' . 'but with protected visibility'
'but with protected visibility'
); );
} }

View File

@ -821,7 +821,7 @@ class DirectorTest extends SapphireTest
$response = Director::test('some-dummy-url'); $response = Director::test('some-dummy-url');
$this->assertEquals(500, $response->getStatusCode()); $this->assertEquals(500, $response->getStatusCode());
$this->assertEquals(_t(Director::class.'.REQUEST_ABORTED', 'Request aborted'), $response->getBody()); $this->assertEquals(_t(Director::class . '.REQUEST_ABORTED', 'Request aborted'), $response->getBody());
$this->assertEquals(2, $filter->preCalls); $this->assertEquals(2, $filter->preCalls);
$this->assertEquals(2, $filter->postCalls); $this->assertEquals(2, $filter->postCalls);
@ -830,7 +830,7 @@ class DirectorTest extends SapphireTest
$response = Director::test('some-dummy-url'); $response = Director::test('some-dummy-url');
$this->assertEquals(400, $response->getStatusCode()); $this->assertEquals(400, $response->getStatusCode());
$this->assertEquals(_t(Director::class.'.INVALID_REQUEST', 'Invalid request'), $response->getBody()); $this->assertEquals(_t(Director::class . '.INVALID_REQUEST', 'Invalid request'), $response->getBody());
$this->assertEquals(3, $filter->preCalls); $this->assertEquals(3, $filter->preCalls);

View File

@ -478,7 +478,7 @@ class EmailTest extends SapphireTest
$subClassTemplate = ModuleResourceLoader::singleton()->resolveResource( $subClassTemplate = ModuleResourceLoader::singleton()->resolveResource(
'silverstripe/framework:tests/php/Control/Email/EmailTest/templates/' 'silverstripe/framework:tests/php/Control/Email/EmailTest/templates/'
. str_replace('\\', '/', EmailSubClass::class) . str_replace('\\', '/', EmailSubClass::class)
.'.ss' . '.ss'
); );
$this->assertTrue($emailTemplate->exists()); $this->assertTrue($emailTemplate->exists());
$this->assertTrue($subClassTemplate->exists()); $this->assertTrue($subClassTemplate->exists());

View File

@ -189,7 +189,7 @@ class HTTPTest extends FunctionalTest
foreach ($urls as $testURL) { foreach ($urls as $testURL) {
$this->assertEquals( $this->assertEquals(
$testURL .'?foo=bar', $testURL . '?foo=bar',
HTTP::setGetVar('foo', 'bar', $testURL), HTTP::setGetVar('foo', 'bar', $testURL),
'Absolute URL and Port Number' 'Absolute URL and Port Number'
); );
@ -226,8 +226,7 @@ class HTTPTest extends FunctionalTest
// background-image // background-image
// Note that using /./ in urls is absolutely acceptable // Note that using /./ in urls is absolutely acceptable
$this->assertEquals( $this->assertEquals(
'<div style="background-image: url(\'http://www.silverstripe.org/./images/mybackground.gif\');">'. '<div style="background-image: url(\'http://www.silverstripe.org/./images/mybackground.gif\');">' . 'Content</div>',
'Content</div>',
HTTP::absoluteURLs('<div style="background-image: url(\'./images/mybackground.gif\');">Content</div>') HTTP::absoluteURLs('<div style="background-image: url(\'./images/mybackground.gif\');">Content</div>')
); );
@ -290,8 +289,7 @@ class HTTPTest extends FunctionalTest
// background // background
// Note that using /./ in urls is absolutely acceptable // Note that using /./ in urls is absolutely acceptable
$this->assertEquals( $this->assertEquals(
'<div background="http://www.silverstripe.org/./themes/silverstripe/images/nav-bg-repeat-2.png">'. '<div background="http://www.silverstripe.org/./themes/silverstripe/images/nav-bg-repeat-2.png">' . 'SS Blog</div>',
'SS Blog</div>',
HTTP::absoluteURLs('<div background="./themes/silverstripe/images/nav-bg-repeat-2.png">SS Blog</div>') HTTP::absoluteURLs('<div background="./themes/silverstripe/images/nav-bg-repeat-2.png">SS Blog</div>')
); );
@ -342,11 +340,9 @@ class HTTPTest extends FunctionalTest
// data uri // data uri
$this->assertEquals( $this->assertEquals(
'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38'. '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38' . 'GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />',
'GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />',
HTTP::absoluteURLs( HTTP::absoluteURLs(
'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH'. '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH' . 'ElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />'
'ElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />'
), ),
'Data URI links are not rewritten' 'Data URI links are not rewritten'
); );

View File

@ -268,7 +268,7 @@ class RequestHandlingTest extends FunctionalTest
403, 403,
$response->getStatusCode(), $response->getStatusCode(),
'Should fail: Invocation through POST form handler, controller action instead of form action,' 'Should fail: Invocation through POST form handler, controller action instead of form action,'
.' not contained in $allowed_actions, with CSRF token' . ' not contained in $allowed_actions, with CSRF token'
); );
$data = array('action_formaction' => 1, 'SecurityID' => $securityId); $data = array('action_formaction' => 1, 'SecurityID' => $securityId);

View File

@ -16,7 +16,7 @@ class SimpleResourceURLGeneratorTest extends SapphireTest
parent::setUp(); parent::setUp();
Director::config()->set( Director::config()->set(
'alternate_base_folder', 'alternate_base_folder',
__DIR__ .'/SimpleResourceURLGeneratorTest/_fakewebroot' __DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot'
); );
Director::config()->set( Director::config()->set(
'alternate_base_url', 'alternate_base_url',
@ -28,9 +28,9 @@ class SimpleResourceURLGeneratorTest extends SapphireTest
{ {
/** @var SimpleResourceURLGenerator $generator */ /** @var SimpleResourceURLGenerator $generator */
$generator = Injector::inst()->get(ResourceURLGenerator::class); $generator = Injector::inst()->get(ResourceURLGenerator::class);
$mtime = filemtime(__DIR__ .'/SimpleResourceURLGeneratorTest/_fakewebroot/basemodule/client/file.js'); $mtime = filemtime(__DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/basemodule/client/file.js');
$this->assertEquals( $this->assertEquals(
'/basemodule/client/file.js?m='.$mtime, '/basemodule/client/file.js?m=' . $mtime,
$generator->urlForResource('basemodule/client/file.js') $generator->urlForResource('basemodule/client/file.js')
); );
} }
@ -40,10 +40,10 @@ class SimpleResourceURLGeneratorTest extends SapphireTest
/** @var SimpleResourceURLGenerator $generator */ /** @var SimpleResourceURLGenerator $generator */
$generator = Injector::inst()->get(ResourceURLGenerator::class); $generator = Injector::inst()->get(ResourceURLGenerator::class);
$mtime = filemtime( $mtime = filemtime(
__DIR__ .'/SimpleResourceURLGeneratorTest/_fakewebroot/vendor/silverstripe/mymodule/client/style.css' __DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/vendor/silverstripe/mymodule/client/style.css'
); );
$this->assertEquals( $this->assertEquals(
'/resources/silverstripe/mymodule/client/style.css?m='.$mtime, '/resources/silverstripe/mymodule/client/style.css?m=' . $mtime,
$generator->urlForResource('vendor/silverstripe/mymodule/client/style.css') $generator->urlForResource('vendor/silverstripe/mymodule/client/style.css')
); );
} }
@ -53,14 +53,14 @@ class SimpleResourceURLGeneratorTest extends SapphireTest
/** @var SimpleResourceURLGenerator $generator */ /** @var SimpleResourceURLGenerator $generator */
$generator = Injector::inst()->get(ResourceURLGenerator::class); $generator = Injector::inst()->get(ResourceURLGenerator::class);
$module = new Module( $module = new Module(
__DIR__ .'/SimpleResourceURLGeneratorTest/_fakewebroot/vendor/silverstripe/mymodule/', __DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/vendor/silverstripe/mymodule/',
__DIR__ .'/SimpleResourceURLGeneratorTest/_fakewebroot/' __DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/'
); );
$mtime = filemtime( $mtime = filemtime(
__DIR__ .'/SimpleResourceURLGeneratorTest/_fakewebroot/vendor/silverstripe/mymodule/client/style.css' __DIR__ . '/SimpleResourceURLGeneratorTest/_fakewebroot/vendor/silverstripe/mymodule/client/style.css'
); );
$this->assertEquals( $this->assertEquals(
'/resources/silverstripe/mymodule/client/style.css?m='.$mtime, '/resources/silverstripe/mymodule/client/style.css?m=' . $mtime,
$generator->urlForResource($module->getResource('client/style.css')) $generator->urlForResource($module->getResource('client/style.css'))
); );
} }

View File

@ -44,14 +44,14 @@ class CacheTest extends SapphireTest
public function testApcuCacheFactory() public function testApcuCacheFactory()
{ {
$cache = Injector::inst()->get(CacheInterface::class .'.TestApcuCache'); $cache = Injector::inst()->get(CacheInterface::class . '.TestApcuCache');
$this->assertInstanceOf( $this->assertInstanceOf(
MockCache::class, MockCache::class,
$cache $cache
); );
$this->assertEquals( $this->assertEquals(
[ [
'TestApcuCache_'.md5(BASE_PATH), 'TestApcuCache_' . md5(BASE_PATH),
2600, 2600,
'ss40test' 'ss40test'
], ],
@ -61,7 +61,7 @@ class CacheTest extends SapphireTest
public function testMemCacheFactory() public function testMemCacheFactory()
{ {
$cache = Injector::inst()->get(CacheInterface::class .'.TestMemcache'); $cache = Injector::inst()->get(CacheInterface::class . '.TestMemcache');
$this->assertInstanceOf( $this->assertInstanceOf(
MockCache::class, MockCache::class,
$cache $cache
@ -69,7 +69,7 @@ class CacheTest extends SapphireTest
$this->assertEquals( $this->assertEquals(
[ [
null, null,
'TestMemCache_'.md5(BASE_PATH), 'TestMemCache_' . md5(BASE_PATH),
5600 5600
], ],
$cache->getArgs() $cache->getArgs()

View File

@ -136,12 +136,7 @@ class ConvertTest extends SapphireTest
"Single quotes are decoded correctly" "Single quotes are decoded correctly"
); );
$val8 = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor '. $val8 = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor ' . 'incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ' . 'exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute ' . 'irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla ' . 'pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia ' . 'deserunt mollit anim id est laborum.';
'incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud '.
'exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute '.
'irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla '.
'pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia '.
'deserunt mollit anim id est laborum.';
$this->assertEquals($val8, Convert::html2raw($val8), 'Test long text is unwrapped'); $this->assertEquals($val8, Convert::html2raw($val8), 'Test long text is unwrapped');
$this->assertEquals( $this->assertEquals(
<<<PHP <<<PHP

View File

@ -29,8 +29,7 @@ class CoreTest extends SapphireTest
$this->assertEquals(TempFolder::getTempFolder(BASE_PATH), $this->tempPath . DIRECTORY_SEPARATOR . $user); $this->assertEquals(TempFolder::getTempFolder(BASE_PATH), $this->tempPath . DIRECTORY_SEPARATOR . $user);
} else { } else {
$user = TempFolder::getTempFolderUsername(); $user = TempFolder::getTempFolderUsername();
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'silverstripe-cache-php' . $base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'silverstripe-cache-php' . preg_replace('/[^\w-\.+]+/', '-', PHP_VERSION);
preg_replace('/[^\w-\.+]+/', '-', PHP_VERSION);
// A typical Windows location for where sites are stored on IIS // A typical Windows location for where sites are stored on IIS
$this->assertEquals( $this->assertEquals(
@ -56,8 +55,7 @@ class CoreTest extends SapphireTest
{ {
parent::tearDown(); parent::tearDown();
$user = TempFolder::getTempFolderUsername(); $user = TempFolder::getTempFolderUsername();
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'silverstripe-cache-php' . $base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'silverstripe-cache-php' . preg_replace('/[^\w-\.+]+/', '-', PHP_VERSION);
preg_replace('/[^\w-\.+]+/', '-', PHP_VERSION);
foreach (array( foreach (array(
'C--inetpub-wwwroot-silverstripe-test-project', 'C--inetpub-wwwroot-silverstripe-test-project',
'-Users-joebloggs-Sites-silverstripe-test-project', '-Users-joebloggs-Sites-silverstripe-test-project',

View File

@ -616,7 +616,7 @@ class InjectorTest extends SapphireTest
NewRequirementsBackend::class, NewRequirementsBackend::class,
DummyRequirements::class => array( DummyRequirements::class => array(
'constructor' => array( 'constructor' => array(
'%$'.OriginalRequirementsBackend::class '%$' . OriginalRequirementsBackend::class
) )
) )
); );
@ -634,7 +634,7 @@ class InjectorTest extends SapphireTest
array( array(
DummyRequirements::class => array( DummyRequirements::class => array(
'constructor' => array( 'constructor' => array(
'%$'.NewRequirementsBackend::class '%$' . NewRequirementsBackend::class
) )
) )
) )
@ -690,7 +690,7 @@ class InjectorTest extends SapphireTest
$config = array( $config = array(
OriginalRequirementsBackend::class, OriginalRequirementsBackend::class,
DummyRequirements::class => array( DummyRequirements::class => array(
'class' => DummyRequirements::class.'(\'%$'.OriginalRequirementsBackend::class.'\')' 'class' => DummyRequirements::class . '(\'%$' . OriginalRequirementsBackend::class . '\')'
) )
); );
$injector->load($config); $injector->load($config);
@ -730,7 +730,7 @@ class InjectorTest extends SapphireTest
Config::modify()->merge( Config::modify()->merge(
Injector::class, Injector::class,
MyChildClass::class, MyChildClass::class,
'%$'.MyParentClass::class '%$' . MyParentClass::class
); );
// Class isn't inherited and parent properties are ignored // Class isn't inherited and parent properties are ignored
@ -766,15 +766,15 @@ class InjectorTest extends SapphireTest
// make sure convert service property is not called on direct calls to create, only on configured // make sure convert service property is not called on direct calls to create, only on configured
// declarations to avoid un-needed function calls // declarations to avoid un-needed function calls
$injector = new Injector(); $injector = new Injector();
$item = $injector->create(ConstructableObject::class, '%$'.TestObject::class); $item = $injector->create(ConstructableObject::class, '%$' . TestObject::class);
$this->assertEquals('%$'.TestObject::class, $item->property); $this->assertEquals('%$' . TestObject::class, $item->property);
// do it again but have test object configured as a constructor dependency // do it again but have test object configured as a constructor dependency
$injector = new Injector(); $injector = new Injector();
$config = array( $config = array(
ConstructableObject::class => array( ConstructableObject::class => array(
'constructor' => array( 'constructor' => array(
'%$'.TestObject::class '%$' . TestObject::class
) )
) )
); );
@ -788,7 +788,7 @@ class InjectorTest extends SapphireTest
$config = array( $config = array(
ConstructableObject::class => array( ConstructableObject::class => array(
'constructor' => array( 'constructor' => array(
'%$'.TestObject::class '%$' . TestObject::class
) )
), ),
); );

View File

@ -16,7 +16,7 @@ class InjectorTestConfigLocator extends SilverStripeServiceConfigurationLocator
return $this->configs[$name] = array( return $this->configs[$name] = array(
'class' => ConstructableObject::class, 'class' => ConstructableObject::class,
'constructor' => array( 'constructor' => array(
'%$'.OtherTestObject::class '%$' . OtherTestObject::class
) )
); );

View File

@ -181,8 +181,8 @@ class ConfigManifestTest extends SapphireTest
foreach (array('dev', 'test', 'live') as $check) { foreach (array('dev', 'test', 'live') as $check) {
$this->assertEquals( $this->assertEquals(
$env == $check ? $check : 'not'.$check, $env == $check ? $check : 'not' . $check,
@$config[ucfirst($check).'Environment'], @$config[ucfirst($check) . 'Environment'],
'Only & except rules correctly detect environment in env ' . $env 'Only & except rules correctly detect environment in env ' . $env
); );
} }

View File

@ -30,7 +30,7 @@ class PhpSyntaxTest extends SapphireTest
$settingTests = array('short_open_tag=Off','short_open_tag=On -d asp_tags=On'); $settingTests = array('short_open_tag=Off','short_open_tag=On -d asp_tags=On');
$files = $this->getAllFiles('php'); $files = $this->getAllFiles('php');
$files[] = FRAMEWORK_PATH.'/src/Dev/Install/config-form.html'; $files[] = FRAMEWORK_PATH . '/src/Dev/Install/config-form.html';
foreach ($files as $i => $file) { foreach ($files as $i => $file) {
$CLI_file = escapeshellarg($file); $CLI_file = escapeshellarg($file);

View File

@ -91,7 +91,7 @@ class ParameterConfirmationTokenTest extends SapphireTest
// Check redirect url // Check redirect url
$home = (BASE_URL ?: '/') . '?'; $home = (BASE_URL ?: '/') . '?';
$current = Controller::join_links(BASE_URL, '/', 'anotherpage'). '?'; $current = Controller::join_links(BASE_URL, '/', 'anotherpage') . '?';
$this->assertStringStartsWith($current, $withoutToken->redirectURL()); $this->assertStringStartsWith($current, $withoutToken->redirectURL());
$this->assertStringStartsWith($current, $emptyParameter->redirectURL()); $this->assertStringStartsWith($current, $emptyParameter->redirectURL());
$this->assertStringStartsWith($current, $nullToken->redirectURL()); $this->assertStringStartsWith($current, $nullToken->redirectURL());

View File

@ -39,11 +39,11 @@ HTML
); );
$result = $parser->getBySelector('div.one'); $result = $parser->getBySelector('div.one');
$this->assertEquals("A", $result[0]['id'].''); $this->assertEquals("A", $result[0]['id'] . '');
$result = $parser->getBySelector('div.two'); $result = $parser->getBySelector('div.two');
$this->assertEquals("A", $result[0]['id'].''); $this->assertEquals("A", $result[0]['id'] . '');
$result = $parser->getBySelector('div.three'); $result = $parser->getBySelector('div.three');
$this->assertEquals("A", $result[0]['id'].''); $this->assertEquals("A", $result[0]['id'] . '');
$result = $parser->getBySelector('div#A p.other'); $result = $parser->getBySelector('div#A p.other');
$this->assertEquals("result", $result[0] . ''); $this->assertEquals("result", $result[0] . '');

View File

@ -117,7 +117,7 @@ class CSVParserTest extends SapphireTest
public function testParsingWithExplicitHeaderRow() public function testParsingWithExplicitHeaderRow()
{ {
/* If your CSV file doesn't have a header row */ /* If your CSV file doesn't have a header row */
$csv = new CSVParser($this->csvPath .'PlayersWithHeader.csv'); $csv = new CSVParser($this->csvPath . 'PlayersWithHeader.csv');
$csv->provideHeaderRow(array('__fn','__bio','__bd','__reg')); $csv->provideHeaderRow(array('__fn','__bio','__bd','__reg'));

View File

@ -79,7 +79,7 @@ class DeprecationTest extends SapphireTest
{ {
$this->assertEquals( $this->assertEquals(
TestDeprecation::get_method(), TestDeprecation::get_method(),
static::class.'->testMethodNameCalculation' static::class . '->testMethodNameCalculation'
); );
} }

View File

@ -44,11 +44,11 @@ class FixtureBlueprintTest extends SapphireTest
'ManyManyRelation' => 'ManyManyRelation' =>
array( array(
array( array(
"=>".DataObjectRelation::class.".relation1" => array(), "=>" . DataObjectRelation::class . ".relation1" => array(),
"Label" => 'This is a label for relation 1' "Label" => 'This is a label for relation 1'
), ),
array( array(
"=>".DataObjectRelation::class.".relation2" => array(), "=>" . DataObjectRelation::class . ".relation2" => array(),
"Label" => 'This is a label for relation 2' "Label" => 'This is a label for relation 2'
) )
) )
@ -109,8 +109,7 @@ class FixtureBlueprintTest extends SapphireTest
'one', 'one',
array( array(
'ManyManyRelation' => 'ManyManyRelation' =>
'=>'.DataObjectRelation::class.'.relation1,' . '=>' . DataObjectRelation::class . '.relation1,' . '=>' . DataObjectRelation::class . '.relation2'
'=>'.DataObjectRelation::class.'.relation2'
), ),
array( array(
DataObjectRelation::class => array( DataObjectRelation::class => array(
@ -129,8 +128,8 @@ class FixtureBlueprintTest extends SapphireTest
array( array(
// Note; using array format here, not comma separated // Note; using array format here, not comma separated
'HasManyRelation' => array( 'HasManyRelation' => array(
'=>'.DataObjectRelation::class.'.relation1', '=>' . DataObjectRelation::class . '.relation1',
'=>'.DataObjectRelation::class.'.relation2' '=>' . DataObjectRelation::class . '.relation2'
) )
), ),
array( array(
@ -177,7 +176,7 @@ class FixtureBlueprintTest extends SapphireTest
$obj = $blueprint->createObject( $obj = $blueprint->createObject(
'one', 'one',
array( array(
'ManyManyRelation' => '=>'.DataObjectRelation::class.'.unknown_identifier' 'ManyManyRelation' => '=>' . DataObjectRelation::class . '.unknown_identifier'
), ),
array( array(
DataObjectRelation::class => array( DataObjectRelation::class => array(
@ -202,7 +201,7 @@ class FixtureBlueprintTest extends SapphireTest
$obj = $blueprint->createObject( $obj = $blueprint->createObject(
'one', 'one',
array( array(
'ManyManyRelation' => DataObjectRelation::class.'.relation1' 'ManyManyRelation' => DataObjectRelation::class . '.relation1'
), ),
array( array(
DataObjectRelation::class => array( DataObjectRelation::class => array(

View File

@ -35,7 +35,7 @@ class FormSchemaTest extends SapphireTest
{ {
$form = new Form(null, 'TestForm', new FieldList(), new FieldList()); $form = new Form(null, 'TestForm', new FieldList(), new FieldList());
$formSchema = new FormSchema(); $formSchema = new FormSchema();
$expected = json_decode(file_get_contents(__DIR__.'/FormSchemaTest/testGetSchema.json'), true); $expected = json_decode(file_get_contents(__DIR__ . '/FormSchemaTest/testGetSchema.json'), true);
$schema = $formSchema->getSchema($form); $schema = $formSchema->getSchema($form);
$this->assertInternalType('array', $schema); $this->assertInternalType('array', $schema);
@ -164,7 +164,7 @@ class FormSchemaTest extends SapphireTest
) )
); );
$formSchema = new FormSchema(); $formSchema = new FormSchema();
$expected = json_decode(file_get_contents(__DIR__.'/FormSchemaTest/testGetNestedSchema.json'), true); $expected = json_decode(file_get_contents(__DIR__ . '/FormSchemaTest/testGetNestedSchema.json'), true);
$schema = $formSchema->getSchema($form); $schema = $formSchema->getSchema($form);
$this->assertInternalType('array', $schema); $this->assertInternalType('array', $schema);
@ -206,7 +206,7 @@ class FormSchemaTest extends SapphireTest
); );
$formSchema = new FormSchema(); $formSchema = new FormSchema();
$schema = $formSchema->getSchema($form); $schema = $formSchema->getSchema($form);
$expected = json_decode(file_get_contents(__DIR__.'/FormSchemaTest/testSchemaValidation.json'), true); $expected = json_decode(file_get_contents(__DIR__ . '/FormSchemaTest/testSchemaValidation.json'), true);
$this->assertInternalType('array', $schema); $this->assertInternalType('array', $schema);
$this->assertEquals($expected, $schema); $this->assertEquals($expected, $schema);
} }

View File

@ -560,11 +560,11 @@ class FormTest extends FunctionalTest
); );
$this->assertEquals(200, $response->getStatusCode(), 'Submission reloads form if security token invalid'); $this->assertEquals(200, $response->getStatusCode(), 'Submission reloads form if security token invalid');
$this->assertTrue( $this->assertTrue(
stripos($response->getBody(), 'name="SecurityID" value="'.$expectedToken.'"') !== false, stripos($response->getBody(), 'name="SecurityID" value="' . $expectedToken . '"') !== false,
'Submission reloads with correct security token after failure' 'Submission reloads with correct security token after failure'
); );
$this->assertTrue( $this->assertTrue(
stripos($response->getBody(), 'name="SecurityID" value="'.$invalidToken.'"') === false, stripos($response->getBody(), 'name="SecurityID" value="' . $invalidToken . '"') === false,
'Submission reloads without incorrect security token after failure' 'Submission reloads without incorrect security token after failure'
); );

View File

@ -95,8 +95,7 @@ class GridFieldDeleteActionTest extends SapphireTest
$this->expectException(HTTPResponse_Exception::class); $this->expectException(HTTPResponse_Exception::class);
$this->expectExceptionMessage(_t( $this->expectExceptionMessage(_t(
"SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE", "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE",
"There seems to have been a technical problem. Please click the back button, ". "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again."
"refresh your browser, and try again."
)); ));
$this->expectExceptionCode(400); $this->expectExceptionCode(400);
$stateID = 'testGridStateActionField'; $stateID = 'testGridStateActionField';
@ -105,7 +104,7 @@ class GridFieldDeleteActionTest extends SapphireTest
'url', 'url',
array(), array(),
array( array(
'action_gridFieldAlterAction?StateID='.$stateID, 'action_gridFieldAlterAction?StateID=' . $stateID,
'SecurityID' => null, 'SecurityID' => null,
) )
); );
@ -138,7 +137,7 @@ class GridFieldDeleteActionTest extends SapphireTest
'url', 'url',
array(), array(),
array( array(
'action_gridFieldAlterAction?StateID='.$stateID => true, 'action_gridFieldAlterAction?StateID=' . $stateID => true,
$token->getName() => $token->getValue(), $token->getName() => $token->getValue(),
) )
); );
@ -172,7 +171,7 @@ class GridFieldDeleteActionTest extends SapphireTest
'url', 'url',
array(), array(),
array( array(
'action_gridFieldAlterAction?StateID='.$stateID=>true, 'action_gridFieldAlterAction?StateID=' . $stateID=>true,
$token->getName() => $token->getValue(), $token->getName() => $token->getValue(),
) )
); );
@ -207,7 +206,7 @@ class GridFieldDeleteActionTest extends SapphireTest
'url', 'url',
array(), array(),
array( array(
'action_gridFieldAlterAction?StateID='.$stateID=>true, 'action_gridFieldAlterAction?StateID=' . $stateID=>true,
$token->getName() => $token->getValue(), $token->getName() => $token->getValue(),
) )
); );

View File

@ -66,9 +66,7 @@ class GridFieldExportButtonTest extends SapphireTest
$button->setExportColumns(['Name' => 'My Name']); $button->setExportColumns(['Name' => 'My Name']);
$this->assertEquals( $this->assertEquals(
'"My Name"'."\n". '"My Name"' . "\n" . 'Test' . "\n" . 'Test2' . "\n",
'Test'."\n".
'Test2'."\n",
$button->generateExportFileData($this->gridField) $button->generateExportFileData($this->gridField)
); );
} }
@ -101,9 +99,7 @@ class GridFieldExportButtonTest extends SapphireTest
]); ]);
$this->assertEquals( $this->assertEquals(
'Name,City'."\n". 'Name,City' . "\n" . 'Test,"City city"' . "\n" . 'Test2,"Quoted ""City"" 2 city"' . "\n",
'Test,"City city"'."\n".
'Test2,"Quoted ""City"" 2 city"'."\n",
$button->generateExportFileData($this->gridField) $button->generateExportFileData($this->gridField)
); );
} }
@ -117,9 +113,7 @@ class GridFieldExportButtonTest extends SapphireTest
]); ]);
$this->assertEquals( $this->assertEquals(
'Name,strtolower'."\n". 'Name,strtolower' . "\n" . 'Test,City' . "\n" . 'Test2,"Quoted ""City"" 2"' . "\n",
'Test,City'."\n".
'Test2,"Quoted ""City"" 2"'."\n",
$button->generateExportFileData($this->gridField) $button->generateExportFileData($this->gridField)
); );
} }
@ -134,8 +128,7 @@ class GridFieldExportButtonTest extends SapphireTest
$button->setCsvHasHeader(false); $button->setCsvHasHeader(false);
$this->assertEquals( $this->assertEquals(
'Test,City'."\n". 'Test,City' . "\n" . 'Test2,"Quoted ""City"" 2"' . "\n",
'Test2,"Quoted ""City"" 2"'."\n",
$button->generateExportFileData($this->gridField) $button->generateExportFileData($this->gridField)
); );
} }
@ -154,23 +147,7 @@ class GridFieldExportButtonTest extends SapphireTest
$this->gridField->setList($arrayList); $this->gridField->setList($arrayList);
$this->assertEquals( $this->assertEquals(
"ID\n". "ID\n" . "1\n" . "2\n" . "3\n" . "4\n" . "5\n" . "6\n" . "7\n" . "8\n" . "9\n" . "10\n" . "11\n" . "12\n" . "13\n" . "14\n" . "15\n" . "16\n",
"1\n".
"2\n".
"3\n".
"4\n".
"5\n".
"6\n".
"7\n".
"8\n".
"9\n".
"10\n".
"11\n".
"12\n".
"13\n".
"14\n".
"15\n".
"16\n",
$button->generateExportFileData($this->gridField) $button->generateExportFileData($this->gridField)
); );
} }

View File

@ -140,7 +140,7 @@ class HTMLEditorFieldTest extends FunctionalTest
= '/assets/HTMLEditorFieldTest/f5c7c2f814/example__ResizedImageWzEwLDIwXQ.jpg'; = '/assets/HTMLEditorFieldTest/f5c7c2f814/example__ResizedImageWzEwLDIwXQ.jpg';
$this->assertEquals($neededFilename, (string)$xml[0]['src'], 'Correct URL of resized image is set.'); $this->assertEquals($neededFilename, (string)$xml[0]['src'], 'Correct URL of resized image is set.');
$this->assertTrue(file_exists(BASE_PATH.DIRECTORY_SEPARATOR.$neededFilename), 'File for resized image exists'); $this->assertTrue(file_exists(BASE_PATH . DIRECTORY_SEPARATOR . $neededFilename), 'File for resized image exists');
$this->assertEquals(false, $obj->HasBrokenFile, 'Referenced image file exists.'); $this->assertEquals(false, $obj->HasBrokenFile, 'Referenced image file exists.');
} }

View File

@ -35,7 +35,7 @@ class TinyMCECombinedGeneratorTest extends SapphireTest
public function testConfig() public function testConfig()
{ {
$module = new Module(Director::baseFolder().'/mycode', Director::baseFolder()); $module = new Module(Director::baseFolder() . '/mycode', Director::baseFolder());
// Disable nonces // Disable nonces
$c = new TinyMCEConfig(); $c = new TinyMCEConfig();
$c->setTheme('testtheme'); $c->setTheme('testtheme');

View File

@ -19,7 +19,7 @@ class TinyMCEConfigTest extends SapphireTest
$this->markTestSkipped("Test skipped without TinyMCE resources folder being installed"); $this->markTestSkipped("Test skipped without TinyMCE resources folder being installed");
} }
$langs = Director::baseFolder().'/'.ModuleResourceLoader::resourcePath($configDir).'/langs'; $langs = Director::baseFolder() . '/' . ModuleResourceLoader::resourcePath($configDir) . '/langs';
// Test all langs exist as real files // Test all langs exist as real files
foreach (TinyMCEConfig::config()->get('tinymce_lang') as $locale => $resource) { foreach (TinyMCEConfig::config()->get('tinymce_lang') as $locale => $resource) {

View File

@ -56,7 +56,7 @@ class TreeDropdownFieldTest extends SapphireTest
$this->assertContains( $this->assertContains(
$folder1->Name, $folder1->Name,
array_column($tree['children'], 'title'), array_column($tree['children'], 'title'),
$folder1->Name.' is found in the json' $folder1->Name . ' is found in the json'
); );
$filtered = array_filter($tree['children'], function ($entry) use ($folder1) { $filtered = array_filter($tree['children'], function ($entry) use ($folder1) {
@ -67,7 +67,7 @@ class TreeDropdownFieldTest extends SapphireTest
$this->assertContains( $this->assertContains(
$folder1Subfolder1->Name, $folder1Subfolder1->Name,
array_column($folder1Tree['children'], 'title'), array_column($folder1Tree['children'], 'title'),
$folder1Subfolder1->Name.' is found in the folder1 entry in the json' $folder1Subfolder1->Name . ' is found in the folder1 entry in the json'
); );
} }
@ -87,13 +87,13 @@ class TreeDropdownFieldTest extends SapphireTest
$this->assertNotContains( $this->assertNotContains(
$folder1->Name, $folder1->Name,
array_column($tree['children'], 'title'), array_column($tree['children'], 'title'),
$folder1->Name.' is not found in the json' $folder1->Name . ' is not found in the json'
); );
$this->assertContains( $this->assertContains(
$folder1Subfolder1->Name, $folder1Subfolder1->Name,
array_column($tree['children'], 'title'), array_column($tree['children'], 'title'),
$folder1Subfolder1->Name.' is found in the json' $folder1Subfolder1->Name . ' is found in the json'
); );
} }
@ -111,31 +111,30 @@ class TreeDropdownFieldTest extends SapphireTest
$folder1Subfolder1 = $this->objFromFixture(Folder::class, 'folder1-subfolder1'); $folder1Subfolder1 = $this->objFromFixture(Folder::class, 'folder1-subfolder1');
$parser = new CSSContentParser($tree); $parser = new CSSContentParser($tree);
$cssPath = 'ul.tree li#selector-TestTree-'.$folder1->ID.' li#selector-TestTree-'. $cssPath = 'ul.tree li#selector-TestTree-' . $folder1->ID . ' li#selector-TestTree-' . $folder1Subfolder1->ID . ' a span.item';
$folder1Subfolder1->ID.' a span.item';
$firstResult = $parser->getBySelector($cssPath); $firstResult = $parser->getBySelector($cssPath);
$this->assertEquals( $this->assertEquals(
$folder1Subfolder1->Name, $folder1Subfolder1->Name,
(string)$firstResult[0], (string)$firstResult[0],
$folder1Subfolder1->Name.' is found, nested under '.$folder1->Name $folder1Subfolder1->Name . ' is found, nested under ' . $folder1->Name
); );
$subfolder = $this->objFromFixture(Folder::class, 'subfolder'); $subfolder = $this->objFromFixture(Folder::class, 'subfolder');
$cssPath = 'ul.tree li#selector-TestTree-'.$subfolder->ID.' a span.item'; $cssPath = 'ul.tree li#selector-TestTree-' . $subfolder->ID . ' a span.item';
$secondResult = $parser->getBySelector($cssPath); $secondResult = $parser->getBySelector($cssPath);
$this->assertEquals( $this->assertEquals(
$subfolder->Name, $subfolder->Name,
(string)$secondResult[0], (string)$secondResult[0],
$subfolder->Name.' is found at root level' $subfolder->Name . ' is found at root level'
); );
// other folders which don't contain the keyword 'sub' are not returned in search results // other folders which don't contain the keyword 'sub' are not returned in search results
$folder2 = $this->objFromFixture(Folder::class, 'folder2'); $folder2 = $this->objFromFixture(Folder::class, 'folder2');
$cssPath = 'ul.tree li#selector-TestTree-'.$folder2->ID.' a span.item'; $cssPath = 'ul.tree li#selector-TestTree-' . $folder2->ID . ' a span.item';
$noResult = $parser->getBySelector($cssPath); $noResult = $parser->getBySelector($cssPath);
$this->assertEmpty( $this->assertEmpty(
$noResult, $noResult,
$folder2.' is not found' $folder2 . ' is not found'
); );
$field = new TreeDropdownField('TestTree', 'Test tree', File::class); $field = new TreeDropdownField('TestTree', 'Test tree', File::class);
@ -149,49 +148,48 @@ class TreeDropdownFieldTest extends SapphireTest
$parser = new CSSContentParser($tree); $parser = new CSSContentParser($tree);
// Even if we used File as the source object, folders are still returned because Folder is a File // Even if we used File as the source object, folders are still returned because Folder is a File
$cssPath = 'ul.tree li#selector-TestTree-'.$folder1->ID.' li#selector-TestTree-'. $cssPath = 'ul.tree li#selector-TestTree-' . $folder1->ID . ' li#selector-TestTree-' . $folder1Subfolder1->ID . ' a span.item';
$folder1Subfolder1->ID.' a span.item';
$firstResult = $parser->getBySelector($cssPath); $firstResult = $parser->getBySelector($cssPath);
$this->assertEquals( $this->assertEquals(
$folder1Subfolder1->Name, $folder1Subfolder1->Name,
(string)$firstResult[0], (string)$firstResult[0],
$folder1Subfolder1->Name.' is found, nested under '.$folder1->Name $folder1Subfolder1->Name . ' is found, nested under ' . $folder1->Name
); );
// Looking for two files with 'sub' in their name, both under the same folder // Looking for two files with 'sub' in their name, both under the same folder
$file1 = $this->objFromFixture(File::class, 'subfolderfile1'); $file1 = $this->objFromFixture(File::class, 'subfolderfile1');
$file2 = $this->objFromFixture(File::class, 'subfolderfile2'); $file2 = $this->objFromFixture(File::class, 'subfolderfile2');
$cssPath = 'ul.tree li#selector-TestTree-'.$subfolder->ID.' li#selector-TestTree-'.$file1->ID.' a'; $cssPath = 'ul.tree li#selector-TestTree-' . $subfolder->ID . ' li#selector-TestTree-' . $file1->ID . ' a';
$firstResult = $parser->getBySelector($cssPath); $firstResult = $parser->getBySelector($cssPath);
$this->assertNotEmpty( $this->assertNotEmpty(
$firstResult, $firstResult,
$file1->Name.' with ID '.$file1->ID.' is in search results' $file1->Name . ' with ID ' . $file1->ID . ' is in search results'
); );
$this->assertEquals( $this->assertEquals(
$file1->Name, $file1->Name,
(string)$firstResult[0], (string)$firstResult[0],
$file1->Name.' is found nested under '.$subfolder->Name $file1->Name . ' is found nested under ' . $subfolder->Name
); );
$cssPath = 'ul.tree li#selector-TestTree-'.$subfolder->ID.' li#selector-TestTree-'.$file2->ID.' a'; $cssPath = 'ul.tree li#selector-TestTree-' . $subfolder->ID . ' li#selector-TestTree-' . $file2->ID . ' a';
$secondResult = $parser->getBySelector($cssPath); $secondResult = $parser->getBySelector($cssPath);
$this->assertNotEmpty( $this->assertNotEmpty(
$secondResult, $secondResult,
$file2->Name.' with ID '.$file2->ID.' is in search results' $file2->Name . ' with ID ' . $file2->ID . ' is in search results'
); );
$this->assertEquals( $this->assertEquals(
$file2->Name, $file2->Name,
(string)$secondResult[0], (string)$secondResult[0],
$file2->Name.' is found nested under '.$subfolder->Name $file2->Name . ' is found nested under ' . $subfolder->Name
); );
// other files which don't include 'sub' are not returned in search results // other files which don't include 'sub' are not returned in search results
$file3 = $this->objFromFixture(File::class, 'asdf'); $file3 = $this->objFromFixture(File::class, 'asdf');
$cssPath = 'ul.tree li#selector-TestTree-'.$file3->ID; $cssPath = 'ul.tree li#selector-TestTree-' . $file3->ID;
$noResult = $parser->getBySelector($cssPath); $noResult = $parser->getBySelector($cssPath);
$this->assertEmpty( $this->assertEmpty(
$noResult, $noResult,
$file3->Name.' is not found' $file3->Name . ' is not found'
); );
} }

View File

@ -14,7 +14,7 @@ class DetailedErrorFormatterTest extends SapphireTest
$formatter = new DetailedErrorFormatter(); $formatter = new DetailedErrorFormatter();
$exception = $generator->mockException(); $exception = $generator->mockException();
$output = ''.$formatter->format(['context' => [ $output = '' . $formatter->format(['context' => [
'exception' => $exception, 'exception' => $exception,
]]); ]]);

View File

@ -193,7 +193,7 @@ class DBHTMLTextTest extends SapphireTest
foreach ($cases as $add) { foreach ($cases as $add) {
$textObj = DBField::create_field('HTMLFragment', $orig); $textObj = DBField::create_field('HTMLFragment', $orig);
$result = $textObj->obj('Summary', [4, $add])->forTemplate(); $result = $textObj->obj('Summary', [4, $add])->forTemplate();
$this->assertEquals($match.Convert::raw2xml($add), $result); $this->assertEquals($match . Convert::raw2xml($add), $result);
} }
} }

View File

@ -26,7 +26,7 @@ class DBStringTest extends SapphireTest
{ {
/** @var DBString $dbField */ /** @var DBString $dbField */
$dbField = Injector::inst()->create( $dbField = Injector::inst()->create(
DBStringTest\MyStringField::class."(['default' => 'Here is my default text'])", DBStringTest\MyStringField::class . "(['default' => 'Here is my default text'])",
'Myfield' 'Myfield'
); );
$this->assertEquals( $this->assertEquals(

View File

@ -19,14 +19,14 @@ class DBTest extends SapphireTest
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_'; $prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
$kernel->setEnvironment(Kernel::DEV); $kernel->setEnvironment(Kernel::DEV);
$this->assertTrue(DB::valid_alternative_database_name($prefix.'tmpdb1234567')); $this->assertTrue(DB::valid_alternative_database_name($prefix . 'tmpdb1234567'));
$this->assertFalse(DB::valid_alternative_database_name($prefix.'tmpdb12345678')); $this->assertFalse(DB::valid_alternative_database_name($prefix . 'tmpdb12345678'));
$this->assertFalse(DB::valid_alternative_database_name('tmpdb1234567')); $this->assertFalse(DB::valid_alternative_database_name('tmpdb1234567'));
$this->assertFalse(DB::valid_alternative_database_name('random')); $this->assertFalse(DB::valid_alternative_database_name('random'));
$this->assertFalse(DB::valid_alternative_database_name('')); $this->assertFalse(DB::valid_alternative_database_name(''));
$kernel->setEnvironment(Kernel::LIVE); $kernel->setEnvironment(Kernel::LIVE);
$this->assertFalse(DB::valid_alternative_database_name($prefix.'tmpdb1234567')); $this->assertFalse(DB::valid_alternative_database_name($prefix . 'tmpdb1234567'));
$kernel->setEnvironment(Kernel::DEV); $kernel->setEnvironment(Kernel::DEV);
} }

View File

@ -1663,7 +1663,7 @@ class DataListTest extends SapphireTest
// with a complex sort expression, so keep using column() below // with a complex sort expression, so keep using column() below
$teamClass = Convert::raw2sql(SubTeam::class); $teamClass = Convert::raw2sql(SubTeam::class);
$list = Team::get()->sort( $list = Team::get()->sort(
'CASE WHEN "DataObjectTest_Team"."ClassName" = \''.$teamClass.'\' THEN 0 ELSE 1 END, "Title" DESC' 'CASE WHEN "DataObjectTest_Team"."ClassName" = \'' . $teamClass . '\' THEN 0 ELSE 1 END, "Title" DESC'
); );
$this->assertEquals( $this->assertEquals(
array( array(

View File

@ -28,14 +28,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn(); $db = DB::get_conn();
$playerList = new DataList(SubTeam::class); $playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('ID')); $playerList = $playerList->setQueriedColumns(array('ID'));
$expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . $expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . '"DataObjectTest_Team"."Created", "DataObjectTest_Team"."ID", CASE WHEN ' . '"DataObjectTest_Team"."ClassName" IS NOT NULL THEN "DataObjectTest_Team"."ClassName" ELSE ' . $db->quoteString(Team::class) . ' END AS "RecordClassName", "DataObjectTest_Team"."Title" ' . 'FROM "DataObjectTest_Team" ' . 'LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = "DataObjectTest_Team"."ID" ' . 'WHERE ("DataObjectTest_Team"."ClassName" IN (?))' . ' ORDER BY "DataObjectTest_Team"."Title" ASC';
'"DataObjectTest_Team"."Created", "DataObjectTest_Team"."ID", CASE WHEN '.
'"DataObjectTest_Team"."ClassName" IS NOT NULL THEN "DataObjectTest_Team"."ClassName" ELSE ' .
$db->quoteString(Team::class).' END AS "RecordClassName", "DataObjectTest_Team"."Title" '.
'FROM "DataObjectTest_Team" ' .
'LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = "DataObjectTest_Team"."ID" ' .
'WHERE ("DataObjectTest_Team"."ClassName" IN (?))' .
' ORDER BY "DataObjectTest_Team"."Title" ASC';
$this->assertSQLEquals($expected, $playerList->sql($parameters)); $this->assertSQLEquals($expected, $playerList->sql($parameters));
} }
@ -44,14 +37,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn(); $db = DB::get_conn();
$playerList = new DataList(SubTeam::class); $playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('Title', 'SubclassDatabaseField')); $playerList = $playerList->setQueriedColumns(array('Title', 'SubclassDatabaseField'));
$expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . $expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . '"DataObjectTest_Team"."Created", "DataObjectTest_Team"."Title", ' . '"DataObjectTest_SubTeam"."SubclassDatabaseField", "DataObjectTest_Team"."ID", CASE WHEN ' . '"DataObjectTest_Team"."ClassName" IS NOT NULL THEN "DataObjectTest_Team"."ClassName" ELSE ' . $db->quoteString(Team::class) . ' END AS "RecordClassName" FROM "DataObjectTest_Team" ' . 'LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = "DataObjectTest_Team"."ID" WHERE ' . '("DataObjectTest_Team"."ClassName" IN (?)) ' . 'ORDER BY "DataObjectTest_Team"."Title" ASC';
'"DataObjectTest_Team"."Created", "DataObjectTest_Team"."Title", ' .
'"DataObjectTest_SubTeam"."SubclassDatabaseField", "DataObjectTest_Team"."ID", CASE WHEN ' .
'"DataObjectTest_Team"."ClassName" IS NOT NULL THEN "DataObjectTest_Team"."ClassName" ELSE ' .
$db->quoteString(Team::class).' END AS "RecordClassName" FROM "DataObjectTest_Team" ' .
'LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = "DataObjectTest_Team"."ID" WHERE ' .
'("DataObjectTest_Team"."ClassName" IN (?)) ' .
'ORDER BY "DataObjectTest_Team"."Title" ASC';
$this->assertSQLEquals($expected, $playerList->sql($parameters)); $this->assertSQLEquals($expected, $playerList->sql($parameters));
} }
@ -60,13 +46,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn(); $db = DB::get_conn();
$playerList = new DataList(SubTeam::class); $playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('Title')); $playerList = $playerList->setQueriedColumns(array('Title'));
$expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . $expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . '"DataObjectTest_Team"."Created", "DataObjectTest_Team"."Title", "DataObjectTest_Team"."ID", ' . 'CASE WHEN "DataObjectTest_Team"."ClassName" IS NOT NULL THEN "DataObjectTest_Team"."ClassName" ELSE ' . $db->quoteString(Team::class) . ' END AS "RecordClassName" FROM "DataObjectTest_Team" ' . 'LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = "DataObjectTest_Team"."ID" WHERE ' . '("DataObjectTest_Team"."ClassName" IN (?)) ' . 'ORDER BY "DataObjectTest_Team"."Title" ASC';
'"DataObjectTest_Team"."Created", "DataObjectTest_Team"."Title", "DataObjectTest_Team"."ID", ' .
'CASE WHEN "DataObjectTest_Team"."ClassName" IS NOT NULL THEN "DataObjectTest_Team"."ClassName" ELSE ' .
$db->quoteString(Team::class).' END AS "RecordClassName" FROM "DataObjectTest_Team" ' .
'LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = "DataObjectTest_Team"."ID" WHERE ' .
'("DataObjectTest_Team"."ClassName" IN (?)) ' .
'ORDER BY "DataObjectTest_Team"."Title" ASC';
$this->assertSQLEquals($expected, $playerList->sql($parameters)); $this->assertSQLEquals($expected, $playerList->sql($parameters));
} }
@ -75,14 +55,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn(); $db = DB::get_conn();
$playerList = new DataList(SubTeam::class); $playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('SubclassDatabaseField')); $playerList = $playerList->setQueriedColumns(array('SubclassDatabaseField'));
$expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . $expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . '"DataObjectTest_Team"."Created", "DataObjectTest_SubTeam"."SubclassDatabaseField", ' . '"DataObjectTest_Team"."ID", CASE WHEN "DataObjectTest_Team"."ClassName" IS NOT NULL THEN ' . '"DataObjectTest_Team"."ClassName" ELSE ' . $db->quoteString(Team::class) . ' END ' . 'AS "RecordClassName", "DataObjectTest_Team"."Title" ' . 'FROM "DataObjectTest_Team" LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = ' . '"DataObjectTest_Team"."ID" WHERE ("DataObjectTest_Team"."ClassName" IN (?)) ' . 'ORDER BY "DataObjectTest_Team"."Title" ASC';
'"DataObjectTest_Team"."Created", "DataObjectTest_SubTeam"."SubclassDatabaseField", ' .
'"DataObjectTest_Team"."ID", CASE WHEN "DataObjectTest_Team"."ClassName" IS NOT NULL THEN ' .
'"DataObjectTest_Team"."ClassName" ELSE '.$db->quoteString(Team::class).' END ' .
'AS "RecordClassName", "DataObjectTest_Team"."Title" ' .
'FROM "DataObjectTest_Team" LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = ' .
'"DataObjectTest_Team"."ID" WHERE ("DataObjectTest_Team"."ClassName" IN (?)) ' .
'ORDER BY "DataObjectTest_Team"."Title" ASC';
$this->assertSQLEquals($expected, $playerList->sql($parameters)); $this->assertSQLEquals($expected, $playerList->sql($parameters));
} }

View File

@ -179,29 +179,29 @@ class DataObjectSchemaTest extends SapphireTest
); );
$this->assertEquals( $this->assertEquals(
[ [
'ID' => DataObjectSchemaTest\HasFields::class.'.PrimaryKey', 'ID' => DataObjectSchemaTest\HasFields::class . '.PrimaryKey',
'ClassName' => DataObjectSchemaTest\BaseDataClass::class.'.DBClassName', 'ClassName' => DataObjectSchemaTest\BaseDataClass::class . '.DBClassName',
'LastEdited' => DataObjectSchemaTest\BaseDataClass::class.'.DBDatetime', 'LastEdited' => DataObjectSchemaTest\BaseDataClass::class . '.DBDatetime',
'Created' => DataObjectSchemaTest\BaseDataClass::class.'.DBDatetime', 'Created' => DataObjectSchemaTest\BaseDataClass::class . '.DBDatetime',
'Title' => DataObjectSchemaTest\BaseDataClass::class.'.Varchar', 'Title' => DataObjectSchemaTest\BaseDataClass::class . '.Varchar',
'Description' => DataObjectSchemaTest\HasFields::class.'.Varchar', 'Description' => DataObjectSchemaTest\HasFields::class . '.Varchar',
'MoneyFieldCurrency' => DataObjectSchemaTest\HasFields::class.'.Varchar(3)', 'MoneyFieldCurrency' => DataObjectSchemaTest\HasFields::class . '.Varchar(3)',
'MoneyFieldAmount' => DataObjectSchemaTest\HasFields::class.'.Decimal(19,4)', 'MoneyFieldAmount' => DataObjectSchemaTest\HasFields::class . '.Decimal(19,4)',
'MoneyField' => DataObjectSchemaTest\HasFields::class.'.Money', 'MoneyField' => DataObjectSchemaTest\HasFields::class . '.Money',
], ],
$schema->fieldSpecs(HasFields::class, DataObjectSchema::INCLUDE_CLASS) $schema->fieldSpecs(HasFields::class, DataObjectSchema::INCLUDE_CLASS)
); );
// DB_ONLY excludes composite field MoneyField // DB_ONLY excludes composite field MoneyField
$this->assertEquals( $this->assertEquals(
[ [
'ID' => DataObjectSchemaTest\HasFields::class.'.PrimaryKey', 'ID' => DataObjectSchemaTest\HasFields::class . '.PrimaryKey',
'ClassName' => DataObjectSchemaTest\BaseDataClass::class.'.DBClassName', 'ClassName' => DataObjectSchemaTest\BaseDataClass::class . '.DBClassName',
'LastEdited' => DataObjectSchemaTest\BaseDataClass::class.'.DBDatetime', 'LastEdited' => DataObjectSchemaTest\BaseDataClass::class . '.DBDatetime',
'Created' => DataObjectSchemaTest\BaseDataClass::class.'.DBDatetime', 'Created' => DataObjectSchemaTest\BaseDataClass::class . '.DBDatetime',
'Title' => DataObjectSchemaTest\BaseDataClass::class.'.Varchar', 'Title' => DataObjectSchemaTest\BaseDataClass::class . '.Varchar',
'Description' => DataObjectSchemaTest\HasFields::class.'.Varchar', 'Description' => DataObjectSchemaTest\HasFields::class . '.Varchar',
'MoneyFieldCurrency' => DataObjectSchemaTest\HasFields::class.'.Varchar(3)', 'MoneyFieldCurrency' => DataObjectSchemaTest\HasFields::class . '.Varchar(3)',
'MoneyFieldAmount' => DataObjectSchemaTest\HasFields::class.'.Decimal(19,4)' 'MoneyFieldAmount' => DataObjectSchemaTest\HasFields::class . '.Decimal(19,4)'
], ],
$schema->fieldSpecs( $schema->fieldSpecs(
HasFields::class, HasFields::class,
@ -212,10 +212,10 @@ class DataObjectSchemaTest extends SapphireTest
// Use all options at once // Use all options at once
$this->assertEquals( $this->assertEquals(
[ [
'ID' => DataObjectSchemaTest\HasFields::class.'.PrimaryKey', 'ID' => DataObjectSchemaTest\HasFields::class . '.PrimaryKey',
'Description' => DataObjectSchemaTest\HasFields::class.'.Varchar', 'Description' => DataObjectSchemaTest\HasFields::class . '.Varchar',
'MoneyFieldCurrency' => DataObjectSchemaTest\HasFields::class.'.Varchar(3)', 'MoneyFieldCurrency' => DataObjectSchemaTest\HasFields::class . '.Varchar(3)',
'MoneyFieldAmount' => DataObjectSchemaTest\HasFields::class.'.Decimal(19,4)', 'MoneyFieldAmount' => DataObjectSchemaTest\HasFields::class . '.Decimal(19,4)',
], ],
$schema->fieldSpecs( $schema->fieldSpecs(
HasFields::class, HasFields::class,

View File

@ -155,8 +155,7 @@ class DataObjectTest extends SapphireTest
$helper = $obj->dbObject($field); $helper = $obj->dbObject($field);
$this->assertTrue( $this->assertTrue(
($helper instanceof DBField), ($helper instanceof DBField),
"for {$field} expected helper to be DBField, but was " . "for {$field} expected helper to be DBField, but was " . (is_object($helper) ? get_class($helper) : "null")
(is_object($helper) ? get_class($helper) : "null")
); );
} }
} }

View File

@ -7,8 +7,8 @@ class CEO extends Staff
private static $table_name = 'DataObjectTest_CEO'; private static $table_name = 'DataObjectTest_CEO';
private static $belongs_to = array( private static $belongs_to = array(
'Company' => Company::class.'.CEO', 'Company' => Company::class . '.CEO',
'PreviousCompany' => Company::class.'.PreviousCEO', 'PreviousCompany' => Company::class . '.PreviousCEO',
'CompanyOwned' => Company::class.'.Owner' 'CompanyOwned' => Company::class . '.Owner'
); );
} }

View File

@ -20,7 +20,7 @@ class Company extends DataObject implements TestOnly
]; ];
private static $has_many = array( private static $has_many = array(
'CurrentStaff' => Staff::class.'.CurrentCompany', 'CurrentStaff' => Staff::class . '.CurrentCompany',
'PreviousStaff' => Staff::class.'.PreviousCompany' 'PreviousStaff' => Staff::class . '.PreviousCompany'
); );
} }

View File

@ -24,13 +24,13 @@ class Player extends Member implements TestOnly
); );
private static $has_many = array( private static $has_many = array(
'Fans' => Fan::class.'.Favourite', // Polymorphic - Player fans 'Fans' => Fan::class . '.Favourite', // Polymorphic - Player fans
'CaptainTeams' => Team::class.'.Captain', 'CaptainTeams' => Team::class . '.Captain',
'FoundingTeams' => Team::class.'.Founder' 'FoundingTeams' => Team::class . '.Founder'
); );
private static $belongs_to = array( private static $belongs_to = array(
'CompanyOwned' => Company::class.'.Owner' 'CompanyOwned' => Company::class . '.Owner'
); );
private static $searchable_fields = array( private static $searchable_fields = array(

View File

@ -39,8 +39,8 @@ class Team extends DataObject implements TestOnly
private static $has_many = array( private static $has_many = array(
'SubTeams' => SubTeam::class, 'SubTeams' => SubTeam::class,
'Comments' => TeamComment::class, 'Comments' => TeamComment::class,
'Fans' => Fan::class.'.Favourite', // Polymorphic - Team fans 'Fans' => Fan::class . '.Favourite', // Polymorphic - Team fans
'PlayerFans' => Player::class.'.FavouriteTeam' 'PlayerFans' => Player::class . '.FavouriteTeam'
); );
private static $many_many = array( private static $many_many = array(
@ -54,8 +54,8 @@ class Team extends DataObject implements TestOnly
); );
private static $belongs_many_many = array( private static $belongs_many_many = array(
'Sponsors' => EquipmentCompany::class.'.SponsoredTeams', 'Sponsors' => EquipmentCompany::class . '.SponsoredTeams',
'EquipmentSuppliers' => EquipmentCompany::class.'.EquipmentCustomers' 'EquipmentSuppliers' => EquipmentCompany::class . '.EquipmentCustomers'
); );
private static $summary_fields = array( private static $summary_fields = array(

View File

@ -356,15 +356,15 @@ class ManyManyListTest extends SapphireTest
// ensure that ManyManyListTest_ExtraFields_Clients.ValueCurrency is // ensure that ManyManyListTest_ExtraFields_Clients.ValueCurrency is
// selected. // selected.
$expected = 'SELECT DISTINCT "ManyManyListTest_ExtraFields_Clients"."WorthCurrency",' $expected = 'SELECT DISTINCT "ManyManyListTest_ExtraFields_Clients"."WorthCurrency",'
.' "ManyManyListTest_ExtraFields_Clients"."WorthAmount", "ManyManyListTest_ExtraFields_Clients"."Reference",' . ' "ManyManyListTest_ExtraFields_Clients"."WorthAmount", "ManyManyListTest_ExtraFields_Clients"."Reference",'
.' "ManyManyListTest_ExtraFields"."ClassName", "ManyManyListTest_ExtraFields"."LastEdited",' . ' "ManyManyListTest_ExtraFields"."ClassName", "ManyManyListTest_ExtraFields"."LastEdited",'
.' "ManyManyListTest_ExtraFields"."Created", "ManyManyListTest_ExtraFields"."ID",' . ' "ManyManyListTest_ExtraFields"."Created", "ManyManyListTest_ExtraFields"."ID",'
.' CASE WHEN "ManyManyListTest_ExtraFields"."ClassName" IS NOT NULL THEN' . ' CASE WHEN "ManyManyListTest_ExtraFields"."ClassName" IS NOT NULL THEN'
.' "ManyManyListTest_ExtraFields"."ClassName" ELSE '. Convert::raw2sql(ManyManyListTest\ExtraFieldsObject::class, true) . ' "ManyManyListTest_ExtraFields"."ClassName" ELSE ' . Convert::raw2sql(ManyManyListTest\ExtraFieldsObject::class, true)
.' END AS "RecordClassName" FROM "ManyManyListTest_ExtraFields" INNER JOIN' . ' END AS "RecordClassName" FROM "ManyManyListTest_ExtraFields" INNER JOIN'
.' "ManyManyListTest_ExtraFields_Clients" ON' . ' "ManyManyListTest_ExtraFields_Clients" ON'
.' "ManyManyListTest_ExtraFields_Clients"."ManyManyListTest_ExtraFieldsID" =' . ' "ManyManyListTest_ExtraFields_Clients"."ManyManyListTest_ExtraFieldsID" ='
.' "ManyManyListTest_ExtraFields"."ID"'; . ' "ManyManyListTest_ExtraFields"."ID"';
$this->assertSQLEquals($expected, $list->sql($parameters)); $this->assertSQLEquals($expected, $list->sql($parameters));
} }

View File

@ -478,8 +478,8 @@ class SQLSelectTest extends SapphireTest
$query->addLeftJoin('MyLastTable', 'MyOtherTable.ID = MyLastTable.ID'); $query->addLeftJoin('MyLastTable', 'MyOtherTable.ID = MyLastTable.ID');
$this->assertSQLEquals( $this->assertSQLEquals(
'SELECT * FROM MyTable '. 'SELECT * FROM MyTable ' .
'INNER JOIN "MyOtherTable" ON MyOtherTable.ID = 2 '. 'INNER JOIN "MyOtherTable" ON MyOtherTable.ID = 2 ' .
'LEFT JOIN "MyLastTable" ON MyOtherTable.ID = MyLastTable.ID', 'LEFT JOIN "MyLastTable" ON MyOtherTable.ID = MyLastTable.ID',
$query->sql($parameters) $query->sql($parameters)
); );
@ -490,8 +490,8 @@ class SQLSelectTest extends SapphireTest
$query->addLeftJoin('MyLastTable', 'MyOtherTable.ID = MyLastTable.ID', 'table2'); $query->addLeftJoin('MyLastTable', 'MyOtherTable.ID = MyLastTable.ID', 'table2');
$this->assertSQLEquals( $this->assertSQLEquals(
'SELECT * FROM MyTable '. 'SELECT * FROM MyTable ' .
'INNER JOIN "MyOtherTable" AS "table1" ON MyOtherTable.ID = 2 '. 'INNER JOIN "MyOtherTable" AS "table1" ON MyOtherTable.ID = 2 ' .
'LEFT JOIN "MyLastTable" AS "table2" ON MyOtherTable.ID = MyLastTable.ID', 'LEFT JOIN "MyLastTable" AS "table2" ON MyOtherTable.ID = MyLastTable.ID',
$query->sql($parameters) $query->sql($parameters)
); );
@ -516,7 +516,7 @@ class SQLSelectTest extends SapphireTest
$query->setOrderBy('COALESCE(Mlt.MyLastTableCount, 0) DESC'); $query->setOrderBy('COALESCE(Mlt.MyLastTableCount, 0) DESC');
$this->assertSQLEquals( $this->assertSQLEquals(
'SELECT *, COALESCE(Mlt.MyLastTableCount, 0) AS "_SortColumn0" FROM MyTable '. 'SELECT *, COALESCE(Mlt.MyLastTableCount, 0) AS "_SortColumn0" FROM MyTable ' .
'INNER JOIN (SELECT * FROM MyOtherTable) AS "Mot" ON Mot.MyTableID = MyTable.ID ' . 'INNER JOIN (SELECT * FROM MyOtherTable) AS "Mot" ON Mot.MyTableID = MyTable.ID ' .
'LEFT JOIN (SELECT MyLastTable.MyOtherTableID, COUNT(1) as MyLastTableCount FROM MyLastTable ' 'LEFT JOIN (SELECT MyLastTable.MyOtherTableID, COUNT(1) as MyLastTableCount FROM MyLastTable '
. 'GROUP BY MyOtherTableID) AS "Mlt" ON Mlt.MyOtherTableID = Mot.ID ' . . 'GROUP BY MyOtherTableID) AS "Mlt" ON Mlt.MyOtherTableID = Mot.ID ' .

View File

@ -35,7 +35,7 @@ class InheritedPermissionsTest extends SapphireTest
->setDefaultPermissions($this->rootPermissions = new TestDefaultPermissionChecker()); ->setDefaultPermissions($this->rootPermissions = new TestDefaultPermissionChecker());
Injector::inst()->registerService( Injector::inst()->registerService(
$permission, $permission,
PermissionChecker::class.'.testpermissions' PermissionChecker::class . '.testpermissions'
); );
// Reset root permission // Reset root permission

View File

@ -40,7 +40,7 @@ class TestPermissionNode extends DataObject implements TestOnly
public static function getInheritedPermissions() public static function getInheritedPermissions()
{ {
/** @var InheritedPermissions $permissions */ /** @var InheritedPermissions $permissions */
return Injector::inst()->get(PermissionChecker::class.'.testpermissions'); return Injector::inst()->get(PermissionChecker::class . '.testpermissions');
} }
public function canEdit($member = null) public function canEdit($member = null)

View File

@ -246,7 +246,7 @@ class MemberTest extends FunctionalTest
"testuser@example.com", "testuser@example.com",
null, null,
'Your password reset link', 'Your password reset link',
'/Security\/changepassword\?m='.$member->ID.'&amp;t=[^"]+/' '/Security\/changepassword\?m=' . $member->ID . '&amp;t=[^"]+/'
); );
} }
@ -805,11 +805,11 @@ class MemberTest extends FunctionalTest
$this->assertTrue( $this->assertTrue(
in_array($admin->getTitle(), $members), in_array($admin->getTitle(), $members),
$admin->getTitle().' should be in the returned list.' $admin->getTitle() . ' should be in the returned list.'
); );
$this->assertTrue( $this->assertTrue(
in_array($otherAdmin->getTitle(), $members), in_array($otherAdmin->getTitle(), $members),
$otherAdmin->getTitle().' should be in the returned list.' $otherAdmin->getTitle() . ' should be in the returned list.'
); );
$this->assertEquals(2, count($members), 'There should be 2 members from the admin group'); $this->assertEquals(2, count($members), 'There should be 2 members from the admin group');
} }
@ -920,7 +920,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$token, 'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => $firstHash->DeviceID 'alc_device' => $firstHash->DeviceID
) )
); );
@ -941,7 +941,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':asdfasd'.str_rot13($token), 'alc_enc' => $m1->ID . ':asdfasd' . str_rot13($token),
'alc_device' => $firstHash->DeviceID 'alc_device' => $firstHash->DeviceID
) )
); );
@ -952,7 +952,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$token, 'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => str_rot13($firstHash->DeviceID) 'alc_device' => str_rot13($firstHash->DeviceID)
) )
); );
@ -1000,7 +1000,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$token, 'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => $firstHash->DeviceID 'alc_device' => $firstHash->DeviceID
) )
); );
@ -1028,7 +1028,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$token, 'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => $firstHash->DeviceID 'alc_device' => $firstHash->DeviceID
) )
); );
@ -1076,7 +1076,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$firstToken, 'alc_enc' => $m1->ID . ':' . $firstToken,
'alc_device' => $firstHash->DeviceID 'alc_device' => $firstHash->DeviceID
) )
); );
@ -1101,7 +1101,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$secondToken, 'alc_enc' => $m1->ID . ':' . $secondToken,
'alc_device' => $secondHash->DeviceID 'alc_device' => $secondHash->DeviceID
) )
); );
@ -1114,7 +1114,7 @@ class MemberTest extends FunctionalTest
$this->session(), $this->session(),
null, null,
array( array(
'alc_enc' => $m1->ID.':'.$secondToken, 'alc_enc' => $m1->ID . ':' . $secondToken,
'alc_device' => $secondHash->DeviceID 'alc_device' => $secondHash->DeviceID
) )
); );

View File

@ -404,7 +404,7 @@ class SecurityTest extends FunctionalTest
$expiredResponse = $this->doTestLoginForm('expired@silverstripe.com', '1nitialPassword'); $expiredResponse = $this->doTestLoginForm('expired@silverstripe.com', '1nitialPassword');
$this->assertEquals(302, $expiredResponse->getStatusCode()); $this->assertEquals(302, $expiredResponse->getStatusCode());
$this->assertEquals( $this->assertEquals(
Director::absoluteURL('Security/changepassword').'?BackURL=test%2Flink', Director::absoluteURL('Security/changepassword') . '?BackURL=test%2Flink',
Director::absoluteURL($expiredResponse->getHeader('Location')) Director::absoluteURL($expiredResponse->getHeader('Location'))
); );
$this->assertEquals( $this->assertEquals(
@ -471,7 +471,7 @@ class SecurityTest extends FunctionalTest
$token = $admin->generateAutologinTokenAndStoreHash(); $token = $admin->generateAutologinTokenAndStoreHash();
// Check. // Check.
$response = $this->get('Security/changepassword/?m='.$admin->ID.'&t=' . $token); $response = $this->get('Security/changepassword/?m=' . $admin->ID . '&t=' . $token);
$this->assertEquals(302, $response->getStatusCode()); $this->assertEquals(302, $response->getStatusCode());
$this->assertEquals( $this->assertEquals(
Director::absoluteURL('Security/changepassword'), Director::absoluteURL('Security/changepassword'),
@ -533,8 +533,7 @@ class SecurityTest extends FunctionalTest
} }
$msg = _t( $msg = _t(
'SilverStripe\\Security\\Member.ERRORLOCKEDOUT2', 'SilverStripe\\Security\\Member.ERRORLOCKEDOUT2',
'Your account has been temporarily disabled because of too many failed attempts at ' . 'Your account has been temporarily disabled because of too many failed attempts at ' . 'logging in. Please try again in {count} minutes.',
'logging in. Please try again in {count} minutes.',
null, null,
array('count' => 15) array('count' => 15)
); );

View File

@ -83,8 +83,7 @@ class ShortcodeParserTest extends SapphireTest
{ {
$tests = array( $tests = array(
'[test_shortcode]', '[test_shortcode]',
'[test_shortcode ]', '[test_shortcode,]', '[test_shortcode, ]'. '[test_shortcode ]', '[test_shortcode,]', '[test_shortcode, ]' . '[test_shortcode/]', '[test_shortcode /]', '[test_shortcode,/]', '[test_shortcode, /]'
'[test_shortcode/]', '[test_shortcode /]', '[test_shortcode,/]', '[test_shortcode, /]'
); );
foreach ($tests as $test) { foreach ($tests as $test) {

View File

@ -585,7 +585,7 @@ class RequirementsTest extends SapphireTest
/* BLOCKED UNCOMBINED FILES ARE NOT INCLUDED */ /* BLOCKED UNCOMBINED FILES ARE NOT INCLUDED */
$this->setupCombinedRequirements($backend); $this->setupCombinedRequirements($backend);
$backend->block($basePath .'/javascript/RequirementsTest_b.js'); $backend->block($basePath . '/javascript/RequirementsTest_b.js');
$combinedFileName2 = '/_combinedfiles/RequirementsTest_bc-3748f67.js'; // SHA1 without file b included $combinedFileName2 = '/_combinedfiles/RequirementsTest_bc-3748f67.js'; // SHA1 without file b included
$combinedFilePath2 = TestAssetStore::base_path() . $combinedFileName2; $combinedFilePath2 = TestAssetStore::base_path() . $combinedFileName2;
clearstatcache(); // needed to get accurate file_exists() results clearstatcache(); // needed to get accurate file_exists() results
@ -750,22 +750,22 @@ class RequirementsTest extends SapphireTest
// Note: SSViewer theme automatically registered due to 'templates' directory // Note: SSViewer theme automatically registered due to 'templates' directory
$data->renderWith('RequirementsTest_Conditionals'); $data->renderWith('RequirementsTest_Conditionals');
$this->assertFileIncluded($backend, 'css', $testPath .'/css/RequirementsTest_a.css'); $this->assertFileIncluded($backend, 'css', $testPath . '/css/RequirementsTest_a.css');
$this->assertFileIncluded( $this->assertFileIncluded(
$backend, $backend,
'js', 'js',
array( array(
$testPath .'/javascript/RequirementsTest_b.js', $testPath . '/javascript/RequirementsTest_b.js',
$testPath .'/javascript/RequirementsTest_c.js' $testPath . '/javascript/RequirementsTest_c.js'
) )
); );
$this->assertFileNotIncluded($backend, 'js', $testPath .'/javascript/RequirementsTest_a.js'); $this->assertFileNotIncluded($backend, 'js', $testPath . '/javascript/RequirementsTest_a.js');
$this->assertFileNotIncluded( $this->assertFileNotIncluded(
$backend, $backend,
'css', 'css',
array( array(
$testPath .'/css/RequirementsTest_b.css', $testPath . '/css/RequirementsTest_b.css',
$testPath .'/css/RequirementsTest_c.css' $testPath . '/css/RequirementsTest_c.css'
) )
); );
$backend->clear(); $backend->clear();
@ -775,22 +775,22 @@ class RequirementsTest extends SapphireTest
) )
); );
$data->renderWith('RequirementsTest_Conditionals'); $data->renderWith('RequirementsTest_Conditionals');
$this->assertFileNotIncluded($backend, 'css', $testPath .'/css/RequirementsTest_a.css'); $this->assertFileNotIncluded($backend, 'css', $testPath . '/css/RequirementsTest_a.css');
$this->assertFileNotIncluded( $this->assertFileNotIncluded(
$backend, $backend,
'js', 'js',
array( array(
$testPath .'/javascript/RequirementsTest_b.js', $testPath . '/javascript/RequirementsTest_b.js',
$testPath .'/javascript/RequirementsTest_c.js' $testPath . '/javascript/RequirementsTest_c.js'
) )
); );
$this->assertFileIncluded($backend, 'js', $testPath .'/javascript/RequirementsTest_a.js'); $this->assertFileIncluded($backend, 'js', $testPath . '/javascript/RequirementsTest_a.js');
$this->assertFileIncluded( $this->assertFileIncluded(
$backend, $backend,
'css', 'css',
array( array(
$testPath .'/css/RequirementsTest_b.css', $testPath . '/css/RequirementsTest_b.css',
$testPath .'/css/RequirementsTest_c.css' $testPath . '/css/RequirementsTest_c.css'
) )
); );
Requirements::set_backend($holder); Requirements::set_backend($holder);
@ -929,10 +929,10 @@ EOS
$backend = Injector::inst()->create(Requirements_Backend::class); $backend = Injector::inst()->create(Requirements_Backend::class);
$this->setupRequirements($backend); $this->setupRequirements($backend);
$backend->javascript($basePath .'/javascript/RequirementsTest_a.js'); $backend->javascript($basePath . '/javascript/RequirementsTest_a.js');
$backend->javascript($basePath .'/javascript/RequirementsTest_b.js?foo=bar&bla=blubb'); $backend->javascript($basePath . '/javascript/RequirementsTest_b.js?foo=bar&bla=blubb');
$backend->css($basePath .'/css/RequirementsTest_a.css'); $backend->css($basePath . '/css/RequirementsTest_a.css');
$backend->css($basePath .'/css/RequirementsTest_b.css?foo=bar&bla=blubb'); $backend->css($basePath . '/css/RequirementsTest_b.css?foo=bar&bla=blubb');
$urlGenerator->setNonceStyle('mtime'); $urlGenerator->setNonceStyle('mtime');
$html = $backend->includeInHTML($template); $html = $backend->includeInHTML($template);

View File

@ -206,7 +206,7 @@ class SSViewerTest extends SapphireTest
if (!$data) { if (!$data) {
$data = new SSViewerTest\TestFixture(); $data = new SSViewerTest\TestFixture();
} }
return trim(''.$t->process($data)); return trim('' . $t->process($data));
} }
public function testRequirements() public function testRequirements()
@ -254,7 +254,7 @@ class SSViewerTest extends SapphireTest
// and make sure the combined content matches the input content, i.e. no loss of functionality // and make sure the combined content matches the input content, i.e. no loss of functionality
if (!file_exists($combinedTestFilePath)) { if (!file_exists($combinedTestFilePath)) {
$this->fail('No combined file was created at expected path: '.$combinedTestFilePath); $this->fail('No combined file was created at expected path: ' . $combinedTestFilePath);
} }
$combinedTestFileContents = file_get_contents($combinedTestFilePath); $combinedTestFileContents = file_get_contents($combinedTestFilePath);
$this->assertContains($jsFileContents, $combinedTestFileContents); $this->assertContains($jsFileContents, $combinedTestFileContents);
@ -1398,7 +1398,7 @@ after'
'BazBarQux', 'BazBarQux',
$this->render( $this->render(
'<% with Foo.Bar.Baz %>{$Name}<% with $Up %>{$Name}{$Qux.Name}<% end_with %>' '<% with Foo.Bar.Baz %>{$Name}<% with $Up %>{$Name}{$Qux.Name}<% end_with %>'
.'<% end_with %>', . '<% end_with %>',
$data $data
) )
); );
@ -1586,7 +1586,7 @@ after'
public function testLayout() public function testLayout()
{ {
$this->useTestTheme( $this->useTestTheme(
__DIR__.'/SSViewerTest', __DIR__ . '/SSViewerTest',
'layouttest', 'layouttest',
function () { function () {
$template = new SSViewer(array('Page')); $template = new SSViewer(array('Page'));
@ -1871,7 +1871,7 @@ EOC;
), ),
); );
foreach ($templates as $template) { foreach ($templates as $template) {
$this->_renderWithSourceFileComments('SSViewerTestComments/'.$template['name'], $template['expected']); $this->_renderWithSourceFileComments('SSViewerTestComments/' . $template['name'], $template['expected']);
} }
} }
private function _renderWithSourceFileComments($name, $expected) private function _renderWithSourceFileComments($name, $expected)
@ -1935,7 +1935,7 @@ EOC;
); );
} else { } else {
$this->markTestSkipped( $this->markTestSkipped(
'Requirement will always fail if the framework dir is not '. 'Requirement will always fail if the framework dir is not ' .
'named \'framework\', since templates require hard coded paths' 'named \'framework\', since templates require hard coded paths'
); );
} }

View File

@ -81,17 +81,17 @@ class i18nTest extends SapphireTest
$provider = Injector::inst()->get(MessageProvider::class); $provider = Injector::inst()->get(MessageProvider::class);
$provider->getTranslator()->addResource( $provider->getTranslator()->addResource(
'array', 'array',
[ i18nTest\TestDataObject::class.'.MyProperty' => 'MyProperty' ], [ i18nTest\TestDataObject::class . '.MyProperty' => 'MyProperty' ],
'en_US' 'en_US'
); );
$provider->getTranslator()->addResource( $provider->getTranslator()->addResource(
'array', 'array',
[ i18nTest\TestDataObject::class.'.MyProperty' => 'Mein Attribut' ], [ i18nTest\TestDataObject::class . '.MyProperty' => 'Mein Attribut' ],
'de_DE' 'de_DE'
); );
$provider->getTranslator()->addResource( $provider->getTranslator()->addResource(
'array', 'array',
[ i18nTest\TestDataObject::class.'.MyUntranslatedProperty' => 'Mein Attribut' ], [ i18nTest\TestDataObject::class . '.MyUntranslatedProperty' => 'Mein Attribut' ],
'en_US' 'en_US'
); );
@ -113,12 +113,12 @@ class i18nTest extends SapphireTest
$provider = Injector::inst()->get(MessageProvider::class); $provider = Injector::inst()->get(MessageProvider::class);
$provider->getTranslator()->addResource( $provider->getTranslator()->addResource(
'array', 'array',
[ i18nTest\TestObject::class.'.MyProperty' => 'Untranslated' ], [ i18nTest\TestObject::class . '.MyProperty' => 'Untranslated' ],
'en_US' 'en_US'
); );
$provider->getTranslator()->addResource( $provider->getTranslator()->addResource(
'array', 'array',
[ i18nTest\TestObject::class.'.my_translatable_property' => 'Übersetzt' ], [ i18nTest\TestObject::class . '.my_translatable_property' => 'Übersetzt' ],
'de_DE' 'de_DE'
); );
@ -260,7 +260,7 @@ class i18nTest extends SapphireTest
// Test missing entity key // Test missing entity key
$translated = i18n::_t( $translated = i18n::_t(
$entity.'_DOES_NOT_EXIST', $entity . '_DOES_NOT_EXIST',
$default, $default,
array("name"=>"Mark", "greeting"=>"welcome", "goodbye"=>"bye") array("name"=>"Mark", "greeting"=>"welcome", "goodbye"=>"bye")
); );
@ -341,7 +341,7 @@ class i18nTest extends SapphireTest
//test injected calls //test injected calls
$this->assertContains( $this->assertContains(
Convert::nl2os( Convert::nl2os(
"TRANS Hello ".Director::absoluteBaseURL()." ".i18n::get_locale().". But it is late, global calls\n" "TRANS Hello " . Director::absoluteBaseURL() . " " . i18n::get_locale() . ". But it is late, global calls\n"
), ),
$parsedHtml, $parsedHtml,
"Testing a translation with just entity and injection array, but with global variables injected in" "Testing a translation with just entity and injection array, but with global variables injected in"

View File

@ -28,7 +28,7 @@ class MyObject extends DataObject implements TestOnly
{ {
$entities = parent::provideI18nEntities(); $entities = parent::provideI18nEntities();
return array_merge($entities, [ return array_merge($entities, [
LeftAndMain::class.'.OTHER_TITLE' => [ LeftAndMain::class . '.OTHER_TITLE' => [
'default' => 'Other title', 'default' => 'Other title',
'module' => 'admin', 'module' => 'admin',
], ],

View File

@ -34,7 +34,7 @@ class TestDataObject extends DataObject implements TestOnly
public function fieldLabels($includerelations = true) public function fieldLabels($includerelations = true)
{ {
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['MyProperty'] = _t(__CLASS__.'.MyProperty', 'My Property'); $labels['MyProperty'] = _t(__CLASS__ . '.MyProperty', 'My Property');
return $labels; return $labels;
} }

View File

@ -11,13 +11,13 @@ class TestObject implements TestOnly, i18nEntityProvider
public static function my_translatable_property() public static function my_translatable_property()
{ {
return _t(__CLASS__.".my_translatable_property", self::$my_translatable_property); return _t(__CLASS__ . ".my_translatable_property", self::$my_translatable_property);
} }
public function provideI18nEntities() public function provideI18nEntities()
{ {
return [ return [
__CLASS__.".my_translatable_property" => self::$my_translatable_property, __CLASS__ . ".my_translatable_property" => self::$my_translatable_property,
]; ];
} }
} }