Merge remote-tracking branch 'origin/4.0' into 4

# Conflicts:
#	src/Core/TempFolder.php
#	src/ORM/DataObject.php
#	src/View/ThemeResourceLoader.php
#	src/includes/constants.php
#	tests/php/Control/SimpleResourceURLGeneratorTest.php
#	tests/php/Forms/HTMLEditor/HTMLEditorFieldTest.php
#	tests/php/View/RequirementsTest.php
This commit is contained in:
Damian Mooyman 2018-01-22 14:57:05 +13:00
commit a3c52f901a
No known key found for this signature in database
GPG Key ID: 78B823A10DE27D1A
134 changed files with 652 additions and 646 deletions

View File

@ -4,25 +4,34 @@ summary: Add custom CSS properties to the rich-text editor.
# WYSIWYG Styles
SilverStripe lets you customise the style of content in the CMS. This is done by setting up a CSS file called
`editor.css` in either your theme or in your `mysite` folder. This is set through
`editor.css` in either your theme or in your `mysite` folder. This is set through yaml config:
```php
use SilverStripe\Forms\HTMLEditor\HtmlEditorConfig;
HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css');
```yaml
---
name: MyCSS
---
SilverStripe\Forms\HTMLEditor\TinyMCEConfig:
editor_css:
- 'mysite/css/editor.css'
```
Will load the `mysite/css/editor.css` file.
If using this config option in `mysite/_config.php`, you will have to instead call:
## Custom style dropdown
The custom style dropdown can be enabled via the `importcss` plugin bundled with admin module. ([Doc](https://www.tinymce.com/docs/plugins/importcss/))
Use the below code in `mysite/_config.php`:
```php
HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css');
use SilverStripe\Forms\HTMLEditor\TinyMCEConfig;
TinyMCEConfig::get('cms')
->addButtonsToLine(1, 'styleselect')
->setOption('importcss_append', true);
```
Any CSS classes within this file will be automatically added to the `WYSIWYG` editors 'style' dropdown. For instance, to
Any CSS classes within this file will be automatically added to the `WYSIWYG` editors 'style' dropdown.
For instance, to
add the color 'red' as an option within the `WYSIWYG` add the following to the `editor.css`
@ -31,10 +40,64 @@ add the color 'red' as an option within the `WYSIWYG` add the following to the `
color: red;
}
```
Adding a tag to the selector will automatically wrap with this tag. For example :
```css
h4.red {
color: red;
}
```
will add an `h4` tag to the selected block.
For further customisation, customize the `style_formats` option.
`style_formats` won't be applied if you do not enable `importcss_append`.
Here is a working example to get you started.  
See related [tinymce doc](https://www.tinymce.com/docs/configure/content-formatting/#style_formats).
```php
use SilverStripe\Forms\HTMLEditor\TinyMCEConfig;
$formats = [
[ 'title' => 'Headings', 'items' => [
['title' => 'Heading 1', 'block' => 'h1' ],
['title' => 'Heading 2', 'block' => 'h2' ],
['title' => 'Heading 3', 'block' => 'h3' ],
['title' => 'Heading 4', 'block' => 'h4' ],
['title' => 'Heading 5', 'block' => 'h5' ],
['title' => 'Heading 6', 'block' => 'h6' ],
[
'title' => 'Subtitle',
'selector' => 'p',
'classes' => 'title-sub',
],
]
],
[
'title' => 'Misc Styles', 'items' => [
[
'title' => 'Style 1',
'selector' => 'ul',
'classes' => 'style1',
'wrapper' => true,
'merge_siblings' => false,
],
[
'title' => 'Button red',
'inline' => 'span',
'classes' => 'btn-red',
'merge_siblings' => true,
],
]
],
];
TinyMCEConfig::get('cms')
->addButtonsToLine(1, 'styleselect')
->setOptions([
'importcss_append' => true,
'style_formats' => $formats,
]);
```
<div class="notice" markdown="1">
After you have defined the `editor.css` make sure you clear your SilverStripe cache for it to take effect.
</div>
## API Documentation

View File

@ -18,13 +18,19 @@
<exclude name="Generic.Files.LineLength.TooLong" />
<exclude name="PEAR.Functions.ValidDefaultValue.NotAtEnd" />
</rule>
<rule phpcbf-only="true" ref="Squiz.Strings.ConcatenationSpacing">
<properties>
<property name="spacing" value="1" />
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<!-- include php files only -->
<arg name="extensions" value="php,lib,inc,php5"/>
<arg name="extensions" value="php,lib,inc,php5"/>
<!-- PHP-PEG generated file not intended for human consumption -->
<exclude-pattern>*/SSTemplateParser.php$</exclude-pattern>
<exclude-pattern>*/_fakewebroot/*</exclude-pattern>
<exclude-pattern>*/fixtures/*</exclude-pattern>
<exclude-pattern>*/_fakewebroot/*</exclude-pattern>
<exclude-pattern>*/fixtures/*</exclude-pattern>
</ruleset>

View File

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

View File

@ -245,7 +245,7 @@ class HTTPResponse
*/
public function removeHeader($header)
{
strtolower($header);
$header = strtolower($header);
unset($this->headers[$header]);
return $this;
}

View File

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

View File

@ -130,9 +130,7 @@ class RSSFeed_Entry extends ViewableData
}
throw new BadMethodCallException(
get_class($this->failover) .
" object has neither an AbsoluteLink nor a Link method." .
" Can't put a link in the RSS feed",
get_class($this->failover) . " object has neither an AbsoluteLink nor a Link method." . " Can't put a link in the RSS feed",
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);
}
$classMessage = Director::isLive() ? 'on this handler' : 'on class '.static::class;
$classMessage = Director::isLive() ? 'on this handler' : 'on class ' . static::class;
try {
if (!$this->hasAction($action)) {
@ -266,8 +266,7 @@ class RequestHandler extends ViewableData
$class = static::class;
$latestParams = var_export($request->latestParams(), true);
Debug::message(
"Rule '{$rule}' matched to action '{$action}' on {$class}. ".
"Latest request params: {$latestParams}"
"Rule '{$rule}' matched to action '{$action}' on {$class}. " . "Latest request params: {$latestParams}"
);
}
@ -306,7 +305,7 @@ class RequestHandler extends ViewableData
*/
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)) {
return new HTTPResponse("Action '$action' isn't available $classMessage.", 404);
@ -566,8 +565,7 @@ class RequestHandler extends ViewableData
// no link defined by default
trigger_error(
'Request handler '.static::class. ' does not have a url_segment defined. '.
'Relying on this link may be an application error',
'Request handler ' . static::class . ' does not have a url_segment defined. ' . 'Relying on this link may be an application error',
E_USER_WARNING
);
return null;

View File

@ -59,7 +59,7 @@ class RequestProcessor implements HTTPMiddleware
foreach ($this->filters as $filter) {
$res = $filter->preRequest($request);
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) {
// extensions with parameters will be stored in config as ExtensionName("Param").
if (strcasecmp($candidate, $extension) === 0 ||
stripos($candidate, $extension.'(') === 0
stripos($candidate, $extension . '(') === 0
) {
$found = true;
unset($config[$key]);

View File

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

View File

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

View File

@ -98,7 +98,7 @@ class ErrorControlChainMiddleware implements HTTPMiddleware
// Fail and redirect the user to the login page
$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 .= "?BackURL=" . urlencode($backURL);
$result = new HTTPResponse();

View File

@ -56,7 +56,7 @@ class ParameterConfirmationToken
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);
// If the token provided is valid, mark it as such
$token = $request->getVar($parameterName.'token');
$token = $request->getVar($parameterName . 'token');
if ($this->checkToken($token)) {
$this->token = $token;
}

View File

@ -85,7 +85,7 @@ class TempFolder
@mkdir($tempPath, 0777);
umask($oldUMask);
// if the folder already exists, correct perms
// if the folder already exists, correct perms
} else {
if ((fileperms($tempPath) & 0777) != 0777) {
@chmod($tempPath, 0777);
@ -108,9 +108,7 @@ class TempFolder
if (!$worked) {
throw new Exception(
'Permission problem gaining access to a temp folder. ' .
'Please create a folder named silverstripe-cache in the base folder ' .
'of the installation and ensure it has the correct permissions'
'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'
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -127,7 +127,7 @@ class DevelopmentAdmin extends Controller
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()) {
// in CLI we cant use httpError because of a bug with stuff being in the output already, see DevAdminControllerTest
throw new Exception($msg);

View File

@ -44,7 +44,7 @@ class FixtureBlueprint
/** @config */
private static $dependencies = array(
'factory' => '%$'.FixtureFactory::class,
'factory' => '%$' . FixtureFactory::class,
);
/**
@ -221,10 +221,10 @@ class FixtureBlueprint
} else {
$hasOneField = preg_replace('/ID$/', '', $fieldName);
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
if ($className === 'SilverStripe\\ORM\\DataObject') {
$obj->{$hasOneField.'Class'} = $fieldClass;
$obj->{$hasOneField . 'Class'} = $fieldClass;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -60,7 +60,7 @@ class CurrencyField extends TextField
public function validate($validator)
{
$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)) {
$validator->validationError(
$this->name,

View File

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

View File

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

View File

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

View File

@ -77,7 +77,7 @@ class FormScaffolder
// tabbed or untabbed
if ($this->tabbed) {
$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

View File

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

View File

@ -1,6 +1,8 @@
<?php
namespace SilverStripe\Forms\GridField;
use SilverStripe\Versioned\Versioned;
/**
* Allows editing of records contained within the GridField, instead of only allowing the ability to view records in
* the GridField.
@ -21,7 +23,10 @@ class GridFieldConfig_RecordEditor extends GridFieldConfig
$this->addComponent($sort = new GridFieldSortableHeader());
$this->addComponent($filter = new GridFieldFilterHeader());
$this->addComponent(new GridFieldDataColumns());
$this->addComponent(new GridFieldVersionedState([ 'Name', 'Title' ]));
// @todo Move to versioned module, add via extension instead
if (class_exists(Versioned::class)) {
$this->addComponent(new GridFieldVersionedState(['Name', 'Title']));
}
$this->addComponent(new GridFieldEditButton());
$this->addComponent(new GridFieldDeleteAction());
$this->addComponent(new GridFieldPageCount('toolbar-header-right'));

View File

@ -119,11 +119,11 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
if (!$record->canEdit()) {
return null;
}
$title = _t(__CLASS__.'.UnlinkRelation', "Unlink");
$title = _t(__CLASS__ . '.UnlinkRelation', "Unlink");
$field = GridField_FormAction::create(
$gridField,
'UnlinkRelation'.$record->ID,
'UnlinkRelation' . $record->ID,
false,
"unlinkrelation",
array('RecordID' => $record->ID)
@ -138,14 +138,14 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
$field = GridField_FormAction::create(
$gridField,
'DeleteRecord'.$record->ID,
'DeleteRecord' . $record->ID,
false,
"deleterecord",
array('RecordID' => $record->ID)
)
->addExtraClass('gridfield-button-delete btn--icon-md font-icon-trash-bin btn--no-text grid-field__icon-action')
->setAttribute('title', _t(__CLASS__.'.Delete', "Delete"))
->setDescription(_t(__CLASS__.'.DELETE_DESCRIPTION', 'Delete'));
->setAttribute('title', _t(__CLASS__ . '.Delete', "Delete"))
->setDescription(_t(__CLASS__ . '.DELETE_DESCRIPTION', 'Delete'));
}
return $field->Field();
}
@ -171,7 +171,7 @@ class GridFieldDeleteAction implements GridField_ColumnProvider, GridField_Actio
if ($actionName == 'deleterecord') {
if (!$item->canDelete()) {
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 {
if (!$item->canEdit()) {
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);
foreach ($filterArguments as $columnName => $value) {
if ($dataList->canFilterBy($columnName) && $value) {
$dataListClone = $dataListClone->filter($columnName.':PartialMatch', $value);
$dataListClone = $dataListClone->filter($columnName . ':PartialMatch', $value);
}
}
return $dataListClone;
@ -196,7 +196,7 @@ class GridFieldFilterHeader implements GridField_HTMLProvider, GridField_DataMan
$field->setAttribute(
'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);

View File

@ -51,8 +51,7 @@ class GridFieldPageCount implements GridField_HTMLProvider
if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) {
throw new LogicException(
static::class . " relies on a GridFieldPaginator to be added " .
"to the same GridField, but none are present."
static::class . " relies on a GridFieldPaginator to be added " . "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);
if ($data) {
return $data->renderWith(get_class($gridField)."_print");
return $data->renderWith(get_class($gridField) . "_print");
}
return null;

View File

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

View File

@ -1,12 +1,21 @@
<?php
namespace SilverStripe\Forms\GridField;
use SilverStripe\ORM\DataObject;
use SilverStripe\Versioned\Versioned;
use SilverStripe\Core\Convert;
/**
* @todo Move to siverstripe/versioned module
*/
class GridFieldVersionedState implements GridField_ColumnProvider
{
/**
* Column name for versioned state
*
* @var string
*/
protected $column = null;
/**
@ -33,9 +42,12 @@ class GridFieldVersionedState implements GridField_ColumnProvider
*/
public function augmentColumns($gridField, &$columns)
{
if (!class_exists(Versioned::class)) {
return;
}
$model = $gridField->getModelClass();
$isModelVersioned = $model::has_extension(Versioned::class);
if (!$isModelVersioned) {
return;
}
@ -61,7 +73,7 @@ class GridFieldVersionedState implements GridField_ColumnProvider
*/
public function getColumnsHandled($gridField)
{
return [$this->column];
return $this->column ? [$this->column] : [];
}
/**
@ -74,7 +86,6 @@ class GridFieldVersionedState implements GridField_ColumnProvider
*/
public function getColumnContent($gridField, $record, $columnName)
{
$flagContent = '';
$flags = $this->getStatusFlags($record);
foreach ($flags as $class => $data) {
@ -140,32 +151,35 @@ class GridFieldVersionedState implements GridField_ColumnProvider
* )
* ```
*
* @param DataObject $record - the record to check status for
* @param Versioned|DataObject $record - the record to check status for
* @return array
*/
protected function getStatusFlags($record)
{
$flags = array();
if (!$record->hasExtension(Versioned::class)) {
return [];
}
$flags = [];
if ($record->isOnLiveOnly()) {
$flags['removedfromdraft'] = array(
'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'),
'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Item is published, but has been deleted from draft'),
'text' => _t(__CLASS__ . '.ONLIVEONLYSHORT', 'On live only'),
'title' => _t(__CLASS__ . '.ONLIVEONLYSHORTHELP', 'Item is published, but has been deleted from draft'),
);
} elseif ($record->isArchived()) {
$flags['archived'] = array(
'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'),
'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Item is removed from draft and live'),
'text' => _t(__CLASS__ . '.ARCHIVEDPAGESHORT', 'Archived'),
'title' => _t(__CLASS__ . '.ARCHIVEDPAGEHELP', 'Item is removed from draft and live'),
);
} elseif ($record->isOnDraftOnly()) {
$flags['addedtodraft'] = array(
'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'),
'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Item has not been published yet")
'text' => _t(__CLASS__ . '.ADDEDTODRAFTSHORT', 'Draft'),
'title' => _t(__CLASS__ . '.ADDEDTODRAFTHELP', "Item has not been published yet")
);
} elseif ($record->isModifiedOnDraft()) {
$flags['modified'] = array(
'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'),
'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Item has unpublished changes'),
'text' => _t(__CLASS__ . '.MODIFIEDONDRAFTSHORT', 'Modified'),
'title' => _t(__CLASS__ . '.MODIFIEDONDRAFTHELP', 'Item has unpublished changes'),
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -357,7 +357,7 @@ class DBQueryBuilder
// Assert that the array version provides the 'limit' key
if (!isset($limit['limit']) || !is_numeric($limit['limit'])) {
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
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
if (!array_key_exists('limit', $limit) || ($limit['limit'] !== null && ! is_numeric($limit['limit']))) {
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
$this->pdoConnection = new PDO(
$driver.implode(';', $dsn),
$driver . implode(';', $dsn),
empty($parameters['username']) ? '' : $parameters['username'],
empty($parameters['password']) ? '' : $parameters['password'],
$options

View File

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

View File

@ -322,7 +322,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if (!is_array($record)) {
if (is_object($record)) {
$passed = "an object of type '".get_class($record)."'";
$passed = "an object of type '" . get_class($record) . "'";
} else {
$passed = "The value '$record'";
}
@ -360,7 +360,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
foreach ($fields as $field => $fieldSpec) {
$fieldClass = strtok($fieldSpec, ".");
if (!array_key_exists($field, $record)) {
$this->record[$field.'_Lazy'] = $fieldClass;
$this->record[$field . '_Lazy'] = $fieldClass;
}
}
}
@ -637,7 +637,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
{
$default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
return i18n::_t(
static::class.'.PLURALS',
static::class . '.PLURALS',
$default,
[ 'count' => $count ]
);
@ -676,7 +676,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
*/
public function i18n_singular_name()
{
return _t(static::class.'.SINGULARNAME', $this->singular_name());
return _t(static::class . '.SINGULARNAME', $this->singular_name());
}
/**
@ -711,7 +711,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
*/
public function i18n_plural_name()
{
return _t(static::class.'.PLURALNAME', $this->plural_name());
return _t(static::class . '.PLURALNAME', $this->plural_name());
}
/**
@ -810,7 +810,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// If the intermediate relationship objects haven't been created, then write them
if ($i<sizeof($relations)-1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) {
$relObj->write();
$relatedFieldName = $relation."ID";
$relatedFieldName = $relation . "ID";
$parentObj->$relatedFieldName = $relObj->ID;
$parentObj->write();
}
@ -829,7 +829,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if ($relObj) {
$relObj->$fieldName = $value;
$relObj->write();
$relatedFieldName = $relation."ID";
$relatedFieldName = $relation . "ID";
$this->$relatedFieldName = $relObj->ID;
$relObj->flushCache();
} else {
@ -1152,7 +1152,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
{
if ($this->ObsoleteClassName) {
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"
);
}
@ -1282,7 +1282,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
}
// Perform an insert on the base table
$insert = new SQLInsert('"'.$baseTable.'"');
$insert = new SQLInsert('"' . $baseTable . '"');
$insert
->assign('"Created"', $now)
->execute();
@ -1566,8 +1566,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if (empty($component)) {
$component = Injector::inst()->create($class);
if ($polymorphic) {
$component->{$joinField.'ID'} = $this->ID;
$component->{$joinField.'Class'} = static::class;
$component->{$joinField . 'ID'} = $this->ID;
$component->{$joinField . 'Class'} = static::class;
} else {
$component->$joinField = $this->ID;
}
@ -2176,8 +2176,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
}
// Do we have a field that needs to be lazy loaded?
if (isset($this->record[$field.'_Lazy'])) {
$tableClass = $this->record[$field.'_Lazy'];
if (isset($this->record[$field . '_Lazy'])) {
$tableClass = $this->record[$field . '_Lazy'];
$this->loadLazyFields($tableClass);
}
@ -2377,8 +2377,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 (isset($this->record[$fieldName.'_Lazy'])) {
$tableClass = $this->record[$fieldName.'_Lazy'];
if (isset($this->record[$fieldName . '_Lazy'])) {
$tableClass = $this->record[$fieldName . '_Lazy'];
$this->loadLazyFields($tableClass);
}
@ -2717,7 +2717,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Inspect relation type
if (ClassInfo::hasMethod($component, $relation)) {
$component = $component->$relation();
$component = $component->$relation();
} elseif ($component instanceof Relation || $component instanceof DataList) {
// $relation could either be a field (aggregate), or another relation
$singleton = DataObject::singleton($component->dataClass());
@ -2728,7 +2728,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
$component = $component->obj($relation);
} else {
throw new LogicException(
"$relation is not a relation/field on ".get_class($component)
"$relation is not a relation/field on " . get_class($component)
);
}
}
@ -3655,9 +3655,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
$singularName = $this->singular_name();
$conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A ';
return [
static::class.'.SINGULARNAME' => $this->singular_name(),
static::class.'.PLURALNAME' => $pluralName,
static::class.'.PLURALS' => [
static::class . '.SINGULARNAME' => $this->singular_name(),
static::class . '.PLURALNAME' => $pluralName,
static::class . '.PLURALS' => [
'one' => $conjunction . $singularName,
'other' => '{count} ' . $pluralName
]

View File

@ -324,7 +324,7 @@ class DataQuery
$query->selectField(
"
CASE WHEN {$baseClassColumn} IS NOT NULL THEN {$baseClassColumn}
ELSE ".Convert::raw2sql($baseDataClass, true)." END",
ELSE " . Convert::raw2sql($baseDataClass, true) . " END",
"RecordClassName"
);
@ -939,7 +939,7 @@ class DataQuery
foreach ($ancestry as $ancestor) {
$ancestorTable = $schema->tableName($ancestor);
if ($ancestorTable !== $foreignTable) {
$ancestorTableAliased = $foreignPrefix.$ancestorTable;
$ancestorTableAliased = $foreignPrefix . $ancestorTable;
$this->query->addLeftJoin(
$ancestorTable,
"\"{$foreignTableAliased}\".\"ID\" = \"{$ancestorTableAliased}\".\"ID\"",
@ -979,7 +979,7 @@ class DataQuery
// Skip if already joined
$foreignBaseClass = $schema->baseDataClass($foreignClass);
$foreignBaseTable = $schema->tableName($foreignBaseClass);
if ($this->query->isJoinedTo($foreignPrefix.$foreignBaseTable)) {
if ($this->query->isJoinedTo($foreignPrefix . $foreignBaseTable)) {
return;
}
@ -989,7 +989,7 @@ class DataQuery
$this->query->addLeftJoin(
$foreignBaseTable,
"{$foreignIDColumn} = {$localColumn}",
$foreignPrefix.$foreignBaseTable
$foreignPrefix . $foreignBaseTable
);
// 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) {
$ancestorTable = $schema->tableName($ancestor);
if ($ancestorTable !== $foreignBaseTable) {
$ancestorTableAliased = $foreignPrefix.$ancestorTable;
$ancestorTableAliased = $foreignPrefix . $ancestorTable;
$this->query->addLeftJoin(
$ancestorTable,
"{$foreignIDColumn} = \"{$ancestorTableAliased}\".\"ID\"",
@ -1048,7 +1048,7 @@ class DataQuery
}
// Join parent class to join table
$relationAliasedTable = $componentPrefix.$relationClassOrTable;
$relationAliasedTable = $componentPrefix . $relationClassOrTable;
$parentIDColumn = $schema->sqlColumnForField($parentClass, 'ID', $parentPrefix);
$this->query->addLeftJoin(
$relationClassOrTable,
@ -1071,7 +1071,7 @@ class DataQuery
foreach ($ancestry as $ancestor) {
$ancestorTable = $schema->tableName($ancestor);
if ($ancestorTable !== $componentBaseTable) {
$ancestorTableAliased = $componentPrefix.$ancestorTable;
$ancestorTableAliased = $componentPrefix . $ancestorTable;
$this->query->addLeftJoin(
$ancestorTable,
"{$componentIDColumn} = \"{$ancestorTableAliased}\".\"ID\"",
@ -1096,7 +1096,7 @@ class DataQuery
$subSelect->selectField($fieldExpression, $field);
$subSelect->setOrderBy(null);
$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;
}

View File

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

View File

@ -17,7 +17,6 @@ namespace SilverStripe\ORM\FieldType;
*/
class DBCurrency extends DBDecimal
{
/**
* @config
* @var string
@ -38,9 +37,9 @@ class DBCurrency extends DBDecimal
$val = $this->config()->currency_symbol . number_format(abs($this->value), 2);
if ($this->value < 0) {
return "($val)";
} else {
return $val;
}
return $val;
}
/**
@ -51,9 +50,8 @@ class DBCurrency extends DBDecimal
$val = $this->config()->currency_symbol . number_format(abs($this->value), 0);
if ($this->value < 0) {
return "($val)";
} else {
return $val;
}
return $val;
}
public function setValue($value, $record = null, $markChanged = true)
@ -62,9 +60,11 @@ class DBCurrency extends DBDecimal
if (is_numeric($value)) {
$this->value = $value;
} elseif (preg_match('/-?\$?[0-9,]+(.[0-9]+)?([Ee][0-9]+)?/', $value, $matches)) {
$this->value = str_replace(array('$',',',$this->config()->currency_symbol), '', $matches[0]);
$this->value = str_replace(['$', ',', $this->config()->currency_symbol], '', $matches[0]);
} else {
$this->value = 0;
}
return $this;
}
}

View File

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

View File

@ -186,11 +186,11 @@ class DBHTMLText extends DBText
if ($tag === 'text()') {
$textFilter = ''; // Disable text filter if allowed
} 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) {
$el->parentNode->removeChild($el);
}

View File

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

View File

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

View File

@ -76,7 +76,7 @@ class SQLAssignmentRow
throw new InvalidArgumentException(
"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) {
if (is_array($tableClause)) {
$table = '"'.$tableClause['table'].'"';
$table = '"' . $tableClause['table'] . '"';
} elseif (is_string($tableClause) && preg_match('/JOIN +("[^"]+") +(AS|ON) +/i', $tableClause, $matches)) {
$table = $matches[1];
} else {
@ -526,7 +526,7 @@ abstract class SQLConditionalExpression extends SQLExpression
$filters = $this->normalisePredicates(func_get_args());
$this->splitQueryParameters($filters, $predicates, $parameters);
$clause = "(".implode(") OR (", $predicates).")";
$clause = "(" . implode(") OR (", $predicates) . ")";
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
if (count($value) != 1) {
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) {
return $this->parsePredicate($key, $pairValue);

View File

@ -110,10 +110,6 @@ class BasicAuth
return true;
}
if ($member instanceof Member) {
Security::setCurrentUser($member);
}
if (!$member && $tryUsingSessionLogin) {
$member = Security::getCurrentUser();
}

View File

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

View File

@ -88,7 +88,7 @@ class Group extends DataObject
parent::populateDefaults();
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",
new Tab(
'Members',
_t(__CLASS__.'.MEMBERS', 'Members'),
_t(__CLASS__ . '.MEMBERS', 'Members'),
new TextField("Title", $this->fieldLabel('Title')),
$parentidfield = DropdownField::create(
'ParentID',
@ -131,7 +131,7 @@ class Group extends DataObject
),
$permissionsTab = new Tab(
'Permissions',
_t(__CLASS__.'.PERMISSIONS', 'Permissions'),
_t(__CLASS__ . '.PERMISSIONS', 'Permissions'),
$permissionsField = new PermissionCheckboxSetField(
'Permissions',
false,
@ -217,14 +217,14 @@ class Group extends DataObject
PermissionRole::get()->count() &&
class_exists(SecurityAdmin::class)
) {
$fields->findOrMakeTab('Root.Roles', _t(__CLASS__.'.ROLES', 'Roles'));
$fields->findOrMakeTab('Root.Roles', _t(__CLASS__ . '.ROLES', 'Roles'));
$fields->addFieldToTab(
'Root.Roles',
new LiteralField(
"",
"<p>" .
_t(
__CLASS__.'.ROLESDESCRIPTION',
__CLASS__ . '.ROLESDESCRIPTION',
"Roles are predefined sets of permissions, and can be assigned to groups.<br />"
. "They are inherited from parent groups if required."
) . '<br />' .
@ -286,7 +286,7 @@ class Group extends DataObject
public function fieldLabels($includerelations = true)
{
$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['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');
@ -515,7 +515,7 @@ class Group extends DataObject
// 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
// 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);
}
}

View File

@ -360,8 +360,7 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher
$baseTable = DataObject::getSchema()->baseDataTable($this->getBaseClass());
$uninheritedPermissions = $stageRecords
->where([
"(\"$typeField\" IN (?, ?) OR " .
"(\"$typeField\" = ? AND \"$groupJoinTable\".\"{$baseTable}ID\" IS NOT NULL))"
"(\"$typeField\" IN (?, ?) OR " . "(\"$typeField\" = ? AND \"$groupJoinTable\".\"{$baseTable}ID\" IS NOT NULL))"
=> [
self::ANYONE,
self::LOGGED_IN_USERS,
@ -370,8 +369,7 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher
])
->leftJoin(
$groupJoinTable,
"\"$groupJoinTable\".\"{$baseTable}ID\" = \"{$baseTable}\".\"ID\" AND " .
"\"$groupJoinTable\".\"GroupID\" IN ($groupIDsSQLList)"
"\"$groupJoinTable\".\"{$baseTable}ID\" = \"{$baseTable}\".\"ID\" AND " . "\"$groupJoinTable\".\"GroupID\" IN ($groupIDsSQLList)"
)->column('ID');
} else {
// 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)
{
$labels = parent::fieldLabels($includerelations);
$labels['Email'] = _t(__CLASS__.'.Email', 'Email Address');
$labels['EmailHashed'] = _t(__CLASS__.'.EmailHashed', 'Email Address (hashed)');
$labels['Status'] = _t(__CLASS__.'.Status', 'Status');
$labels['IP'] = _t(__CLASS__.'.IP', 'IP Address');
$labels['Email'] = _t(__CLASS__ . '.Email', 'Email Address');
$labels['EmailHashed'] = _t(__CLASS__ . '.EmailHashed', 'Email Address (hashed)');
$labels['Status'] = _t(__CLASS__ . '.Status', 'Status');
$labels['IP'] = _t(__CLASS__ . '.IP', 'IP Address');
return $labels;
}

View File

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

View File

@ -86,14 +86,14 @@ class CMSMemberLoginForm extends MemberLoginForm
// Make actions
$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'),
LiteralField::create(
'doLogout',
sprintf(
'<a class="btn btn-secondary" href="%s" target="_top">%s</a>',
Convert::raw2att($logoutLink),
_t(__CLASS__.'.BUTTONLOGOUT', "Log out")
_t(__CLASS__ . '.BUTTONLOGOUT', "Log out")
)
),
LiteralField::create(
@ -101,7 +101,7 @@ class CMSMemberLoginForm extends MemberLoginForm
sprintf(
'<a href="%s" class="cms-security__container__form__forgotPassword btn btn-secondary" target="_top">%s</a>',
$this->getExternalLink('lostpassword'),
_t(__CLASS__.'.BUTTONFORGOTPASSWORD', "Forgot password")
_t(__CLASS__ . '.BUTTONFORGOTPASSWORD', "Forgot password")
)
)
]);
@ -125,6 +125,6 @@ class CMSMemberLoginForm extends MemberLoginForm
*/
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');
$allCodes = array();
$adminCategory = _t(__CLASS__.'.AdminGroup', 'Administrator');
$adminCategory = _t(__CLASS__ . '.AdminGroup', 'Administrator');
$allCodes[$adminCategory]['ADMIN'] = array(
'name' => _t(__CLASS__.'.FULLADMINRIGHTS', 'Full administrative rights'),
'name' => _t(__CLASS__ . '.FULLADMINRIGHTS', 'Full administrative rights'),
'help' => _t(
'SilverStripe\\Security\\Permission.FULLADMINRIGHTS_HELP',
'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
// Localise all permission categories
$keys[__CLASS__.'.AdminGroup'] = 'Administrator';
$keys[__CLASS__.'.CMS_ACCESS_CATEGORY'] = 'CMS Access';
$keys[__CLASS__.'.CONTENT_CATEGORY'] = 'Content permissions';
$keys[__CLASS__.'.PERMISSIONS_CATEGORY'] = 'Roles and access permissions';
$keys[__CLASS__ . '.AdminGroup'] = 'Administrator';
$keys[__CLASS__ . '.CMS_ACCESS_CATEGORY'] = 'CMS Access';
$keys[__CLASS__ . '.CONTENT_CATEGORY'] = 'Content permissions';
$keys[__CLASS__ . '.PERMISSIONS_CATEGORY'] = 'Roles and access permissions';
return $keys;
}
}

View File

@ -225,7 +225,7 @@ class PermissionCheckboxSetField extends FormField
} elseif ($this->records && $this->records->Count() > 1 && isset($uninheritedCodes[$code])) {
// If code assignments are collected from more than one "source group",
// 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

View File

@ -145,7 +145,7 @@ class RememberLoginHash extends DataObject
$now = DBDatetime::now();
$expiryDate = new DateTime($now->Rfc2822());
$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->extend('onAfterGenerateToken');
$rememberLoginHash->write();

View File

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

View File

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

View File

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

View File

@ -30,7 +30,7 @@ class ShortcodeParser
public function img_shortcode($attrs)
{
return "<img src='".$attrs['src']."'>";
return "<img src='" . $attrs['src'] . "'>";
}
protected static $instances = array();
@ -191,9 +191,9 @@ class ShortcodeParser
// Missing tag
if ($content === false) {
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) {
$content = '<strong class="warning">'.$tag['text'].'</strong>';
$content = '<strong class="warning">' . $tag['text'] . '</strong>';
} elseif (ShortcodeParser::$error_behavior == ShortcodeParser::STRIP) {
return '';
} else {
@ -271,7 +271,7 @@ class ShortcodeParser
protected static function attrrx()
{
return '/'.self::$attrrx.'/xS';
return '/' . self::$attrrx . '/xS';
}
protected static $tagrx = '
@ -296,7 +296,7 @@ class ShortcodeParser
protected static function tagrx()
{
return '/'.sprintf(self::$tagrx, self::$attrrx).'/xS';
return '/' . sprintf(self::$tagrx, self::$attrrx) . '/xS';
}
const WARN = 'warn';
@ -372,13 +372,11 @@ class ShortcodeParser
$err = null;
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']) {
$err = 'Close tag "'.$tags[$i]['close'].'" preceded by another close tag "'.
$tags[$i-1]['close'].'"';
$err = 'Close tag "' . $tags[$i]['close'] . '" preceded by another close tag "' . $tags[$i-1]['close'] . '"';
} elseif ($tags[$i]['close'] != $tags[$i-1]['open']) {
$err = 'Close tag "'.$tags[$i]['close'].'" doesn\'t match preceding open tag "'.
$tags[$i-1]['open'].'"';
$err = 'Close tag "' . $tags[$i]['close'] . '" doesn\'t match preceding open tag "' . $tags[$i-1]['open'] . '"';
}
if ($err) {
@ -502,7 +500,7 @@ class ShortcodeParser
$markerClass = self::$marker_class;
$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) {
if (in_array(strtolower($node->tagName), self::$block_level_elements)) {
user_error(
'Requested to insert block tag '.$node->tagName.
' inline - probably this will break HTML compliance',
'Requested to insert block tag ' . $node->tagName . ' inline - probably this will break HTML compliance',
E_USER_WARNING
);
}
// NOP
} 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);
// 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
$parents = $this->findParentsForMarkers($shortcodes);
@ -729,7 +726,7 @@ class ShortcodeParser
$content = preg_replace_callback(
// Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers()
// 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) {
$tag = $tags[$matches[1]];
return $parser->getShortcodeReplacementText($tag);

View File

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

View File

@ -398,7 +398,7 @@ class ViewableData implements IteratorAggregate
}
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
$class = get_class($this->object);
if ($field) {
return "<b>Debugging Information for {$class}->{$field}</b><br/>" .
($this->object->hasMethod($field) ? "Has method '$field'<br/>" : null) .
($this->object->hasField($field) ? "Has field '$field'<br/>" : null);
return "<b>Debugging Information for {$class}->{$field}</b><br/>" . ($this->object->hasMethod($field) ? "Has method '$field'<br/>" : null) . ($this->object->hasField($field) ? "Has field '$field'<br/>" : null);
}
// debugging information for the entire class

View File

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

View File

@ -9,7 +9,6 @@ use SilverStripe\Core\TempFolder;
* This file is the Framework constants bootstrap. It will prepare some basic common constants.
*
* It takes care of:
* - Normalisation of $_SERVER values
* - Initialisation of necessary constants (mostly paths)
*
* Initialized constants:
@ -24,6 +23,8 @@ use SilverStripe\Core\TempFolder;
* - THEMES_PATH: Absolute filepath, e.g. "/var/www/my-webroot/themes"
* - FRAMEWORK_DIR: Path relative to webroot, e.g. "framework"
* - FRAMEWORK_PATH:Absolute filepath, e.g. "/var/www/my-webroot/framework"
* - PUBLIC_DIR: Webroot path relative to project root, e.g. "public" or ""
* - PUBLIC_PATH: Absolute path to webroot, e.g. "/var/www/project/public"
* - THIRDPARTY_DIR: Path relative to webroot, e.g. "framework/thirdparty"
* - THIRDPARTY_PATH: Absolute filepath, e.g. "/var/www/my-webroot/framework/thirdparty"
*/
@ -160,7 +161,7 @@ if (!defined('ASSETS_PATH')) {
// Custom include path - deprecated
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

View File

@ -1,9 +1,7 @@
<?php
if (!defined('BASE_PATH')) {
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";
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";
exit(1);
}

View File

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

View File

@ -827,7 +827,7 @@ class DirectorTest extends SapphireTest
$response = Director::test('some-dummy-url');
$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->postCalls);
@ -836,7 +836,7 @@ class DirectorTest extends SapphireTest
$response = Director::test('some-dummy-url');
$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);

View File

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

View File

@ -47,4 +47,15 @@ class HTTPResponseTest extends SapphireTest
// Fail if we get to here
$this->assertFalse(true, 'Something went wrong with our test exception');
}
public function testRemoveHeader()
{
$response = new HTTPResponse();
$response->addHeader('X-Animal', 'Monkey');
$this->assertSame('Monkey', $response->getHeader('X-Animal'));
$response->removeHeader('X-Animal');
$this->assertEmpty($response->getHeader('X-Animal'));
}
}

View File

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

View File

@ -268,7 +268,7 @@ class RequestHandlingTest extends FunctionalTest
403,
$response->getStatusCode(),
'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);

View File

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

View File

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

View File

@ -136,12 +136,7 @@ class ConvertTest extends SapphireTest
"Single quotes are decoded correctly"
);
$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.';
$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.';
$this->assertEquals($val8, Convert::html2raw($val8), 'Test long text is unwrapped');
$this->assertEquals(
<<<PHP

View File

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

View File

@ -616,7 +616,7 @@ class InjectorTest extends SapphireTest
NewRequirementsBackend::class,
DummyRequirements::class => array(
'constructor' => array(
'%$'.OriginalRequirementsBackend::class
'%$' . OriginalRequirementsBackend::class
)
)
);
@ -634,7 +634,7 @@ class InjectorTest extends SapphireTest
array(
DummyRequirements::class => array(
'constructor' => array(
'%$'.NewRequirementsBackend::class
'%$' . NewRequirementsBackend::class
)
)
)
@ -690,7 +690,7 @@ class InjectorTest extends SapphireTest
$config = array(
OriginalRequirementsBackend::class,
DummyRequirements::class => array(
'class' => DummyRequirements::class.'(\'%$'.OriginalRequirementsBackend::class.'\')'
'class' => DummyRequirements::class . '(\'%$' . OriginalRequirementsBackend::class . '\')'
)
);
$injector->load($config);
@ -730,7 +730,7 @@ class InjectorTest extends SapphireTest
Config::modify()->merge(
Injector::class,
MyChildClass::class,
'%$'.MyParentClass::class
'%$' . MyParentClass::class
);
// 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
// declarations to avoid un-needed function calls
$injector = new Injector();
$item = $injector->create(ConstructableObject::class, '%$'.TestObject::class);
$this->assertEquals('%$'.TestObject::class, $item->property);
$item = $injector->create(ConstructableObject::class, '%$' . TestObject::class);
$this->assertEquals('%$' . TestObject::class, $item->property);
// do it again but have test object configured as a constructor dependency
$injector = new Injector();
$config = array(
ConstructableObject::class => array(
'constructor' => array(
'%$'.TestObject::class
'%$' . TestObject::class
)
)
);
@ -788,7 +788,7 @@ class InjectorTest extends SapphireTest
$config = array(
ConstructableObject::class => array(
'constructor' => array(
'%$'.TestObject::class
'%$' . TestObject::class
)
),
);

View File

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

View File

@ -181,8 +181,8 @@ class ConfigManifestTest extends SapphireTest
foreach (array('dev', 'test', 'live') as $check) {
$this->assertEquals(
$env == $check ? $check : 'not'.$check,
@$config[ucfirst($check).'Environment'],
$env == $check ? $check : 'not' . $check,
@$config[ucfirst($check) . 'Environment'],
'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');
$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) {
$CLI_file = escapeshellarg($file);

View File

@ -91,7 +91,7 @@ class ParameterConfirmationTokenTest extends SapphireTest
// Check redirect 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, $emptyParameter->redirectURL());
$this->assertStringStartsWith($current, $nullToken->redirectURL());

View File

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

View File

@ -117,7 +117,7 @@ class CSVParserTest extends SapphireTest
public function testParsingWithExplicitHeaderRow()
{
/* 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'));

View File

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

View File

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

View File

@ -16,25 +16,38 @@ class SapphireTestTest extends SapphireTest
public function provideResolveFixturePath()
{
return [
[__DIR__ . '/CsvBulkLoaderTest.yml', './CsvBulkLoaderTest.yml'],
//same dir
[__DIR__ . '/CsvBulkLoaderTest.yml', 'CsvBulkLoaderTest.yml'],
// Filename only
[dirname(__DIR__) . '/ORM/DataObjectTest.yml', '../ORM/DataObjectTest.yml'],
// Parent path
[dirname(__DIR__) . '/ORM/DataObjectTest.yml', dirname(__DIR__) . '/ORM/DataObjectTest.yml'],
// Absolute path
'sameDirectory' => [
__DIR__ . '/CsvBulkLoaderTest.yml',
'./CsvBulkLoaderTest.yml',
'Could not resolve fixture path relative from same directory',
],
'filenameOnly' => [
__DIR__ . '/CsvBulkLoaderTest.yml',
'CsvBulkLoaderTest.yml',
'Could not resolve fixture path from filename only',
],
'parentPath' => [
dirname(__DIR__) . '/ORM/DataObjectTest.yml',
'../ORM/DataObjectTest.yml',
'Could not resolve fixture path from parent path',
],
'absolutePath' => [
dirname(__DIR__) . '/ORM/DataObjectTest.yml',
dirname(__DIR__) . '/ORM/DataObjectTest.yml',
'Could not relsolve fixture path from absolute path',
],
];
}
/**
* @dataProvider provideResolveFixturePath
*/
public function testResolveFixturePath($expected, $path)
public function testResolveFixturePath($expected, $path, $message)
{
$this->assertEquals(
$expected,
$this->resolveFixturePath($path)
$this->resolveFixturePath($path),
$message
);
}
@ -46,10 +59,10 @@ class SapphireTestTest extends SapphireTest
$this->logOut();
$this->assertFalse(Permission::check('ADMIN'));
$this->actWithPermission('ADMIN', function () {
$this->assertTrue(Permission::check('ADMIN'));
$this->assertTrue(Permission::check('ADMIN'), 'Member should now have ADMIN role');
// check nested actAs calls work as expected
Member::actAs(null, function () {
$this->assertFalse(Permission::check('ADMIN'));
$this->assertFalse(Permission::check('ADMIN'), 'Member should not act as ADMIN any more after reset');
});
});
}
@ -59,9 +72,16 @@ class SapphireTestTest extends SapphireTest
*/
public function testCreateMemberWithPermission()
{
$this->assertCount(0, Member::get()->filter(['Email' => 'TESTPERM@example.org']));
$this->assertEmpty(
Member::get()->filter(['Email' => 'TESTPERM@example.org']),
'DB should not have the test member created when the test starts'
);
$this->createMemberWithPermission('TESTPERM');
$this->assertCount(1, Member::get()->filter(['Email' => 'TESTPERM@example.org']));
$this->assertCount(
1,
Member::get()->filter(['Email' => 'TESTPERM@example.org']),
'Database should now contain the test member'
);
}
/**
@ -69,13 +89,30 @@ class SapphireTestTest extends SapphireTest
*
* @param $match
* @param $itemsForList
*
* @testdox Has assertion assertListAllMatch
*/
public function testAssertListAllMatch($match, $itemsForList)
public function testAssertListAllMatch($match, $itemsForList, $message)
{
$list = $this->generateArrayListFromItems($itemsForList);
$this->assertListAllMatch($match, $list);
$this->assertListAllMatch($match, $list, $message);
}
/**
* generate SS_List as this is not possible in dataProvider
*
* @param array $itemsForList
*
* @return ArrayList
*/
private function generateArrayListFromItems($itemsForList)
{
$list = ArrayList::create();
foreach ($itemsForList as $data) {
$list->push(Member::create($data));
}
return $list;
}
/**
@ -100,6 +137,7 @@ class SapphireTestTest extends SapphireTest
*
* @param $matches
* @param $itemsForList
*
* @testdox Has assertion assertListContains
*/
public function testAssertListContains($matches, $itemsForList)
@ -109,7 +147,7 @@ class SapphireTestTest extends SapphireTest
$list->push(Member::create(['FirstName' => 'Bar', 'Surname' => 'Bar']));
$list->push(Member::create(['FirstName' => 'Baz', 'Surname' => 'Baz']));
$this->assertListContains($matches, $list);
$this->assertListContains($matches, $list, 'The list does not contain the expected items');
}
/**
@ -143,7 +181,7 @@ class SapphireTestTest extends SapphireTest
{
$list = $this->generateArrayListFromItems($itemsForList);
$this->assertListNotContains($matches, $list);
$this->assertListNotContains($matches, $list, 'List contains forbidden items');
}
/**
@ -151,6 +189,7 @@ class SapphireTestTest extends SapphireTest
*
* @param $matches
* @param $itemsForList
*
* @testdox assertion assertListNotContains throws a exception when a matching item is found in the list
*
* @expectedException \PHPUnit_Framework_ExpectationFailedException
@ -165,7 +204,6 @@ class SapphireTestTest extends SapphireTest
$this->assertListNotContains($matches, $list);
}
/**
* @dataProvider \SilverStripe\Dev\Tests\SapphireTestTest\DataProvider::provideEqualListsWithEmptyList()
* @testdox Has assertion assertListEquals
@ -177,7 +215,7 @@ class SapphireTestTest extends SapphireTest
{
$list = $this->generateArrayListFromItems($itemsForList);
$this->assertListEquals($matches, $list);
$this->assertListEquals($matches, $list, 'Lists do not equal');
}
/**
@ -195,19 +233,4 @@ class SapphireTestTest extends SapphireTest
$this->assertListEquals($matches, $list);
}
/**
* generate SS_List as this is not possible in dataProvider
*
* @param $itemsForList array
* @return ArrayList
*/
private function generateArrayListFromItems($itemsForList)
{
$list = ArrayList::create();
foreach ($itemsForList as $data) {
$list->push(Member::create($data));
}
return $list;
}
}

View File

@ -7,12 +7,17 @@ use SilverStripe\Dev\TestOnly;
class DataProvider implements TestOnly
{
protected static $oneItemList = [
['FirstName' => 'Ingo', 'Surname' => 'Schommer']
['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
];
protected static $twoItemList = [
['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
['FirstName' => 'Sam', 'Surname' => 'Minnee']
['FirstName' => 'Sam', 'Surname' => 'Minnee'],
];
protected static $memberList = [
['FirstName' => 'Ingo', 'Surname' => 'Schommer', 'Locale' => 'en_US'],
['FirstName' => 'Sam', 'Surname' => 'Minnee', 'Locale' => 'en_US'],
];
/**
@ -21,11 +26,11 @@ class DataProvider implements TestOnly
public static function provideEqualListsWithEmptyList()
{
return array_merge(
[ //empty list
[
[
'emptyLists' => [
[],
[]
]
[],
],
],
self::provideEqualLists()
);
@ -38,37 +43,37 @@ class DataProvider implements TestOnly
{
return [
[
[ //one param
['FirstName' => 'Ingo']
],
self::$oneItemList
],
[
[ //two params
['FirstName' => 'Ingo', 'Surname' => 'Schommer']
],
self::$oneItemList
],
[ //only one param
[
'oneParameterOneItem' => [
['FirstName' => 'Ingo'],
['FirstName' => 'Sam']
],
self::$twoItemList
self::$oneItemList,
],
[
[ //two params
'twoParametersOneItem' => [
['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
['FirstName' => 'Sam', 'Surname' => 'Minnee']
],
self::$twoItemList
self::$oneItemList,
],
[
[ //mixed
['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
['FirstName' => 'Sam']
'oneParameterTwoItems' => [
['FirstName' => 'Ingo'],
['FirstName' => 'Sam'],
],
self::$twoItemList
self::$twoItemList,
],
[
'twoParametersTwoItems' => [
['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
['FirstName' => 'Sam', 'Surname' => 'Minnee'],
],
self::$twoItemList,
],
[
'mixedParametersTwoItems' => [
['FirstName' => 'Ingo', 'Surname' => 'Schommer'],
['FirstName' => 'Sam'],
],
self::$twoItemList,
],
];
}
@ -80,40 +85,38 @@ class DataProvider implements TestOnly
{
return [
[ //empty list
[
['FirstName' => 'Ingo']
[
'checkAgainstEmptyList' => [
['FirstName' => 'Ingo'],
],
[]
[],
],
[
[ //one item expected
['FirstName' => 'Ingo']
]
,
self::$twoItemList
'oneItemExpectedListContainsMore' => [
['FirstName' => 'Ingo'],
],
self::$twoItemList,
],
[ //one item with wrong param
[
[
'oneExpectationHasWrontParamter' => [
['FirstName' => 'IngoXX'],
['FirstName' => 'Sam']
]
,
self::$twoItemList
['FirstName' => 'Sam'],
],
self::$twoItemList,
],
[
[ //two params wrong
'differentParametersInDifferentItemsAreWrong' => [
['FirstName' => 'IngoXXX', 'Surname' => 'Schommer'],
['FirstName' => 'Sam', 'Surname' => 'MinneeXXX']
['FirstName' => 'Sam', 'Surname' => 'MinneeXXX'],
],
self::$twoItemList
self::$twoItemList,
],
[
[ //mixed
'differentParametersNotMatching' => [
['FirstName' => 'Daniel', 'Surname' => 'Foo'],
['FirstName' => 'Dan']
['FirstName' => 'Dan'],
],
self::$twoItemList
self::$twoItemList,
],
];
}
@ -124,32 +127,31 @@ class DataProvider implements TestOnly
public static function provideNotContainingList()
{
return [
[ //empty list
'listIsEmpty' => [
[
['FirstName' => 'Ingo']
['FirstName' => 'Ingo'],
],
[]
[],
],
[
[ //one item expected
['FirstName' => 'Sam']
]
,
self::$oneItemList
'oneItemIsExpected' => [
[
['FirstName' => 'Sam'],
],
self::$oneItemList,
],
[
[ //two params wrong
'twoParametersAreWrong' => [
[
['FirstName' => 'IngoXXX', 'Surname' => 'Schommer'],
['FirstName' => 'Sam', 'Surname' => 'MinneeXXX']
['FirstName' => 'Sam', 'Surname' => 'MinneeXXX'],
],
self::$twoItemList
self::$twoItemList,
],
[
[ //mixed
'mixedList' => [
[
['FirstName' => 'Daniel', 'Surname' => 'Foo'],
['FirstName' => 'Dan']
['FirstName' => 'Dan'],
],
self::$twoItemList
self::$twoItemList,
],
];
}
@ -159,14 +161,17 @@ class DataProvider implements TestOnly
*/
public static function provideAllMatchingList()
{
$list = [
['FirstName' => 'Ingo', 'Surname' => 'Schommer', 'Locale' => 'en_US'],
['FirstName' => 'Sam', 'Surname' => 'Minnee', 'Locale' => 'en_US']
];
return [
[[], $list], //empty match
[['Locale' => 'en_US'], $list] //all items have this field set
'emptyMatch' => [
[],
self::$memberList,
'empty list did not match',
],
'allItemsWithLocaleSet' => [
['Locale' => 'en_US'],
self::$memberList,
'list with Locale set in all items did not match',
],
];
}
@ -175,13 +180,8 @@ class DataProvider implements TestOnly
*/
public static function provideNotMatchingList()
{
$list = [
['FirstName' => 'Ingo', 'Surname' => 'Schommer', 'Locale' => 'en_US'],
['FirstName' => 'Sam', 'Surname' => 'Minnee', 'Locale' => 'en_US']
];
return [
[['FirstName' => 'Ingo'], $list] //not all items have this field set
'notAllItemsHaveLocaleSet' => [['FirstName' => 'Ingo'], self::$memberList],
];
}
}

View File

@ -35,7 +35,7 @@ class FormSchemaTest extends SapphireTest
{
$form = new Form(null, 'TestForm', new FieldList(), new FieldList());
$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);
$this->assertInternalType('array', $schema);
@ -164,7 +164,7 @@ class FormSchemaTest extends SapphireTest
)
);
$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);
$this->assertInternalType('array', $schema);
@ -206,7 +206,7 @@ class FormSchemaTest extends SapphireTest
);
$formSchema = new FormSchema();
$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->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->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'
);
$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'
);

View File

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

View File

@ -66,9 +66,7 @@ class GridFieldExportButtonTest extends SapphireTest
$button->setExportColumns(['Name' => 'My Name']);
$this->assertEquals(
'"My Name"'."\n".
'Test'."\n".
'Test2'."\n",
'"My Name"' . "\n" . 'Test' . "\n" . 'Test2' . "\n",
$button->generateExportFileData($this->gridField)
);
}
@ -101,9 +99,7 @@ class GridFieldExportButtonTest extends SapphireTest
]);
$this->assertEquals(
'Name,City'."\n".
'Test,"City city"'."\n".
'Test2,"Quoted ""City"" 2 city"'."\n",
'Name,City' . "\n" . 'Test,"City city"' . "\n" . 'Test2,"Quoted ""City"" 2 city"' . "\n",
$button->generateExportFileData($this->gridField)
);
}
@ -117,9 +113,7 @@ class GridFieldExportButtonTest extends SapphireTest
]);
$this->assertEquals(
'Name,strtolower'."\n".
'Test,City'."\n".
'Test2,"Quoted ""City"" 2"'."\n",
'Name,strtolower' . "\n" . 'Test,City' . "\n" . 'Test2,"Quoted ""City"" 2"' . "\n",
$button->generateExportFileData($this->gridField)
);
}
@ -134,8 +128,7 @@ class GridFieldExportButtonTest extends SapphireTest
$button->setCsvHasHeader(false);
$this->assertEquals(
'Test,City'."\n".
'Test2,"Quoted ""City"" 2"'."\n",
'Test,City' . "\n" . 'Test2,"Quoted ""City"" 2"' . "\n",
$button->generateExportFileData($this->gridField)
);
}
@ -154,23 +147,7 @@ class GridFieldExportButtonTest extends SapphireTest
$this->gridField->setList($arrayList);
$this->assertEquals(
"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",
"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",
$button->generateExportFileData($this->gridField)
);
}

View File

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

View File

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

View File

@ -19,7 +19,7 @@ class TinyMCEConfigTest extends SapphireTest
$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
foreach (TinyMCEConfig::config()->get('tinymce_lang') as $locale => $resource) {

View File

@ -56,7 +56,7 @@ class TreeDropdownFieldTest extends SapphireTest
$this->assertContains(
$folder1->Name,
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) {
@ -67,7 +67,7 @@ class TreeDropdownFieldTest extends SapphireTest
$this->assertContains(
$folder1Subfolder1->Name,
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(
$folder1->Name,
array_column($tree['children'], 'title'),
$folder1->Name.' is not found in the json'
$folder1->Name . ' is not found in the json'
);
$this->assertContains(
$folder1Subfolder1->Name,
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');
$parser = new CSSContentParser($tree);
$cssPath = 'ul.tree li#selector-TestTree-'.$folder1->ID.' li#selector-TestTree-'.
$folder1Subfolder1->ID.' a span.item';
$cssPath = 'ul.tree li#selector-TestTree-' . $folder1->ID . ' li#selector-TestTree-' . $folder1Subfolder1->ID . ' a span.item';
$firstResult = $parser->getBySelector($cssPath);
$this->assertEquals(
$folder1Subfolder1->Name,
(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');
$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);
$this->assertEquals(
$subfolder->Name,
(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
$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);
$this->assertEmpty(
$noResult,
$folder2.' is not found'
$folder2 . ' is not found'
);
$field = new TreeDropdownField('TestTree', 'Test tree', File::class);
@ -149,49 +148,48 @@ class TreeDropdownFieldTest extends SapphireTest
$parser = new CSSContentParser($tree);
// 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-'.
$folder1Subfolder1->ID.' a span.item';
$cssPath = 'ul.tree li#selector-TestTree-' . $folder1->ID . ' li#selector-TestTree-' . $folder1Subfolder1->ID . ' a span.item';
$firstResult = $parser->getBySelector($cssPath);
$this->assertEquals(
$folder1Subfolder1->Name,
(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
$file1 = $this->objFromFixture(File::class, 'subfolderfile1');
$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);
$this->assertNotEmpty(
$firstResult,
$file1->Name.' with ID '.$file1->ID.' is in search results'
$file1->Name . ' with ID ' . $file1->ID . ' is in search results'
);
$this->assertEquals(
$file1->Name,
(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);
$this->assertNotEmpty(
$secondResult,
$file2->Name.' with ID '.$file2->ID.' is in search results'
$file2->Name . ' with ID ' . $file2->ID . ' is in search results'
);
$this->assertEquals(
$file2->Name,
(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
$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);
$this->assertEmpty(
$noResult,
$file3->Name.' is not found'
$file3->Name . ' is not found'
);
}

View File

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

View File

@ -193,7 +193,7 @@ class DBHTMLTextTest extends SapphireTest
foreach ($cases as $add) {
$textObj = DBField::create_field('HTMLFragment', $orig);
$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 */
$dbField = Injector::inst()->create(
DBStringTest\MyStringField::class."(['default' => 'Here is my default text'])",
DBStringTest\MyStringField::class . "(['default' => 'Here is my default text'])",
'Myfield'
);
$this->assertEquals(

View File

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

View File

@ -1663,7 +1663,7 @@ class DataListTest extends SapphireTest
// with a complex sort expression, so keep using column() below
$teamClass = Convert::raw2sql(SubTeam::class);
$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(
array(

View File

@ -28,14 +28,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn();
$playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('ID'));
$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';
$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';
$this->assertSQLEquals($expected, $playerList->sql($parameters));
}
@ -44,14 +37,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn();
$playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('Title', 'SubclassDatabaseField'));
$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';
$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';
$this->assertSQLEquals($expected, $playerList->sql($parameters));
}
@ -60,13 +46,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn();
$playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('Title'));
$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';
$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';
$this->assertSQLEquals($expected, $playerList->sql($parameters));
}
@ -75,14 +55,7 @@ class DataObjectLazyLoadingTest extends SapphireTest
$db = DB::get_conn();
$playerList = new DataList(SubTeam::class);
$playerList = $playerList->setQueriedColumns(array('SubclassDatabaseField'));
$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';
$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';
$this->assertSQLEquals($expected, $playerList->sql($parameters));
}

View File

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

View File

@ -156,8 +156,7 @@ class DataObjectTest extends SapphireTest
$helper = $obj->dbObject($field);
$this->assertTrue(
($helper instanceof DBField),
"for {$field} expected helper to be DBField, but was " .
(is_object($helper) ? get_class($helper) : "null")
"for {$field} expected helper to be DBField, but was " . (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 $belongs_to = array(
'Company' => Company::class.'.CEO',
'PreviousCompany' => Company::class.'.PreviousCEO',
'CompanyOwned' => Company::class.'.Owner'
'Company' => Company::class . '.CEO',
'PreviousCompany' => Company::class . '.PreviousCEO',
'CompanyOwned' => Company::class . '.Owner'
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -246,7 +246,7 @@ class MemberTest extends FunctionalTest
"testuser@example.com",
null,
'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(
in_array($admin->getTitle(), $members),
$admin->getTitle().' should be in the returned list.'
$admin->getTitle() . ' should be in the returned list.'
);
$this->assertTrue(
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');
}
@ -920,7 +920,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$token,
'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => $firstHash->DeviceID
)
);
@ -941,7 +941,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':asdfasd'.str_rot13($token),
'alc_enc' => $m1->ID . ':asdfasd' . str_rot13($token),
'alc_device' => $firstHash->DeviceID
)
);
@ -952,7 +952,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$token,
'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => str_rot13($firstHash->DeviceID)
)
);
@ -1000,7 +1000,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$token,
'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => $firstHash->DeviceID
)
);
@ -1028,7 +1028,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$token,
'alc_enc' => $m1->ID . ':' . $token,
'alc_device' => $firstHash->DeviceID
)
);
@ -1076,7 +1076,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$firstToken,
'alc_enc' => $m1->ID . ':' . $firstToken,
'alc_device' => $firstHash->DeviceID
)
);
@ -1101,7 +1101,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$secondToken,
'alc_enc' => $m1->ID . ':' . $secondToken,
'alc_device' => $secondHash->DeviceID
)
);
@ -1114,7 +1114,7 @@ class MemberTest extends FunctionalTest
$this->session(),
null,
array(
'alc_enc' => $m1->ID.':'.$secondToken,
'alc_enc' => $m1->ID . ':' . $secondToken,
'alc_device' => $secondHash->DeviceID
)
);

View File

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

View File

@ -83,8 +83,7 @@ class ShortcodeParserTest extends SapphireTest
{
$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, /]'
);
foreach ($tests as $test) {

View File

@ -977,7 +977,7 @@ EOS
$backend->javascript(
'javascript/RequirementsTest_b.js',
[
'provides' => [
'provides' => [
'javascript/RequirementsTest_a.js',
'javascript/RequirementsTest_c.js',
],

View File

@ -206,7 +206,7 @@ class SSViewerTest extends SapphireTest
if (!$data) {
$data = new SSViewerTest\TestFixture();
}
return trim(''.$t->process($data));
return trim('' . $t->process($data));
}
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
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);
$this->assertContains($jsFileContents, $combinedTestFileContents);
@ -1398,7 +1398,7 @@ after'
'BazBarQux',
$this->render(
'<% with Foo.Bar.Baz %>{$Name}<% with $Up %>{$Name}{$Qux.Name}<% end_with %>'
.'<% end_with %>',
. '<% end_with %>',
$data
)
);
@ -1586,7 +1586,7 @@ after'
public function testLayout()
{
$this->useTestTheme(
__DIR__.'/SSViewerTest',
__DIR__ . '/SSViewerTest',
'layouttest',
function () {
$template = new SSViewer(array('Page'));
@ -1871,7 +1871,7 @@ EOC;
),
);
foreach ($templates as $template) {
$this->_renderWithSourceFileComments('SSViewerTestComments/'.$template['name'], $template['expected']);
$this->_renderWithSourceFileComments('SSViewerTestComments/' . $template['name'], $template['expected']);
}
}
private function _renderWithSourceFileComments($name, $expected)
@ -1935,7 +1935,7 @@ EOC;
);
} else {
$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'
);
}

View File

@ -81,17 +81,17 @@ class i18nTest extends SapphireTest
$provider = Injector::inst()->get(MessageProvider::class);
$provider->getTranslator()->addResource(
'array',
[ i18nTest\TestDataObject::class.'.MyProperty' => 'MyProperty' ],
[ i18nTest\TestDataObject::class . '.MyProperty' => 'MyProperty' ],
'en_US'
);
$provider->getTranslator()->addResource(
'array',
[ i18nTest\TestDataObject::class.'.MyProperty' => 'Mein Attribut' ],
[ i18nTest\TestDataObject::class . '.MyProperty' => 'Mein Attribut' ],
'de_DE'
);
$provider->getTranslator()->addResource(
'array',
[ i18nTest\TestDataObject::class.'.MyUntranslatedProperty' => 'Mein Attribut' ],
[ i18nTest\TestDataObject::class . '.MyUntranslatedProperty' => 'Mein Attribut' ],
'en_US'
);
@ -113,12 +113,12 @@ class i18nTest extends SapphireTest
$provider = Injector::inst()->get(MessageProvider::class);
$provider->getTranslator()->addResource(
'array',
[ i18nTest\TestObject::class.'.MyProperty' => 'Untranslated' ],
[ i18nTest\TestObject::class . '.MyProperty' => 'Untranslated' ],
'en_US'
);
$provider->getTranslator()->addResource(
'array',
[ i18nTest\TestObject::class.'.my_translatable_property' => 'Übersetzt' ],
[ i18nTest\TestObject::class . '.my_translatable_property' => 'Übersetzt' ],
'de_DE'
);
@ -260,7 +260,7 @@ class i18nTest extends SapphireTest
// Test missing entity key
$translated = i18n::_t(
$entity.'_DOES_NOT_EXIST',
$entity . '_DOES_NOT_EXIST',
$default,
array("name"=>"Mark", "greeting"=>"welcome", "goodbye"=>"bye")
);
@ -341,7 +341,7 @@ class i18nTest extends SapphireTest
//test injected calls
$this->assertContains(
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,
"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();
return array_merge($entities, [
LeftAndMain::class.'.OTHER_TITLE' => [
LeftAndMain::class . '.OTHER_TITLE' => [
'default' => 'Other title',
'module' => 'admin',
],

View File

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

View File

@ -11,13 +11,13 @@ class TestObject implements TestOnly, i18nEntityProvider
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()
{
return [
__CLASS__.".my_translatable_property" => self::$my_translatable_property,
__CLASS__ . ".my_translatable_property" => self::$my_translatable_property,
];
}
}