Use short array syntax across the module's codebase

This commit is contained in:
Michal Kleiner 2020-04-19 16:18:01 +12:00
parent e25d0861fd
commit d8331c1e0a
56 changed files with 432 additions and 429 deletions

View File

@ -30,7 +30,7 @@ call_user_func(function () {
*/ */
ShortcodeParser::get('default')->register( ShortcodeParser::get('default')->register(
'sitetree_link', 'sitetree_link',
array(SiteTree::class, 'link_shortcode_handler') [SiteTree::class, 'link_shortcode_handler']
); );
// TODO Remove once we can configure CMSMenu through static, nested configuration files // TODO Remove once we can configure CMSMenu through static, nested configuration files

View File

@ -51,8 +51,8 @@ class CMSBatchAction_Restore extends CMSBatchAction
public function applicablePages($ids) public function applicablePages($ids)
{ {
// Basic permission check based on SiteTree::canEdit // Basic permission check based on SiteTree::canEdit
if (!Permission::check(array("ADMIN", "SITETREE_EDIT_ALL"))) { if (!Permission::check(["ADMIN", "SITETREE_EDIT_ALL"])) {
return array(); return [];
} }
// Get pages that exist in stage and remove them from the restore-able set // Get pages that exist in stage and remove them from the restore-able set

View File

@ -127,7 +127,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
*/ */
private static $page_length = 15; private static $page_length = 15;
private static $allowed_actions = array( private static $allowed_actions = [
'archive', 'archive',
'deleteitems', 'deleteitems',
'DeleteItemsForm', 'DeleteItemsForm',
@ -151,13 +151,13 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
'listview', 'listview',
'ListViewForm', 'ListViewForm',
'childfilter', 'childfilter',
); ];
private static $url_handlers = [ private static $url_handlers = [
'EditForm/$ID' => 'EditForm', 'EditForm/$ID' => 'EditForm',
]; ];
private static $casting = array( private static $casting = [
'TreeIsFiltered' => 'Boolean', 'TreeIsFiltered' => 'Boolean',
'AddForm' => 'HTMLFragment', 'AddForm' => 'HTMLFragment',
'LinkPages' => 'Text', 'LinkPages' => 'Text',
@ -169,7 +169,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
'SiteTreeHints' => 'HTMLFragment', 'SiteTreeHints' => 'HTMLFragment',
'SecurityID' => 'Text', 'SecurityID' => 'Text',
'SiteTreeAsUL' => 'HTMLFragment', 'SiteTreeAsUL' => 'HTMLFragment',
); ];
private static $dependencies = [ private static $dependencies = [
'HintsCache' => '%$' . CacheInterface::class . '.CMSMain_SiteTreeHints', 'HintsCache' => '%$' . CacheInterface::class . '.CMSMain_SiteTreeHints',
@ -448,10 +448,10 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
public function LinkWithSearch($link) public function LinkWithSearch($link)
{ {
// Whitelist to avoid side effects // Whitelist to avoid side effects
$params = array( $params = [
'q' => (array)$this->getRequest()->getVar('q'), 'q' => (array)$this->getRequest()->getVar('q'),
'ParentID' => $this->getRequest()->getVar('ParentID') 'ParentID' => $this->getRequest()->getVar('ParentID')
); ];
$link = Controller::join_links( $link = Controller::join_links(
$link, $link,
array_filter(array_values($params)) ? '?' . http_build_query($params) : null array_filter(array_values($params)) ? '?' . http_build_query($params) : null
@ -681,7 +681,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
*/ */
public function updatetreenodes($request) public function updatetreenodes($request)
{ {
$data = array(); $data = [];
$ids = explode(',', $request->getVar('ids')); $ids = explode(',', $request->getVar('ids'));
foreach ($ids as $id) { foreach ($ids as $id) {
if ($id === "") { if ($id === "") {
@ -724,12 +724,12 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$this->getTreeNodeCustomisations() $this->getTreeNodeCustomisations()
); );
$data[$id] = array( $data[$id] = [
'html' => $html, 'html' => $html,
'ParentID' => $record->ParentID, 'ParentID' => $record->ParentID,
'NextID' => $next ? $next->ID : null, 'NextID' => $next ? $next->ID : null,
'PrevID' => $prev ? $prev->ID : null 'PrevID' => $prev ? $prev->ID : null
); ];
} }
return $this return $this
->getResponse() ->getResponse()
@ -799,7 +799,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
} }
$siblingIDs = $request->requestVar('SiblingIDs'); $siblingIDs = $request->requestVar('SiblingIDs');
$statusUpdates = array('modified'=>array()); $statusUpdates = ['modified'=>[]];
if (!$node->canEdit()) { if (!$node->canEdit()) {
return Security::permissionFailure($this); return Security::permissionFailure($this);
@ -810,16 +810,16 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$node->ParentID = (int)$parentID; $node->ParentID = (int)$parentID;
$node->write(); $node->write();
$statusUpdates['modified'][$node->ID] = array( $statusUpdates['modified'][$node->ID] = [
'TreeTitle' => $node->TreeTitle 'TreeTitle' => $node->TreeTitle
); ];
// Update all dependent pages // Update all dependent pages
$virtualPages = VirtualPage::get()->filter("CopyContentFromID", $node->ID); $virtualPages = VirtualPage::get()->filter("CopyContentFromID", $node->ID);
foreach ($virtualPages as $virtualPage) { foreach ($virtualPages as $virtualPage) {
$statusUpdates['modified'][$virtualPage->ID] = array( $statusUpdates['modified'][$virtualPage->ID] = [
'TreeTitle' => $virtualPage->TreeTitle() 'TreeTitle' => $virtualPage->TreeTitle()
); ];
} }
$this->getResponse()->addHeader( $this->getResponse()->addHeader(
@ -835,9 +835,9 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
if ($id == $node->ID) { if ($id == $node->ID) {
$node->Sort = ++$counter; $node->Sort = ++$counter;
$node->write(); $node->write();
$statusUpdates['modified'][$node->ID] = array( $statusUpdates['modified'][$node->ID] = [
'TreeTitle' => $node->TreeTitle 'TreeTitle' => $node->TreeTitle
); ];
} elseif (is_numeric($id)) { } elseif (is_numeric($id)) {
// Nodes that weren't "actually moved" shouldn't be registered as // Nodes that weren't "actually moved" shouldn't be registered as
// having been edited; do a direct SQL update instead // having been edited; do a direct SQL update instead
@ -845,7 +845,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$table = DataObject::getSchema()->baseDataTable($className); $table = DataObject::getSchema()->baseDataTable($className);
DB::prepared_query( DB::prepared_query(
"UPDATE \"$table\" SET \"Sort\" = ? WHERE \"ID\" = ?", "UPDATE \"$table\" SET \"Sort\" = ? WHERE \"ID\" = ?",
array($counter, $id) [$counter, $id]
); );
} }
} }
@ -1013,7 +1013,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
*/ */
protected function getPageTypes() protected function getPageTypes()
{ {
$pageTypes = array(); $pageTypes = [];
foreach (SiteTree::page_type_classes() as $pageTypeClass) { foreach (SiteTree::page_type_classes() as $pageTypeClass) {
$pageTypes[$pageTypeClass] = SiteTree::singleton($pageTypeClass)->i18n_singular_name(); $pageTypes[$pageTypeClass] = SiteTree::singleton($pageTypeClass)->i18n_singular_name();
} }
@ -1070,10 +1070,10 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
/** @var SiteTree $record */ /** @var SiteTree $record */
$record = $this->currentPage(); $record = $this->currentPage();
if (!$record) { if (!$record) {
$items->push(new ArrayData(array( $items->push(new ArrayData([
'Title' => CMSPagesController::menu_title(), 'Title' => CMSPagesController::menu_title(),
'Link' => ($unlinked) ? false : $this->LinkPages() 'Link' => ($unlinked) ? false : $this->LinkPages()
))); ]));
$this->extend('updateBreadcrumbs', $items); $this->extend('updateBreadcrumbs', $items);
@ -1086,12 +1086,12 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$ancestors->push($record); $ancestors->push($record);
/** @var SiteTree $ancestor */ /** @var SiteTree $ancestor */
foreach ($ancestors as $ancestor) { foreach ($ancestors as $ancestor) {
$items->push(new ArrayData(array( $items->push(new ArrayData([
'Title' => $ancestor->getMenuTitle(), 'Title' => $ancestor->getMenuTitle(),
'Link' => ($unlinked) 'Link' => ($unlinked)
? false ? false
: $ancestor->CMSEditLink() : $ancestor->CMSEditLink()
))); ]));
} }
$this->extend('updateBreadcrumbs', $items); $this->extend('updateBreadcrumbs', $items);
@ -1196,13 +1196,13 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
continue; continue;
} }
$result->push(new ArrayData(array( $result->push(new ArrayData([
'ClassName' => $class, 'ClassName' => $class,
'AddAction' => $instance->i18n_singular_name(), 'AddAction' => $instance->i18n_singular_name(),
'Description' => $instance->i18n_classDescription(), 'Description' => $instance->i18n_classDescription(),
'IconURL' => $instance->getPageIconURL(), 'IconURL' => $instance->getPageIconURL(),
'Title' => $instance->i18n_singular_name(), 'Title' => $instance->i18n_singular_name(),
))); ]));
} }
$result = $result->sort('AddAction'); $result = $result->sort('AddAction');
@ -1376,7 +1376,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
// TODO Can't merge $FormAttributes in template at the moment // TODO Can't merge $FormAttributes in template at the moment
$form->addExtraClass('center ' . $this->BaseCSSClasses()); $form->addExtraClass('center ' . $this->BaseCSSClasses());
// Set validation exemptions for specific actions // Set validation exemptions for specific actions
$form->setValidationExemptActions(array( $form->setValidationExemptActions([
'restore', 'restore',
'revert', 'revert',
'deletefromlive', 'deletefromlive',
@ -1385,7 +1385,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
'rollback', 'rollback',
'doRollback', 'doRollback',
'archive', 'archive',
)); ]);
// Announce the capability so the frontend can decide whether to allow preview or not. // Announce the capability so the frontend can decide whether to allow preview or not.
if ($record instanceof CMSPreviewable) { if ($record instanceof CMSPreviewable) {
@ -1562,14 +1562,14 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
// Build hints specific to this class // Build hints specific to this class
// Identify disallows and set globals // Identify disallows and set globals
$classes = SiteTree::page_type_classes(); $classes = SiteTree::page_type_classes();
$disallowedChildren = array(); $disallowedChildren = [];
foreach ($classes as $class) { foreach ($classes as $class) {
$obj = singleton($class); $obj = singleton($class);
if ($obj instanceof HiddenClass) { if ($obj instanceof HiddenClass) {
continue; continue;
} }
if (!$obj->canCreate(null, array('Parent' => $parent))) { if (!$obj->canCreate(null, ['Parent' => $parent])) {
$disallowedChildren[] = $class; $disallowedChildren[] = $class;
} }
} }
@ -1610,7 +1610,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
* @return SS_List * @return SS_List
* @throws InvalidArgumentException if invalid filter class is passed. * @throws InvalidArgumentException if invalid filter class is passed.
*/ */
public function getList($params = array(), $parentID = 0) public function getList($params = [], $parentID = 0)
{ {
if ($filter = $this->getQueryFilter($params)) { if ($filter = $this->getQueryFilter($params)) {
return $filter->getFilteredPages(); return $filter->getFilteredPages();
@ -1643,7 +1643,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$gridFieldConfig->addComponent( $gridFieldConfig->addComponent(
GridFieldLevelup::create($parentID) GridFieldLevelup::create($parentID)
->setLinkSpec($linkSpec) ->setLinkSpec($linkSpec)
->setAttributes(array('data-pjax-target' => 'ListViewForm,Breadcrumbs')) ->setAttributes(['data-pjax-target' => 'ListViewForm,Breadcrumbs'])
); );
$this->setCurrentPageID($parentID); $this->setCurrentPageID($parentID);
} }
@ -1653,28 +1653,28 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$columns = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class); $columns = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class);
// Don't allow navigating into children nodes on filtered lists // Don't allow navigating into children nodes on filtered lists
$fields = array( $fields = [
'getTreeTitle' => _t('SilverStripe\\CMS\\Model\\SiteTree.PAGETITLE', 'Page Title'), 'getTreeTitle' => _t('SilverStripe\\CMS\\Model\\SiteTree.PAGETITLE', 'Page Title'),
'singular_name' => _t('SilverStripe\\CMS\\Model\\SiteTree.PAGETYPE', 'Page Type'), 'singular_name' => _t('SilverStripe\\CMS\\Model\\SiteTree.PAGETYPE', 'Page Type'),
'LastEdited' => _t('SilverStripe\\CMS\\Model\\SiteTree.LASTUPDATED', 'Last Updated'), 'LastEdited' => _t('SilverStripe\\CMS\\Model\\SiteTree.LASTUPDATED', 'Last Updated'),
); ];
/** @var GridFieldSortableHeader $sortableHeader */ /** @var GridFieldSortableHeader $sortableHeader */
$sortableHeader = $gridField->getConfig()->getComponentByType(GridFieldSortableHeader::class); $sortableHeader = $gridField->getConfig()->getComponentByType(GridFieldSortableHeader::class);
$sortableHeader->setFieldSorting(array('getTreeTitle' => 'Title')); $sortableHeader->setFieldSorting(['getTreeTitle' => 'Title']);
$gridField->getState()->ParentID = $parentID; $gridField->getState()->ParentID = $parentID;
if (!$params) { if (!$params) {
$fields = array_merge(array('listChildrenLink' => ''), $fields); $fields = array_merge(['listChildrenLink' => ''], $fields);
} }
$columns->setDisplayFields($fields); $columns->setDisplayFields($fields);
$columns->setFieldCasting(array( $columns->setFieldCasting([
'Created' => 'DBDatetime->Ago', 'Created' => 'DBDatetime->Ago',
'LastEdited' => 'DBDatetime->FormatFromSettings', 'LastEdited' => 'DBDatetime->FormatFromSettings',
'getTreeTitle' => 'HTMLFragment' 'getTreeTitle' => 'HTMLFragment'
)); ]);
$columns->setFieldFormatting(array( $columns->setFieldFormatting([
'listChildrenLink' => function ($value, &$item) { 'listChildrenLink' => function ($value, &$item) {
/** @var SiteTree $item */ /** @var SiteTree $item */
$num = $item ? $item->numChildren() : null; $num = $item ? $item->numChildren() : null;
@ -1700,7 +1700,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$breadcrumbs = preg_replace('/\s?\/\s?/', '/', trim($breadcrumbs)); $breadcrumbs = preg_replace('/\s?\/\s?/', '/', trim($breadcrumbs));
return $title . sprintf('<p class="small cms-list__item-breadcrumbs">%s</p>', $breadcrumbs); return $title . sprintf('<p class="small cms-list__item-breadcrumbs">%s</p>', $breadcrumbs);
} }
)); ]);
$negotiator = $this->getResponseNegotiator(); $negotiator = $this->getResponseNegotiator();
$listview = Form::create( $listview = Form::create(
@ -1714,11 +1714,11 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$request = $this->getRequest(); $request = $this->getRequest();
if ($request->isAjax() && $negotiator) { if ($request->isAjax() && $negotiator) {
$result = $listview->forTemplate(); $result = $listview->forTemplate();
return $negotiator->respond($request, array( return $negotiator->respond($request, [
'CurrentForm' => function () use ($result) { 'CurrentForm' => function () use ($result) {
return $result; return $result;
} }
)); ]);
} }
}); });
@ -1843,7 +1843,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
__CLASS__ . '.NEWPAGE', __CLASS__ . '.NEWPAGE',
"New {pagetype}", "New {pagetype}",
'followed by a page type title', 'followed by a page type title',
array('pagetype' => singleton($className)->i18n_singular_name()) ['pagetype' => singleton($className)->i18n_singular_name()]
); );
$newItem->ClassName = $className; $newItem->ClassName = $className;
$newItem->ParentID = $parentID; $newItem->ParentID = $parentID;
@ -1854,7 +1854,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$table = DataObject::singleton(SiteTree::class)->baseTable(); $table = DataObject::singleton(SiteTree::class)->baseTable();
$maxSort = DB::prepared_query( $maxSort = DB::prepared_query(
"SELECT MAX(\"Sort\") FROM \"$table\" WHERE \"ParentID\" = ?", "SELECT MAX(\"Sort\") FROM \"$table\" WHERE \"ParentID\" = ?",
array($parentID) [$parentID]
)->value(); )->value();
$newItem->Sort = (int)$maxSort + 1; $newItem->Sort = (int)$maxSort + 1;
} }
@ -1911,9 +1911,9 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
/** @var SiteTree $record */ /** @var SiteTree $record */
$table = DataObject::singleton(SiteTree::class)->baseTable(); $table = DataObject::singleton(SiteTree::class)->baseTable();
$liveTable = DataObject::singleton(SiteTree::class)->stageTable($table, Versioned::LIVE); $liveTable = DataObject::singleton(SiteTree::class)->stageTable($table, Versioned::LIVE);
$record = Versioned::get_one_by_stage(SiteTree::class, Versioned::LIVE, array( $record = Versioned::get_one_by_stage(SiteTree::class, Versioned::LIVE, [
"\"$liveTable\".\"ID\"" => $id "\"$liveTable\".\"ID\"" => $id
)); ]);
// a user can restore a page without publication rights, as it just adds a new draft state // a user can restore a page without publication rights, as it just adds a new draft state
// (this action should just be available when page has been "deleted from draft") // (this action should just be available when page has been "deleted from draft")
@ -1932,7 +1932,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
__CLASS__ . '.RESTORED', __CLASS__ . '.RESTORED',
"Restored '{title}' successfully", "Restored '{title}' successfully",
'Param {title} is a title', 'Param {title} is a title',
array('title' => $record->Title) ['title' => $record->Title]
)) ))
); );
@ -2051,10 +2051,10 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
*/ */
public function rollback() public function rollback()
{ {
return $this->doRollback(array( return $this->doRollback([
'ID' => $this->currentPageID(), 'ID' => $this->currentPageID(),
'Version' => $this->getRequest()->param('VersionID') 'Version' => $this->getRequest()->param('VersionID')
), null); ], null);
} }
/** /**
@ -2082,7 +2082,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
$message = _t( $message = _t(
__CLASS__ . '.ROLLEDBACKVERSIONv2', __CLASS__ . '.ROLLEDBACKVERSIONv2',
"Rolled back to version #{version}.", "Rolled back to version #{version}.",
array('version' => $data['Version']) ['version' => $data['Version']]
); );
} else { } else {
$record->doRevertToLive(); $record->doRevertToLive();
@ -2118,7 +2118,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
{ {
$batchActions = CMSBatchActionHandler::config()->batch_actions; $batchActions = CMSBatchActionHandler::config()->batch_actions;
$forms = array(); $forms = [];
foreach ($batchActions as $urlSegment => $batchAction) { foreach ($batchActions as $urlSegment => $batchAction) {
$SNG_action = singleton($batchAction); $SNG_action = singleton($batchAction);
if ($SNG_action->canView() && $fieldset = $SNG_action->getParameterFields()) { if ($SNG_action->canView() && $fieldset = $SNG_action->getParameterFields()) {
@ -2189,7 +2189,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
break; break;
} }
} }
$response .= _t(__CLASS__ . '.PUBPAGES', "Done: Published {count} pages", array('count' => $count)); $response .= _t(__CLASS__ . '.PUBPAGES', "Done: Published {count} pages", ['count' => $count]);
} else { } else {
$token = SecurityToken::inst(); $token = SecurityToken::inst();
$fields = new FieldList(); $fields = new FieldList();
@ -2243,7 +2243,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
rawurlencode(_t( rawurlencode(_t(
__CLASS__ . '.RESTORED', __CLASS__ . '.RESTORED',
"Restored '{title}' successfully", "Restored '{title}' successfully",
array('title' => $restoredPage->Title) ['title' => $restoredPage->Title]
)) ))
); );
@ -2281,7 +2281,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
rawurlencode(_t( rawurlencode(_t(
__CLASS__ . '.DUPLICATED', __CLASS__ . '.DUPLICATED',
"Duplicated '{title}' successfully", "Duplicated '{title}' successfully",
array('title' => $newPage->Title) ['title' => $newPage->Title]
)) ))
); );
$url = $newPage->CMSEditLink(); $url = $newPage->CMSEditLink();
@ -2319,7 +2319,7 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
rawurlencode(_t( rawurlencode(_t(
__CLASS__ . '.DUPLICATEDWITHCHILDREN', __CLASS__ . '.DUPLICATEDWITHCHILDREN',
"Duplicated '{title}' and children successfully", "Duplicated '{title}' and children successfully",
array('title' => $newPage->Title) ['title' => $newPage->Title]
)) ))
); );
$url = $newPage->CMSEditLink(); $url = $newPage->CMSEditLink();
@ -2335,17 +2335,17 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
public function providePermissions() public function providePermissions()
{ {
$title = CMSPagesController::menu_title(); $title = CMSPagesController::menu_title();
return array( return [
"CMS_ACCESS_CMSMain" => array( "CMS_ACCESS_CMSMain" => [
'name' => _t(__CLASS__ . '.ACCESS', "Access to '{title}' section", array('title' => $title)), 'name' => _t(__CLASS__ . '.ACCESS', "Access to '{title}' section", ['title' => $title]),
'category' => _t('SilverStripe\\Security\\Permission.CMS_ACCESS_CATEGORY', 'CMS Access'), 'category' => _t('SilverStripe\\Security\\Permission.CMS_ACCESS_CATEGORY', 'CMS Access'),
'help' => _t( 'help' => _t(
__CLASS__ . '.ACCESS_HELP', __CLASS__ . '.ACCESS_HELP',
'Allow viewing of the section containing page tree and content. View and edit permissions can be handled through page specific dropdowns, as well as the separate "Content permissions".' 'Allow viewing of the section containing page tree and content. View and edit permissions can be handled through page specific dropdowns, as well as the separate "Content permissions".'
), ),
'sort' => -99 // below "CMS_ACCESS_LeftAndMain", but above everything else 'sort' => -99 // below "CMS_ACCESS_LeftAndMain", but above everything else
) ]
); ];
} }
/** /**

View File

@ -31,18 +31,18 @@ class CMSPageAddController extends CMSPageEditController
private static $menu_title = 'Add page'; private static $menu_title = 'Add page';
private static $required_permission_codes = 'CMS_ACCESS_CMSMain'; private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
private static $allowed_actions = array( private static $allowed_actions = [
'AddForm', 'AddForm',
'doAdd', 'doAdd',
'doCancel' 'doCancel'
); ];
/** /**
* @return Form * @return Form
*/ */
public function AddForm() public function AddForm()
{ {
$pageTypes = array(); $pageTypes = [];
$defaultIcon = Config::inst()->get(SiteTree::class, 'icon_class'); $defaultIcon = Config::inst()->get(SiteTree::class, 'icon_class');
foreach ($this->PageTypes() as $type) { foreach ($this->PageTypes() as $type) {
@ -67,7 +67,7 @@ class CMSPageAddController extends CMSPageEditController
// Ensure generic page type shows on top // Ensure generic page type shows on top
if (isset($pageTypes['Page'])) { if (isset($pageTypes['Page'])) {
$pageTitle = $pageTypes['Page']; $pageTitle = $pageTypes['Page'];
$pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes); $pageTypes = array_merge(['Page' => $pageTitle], $pageTypes);
} }
$numericLabelTmpl = '<span class="step-label"><span class="flyout">Step %d. </span><span class="title">%s</span></span>'; $numericLabelTmpl = '<span class="step-label"><span class="flyout">Step %d. </span><span class="title">%s</span></span>';
@ -78,7 +78,7 @@ class CMSPageAddController extends CMSPageEditController
$fields = new FieldList( $fields = new FieldList(
$parentModeField = new SelectionGroup( $parentModeField = new SelectionGroup(
"ParentModeField", "ParentModeField",
array( [
new SelectionGroup_Item( new SelectionGroup_Item(
"top", "top",
null, null,
@ -95,7 +95,7 @@ class CMSPageAddController extends CMSPageEditController
), ),
$childTitle $childTitle
) )
) ]
), ),
new LiteralField( new LiteralField(
'RestrictedNote', 'RestrictedNote',
@ -170,11 +170,11 @@ class CMSPageAddController extends CMSPageEditController
$request = $this->getRequest(); $request = $this->getRequest();
if ($request->isAjax() && $negotiator) { if ($request->isAjax() && $negotiator) {
$result = $form->forTemplate(); $result = $form->forTemplate();
return $negotiator->respond($request, array( return $negotiator->respond($request, [
'CurrentForm' => function () use ($result) { 'CurrentForm' => function () use ($result) {
return $result; return $result;
} }
)); ]);
} }
return null; return null;
}); });
@ -211,7 +211,7 @@ class CMSPageAddController extends CMSPageEditController
$parentID = 0; $parentID = 0;
} }
if (!singleton($className)->canCreate(Security::getCurrentUser(), array('Parent' => $parentObj))) { if (!singleton($className)->canCreate(Security::getCurrentUser(), ['Parent' => $parentObj])) {
return Security::permissionFailure($this); return Security::permissionFailure($this);
} }

View File

@ -28,9 +28,9 @@ class CMSPageEditController extends CMSMain
private static $required_permission_codes = 'CMS_ACCESS_CMSMain'; private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
private static $allowed_actions = array( private static $allowed_actions = [
'AddToCampaignForm', 'AddToCampaignForm',
); ];
public function getClientConfig() public function getClientConfig()
{ {

View File

@ -39,18 +39,18 @@ class CMSPageHistoryController extends CMSMain
private static $required_permission_codes = 'CMS_ACCESS_CMSMain'; private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
private static $allowed_actions = array( private static $allowed_actions = [
'EditForm', 'EditForm',
'VersionsForm', 'VersionsForm',
'CompareVersionsForm', 'CompareVersionsForm',
'show', 'show',
'compare' 'compare'
); ];
private static $url_handlers = array( private static $url_handlers = [
'$Action/$ID/$VersionID/$OtherVersionID' => 'handleAction', '$Action/$ID/$VersionID/$OtherVersionID' => 'handleAction',
'EditForm/$ID/$VersionID' => 'EditForm', 'EditForm/$ID/$VersionID' => 'EditForm',
); ];
/** /**
* Current version ID for this request. Can be 0 for latest version * Current version ID for this request. Can be 0 for latest version
@ -101,7 +101,7 @@ class CMSPageHistoryController extends CMSMain
}); });
$negotiator->setCallback('default', function () use ($form) { $negotiator->setCallback('default', function () use ($form) {
return $this return $this
->customise(array('EditForm' => $form)) ->customise(['EditForm' => $form])
->renderWith($this->getViewer('show')); ->renderWith($this->getViewer('show'));
}); });
@ -124,7 +124,7 @@ class CMSPageHistoryController extends CMSMain
return $form ? $form->forTemplate() : $this->renderWith($this->getTemplatesWithSuffix('_Content')); return $form ? $form->forTemplate() : $this->renderWith($this->getTemplatesWithSuffix('_Content'));
}); });
$negotiator->setCallback('default', function () use ($form) { $negotiator->setCallback('default', function () use ($form) {
return $this->customise(array('EditForm' => $form))->renderWith($this->getViewer('show')); return $this->customise(['EditForm' => $form])->renderWith($this->getViewer('show'));
}); });
return $negotiator->respond($request); return $negotiator->respond($request);
@ -229,10 +229,10 @@ class CMSPageHistoryController extends CMSMain
$message = _t( $message = _t(
__CLASS__ . '.COMPARINGVERSION', __CLASS__ . '.COMPARINGVERSION',
"Comparing versions {version1} and {version2}.", "Comparing versions {version1} and {version2}.",
array( [
'version1' => sprintf('%s (<a href="%s">%s</a>)', $versionID, Controller::join_links($link, $versionID), $view), 'version1' => sprintf('%s (<a href="%s">%s</a>)', $versionID, Controller::join_links($link, $versionID), $view),
'version2' => sprintf('%s (<a href="%s">%s</a>)', $compareID, Controller::join_links($link, $compareID), $view) 'version2' => sprintf('%s (<a href="%s">%s</a>)', $compareID, Controller::join_links($link, $compareID), $view)
) ]
); );
$revert->setReadonly(true); $revert->setReadonly(true);
@ -243,7 +243,7 @@ class CMSPageHistoryController extends CMSMain
$message = _t( $message = _t(
__CLASS__ . '.VIEWINGVERSION', __CLASS__ . '.VIEWINGVERSION',
"Currently viewing version {version}.", "Currently viewing version {version}.",
array('version' => $versionID) ['version' => $versionID]
); );
} }
} }
@ -251,17 +251,17 @@ class CMSPageHistoryController extends CMSMain
/** @var Tab $mainTab */ /** @var Tab $mainTab */
$mainTab = $fields->fieldByName('Root.Main'); $mainTab = $fields->fieldByName('Root.Main');
$mainTab->unshift( $mainTab->unshift(
LiteralField::create('CurrentlyViewingMessage', ArrayData::create(array( LiteralField::create('CurrentlyViewingMessage', ArrayData::create([
'Content' => DBField::create_field('HTMLFragment', $message), 'Content' => DBField::create_field('HTMLFragment', $message),
'Classes' => 'alert alert-info' 'Classes' => 'alert alert-info'
))->renderWith($this->getTemplatesWithSuffix('_notice'))) ])->renderWith($this->getTemplatesWithSuffix('_notice')))
); );
$form->setFields($fields->makeReadonly()); $form->setFields($fields->makeReadonly());
$form->loadDataFrom(array( $form->loadDataFrom([
"ID" => $id, "ID" => $id,
"Version" => $versionID, "Version" => $versionID,
)); ]);
if ($record->isLatestVersion()) { if ($record->isLatestVersion()) {
$revert->setReadonly(true); $revert->setReadonly(true);
@ -322,9 +322,9 @@ class CMSPageHistoryController extends CMSMain
$vd = new ViewableData(); $vd = new ViewableData();
$versionsHtml = $vd->customise(array( $versionsHtml = $vd->customise([
'Versions' => $versions 'Versions' => $versions
))->renderWith($this->getTemplatesWithSuffix('_versions')); ])->renderWith($this->getTemplatesWithSuffix('_versions'));
} }
$fields = new FieldList( $fields = new FieldList(
@ -411,10 +411,10 @@ class CMSPageHistoryController extends CMSMain
$form->addExtraClass('compare'); $form->addExtraClass('compare');
$form->loadDataFrom($record); $form->loadDataFrom($record);
$form->loadDataFrom(array( $form->loadDataFrom([
"ID" => $id, "ID" => $id,
"Version" => $fromVersion, "Version" => $fromVersion,
)); ]);
// Comparison views shouldn't be editable. // Comparison views shouldn't be editable.
// As the comparison output is HTML and not valid values for the various field types // As the comparison output is HTML and not valid values for the various field types

View File

@ -40,17 +40,17 @@ class CMSPagesController extends CMSMain
$page = SiteTree::get()->byID($parentID); $page = SiteTree::get()->byID($parentID);
//build a reversed list of the parent tree //build a reversed list of the parent tree
$pages = array(); $pages = [];
while ($page) { while ($page) {
array_unshift($pages, $page); //add to start of array so that array is in reverse order array_unshift($pages, $page); //add to start of array so that array is in reverse order
$page = $page->Parent; $page = $page->Parent;
} }
//turns the title and link of the breadcrumbs into template-friendly variables //turns the title and link of the breadcrumbs into template-friendly variables
$params = array_filter(array( $params = array_filter([
'view' => $this->getRequest()->getVar('view'), 'view' => $this->getRequest()->getVar('view'),
'q' => $this->getRequest()->getVar('q') 'q' => $this->getRequest()->getVar('q')
)); ]);
foreach ($pages as $page) { foreach ($pages as $page) {
$params['ParentID'] = $page->ID; $params['ParentID'] = $page->ID;
$item = new stdClass(); $item = new stdClass();

View File

@ -32,7 +32,7 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
* *
* @var array * @var array
*/ */
protected $params = array(); protected $params = [];
/** /**
* List of filtered items and all their parents * List of filtered items and all their parents
@ -54,7 +54,7 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
/** /**
* @var array * @var array
*/ */
protected $_cache_expanded = array(); protected $_cache_expanded = [];
/** /**
* @var string * @var string
@ -80,7 +80,7 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
array_shift($filters); array_shift($filters);
// add filters to map // add filters to map
$filterMap = array(); $filterMap = [];
foreach ($filters as $filter) { foreach ($filters as $filter) {
$filterMap[$filter] = $filter::title(); $filterMap[$filter] = $filter::title();
} }
@ -148,9 +148,9 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
*/ */
protected function populateIDs() protected function populateIDs()
{ {
$parents = array(); $parents = [];
$this->_cache_ids = array(); $this->_cache_ids = [];
$this->_cache_highlight_ids = array(); $this->_cache_highlight_ids = [];
if ($pages = $this->pagesIncluded()) { if ($pages = $this->pagesIncluded()) {
// And keep a record of parents we don't need to get // And keep a record of parents we don't need to get
@ -165,7 +165,7 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
$q = Versioned::get_including_deleted(SiteTree::class) $q = Versioned::get_including_deleted(SiteTree::class)
->byIDs(array_keys($parents)); ->byIDs(array_keys($parents));
$list = $q->map('ID', 'ParentID'); $list = $q->map('ID', 'ParentID');
$parents = array(); $parents = [];
foreach ($list as $id => $parentID) { foreach ($list as $id => $parentID) {
if ($parentID) { if ($parentID) {
$parents[$parentID] = true; $parents[$parentID] = true;
@ -202,12 +202,12 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
switch ($name) { switch ($name) {
case 'Term': case 'Term':
$query = $query->filterAny(array( $query = $query->filterAny([
'URLSegment:PartialMatch' => $val, 'URLSegment:PartialMatch' => $val,
'Title:PartialMatch' => $val, 'Title:PartialMatch' => $val,
'MenuTitle:PartialMatch' => $val, 'MenuTitle:PartialMatch' => $val,
'Content:PartialMatch' => $val 'Content:PartialMatch' => $val
)); ]);
break; break;
case 'LastEditedFrom': case 'LastEditedFrom':
@ -231,7 +231,7 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
if ($field) { if ($field) {
$filter = $field->defaultSearchFilter(); $filter = $field->defaultSearchFilter();
$filter->setValue($val); $filter->setValue($val);
$query = $query->alterDataQuery(array($filter, 'apply')); $query = $query->alterDataQuery([$filter, 'apply']);
} }
} }
} }
@ -246,10 +246,10 @@ abstract class CMSSiteTreeFilter implements LeftAndMain_SearchFilter
*/ */
protected function mapIDs($pages) protected function mapIDs($pages)
{ {
$ids = array(); $ids = [];
if ($pages) { if ($pages) {
foreach ($pages as $page) { foreach ($pages as $page) {
$ids[] = array('ID' => $page->ID, 'ParentID' => $page->ParentID); $ids[] = ['ID' => $page->ID, 'ParentID' => $page->ParentID];
} }
} }
return $ids; return $ids;

View File

@ -523,11 +523,11 @@ HTML;
$content = new DBHTMLText('Content'); $content = new DBHTMLText('Content');
// As of SS4, index.php is required and should never be deleted. // As of SS4, index.php is required and should never be deleted.
$installfiles = array( $installfiles = [
'install.php', 'install.php',
'install-frameworkmissing.html', 'install-frameworkmissing.html',
'index.html' 'index.html'
); ];
$unsuccessful = new ArrayList(); $unsuccessful = new ArrayList();
foreach ($installfiles as $installfile) { foreach ($installfiles as $installfile) {
@ -537,7 +537,7 @@ HTML;
} }
if (file_exists($installfilepath)) { if (file_exists($installfilepath)) {
$unsuccessful->push(new ArrayData(array('File' => $installfile))); $unsuccessful->push(new ArrayData(['File' => $installfile]));
} }
} }

View File

@ -63,9 +63,9 @@ class ModelAsController extends Controller implements NestedController
$this->getResponse()->redirect(Controller::join_links( $this->getResponse()->redirect(Controller::join_links(
Director::absoluteBaseURL(), Director::absoluteBaseURL(),
'dev/build', 'dev/build',
'?' . http_build_query(array( '?' . http_build_query([
'returnURL' => isset($_GET['url']) ? $_GET['url'] : null, 'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
)) ])
)); ));
} }
} }

View File

@ -54,7 +54,7 @@ class OldPageRedirector extends Extension
/** /**
* Attempt to find an old/renamed page from some given the URL as an array * Attempt to find an old/renamed page from some given the URL as an array
* *
* @param array $params The array of URL, e.g. /foo/bar as array('foo', 'bar') * @param array $params The array of URL, e.g. /foo/bar as ['foo', 'bar']
* @param SiteTree|null $parent The current parent in the recursive flow * @param SiteTree|null $parent The current parent in the recursive flow
* @param boolean $redirect Whether we've found an old page worthy of a redirect * @param boolean $redirect Whether we've found an old page worthy of a redirect
* *
@ -68,13 +68,13 @@ class OldPageRedirector extends Extension
if (empty($URL)) { if (empty($URL)) {
return false; return false;
} }
$pages = SiteTree::get()->filter(array( $pages = SiteTree::get()->filter([
'URLSegment' => $URL, 'URLSegment' => $URL,
)); ]);
if ($parent || is_numeric($parent)) { if ($parent || is_numeric($parent)) {
$pages = $pages->filter(array( $pages = $pages->filter([
'ParentID' => is_numeric($parent) ? $parent : $parent->ID, 'ParentID' => is_numeric($parent) ? $parent : $parent->ID,
)); ]);
} }
/** @var SiteTree $page */ /** @var SiteTree $page */
$page = $pages->first(); $page = $pages->first();

View File

@ -78,9 +78,9 @@ class RootURLController extends Controller implements Resettable
$this->getResponse()->redirect(Controller::join_links( $this->getResponse()->redirect(Controller::join_links(
Director::absoluteBaseURL(), Director::absoluteBaseURL(),
'dev/build', 'dev/build',
'?' . http_build_query(array( '?' . http_build_query([
'returnURL' => isset($_GET['url']) ? $_GET['url'] : null, 'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
)) ])
)); ));
} }
} }

View File

@ -41,7 +41,7 @@ class SilverStripeNavigator extends ViewableData
*/ */
public function getItems() public function getItems()
{ {
$items = array(); $items = [];
$classes = ClassInfo::subclassesFor(SilverStripeNavigatorItem::class); $classes = ClassInfo::subclassesFor(SilverStripeNavigatorItem::class);
array_shift($classes); array_shift($classes);
@ -99,9 +99,9 @@ class SilverStripeNavigator extends ViewableData
} }
} }
return array( return [
'items' => $html, 'items' => $html,
'message' => $message 'message' => $message
); ];
} }
} }

View File

@ -17,10 +17,10 @@ class InternalLinkModalExtension extends Extension
'editorAnchorLink/$ItemID' => 'editorAnchorLink', // Matches LeftAndMain::methodSchema args 'editorAnchorLink/$ItemID' => 'editorAnchorLink', // Matches LeftAndMain::methodSchema args
]; ];
private static $allowed_actions = array( private static $allowed_actions = [
'editorInternalLink', 'editorInternalLink',
'editorAnchorLink', 'editorAnchorLink',
); ];
/** /**
* @return ModalController * @return ModalController

View File

@ -38,9 +38,9 @@ class SiteTreeURLSegmentField extends TextField
*/ */
protected $defaultUrl; protected $defaultUrl;
private static $allowed_actions = array( private static $allowed_actions = [
'suggest' 'suggest'
); ];
public function Value() public function Value()
{ {
@ -51,15 +51,15 @@ class SiteTreeURLSegmentField extends TextField
{ {
return array_merge( return array_merge(
parent::getAttributes(), parent::getAttributes(),
array( [
'data-prefix' => $this->getURLPrefix(), 'data-prefix' => $this->getURLPrefix(),
'data-suffix' => '?stage=Stage', 'data-suffix' => '?stage=Stage',
'data-default-url' => $this->getDefaultURL() 'data-default-url' => $this->getDefaultURL()
) ]
); );
} }
public function Field($properties = array()) public function Field($properties = [])
{ {
return parent::Field($properties); return parent::Field($properties);
} }
@ -87,7 +87,7 @@ class SiteTreeURLSegmentField extends TextField
} }
Controller::curr()->getResponse()->addHeader('Content-Type', 'application/json'); Controller::curr()->getResponse()->addHeader('Content-Type', 'application/json');
return json_encode(array('value' => $page->URLSegment)); return json_encode(['value' => $page->URLSegment]);
} }
/** /**

View File

@ -158,10 +158,10 @@ class RedirectorPage extends Page
if (empty($urlParts['scheme'])) { if (empty($urlParts['scheme'])) {
// no scheme, assume http // no scheme, assume http
$this->ExternalURL = 'http://' . $this->ExternalURL; $this->ExternalURL = 'http://' . $this->ExternalURL;
} elseif (!in_array($urlParts['scheme'], array( } elseif (!in_array($urlParts['scheme'], [
'http', 'http',
'https', 'https',
))) { ])) {
// we only allow http(s) urls // we only allow http(s) urls
$this->ExternalURL = ''; $this->ExternalURL = '';
} }
@ -182,15 +182,15 @@ class RedirectorPage extends Page
$fields->addFieldsToTab( $fields->addFieldsToTab(
'Root.Main', 'Root.Main',
array( [
new HeaderField('RedirectorDescHeader', _t(__CLASS__.'.HEADER', "This page will redirect users to another page")), new HeaderField('RedirectorDescHeader', _t(__CLASS__.'.HEADER', "This page will redirect users to another page")),
new OptionsetField( new OptionsetField(
"RedirectionType", "RedirectionType",
_t(__CLASS__.'.REDIRECTTO', "Redirect to"), _t(__CLASS__.'.REDIRECTTO', "Redirect to"),
array( [
"Internal" => _t(__CLASS__.'.REDIRECTTOPAGE', "A page on your website"), "Internal" => _t(__CLASS__.'.REDIRECTTOPAGE', "A page on your website"),
"External" => _t(__CLASS__.'.REDIRECTTOEXTERNAL', "Another website"), "External" => _t(__CLASS__.'.REDIRECTTOEXTERNAL', "Another website"),
), ],
"Internal" "Internal"
), ),
new TreeDropdownField( new TreeDropdownField(
@ -199,7 +199,7 @@ class RedirectorPage extends Page
SiteTree::class SiteTree::class
), ),
new TextField("ExternalURL", _t(__CLASS__.'.OTHERURL', "Other website URL")) new TextField("ExternalURL", _t(__CLASS__.'.OTHERURL', "Other website URL"))
) ]
); );
}); });

View File

@ -135,7 +135,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
* Drastically reduces admin page load when there are a lot of page types * Drastically reduces admin page load when there are a lot of page types
* @var array * @var array
*/ */
protected static $_allowedChildren = array(); protected static $_allowedChildren = [];
/** /**
* Determines if the Draft Preview panel will appear when in the CMS admin * Determines if the Draft Preview panel will appear when in the CMS admin
@ -213,7 +213,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
*/ */
private static $controller_name = null; private static $controller_name = null;
private static $db = array( private static $db = [
"URLSegment" => "Varchar(255)", "URLSegment" => "Varchar(255)",
"Title" => "Varchar(255)", "Title" => "Varchar(255)",
"MenuTitle" => "Varchar(100)", "MenuTitle" => "Varchar(100)",
@ -226,26 +226,26 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
"HasBrokenFile" => "Boolean", "HasBrokenFile" => "Boolean",
"HasBrokenLink" => "Boolean", "HasBrokenLink" => "Boolean",
"ReportClass" => "Varchar", "ReportClass" => "Varchar",
); ];
private static $indexes = array( private static $indexes = [
"URLSegment" => true, "URLSegment" => true,
); ];
private static $has_many = [ private static $has_many = [
"VirtualPages" => VirtualPage::class . '.CopyContentFrom', "VirtualPages" => VirtualPage::class . '.CopyContentFrom',
'BackLinks' => SiteTreeLink::class . '.Linked', 'BackLinks' => SiteTreeLink::class . '.Linked',
]; ];
private static $owned_by = array( private static $owned_by = [
"VirtualPages" "VirtualPages"
); ];
private static $cascade_deletes = [ private static $cascade_deletes = [
'VirtualPages', 'VirtualPages',
]; ];
private static $casting = array( private static $casting = [
"Breadcrumbs" => "HTMLFragment", "Breadcrumbs" => "HTMLFragment",
"LastEdited" => "Datetime", "LastEdited" => "Datetime",
"Created" => "Datetime", "Created" => "Datetime",
@ -255,18 +255,18 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
'CMSEditLink' => 'Text', 'CMSEditLink' => 'Text',
'TreeTitle' => 'HTMLFragment', 'TreeTitle' => 'HTMLFragment',
'MetaTags' => 'HTMLFragment', 'MetaTags' => 'HTMLFragment',
); ];
private static $defaults = array( private static $defaults = [
"ShowInMenus" => 1, "ShowInMenus" => 1,
"ShowInSearch" => 1, "ShowInSearch" => 1,
); ];
private static $table_name = 'SiteTree'; private static $table_name = 'SiteTree';
private static $versioning = array( private static $versioning = [
"Stage", "Live" "Stage", "Live"
); ];
private static $default_sort = "\"Sort\""; private static $default_sort = "\"Sort\"";
@ -300,14 +300,14 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
InheritedPermissionsExtension::class, InheritedPermissionsExtension::class,
]; ];
private static $searchable_fields = array( private static $searchable_fields = [
'Title', 'Title',
'Content', 'Content',
); ];
private static $field_labels = array( private static $field_labels = [
'URLSegment' => 'URL' 'URLSegment' => 'URL'
); ];
/** /**
* @config * @config
@ -422,9 +422,9 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
// Grab the initial root level page to traverse down from. // Grab the initial root level page to traverse down from.
$URLSegment = array_shift($parts); $URLSegment = array_shift($parts);
$conditions = array($urlSegmentExpr => rawurlencode($URLSegment)); $conditions = [$urlSegmentExpr => rawurlencode($URLSegment)];
if (self::config()->get('nested_urls')) { if (self::config()->get('nested_urls')) {
$conditions[] = array($parentIDExpr => 0); $conditions[] = [$parentIDExpr => 0];
} }
/** @var SiteTree $sitetree */ /** @var SiteTree $sitetree */
$sitetree = DataObject::get_one(self::class, $conditions, $cache); $sitetree = DataObject::get_one(self::class, $conditions, $cache);
@ -432,9 +432,9 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
/// Fall back on a unique URLSegment for b/c. /// Fall back on a unique URLSegment for b/c.
if (!$sitetree if (!$sitetree
&& self::config()->get('nested_urls') && self::config()->get('nested_urls')
&& $sitetree = DataObject::get_one(self::class, array( && $sitetree = DataObject::get_one(self::class, [
$urlSegmentExpr => $URLSegment $urlSegmentExpr => $URLSegment
), $cache) ], $cache)
) { ) {
return $sitetree; return $sitetree;
} }
@ -465,10 +465,10 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
foreach ($parts as $segment) { foreach ($parts as $segment) {
$next = DataObject::get_one( $next = DataObject::get_one(
self::class, self::class,
array( [
$urlSegmentExpr => $segment, $urlSegmentExpr => $segment,
$parentIDExpr => $sitetree->ID $parentIDExpr => $sitetree->ID
), ],
$cache $cache
); );
@ -509,7 +509,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
unset($classes[$baseClassIndex]); unset($classes[$baseClassIndex]);
} }
$kill_ancestors = array(); $kill_ancestors = [];
// figure out if there are any classes we don't want to appear // figure out if there are any classes we don't want to appear
foreach ($classes as $class) { foreach ($classes as $class) {
@ -678,9 +678,9 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
Versioned::set_stage(Versioned::LIVE); Versioned::set_stage(Versioned::LIVE);
$tablename = $this->baseTable(); $tablename = $this->baseTable();
/** @var SiteTree $live */ /** @var SiteTree $live */
$live = Versioned::get_one_by_stage(self::class, Versioned::LIVE, array( $live = Versioned::get_one_by_stage(self::class, Versioned::LIVE, [
"\"$tablename\".\"ID\"" => $this->ID "\"$tablename\".\"ID\"" => $this->ID
)); ]);
if ($live) { if ($live) {
$link = $live->AbsoluteLink(); $link = $live->AbsoluteLink();
if ($includeStageEqualsLive) { if ($includeStageEqualsLive) {
@ -890,11 +890,11 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
{ {
$pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden); $pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);
$template = SSViewer::create('BreadcrumbsTemplate'); $template = SSViewer::create('BreadcrumbsTemplate');
return $template->process($this->customise(new ArrayData(array( return $template->process($this->customise(new ArrayData([
"Pages" => $pages, "Pages" => $pages,
"Unlinked" => $unlinked, "Unlinked" => $unlinked,
"Delimiter" => $delimiter, "Delimiter" => $delimiter,
)))); ])));
} }
@ -910,7 +910,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false) public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false)
{ {
$page = $this; $page = $this;
$pages = array(); $pages = [];
while ($page while ($page
&& $page->exists() && $page->exists()
@ -1016,7 +1016,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
* @param array $context Context argument for canCreate() * @param array $context Context argument for canCreate()
* @return bool True if the the member is allowed to do the given action * @return bool True if the the member is allowed to do the given action
*/ */
public function can($perm, $member = null, $context = array()) public function can($perm, $member = null, $context = [])
{ {
if (!$member) { if (!$member) {
$member = Security::getCurrentUser(); $member = Security::getCurrentUser();
@ -1111,7 +1111,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
} }
// admin override // admin override
if ($member && Permission::checkMember($member, array("ADMIN", "SITETREE_VIEW_ALL"))) { if ($member && Permission::checkMember($member, ["ADMIN", "SITETREE_VIEW_ALL"])) {
return true; return true;
} }
@ -1212,7 +1212,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
} }
// Default permission check // Default permission check
if (Permission::checkMember($member, array("ADMIN", "SITETREE_EDIT_ALL"))) { if (Permission::checkMember($member, ["ADMIN", "SITETREE_EDIT_ALL"])) {
return true; return true;
} }
@ -1234,12 +1234,12 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
* @uses DataExtension->canCreate() * @uses DataExtension->canCreate()
* *
* @param Member $member * @param Member $member
* @param array $context Optional array which may contain array('Parent' => $parentObj) * @param array $context Optional array which may contain ['Parent' => $parentObj]
* If a parent page is known, it will be checked for validity. * If a parent page is known, it will be checked for validity.
* If omitted, it will be assumed this is to be created as a top level page. * If omitted, it will be assumed this is to be created as a top level page.
* @return bool True if the current user can create pages on this class. * @return bool True if the current user can create pages on this class.
*/ */
public function canCreate($member = null, $context = array()) public function canCreate($member = null, $context = [])
{ {
if (!$member) { if (!$member) {
$member = Security::getCurrentUser(); $member = Security::getCurrentUser();
@ -1557,7 +1557,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$tablename = $this->baseTable(); $tablename = $this->baseTable();
$this->Sort = DB::prepared_query( $this->Sort = DB::prepared_query(
"SELECT MAX(\"Sort\") + 1 FROM \"$tablename\" WHERE \"ParentID\" = ?", "SELECT MAX(\"Sort\") + 1 FROM \"$tablename\" WHERE \"ParentID\" = ?",
array($parentID) [$parentID]
)->value(); )->value();
} }
@ -1565,7 +1565,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$defaultSegment = $this->generateURLSegment(_t( $defaultSegment = $this->generateURLSegment(_t(
'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE', 'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
'New {pagetype}', 'New {pagetype}',
array('pagetype' => $this->i18n_singular_name()) ['pagetype' => $this->i18n_singular_name()]
)); ));
if ((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) { if ((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) {
$this->URLSegment = $this->generateURLSegment($this->Title); $this->URLSegment = $this->generateURLSegment($this->Title);
@ -1597,7 +1597,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
} }
// Check to see if we've only altered fields that shouldn't affect versioning // Check to see if we've only altered fields that shouldn't affect versioning
$fieldsIgnoredByVersioning = array('HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount'); $fieldsIgnoredByVersioning = ['HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount'];
$changedFields = array_keys($this->getChangedFields(true, 2)); $changedFields = array_keys($this->getChangedFields(true, 2));
// This more rigorous check is inline with the test that write() does to decide whether or not to write to the // This more rigorous check is inline with the test that write() does to decide whether or not to write to the
@ -1682,7 +1682,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
_t( _t(
'SilverStripe\\CMS\\Model\\SiteTree.PageTypeNotAllowed', 'SilverStripe\\CMS\\Model\\SiteTree.PageTypeNotAllowed',
'Page type "{type}" not allowed as child of this parent page', 'Page type "{type}" not allowed as child of this parent page',
array('type' => $subject->i18n_singular_name()) ['type' => $subject->i18n_singular_name()]
), ),
ValidationResult::TYPE_ERROR, ValidationResult::TYPE_ERROR,
'ALLOWED_CHILDREN' 'ALLOWED_CHILDREN'
@ -1696,7 +1696,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
_t( _t(
'SilverStripe\\CMS\\Model\\SiteTree.PageTypNotAllowedOnRoot', 'SilverStripe\\CMS\\Model\\SiteTree.PageTypNotAllowedOnRoot',
'Page type "{type}" is not allowed on the root level', 'Page type "{type}" is not allowed on the root level',
array('type' => $this->i18n_singular_name()) ['type' => $this->i18n_singular_name()]
), ),
ValidationResult::TYPE_ERROR, ValidationResult::TYPE_ERROR,
'CAN_BE_ROOT' 'CAN_BE_ROOT'
@ -1888,10 +1888,10 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
} }
// Redirector pages // Redirector pages
$redirectors = RedirectorPage::get()->where(array( $redirectors = RedirectorPage::get()->where([
'"RedirectorPage"."RedirectionType"' => 'Internal', '"RedirectorPage"."RedirectionType"' => 'Internal',
'"RedirectorPage"."LinkToID"' => $this->ID '"RedirectorPage"."LinkToID"' => $this->ID
))->alterDataQuery(function ($query) { ])->alterDataQuery(function ($query) {
$query->selectField("'Redirector page'", "DependentLinkType"); $query->selectField("'Redirector page'", "DependentLinkType");
}); });
$items->merge($redirectors); $items->merge($redirectors);
@ -1937,7 +1937,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
if ($this->ID && is_numeric($this->ID)) { if ($this->ID && is_numeric($this->ID)) {
$linkedPages = $this->VirtualPages(); $linkedPages = $this->VirtualPages();
$parentPageLinks = array(); $parentPageLinks = [];
if ($linkedPages->count() > 0) { if ($linkedPages->count() > 0) {
/** @var VirtualPage $linkedPage */ /** @var VirtualPage $linkedPage */
@ -1964,7 +1964,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$statusMessage[] = _t( $statusMessage[] = _t(
'SilverStripe\\CMS\\Model\\SiteTree.APPEARSVIRTUALPAGES', 'SilverStripe\\CMS\\Model\\SiteTree.APPEARSVIRTUALPAGES',
"This content also appears on the virtual pages in the {title} sections.", "This content also appears on the virtual pages in the {title} sections.",
array('title' => $parentList) ['title' => $parentList]
); );
} }
} }
@ -1980,10 +1980,10 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$dependentPages = $this->DependentPages(); $dependentPages = $this->DependentPages();
$dependentPagesCount = $dependentPages->count(); $dependentPagesCount = $dependentPages->count();
if ($dependentPagesCount) { if ($dependentPagesCount) {
$dependentColumns = array( $dependentColumns = [
'Title' => $this->fieldLabel('Title'), 'Title' => $this->fieldLabel('Title'),
'DependentLinkType' => _t(__CLASS__.'.DependtPageColumnLinkType', 'Link type'), 'DependentLinkType' => _t(__CLASS__.'.DependtPageColumnLinkType', 'Link type'),
); ];
if (class_exists(Subsite::class)) { if (class_exists(Subsite::class)) {
$dependentColumns['Subsite.Title'] = Subsite::singleton()->i18n_singular_name(); $dependentColumns['Subsite.Title'] = Subsite::singleton()->i18n_singular_name();
} }
@ -1998,7 +1998,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$dataColumns = $dependentTable->getConfig()->getComponentByType(GridFieldDataColumns::class); $dataColumns = $dependentTable->getConfig()->getComponentByType(GridFieldDataColumns::class);
$dataColumns $dataColumns
->setDisplayFields($dependentColumns) ->setDisplayFields($dependentColumns)
->setFieldFormatting(array( ->setFieldFormatting([
'Title' => function ($value, &$item) { 'Title' => function ($value, &$item) {
$title = $item->Title; $title = $item->Title;
$untitled = _t( $untitled = _t(
@ -2016,7 +2016,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$tag $tag
); );
} }
)); ]);
$dependentTable->getConfig()->addComponent(new GridFieldLazyLoader()); $dependentTable->getConfig()->addComponent(new GridFieldLazyLoader());
} }
@ -2030,7 +2030,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
->setDefaultURL($this->generateURLSegment(_t( ->setDefaultURL($this->generateURLSegment(_t(
'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE', 'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
'New {pagetype}', 'New {pagetype}',
array('pagetype' => $this->i18n_singular_name()) ['pagetype' => $this->i18n_singular_name()]
))) )))
->addExtraClass(($this->isHomePage() ? 'homepage-warning' : '')); ->addExtraClass(($this->isHomePage() ? 'homepage-warning' : ''));
$helpText = (self::config()->get('nested_urls') && $this->numChildren()) $helpText = (self::config()->get('nested_urls') && $this->numChildren())
@ -2053,10 +2053,10 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
ToggleCompositeField::create( ToggleCompositeField::create(
'Metadata', 'Metadata',
_t(__CLASS__.'.MetadataToggle', 'Metadata'), _t(__CLASS__.'.MetadataToggle', 'Metadata'),
array( [
$metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')), $metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')),
$metaFieldExtra = new TextareaField("ExtraMeta", $this->fieldLabel('ExtraMeta')) $metaFieldExtra = new TextareaField("ExtraMeta", $this->fieldLabel('ExtraMeta'))
) ]
)->setHeadingLevel(4) )->setHeadingLevel(4)
), ),
$tabDependent = new Tab( $tabDependent = new Tab(
@ -2099,7 +2099,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$obsoleteWarning = _t( $obsoleteWarning = _t(
'SilverStripe\\CMS\\Model\\SiteTree.OBSOLETECLASS', 'SilverStripe\\CMS\\Model\\SiteTree.OBSOLETECLASS',
"This page is of obsolete type {type}. Saving will reset its type and you may lose data", "This page is of obsolete type {type}. Saving will reset its type and you may lose data",
array('type' => $this->ObsoleteClassName) ['type' => $this->ObsoleteClassName]
); );
$fields->addFieldToTab( $fields->addFieldToTab(
@ -2159,10 +2159,10 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$this->getClassDropdown() $this->getClassDropdown()
), ),
$parentTypeSelector = new CompositeField( $parentTypeSelector = new CompositeField(
$parentType = new OptionsetField("ParentType", _t("SilverStripe\\CMS\\Model\\SiteTree.PAGELOCATION", "Page location"), array( $parentType = new OptionsetField("ParentType", _t("SilverStripe\\CMS\\Model\\SiteTree.PAGELOCATION", "Page location"), [
"root" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_ROOT", "Top-level page"), "root" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_ROOT", "Top-level page"),
"subpage" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"), "subpage" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"),
)), ]),
$parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), self::class, 'ID', 'MenuTitle') $parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), self::class, 'ID', 'MenuTitle')
), ),
$visibility = new FieldGroup( $visibility = new FieldGroup(
@ -2361,10 +2361,10 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$moreOptions->push( $moreOptions->push(
new LiteralField( new LiteralField(
'Information', 'Information',
$this->customise(array( $this->customise([
'Live' => $liveRecord, 'Live' => $liveRecord,
'ExistsOnLive' => $isPublished 'ExistsOnLive' => $isPublished
))->renderWith($infoTemplate) ])->renderWith($infoTemplate)
) )
); );
@ -2375,7 +2375,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
if ($stageRecord && $stageRecord->Version != $this->Version) { if ($stageRecord && $stageRecord->Version != $this->Version) {
$moreOptions->push(FormAction::create('email', _t('SilverStripe\\CMS\\Controllers\\CMSMain.EMAIL', 'Email'))); $moreOptions->push(FormAction::create('email', _t('SilverStripe\\CMS\\Controllers\\CMSMain.EMAIL', 'Email')));
$moreOptions->push(FormAction::create('rollback', _t('SilverStripe\\CMS\\Controllers\\CMSMain.ROLLBACK', 'Roll back to this version'))); $moreOptions->push(FormAction::create('rollback', _t('SilverStripe\\CMS\\Controllers\\CMSMain.ROLLBACK', 'Roll back to this version')));
$actions = new FieldList(array($majorActions, $rootTabSet)); $actions = new FieldList([$majorActions, $rootTabSet]);
// getCMSActions() can be extended with updateCMSActions() on a extension // getCMSActions() can be extended with updateCMSActions() on a extension
$this->extend('updateCMSActions', $actions); $this->extend('updateCMSActions', $actions);
@ -2481,7 +2481,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
} }
} }
$actions = new FieldList(array($majorActions, $rootTabSet)); $actions = new FieldList([$majorActions, $rootTabSet]);
// Hook for extensions to add/remove actions. // Hook for extensions to add/remove actions.
$this->extend('updateCMSActions', $actions); $this->extend('updateCMSActions', $actions);
@ -2599,7 +2599,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$classes = self::page_type_classes(); $classes = self::page_type_classes();
$currentClass = null; $currentClass = null;
$result = array(); $result = [];
foreach ($classes as $class) { foreach ($classes as $class) {
$instance = singleton($class); $instance = singleton($class);
@ -2613,7 +2613,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
if ($instance instanceof HiddenClass) { if ($instance instanceof HiddenClass) {
continue; continue;
} }
if (!$instance->canCreate(null, array('Parent' => $this->ParentID ? $this->Parent() : null))) { if (!$instance->canCreate(null, ['Parent' => $this->ParentID ? $this->Parent() : null])) {
continue; continue;
} }
} }
@ -2829,7 +2829,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
* "deletedonlive" => "Deleted" * "deletedonlive" => "Deleted"
* *
* Example (with optional title attribute): * Example (with optional title attribute):
* "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted') * "deletedonlive" => ['text' => "Deleted", 'title' => 'This page has been deleted']
* *
* @param bool $cached Whether to serve the fields from cache; false regenerate them * @param bool $cached Whether to serve the fields from cache; false regenerate them
* @return array * @return array
@ -2837,27 +2837,27 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
public function getStatusFlags($cached = true) public function getStatusFlags($cached = true)
{ {
if (!$this->_cache_statusFlags || !$cached) { if (!$this->_cache_statusFlags || !$cached) {
$flags = array(); $flags = [];
if ($this->isOnLiveOnly()) { if ($this->isOnLiveOnly()) {
$flags['removedfromdraft'] = array( $flags['removedfromdraft'] = [
'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'), 'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'),
'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Page is published, but has been deleted from draft'), 'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Page is published, but has been deleted from draft'),
); ];
} elseif ($this->isArchived()) { } elseif ($this->isArchived()) {
$flags['archived'] = array( $flags['archived'] = [
'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'), 'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'),
'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'), 'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'),
); ];
} elseif ($this->isOnDraftOnly()) { } elseif ($this->isOnDraftOnly()) {
$flags['addedtodraft'] = array( $flags['addedtodraft'] = [
'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'), 'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'),
'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Page has not been published yet") 'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Page has not been published yet")
); ];
} elseif ($this->isModifiedOnDraft()) { } elseif ($this->isModifiedOnDraft()) {
$flags['modified'] = array( $flags['modified'] = [
'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'), 'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'),
'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'), 'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'),
); ];
} }
$this->extend('updateStatusFlags', $flags); $this->extend('updateStatusFlags', $flags);
@ -2898,11 +2898,11 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
Convert::raw2htmlid(static::class), Convert::raw2htmlid(static::class),
$this->isHomePage() ? ' homepage' : '', $this->isHomePage() ? ' homepage' : '',
Convert::raw2att(json_encode($children)), Convert::raw2att(json_encode($children)),
Convert::raw2xml(str_replace(array("\n","\r"), "", $this->MenuTitle)) Convert::raw2xml(str_replace(["\n","\r"], "", $this->MenuTitle))
); );
foreach ($flags as $class => $data) { foreach ($flags as $class => $data) {
if (is_string($data)) { if (is_string($data)) {
$data = array('text' => $data); $data = ['text' => $data];
} }
$treeTitle .= sprintf( $treeTitle .= sprintf(
"<span class=\"badge %s\"%s>%s</span>", "<span class=\"badge %s\"%s>%s</span>",
@ -2925,7 +2925,7 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
public function Level($level) public function Level($level)
{ {
$parent = $this; $parent = $this;
$stack = array($parent); $stack = [$parent];
while (($parent = $parent->Parent()) && $parent->exists()) { while (($parent = $parent->Parent()) && $parent->exists()) {
array_unshift($stack, $parent); array_unshift($stack, $parent);
} }
@ -3039,38 +3039,38 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
public function providePermissions() public function providePermissions()
{ {
return array( return [
'SITETREE_GRANT_ACCESS' => array( 'SITETREE_GRANT_ACCESS' => [
'name' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'), 'name' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'),
'help' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_HELP', 'Allow setting of page-specific access restrictions in the "Pages" section.'), 'help' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_HELP', 'Allow setting of page-specific access restrictions in the "Pages" section.'),
'category' => _t('SilverStripe\\Security\\Permission.PERMISSIONS_CATEGORY', 'Roles and access permissions'), 'category' => _t('SilverStripe\\Security\\Permission.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
'sort' => 100 'sort' => 100
), ],
'SITETREE_VIEW_ALL' => array( 'SITETREE_VIEW_ALL' => [
'name' => _t(__CLASS__.'.VIEW_ALL_DESCRIPTION', 'View any page'), 'name' => _t(__CLASS__.'.VIEW_ALL_DESCRIPTION', 'View any page'),
'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'), 'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
'sort' => -100, 'sort' => -100,
'help' => _t(__CLASS__.'.VIEW_ALL_HELP', 'Ability to view any page on the site, regardless of the settings on the Access tab. Requires the "Access to \'Pages\' section" permission') 'help' => _t(__CLASS__.'.VIEW_ALL_HELP', 'Ability to view any page on the site, regardless of the settings on the Access tab. Requires the "Access to \'Pages\' section" permission')
), ],
'SITETREE_EDIT_ALL' => array( 'SITETREE_EDIT_ALL' => [
'name' => _t(__CLASS__.'.EDIT_ALL_DESCRIPTION', 'Edit any page'), 'name' => _t(__CLASS__.'.EDIT_ALL_DESCRIPTION', 'Edit any page'),
'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'), 'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
'sort' => -50, 'sort' => -50,
'help' => _t(__CLASS__.'.EDIT_ALL_HELP', 'Ability to edit any page on the site, regardless of the settings on the Access tab. Requires the "Access to \'Pages\' section" permission') 'help' => _t(__CLASS__.'.EDIT_ALL_HELP', 'Ability to edit any page on the site, regardless of the settings on the Access tab. Requires the "Access to \'Pages\' section" permission')
), ],
'SITETREE_REORGANISE' => array( 'SITETREE_REORGANISE' => [
'name' => _t(__CLASS__.'.REORGANISE_DESCRIPTION', 'Change site structure'), 'name' => _t(__CLASS__.'.REORGANISE_DESCRIPTION', 'Change site structure'),
'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'), 'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
'help' => _t(__CLASS__.'.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'), 'help' => _t(__CLASS__.'.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'),
'sort' => 100 'sort' => 100
), ],
'VIEW_DRAFT_CONTENT' => array( 'VIEW_DRAFT_CONTENT' => [
'name' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT', 'View draft content'), 'name' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT', 'View draft content'),
'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'), 'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
'help' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT_HELP', 'Applies to viewing pages outside of the CMS in draft mode. Useful for external collaborators without CMS access.'), 'help' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT_HELP', 'Applies to viewing pages outside of the CMS in draft mode. Useful for external collaborators without CMS access.'),
'sort' => 100 'sort' => 100
) ]
); ];
} }
/** /**

View File

@ -26,7 +26,7 @@ class SiteTreeLinkTracking_Parser
*/ */
public function process(HTMLValue $htmlValue) public function process(HTMLValue $htmlValue)
{ {
$results = array(); $results = [];
$links = $htmlValue->getElementsByTagName('a'); $links = $htmlValue->getElementsByTagName('a');
if (!$links) { if (!$links) {
@ -46,19 +46,19 @@ class SiteTreeLinkTracking_Parser
// Definitely broken links. // Definitely broken links.
if ($href == '' || $href[0] == '/') { if ($href == '' || $href[0] == '/') {
$results[] = array( $results[] = [
'Type' => 'broken', 'Type' => 'broken',
'Target' => null, 'Target' => null,
'Anchor' => null, 'Anchor' => null,
'DOMReference' => $link, 'DOMReference' => $link,
'Broken' => true 'Broken' => true
); ];
continue; continue;
} }
// Link to a page on this site. // Link to a page on this site.
$matches = array(); $matches = [];
if (preg_match('/\[sitetree_link(?:\s*|%20|,)?id=(?<id>[0-9]+)\](#(?<anchor>.*))?/i', $href, $matches)) { if (preg_match('/\[sitetree_link(?:\s*|%20|,)?id=(?<id>[0-9]+)\](#(?<anchor>.*))?/i', $href, $matches)) {
// Check if page link is broken // Check if page link is broken
/** @var SiteTree $page */ /** @var SiteTree $page */
@ -74,13 +74,13 @@ class SiteTreeLinkTracking_Parser
$broken = false; $broken = false;
} }
$results[] = array( $results[] = [
'Type' => 'sitetree', 'Type' => 'sitetree',
'Target' => $matches['id'], 'Target' => $matches['id'],
'Anchor' => empty($matches['anchor']) ? null : $matches['anchor'], 'Anchor' => empty($matches['anchor']) ? null : $matches['anchor'],
'DOMReference' => $link, 'DOMReference' => $link,
'Broken' => $broken 'Broken' => $broken
); ];
continue; continue;
} }
@ -88,13 +88,13 @@ class SiteTreeLinkTracking_Parser
// Local anchor. // Local anchor.
if (preg_match('/^#(.*)/i', $href, $matches)) { if (preg_match('/^#(.*)/i', $href, $matches)) {
$anchor = preg_quote($matches[1], '#'); $anchor = preg_quote($matches[1], '#');
$results[] = array( $results[] = [
'Type' => 'localanchor', 'Type' => 'localanchor',
'Target' => null, 'Target' => null,
'Anchor' => $matches[1], 'Anchor' => $matches[1],
'DOMReference' => $link, 'DOMReference' => $link,
'Broken' => !preg_match("#(name|id)=\"{$anchor}\"#", $htmlValue->getContent()) 'Broken' => !preg_match("#(name|id)=\"{$anchor}\"#", $htmlValue->getContent())
); ];
continue; continue;
} }

View File

@ -37,7 +37,7 @@ class VirtualPage extends Page
* @var array Define fields that are not virtual - the virtual page must define these fields themselves. * @var array Define fields that are not virtual - the virtual page must define these fields themselves.
* Note that anything in {@link self::config()->initially_copied_fields} is implicitly included in this list. * Note that anything in {@link self::config()->initially_copied_fields} is implicitly included in this list.
*/ */
private static $non_virtual_fields = array( private static $non_virtual_fields = [
"ID", "ID",
"ClassName", "ClassName",
"ObsoleteClassName", "ObsoleteClassName",
@ -57,28 +57,28 @@ class VirtualPage extends Page
"CanEditType", "CanEditType",
"CopyContentFromID", "CopyContentFromID",
"HasBrokenLink", "HasBrokenLink",
); ];
/** /**
* @var array Define fields that are initially copied to virtual pages but left modifiable after that. * @var array Define fields that are initially copied to virtual pages but left modifiable after that.
*/ */
private static $initially_copied_fields = array( private static $initially_copied_fields = [
'ShowInMenus', 'ShowInMenus',
'ShowInSearch', 'ShowInSearch',
'URLSegment', 'URLSegment',
); ];
private static $has_one = array( private static $has_one = [
"CopyContentFrom" => SiteTree::class, "CopyContentFrom" => SiteTree::class,
); ];
private static $owns = array( private static $owns = [
"CopyContentFrom", "CopyContentFrom",
); ];
private static $db = array( private static $db = [
"VersionID" => "Int", "VersionID" => "Int",
); ];
private static $table_name = 'VirtualPage'; private static $table_name = 'VirtualPage';
@ -92,7 +92,7 @@ class VirtualPage extends Page
// Check if copied page exists // Check if copied page exists
$record = $this->CopyContentFrom(); $record = $this->CopyContentFrom();
if (!$record || !$record->exists()) { if (!$record || !$record->exists()) {
return array(); return [];
} }
// Diff db with non-virtual fields // Diff db with non-virtual fields
@ -160,7 +160,7 @@ class VirtualPage extends Page
if ($copy && $copy->exists()) { if ($copy && $copy->exists()) {
return $copy->allowedChildren(); return $copy->allowedChildren();
} }
return array(); return [];
} }
public function syncLinkTracking() public function syncLinkTracking()
@ -237,7 +237,7 @@ class VirtualPage extends Page
} }
} }
$msgs = array(); $msgs = [];
$fields->addFieldToTab('Root.Main', $copyContentFromField, 'Title'); $fields->addFieldToTab('Root.Main', $copyContentFromField, 'Title');
@ -350,7 +350,7 @@ class VirtualPage extends Page
_t( _t(
self::class . '.PageTypNotAllowedOnRoot', self::class . '.PageTypNotAllowedOnRoot',
'Original page type "{type}" is not allowed on the root level for this virtual page', 'Original page type "{type}" is not allowed on the root level for this virtual page',
array('type' => $orig->i18n_singular_name()) ['type' => $orig->i18n_singular_name()]
), ),
ValidationResult::TYPE_ERROR, ValidationResult::TYPE_ERROR,
'CAN_BE_ROOT_VIRTUAL' 'CAN_BE_ROOT_VIRTUAL'
@ -474,7 +474,7 @@ class VirtualPage extends Page
if (parent::hasMethod($method)) { if (parent::hasMethod($method)) {
return parent::__call($method, $args); return parent::__call($method, $args);
} else { } else {
return call_user_func_array(array($this->CopyContentFrom(), $method), $args); return call_user_func_array([$this->CopyContentFrom(), $method], $args);
} }
} }

View File

@ -34,9 +34,9 @@ class BrokenFilesReport extends Report
ClassInfo::subclassesFor(RedirectorPage::class) ClassInfo::subclassesFor(RedirectorPage::class)
); );
$classParams = DB::placeholders($classes); $classParams = DB::placeholders($classes);
$classFilter = array( $classFilter = [
"\"ClassName\" IN ($classParams) AND \"HasBrokenFile\" = 1" => $classes "\"ClassName\" IN ($classParams) AND \"HasBrokenFile\" = 1" => $classes
); ];
$stage = isset($params['OnLive']) ? Versioned::LIVE : Versioned::DRAFT; $stage = isset($params['OnLive']) ? Versioned::LIVE : Versioned::DRAFT;
return Versioned::get_by_stage(SiteTree::class, $stage, $classFilter); return Versioned::get_by_stage(SiteTree::class, $stage, $classFilter);
@ -44,12 +44,12 @@ class BrokenFilesReport extends Report
public function columns() public function columns()
{ {
return array( return [
"Title" => array( "Title" => [
"title" => "Title", // todo: use NestedTitle(2) "title" => "Title", // todo: use NestedTitle(2)
"link" => true, "link" => true,
), ],
); ];
} }
public function getParameterFields() public function getParameterFields()

View File

@ -157,10 +157,10 @@ class BrokenLinksReport extends Report
public function parameterFields() public function parameterFields()
{ {
return FieldList::create( return FieldList::create(
DropdownField::create('CheckSite', _t(__CLASS__ . '.CheckSite', 'Check site'), array( DropdownField::create('CheckSite', _t(__CLASS__ . '.CheckSite', 'Check site'), [
'Published' => _t(__CLASS__ . '.CheckSiteDropdownPublished', 'Published Site'), 'Published' => _t(__CLASS__ . '.CheckSiteDropdownPublished', 'Published Site'),
'Draft' => _t(__CLASS__ . '.CheckSiteDropdownDraft', 'Draft Site') 'Draft' => _t(__CLASS__ . '.CheckSiteDropdownDraft', 'Draft Site')
)), ]),
DropdownField::create( DropdownField::create(
'Reason', 'Reason',
_t(__CLASS__ . '.ReasonDropdown', 'Problem to check'), _t(__CLASS__ . '.ReasonDropdown', 'Problem to check'),

View File

@ -28,21 +28,21 @@ class BrokenRedirectorPagesReport extends Report
{ {
$classes = ClassInfo::subclassesFor(RedirectorPage::class); $classes = ClassInfo::subclassesFor(RedirectorPage::class);
$classParams = DB::placeholders($classes); $classParams = DB::placeholders($classes);
$classFilter = array( $classFilter = [
"\"ClassName\" IN ($classParams) AND \"HasBrokenLink\" = 1" => $classes "\"ClassName\" IN ($classParams) AND \"HasBrokenLink\" = 1" => $classes
); ];
$stage = isset($params['OnLive']) ? 'Live' : 'Stage'; $stage = isset($params['OnLive']) ? 'Live' : 'Stage';
return Versioned::get_by_stage(SiteTree::class, $stage, $classFilter); return Versioned::get_by_stage(SiteTree::class, $stage, $classFilter);
} }
public function columns() public function columns()
{ {
return array( return [
"Title" => array( "Title" => [
"title" => "Title", // todo: use NestedTitle(2) "title" => "Title", // todo: use NestedTitle(2)
"link" => true, "link" => true,
), ],
); ];
} }
public function getParameterFields() public function getParameterFields()

View File

@ -28,21 +28,21 @@ class BrokenVirtualPagesReport extends Report
{ {
$classes = ClassInfo::subclassesFor(VirtualPage::class); $classes = ClassInfo::subclassesFor(VirtualPage::class);
$classParams = DB::placeholders($classes); $classParams = DB::placeholders($classes);
$classFilter = array( $classFilter = [
"\"ClassName\" IN ($classParams) AND \"HasBrokenLink\" = 1" => $classes "\"ClassName\" IN ($classParams) AND \"HasBrokenLink\" = 1" => $classes
); ];
$stage = isset($params['OnLive']) ? 'Live' : 'Stage'; $stage = isset($params['OnLive']) ? 'Live' : 'Stage';
return Versioned::get_by_stage(SiteTree::class, $stage, $classFilter); return Versioned::get_by_stage(SiteTree::class, $stage, $classFilter);
} }
public function columns() public function columns()
{ {
return array( return [
"Title" => array( "Title" => [
"title" => "Title", // todo: use NestedTitle(2) "title" => "Title", // todo: use NestedTitle(2)
"link" => true, "link" => true,
), ],
); ];
} }
public function getParameterFields() public function getParameterFields()

View File

@ -41,11 +41,11 @@ class EmptyPagesReport extends Report
public function columns() public function columns()
{ {
return array( return [
"Title" => array( "Title" => [
"title" => "Title", // todo: use NestedTitle(2) "title" => "Title", // todo: use NestedTitle(2)
"link" => true, "link" => true,
), ],
); ];
} }
} }

View File

@ -36,11 +36,11 @@ class RecentlyEditedReport extends Report
public function columns() public function columns()
{ {
return array( return [
"Title" => array( "Title" => [
"title" => "Title", // todo: use NestedTitle(2) "title" => "Title", // todo: use NestedTitle(2)
"link" => true, "link" => true,
), ],
); ];
} }
} }

View File

@ -15,9 +15,9 @@ use SilverStripe\ORM\Search\FulltextSearchable;
*/ */
class ContentControllerSearchExtension extends Extension class ContentControllerSearchExtension extends Extension
{ {
private static $allowed_actions = array( private static $allowed_actions = [
'SearchForm', 'SearchForm',
); ];
/** /**
* Site search form * Site search form
@ -54,11 +54,11 @@ class ContentControllerSearchExtension extends Extension
*/ */
public function results($data, $form, $request) public function results($data, $form, $request)
{ {
$data = array( $data = [
'Results' => $form->getResults(), 'Results' => $form->getResults(),
'Query' => DBField::create_field('Text', $form->getSearchQuery()), 'Query' => DBField::create_field('Text', $form->getSearchQuery()),
'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results') 'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results')
); ];
return $this->owner->customise($data)->renderWith(array('Page_results', 'Page')); return $this->owner->customise($data)->renderWith(['Page_results', 'Page']);
} }
} }

View File

@ -41,14 +41,14 @@ class SearchForm extends Form
* *
* @var array * @var array
*/ */
protected $classesToSearch = array( protected $classesToSearch = [
SiteTree::class, SiteTree::class,
File::class File::class
); ];
private static $casting = array( private static $casting = [
'SearchQuery' => 'Text' 'SearchQuery' => 'Text'
); ];
/** /**
* @skipUpgrade * @skipUpgrade
@ -97,7 +97,7 @@ class SearchForm extends Form
*/ */
public function classesToSearch($classes) public function classesToSearch($classes)
{ {
$supportedClasses = array(SiteTree::class, File::class); $supportedClasses = [SiteTree::class, File::class];
$illegalClasses = array_diff($classes, $supportedClasses); $illegalClasses = array_diff($classes, $supportedClasses);
if ($illegalClasses) { if ($illegalClasses) {
throw new BadMethodCallException( throw new BadMethodCallException(

View File

@ -40,12 +40,12 @@ use SilverStripe\View\Requirements;
class RemoveOrphanedPagesTask extends Controller class RemoveOrphanedPagesTask extends Controller
{ {
private static $allowed_actions = array( private static $allowed_actions = [
'index' => 'ADMIN', 'index' => 'ADMIN',
'Form' => 'ADMIN', 'Form' => 'ADMIN',
'run' => 'ADMIN', 'run' => 'ADMIN',
'handleAction' => 'ADMIN', 'handleAction' => 'ADMIN',
); ];
protected $title = 'Removed orphaned pages without existing parents from both stage and live'; protected $title = 'Removed orphaned pages without existing parents from both stage and live';
@ -92,7 +92,7 @@ in the other stage:<br />
public function Form() public function Form()
{ {
$fields = new FieldList(); $fields = new FieldList();
$source = array(); $source = [];
$fields->push(new HeaderField( $fields->push(new HeaderField(
'Header', 'Header',
@ -113,7 +113,7 @@ in the other stage:<br />
$liveRecord = Versioned::get_one_by_stage( $liveRecord = Versioned::get_one_by_stage(
$this->orphanedSearchClass, $this->orphanedSearchClass,
'Live', 'Live',
array("\"$orphanBaseTable\".\"ID\"" => $orphan->ID) ["\"$orphanBaseTable\".\"ID\"" => $orphan->ID]
); );
$label = sprintf( $label = sprintf(
'<a href="admin/pages/edit/show/%d">%s</a> <small>(#%d, Last Modified Date: %s, Last Modifier: %s, %s)</small>', '<a href="admin/pages/edit/show/%d">%s</a> <small>(#%d, Last Modified Date: %s, Last Modifier: %s, %s)</small>',
@ -147,7 +147,7 @@ in the other stage:<br />
$fields->push(new OptionsetField( $fields->push(new OptionsetField(
'OrphanOperation', 'OrphanOperation',
_t('SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.CHOOSEOPERATION', 'Choose operation:'), _t('SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.CHOOSEOPERATION', 'Choose operation:'),
array( [
'rebase' => _t( 'rebase' => _t(
'SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.OPERATION_REBASE', 'SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.OPERATION_REBASE',
sprintf( sprintf(
@ -156,7 +156,7 @@ in the other stage:<br />
) )
), ),
'remove' => _t('SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.OPERATION_REMOVE', 'Remove selected from all stages (WARNING: Will destroy all selected pages from both stage and live)'), 'remove' => _t('SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.OPERATION_REMOVE', 'Remove selected from all stages (WARNING: Will destroy all selected pages from both stage and live)'),
), ],
'rebase' 'rebase'
)); ));
$fields->push(new LiteralField( $fields->push(new LiteralField(
@ -231,22 +231,22 @@ in the other stage:<br />
$content = _t('SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.NONEREMOVED', 'None removed'); $content = _t('SilverStripe\\CMS\\Tasks\\RemoveOrphanedPagesTask.NONEREMOVED', 'None removed');
} }
return $this->customise(array( return $this->customise([
'Content' => $content, 'Content' => $content,
'Form' => ' ' 'Form' => ' '
))->renderWith('BlankPage'); ])->renderWith('BlankPage');
} }
protected function removeOrphans($orphanIDs) protected function removeOrphans($orphanIDs)
{ {
$removedOrphans = array(); $removedOrphans = [];
$orphanBaseTable = DataObject::getSchema()->baseDataTable($this->orphanedSearchClass); $orphanBaseTable = DataObject::getSchema()->baseDataTable($this->orphanedSearchClass);
foreach ($orphanIDs as $id) { foreach ($orphanIDs as $id) {
/** @var SiteTree $stageRecord */ /** @var SiteTree $stageRecord */
$stageRecord = Versioned::get_one_by_stage( $stageRecord = Versioned::get_one_by_stage(
$this->orphanedSearchClass, $this->orphanedSearchClass,
Versioned::DRAFT, Versioned::DRAFT,
array("\"$orphanBaseTable\".\"ID\"" => $id) ["\"$orphanBaseTable\".\"ID\"" => $id]
); );
if ($stageRecord) { if ($stageRecord) {
$removedOrphans[$stageRecord->ID] = sprintf('Removed %s (#%d) from Stage', $stageRecord->Title, $stageRecord->ID); $removedOrphans[$stageRecord->ID] = sprintf('Removed %s (#%d) from Stage', $stageRecord->Title, $stageRecord->ID);
@ -258,7 +258,7 @@ in the other stage:<br />
$liveRecord = Versioned::get_one_by_stage( $liveRecord = Versioned::get_one_by_stage(
$this->orphanedSearchClass, $this->orphanedSearchClass,
Versioned::LIVE, Versioned::LIVE,
array("\"$orphanBaseTable\".\"ID\"" => $id) ["\"$orphanBaseTable\".\"ID\"" => $id]
); );
if ($liveRecord) { if ($liveRecord) {
$removedOrphans[$liveRecord->ID] = sprintf('Removed %s (#%d) from Live', $liveRecord->Title, $liveRecord->ID); $removedOrphans[$liveRecord->ID] = sprintf('Removed %s (#%d) from Live', $liveRecord->Title, $liveRecord->ID);
@ -285,14 +285,14 @@ in the other stage:<br />
$holder->Title = $this->rebaseHolderTitle(); $holder->Title = $this->rebaseHolderTitle();
$holder->write(); $holder->write();
$removedOrphans = array(); $removedOrphans = [];
$orphanBaseTable = DataObject::getSchema()->baseDataTable($this->orphanedSearchClass); $orphanBaseTable = DataObject::getSchema()->baseDataTable($this->orphanedSearchClass);
foreach ($orphanIDs as $id) { foreach ($orphanIDs as $id) {
/** @var SiteTree $stageRecord */ /** @var SiteTree $stageRecord */
$stageRecord = Versioned::get_one_by_stage( $stageRecord = Versioned::get_one_by_stage(
$this->orphanedSearchClass, $this->orphanedSearchClass,
'Stage', 'Stage',
array("\"$orphanBaseTable\".\"ID\"" => $id) ["\"$orphanBaseTable\".\"ID\"" => $id]
); );
if ($stageRecord) { if ($stageRecord) {
$removedOrphans[$stageRecord->ID] = sprintf('Rebased %s (#%d)', $stageRecord->Title, $stageRecord->ID); $removedOrphans[$stageRecord->ID] = sprintf('Rebased %s (#%d)', $stageRecord->Title, $stageRecord->ID);
@ -308,7 +308,7 @@ in the other stage:<br />
$liveRecord = Versioned::get_one_by_stage( $liveRecord = Versioned::get_one_by_stage(
$this->orphanedSearchClass, $this->orphanedSearchClass,
'Live', 'Live',
array("\"$orphanBaseTable\".\"ID\"" => $id) ["\"$orphanBaseTable\".\"ID\"" => $id]
); );
if ($liveRecord) { if ($liveRecord) {
$removedOrphans[$liveRecord->ID] = sprintf('Rebased %s (#%d)', $liveRecord->Title, $liveRecord->ID); $removedOrphans[$liveRecord->ID] = sprintf('Rebased %s (#%d)', $liveRecord->Title, $liveRecord->ID);
@ -341,22 +341,22 @@ in the other stage:<br />
* @param int|array $limit * @param int|array $limit
* @return SS_List * @return SS_List
*/ */
public function getOrphanedPages($class = SiteTree::class, $filter = array(), $sort = null, $join = null, $limit = null) public function getOrphanedPages($class = SiteTree::class, $filter = [], $sort = null, $join = null, $limit = null)
{ {
// Alter condition // Alter condition
$table = DataObject::getSchema()->tableName($class); $table = DataObject::getSchema()->tableName($class);
if (empty($filter)) { if (empty($filter)) {
$where = array(); $where = [];
} elseif (is_array($filter)) { } elseif (is_array($filter)) {
$where = $filter; $where = $filter;
} else { } else {
$where = array($filter); $where = [$filter];
} }
$where[] = array("\"{$table}\".\"ParentID\" != ?" => 0); $where[] = ["\"{$table}\".\"ParentID\" != ?" => 0];
$where[] = '"Parents"."ID" IS NULL'; $where[] = '"Parents"."ID" IS NULL';
$orphans = new ArrayList(); $orphans = new ArrayList();
foreach (array(Versioned::DRAFT, Versioned::LIVE) as $stage) { foreach ([Versioned::DRAFT, Versioned::LIVE] as $stage) {
$table .= ($stage == Versioned::LIVE) ? '_Live' : ''; $table .= ($stage == Versioned::LIVE) ? '_Live' : '';
$stageOrphans = Versioned::get_by_stage( $stageOrphans = Versioned::get_by_stage(
$class, $class,

View File

@ -9,9 +9,9 @@ use SilverStripe\ORM\DataObject;
class SiteTreeMaintenanceTask extends Controller class SiteTreeMaintenanceTask extends Controller
{ {
private static $allowed_actions = array( private static $allowed_actions = [
'*' => 'ADMIN' '*' => 'ADMIN'
); ];
public function makelinksunique() public function makelinksunique()
{ {
@ -27,13 +27,13 @@ class SiteTreeMaintenanceTask extends Controller
echo _t( echo _t(
'SilverStripe\\CMS\\Model\\SiteTree.LINKSCHANGEDTO', 'SilverStripe\\CMS\\Model\\SiteTree.LINKSCHANGEDTO',
" changed {url1} -> {url2}", " changed {url1} -> {url2}",
array('url1' => $urlSegment, 'url2' => $page->URLSegment) ['url1' => $urlSegment, 'url2' => $page->URLSegment]
); );
} else { } else {
echo _t( echo _t(
'SilverStripe\\CMS\\Model\\SiteTree.LINKSALREADYUNIQUE', 'SilverStripe\\CMS\\Model\\SiteTree.LINKSALREADYUNIQUE',
" {url} is already unique", " {url} is already unique",
array('url' => $urlSegment) ['url' => $urlSegment]
); );
} }
die(); die();

View File

@ -10,5 +10,8 @@
<exclude name="Squiz.Classes.ValidClassName.NotCamelCaps" /> <exclude name="Squiz.Classes.ValidClassName.NotCamelCaps" />
<exclude name="Generic.Files.LineLength.TooLong" /> <exclude name="Generic.Files.LineLength.TooLong" />
</rule> </rule>
<!-- use short array syntax -->
<rule ref="Generic.Arrays.DisallowLongArraySyntax" />
</ruleset> </ruleset>

View File

@ -52,7 +52,7 @@ class FixtureContext extends BehatFixtureContext
$targetObj = $this->fixtureFactory->get($targetClass, $targetId); $targetObj = $this->fixtureFactory->get($targetClass, $targetId);
} }
$fields = array('LinkToID' => $targetObj->ID); $fields = ['LinkToID' => $targetObj->ID];
/** @var RedirectorPage $obj */ /** @var RedirectorPage $obj */
$obj = $this->fixtureFactory->get($class, $id); $obj = $this->fixtureFactory->get($class, $id);
if ($obj) { if ($obj) {

View File

@ -12,8 +12,8 @@ class ThemeContext implements Context
{ {
use MainContextAwareTrait; use MainContextAwareTrait;
protected $restoreFiles = array(); protected $restoreFiles = [];
protected $restoreDirectories = array(); protected $restoreDirectories = [];
/** /**
* Create a test theme * Create a test theme
@ -98,7 +98,7 @@ class ThemeContext implements Context
} }
} }
$this->restoreFiles = array(); $this->restoreFiles = [];
} }
// Restore any created directories: that is, delete them // Restore any created directories: that is, delete them
@ -109,7 +109,7 @@ class ThemeContext implements Context
rmdir($dir); rmdir($dir);
} }
$this->restoreDirectories = array(); $this->restoreDirectories = [];
} }
} }
} }

View File

@ -144,9 +144,9 @@ class CMSBatchActionsTest extends SapphireTest
// Run restore // Run restore
$result = json_decode($action->run($list), true); $result = json_decode($action->run($list), true);
$this->assertEquals( $this->assertEquals(
array( [
$archivedxID => $archivedxID $archivedxID => $archivedxID
), ],
$result['success'] $result['success']
); );
$archivedx = SiteTree::get()->byID($archivedxID); $archivedx = SiteTree::get()->byID($archivedxID);
@ -164,12 +164,12 @@ class CMSBatchActionsTest extends SapphireTest
// Run restore // Run restore
$result = json_decode($action->run($list), true); $result = json_decode($action->run($list), true);
$this->assertEquals( $this->assertEquals(
array( [
// Order of archived is opposite to order items are passed in, as // Order of archived is opposite to order items are passed in, as
// these are sorted by level first // these are sorted by level first
$archivedID => $archivedID, $archivedID => $archivedID,
$archivedyID => $archivedyID $archivedyID => $archivedyID
), ],
$result['success'] $result['success']
); );
$archived = SiteTree::get()->byID($archivedID); $archived = SiteTree::get()->byID($archivedID);

View File

@ -30,7 +30,7 @@ class CMSMainTest extends FunctionalTest
{ {
protected static $fixture_file = 'CMSMainTest.yml'; protected static $fixture_file = 'CMSMainTest.yml';
protected static $orig = array(); protected static $orig = [];
public function setUp() public function setUp()
{ {
@ -136,7 +136,7 @@ class CMSMainTest extends FunctionalTest
// Some modules (e.g., cmsworkflow) will remove this action // Some modules (e.g., cmsworkflow) will remove this action
$actions = CMSBatchActionHandler::config()->batch_actions; $actions = CMSBatchActionHandler::config()->batch_actions;
if (isset($actions['publish'])) { if (isset($actions['publish'])) {
$response = $this->get('admin/pages/batchactions/publish?ajax=1&csvIDs=' . implode(',', array($page1->ID, $page2->ID))); $response = $this->get('admin/pages/batchactions/publish?ajax=1&csvIDs=' . implode(',', [$page1->ID, $page2->ID]));
$responseData = json_decode($response->getBody(), true); $responseData = json_decode($response->getBody(), true);
$this->assertArrayHasKey($page1->ID, $responseData['modified']); $this->assertArrayHasKey($page1->ID, $responseData['modified']);
$this->assertArrayHasKey($page2->ID, $responseData['modified']); $this->assertArrayHasKey($page2->ID, $responseData['modified']);
@ -144,8 +144,8 @@ class CMSMainTest extends FunctionalTest
// Get the latest version of the redirector page // Get the latest version of the redirector page
$pageID = $this->idFromFixture(RedirectorPage::class, 'page5'); $pageID = $this->idFromFixture(RedirectorPage::class, 'page5');
$latestID = DB::prepared_query('select max("Version") from "RedirectorPage_Versions" where "RecordID" = ?', array($pageID))->value(); $latestID = DB::prepared_query('select max("Version") from "RedirectorPage_Versions" where "RecordID" = ?', [$pageID])->value();
$dsCount = DB::prepared_query('select count("Version") from "RedirectorPage_Versions" where "RecordID" = ? and "Version"= ?', array($pageID, $latestID))->value(); $dsCount = DB::prepared_query('select count("Version") from "RedirectorPage_Versions" where "RecordID" = ? and "Version"= ?', [$pageID, $latestID])->value();
$this->assertEquals(1, $dsCount, "Published page has no duplicate version records: it has " . $dsCount . " for version " . $latestID); $this->assertEquals(1, $dsCount, "Published page has no duplicate version records: it has " . $dsCount . " for version " . $latestID);
$this->session()->clear('loggedInAs'); $this->session()->clear('loggedInAs');
@ -213,9 +213,9 @@ class CMSMainTest extends FunctionalTest
$response = $this->get('admin/pages/edit/show/' . $pageID); $response = $this->get('admin/pages/edit/show/' . $pageID);
$livePage = Versioned::get_one_by_stage(SiteTree::class, Versioned::LIVE, array( $livePage = Versioned::get_one_by_stage(SiteTree::class, Versioned::LIVE, [
'"SiteTree"."ID"' => $pageID '"SiteTree"."ID"' => $pageID
)); ]);
$this->assertInstanceOf(SiteTree::class, $livePage); $this->assertInstanceOf(SiteTree::class, $livePage);
$this->assertTrue($livePage->canDelete()); $this->assertTrue($livePage->canDelete());
@ -274,16 +274,16 @@ class CMSMainTest extends FunctionalTest
$this->get('admin/pages/add'); $this->get('admin/pages/add');
$response = $this->post( $response = $this->post(
'admin/pages/add/AddForm', 'admin/pages/add/AddForm',
array( [
'ParentID' => '0', 'ParentID' => '0',
'PageType' => 'Page', 'PageType' => 'Page',
'Locale' => 'en_US', 'Locale' => 'en_US',
'action_doAdd' => 1, 'action_doAdd' => 1,
'ajax' => 1, 'ajax' => 1,
), ],
array( [
'X-Pjax' => 'CurrentForm,Breadcrumbs', 'X-Pjax' => 'CurrentForm,Breadcrumbs',
) ]
); );
// should redirect, which is a permission error // should redirect, which is a permission error
$this->assertEquals(403, $response->getStatusCode(), 'Add TopLevel page must fail for normal user'); $this->assertEquals(403, $response->getStatusCode(), 'Add TopLevel page must fail for normal user');
@ -294,16 +294,16 @@ class CMSMainTest extends FunctionalTest
$response = $this->post( $response = $this->post(
'admin/pages/add/AddForm', 'admin/pages/add/AddForm',
array( [
'ParentID' => '0', 'ParentID' => '0',
'PageType' => 'Page', 'PageType' => 'Page',
'Locale' => 'en_US', 'Locale' => 'en_US',
'action_doAdd' => 1, 'action_doAdd' => 1,
'ajax' => 1, 'ajax' => 1,
), ],
array( [
'X-Pjax' => 'CurrentForm,Breadcrumbs', 'X-Pjax' => 'CurrentForm,Breadcrumbs',
) ]
); );
$location = $response->getHeader('X-ControllerURL'); $location = $response->getHeader('X-ControllerURL');
@ -327,16 +327,16 @@ class CMSMainTest extends FunctionalTest
$this->get('admin/pages/add'); $this->get('admin/pages/add');
$response = $this->post( $response = $this->post(
'admin/pages/add/AddForm', 'admin/pages/add/AddForm',
array( [
'ParentID' => '0', 'ParentID' => '0',
'PageType' => CMSMainTest_ClassA::class, 'PageType' => CMSMainTest_ClassA::class,
'Locale' => 'en_US', 'Locale' => 'en_US',
'action_doAdd' => 1, 'action_doAdd' => 1,
'ajax' => 1 'ajax' => 1
), ],
array( [
'X-Pjax' => 'CurrentForm,Breadcrumbs', 'X-Pjax' => 'CurrentForm,Breadcrumbs',
) ]
); );
$this->assertFalse($response->isError()); $this->assertFalse($response->isError());
$ok = preg_match('/edit\/show\/(\d*)/', $response->getHeader('X-ControllerURL'), $matches); $ok = preg_match('/edit\/show\/(\d*)/', $response->getHeader('X-ControllerURL'), $matches);
@ -347,16 +347,16 @@ class CMSMainTest extends FunctionalTest
$this->get('admin/pages/add'); $this->get('admin/pages/add');
$response = $this->post( $response = $this->post(
'admin/pages/add/AddForm', 'admin/pages/add/AddForm',
array( [
'ParentID' => $newPageId, 'ParentID' => $newPageId,
'PageType' => CMSMainTest_ClassB::class, 'PageType' => CMSMainTest_ClassB::class,
'Locale' => 'en_US', 'Locale' => 'en_US',
'action_doAdd' => 1, 'action_doAdd' => 1,
'ajax' => 1 'ajax' => 1
), ],
array( [
'X-Pjax' => 'CurrentForm,Breadcrumbs', 'X-Pjax' => 'CurrentForm,Breadcrumbs',
) ]
); );
$this->assertFalse($response->isError()); $this->assertFalse($response->isError());
$this->assertEmpty($response->getBody()); $this->assertEmpty($response->getBody());
@ -373,16 +373,16 @@ class CMSMainTest extends FunctionalTest
$this->get('admin/pages/add'); $this->get('admin/pages/add');
$response = $this->post( $response = $this->post(
'admin/pages/add/AddForm', 'admin/pages/add/AddForm',
array( [
'ParentID' => $newPageId, 'ParentID' => $newPageId,
'PageType' => 'Page', 'PageType' => 'Page',
'Locale' => 'en_US', 'Locale' => 'en_US',
'action_doAdd' => 1, 'action_doAdd' => 1,
'ajax' => 1 'ajax' => 1
), ],
array( [
'X-Pjax' => 'CurrentForm,Breadcrumbs', 'X-Pjax' => 'CurrentForm,Breadcrumbs',
) ]
); );
$this->assertEquals(403, $response->getStatusCode(), 'Add disallowed child should fail'); $this->assertEquals(403, $response->getStatusCode(), 'Add disallowed child should fail');
@ -445,7 +445,7 @@ class CMSMainTest extends FunctionalTest
$pages = $controller->getList()->sort('Title'); $pages = $controller->getList()->sort('Title');
$this->assertEquals(28, $pages->count()); $this->assertEquals(28, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Home', 'Page 1', 'Page 10', 'Page 11', 'Page 12'), ['Home', 'Page 1', 'Page 10', 'Page 11', 'Page 12'],
$pages->Limit(5)->column('Title') $pages->Limit(5)->column('Title')
); );
@ -467,40 +467,40 @@ class CMSMainTest extends FunctionalTest
$pages = $controller->getList()->sort('Title'); $pages = $controller->getList()->sort('Title');
$this->assertEquals(26, $pages->count()); $this->assertEquals(26, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Home', 'Page 10', 'Page 11', 'Page 13', 'Page 14'), ['Home', 'Page 10', 'Page 11', 'Page 13', 'Page 14'],
$pages->Limit(5)->column('Title') $pages->Limit(5)->column('Title')
); );
// Test deleted page filter // Test deleted page filter
$params = array( $params = [
'FilterClass' => 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_StatusDeletedPages' 'FilterClass' => 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_StatusDeletedPages'
); ];
$pages = $controller->getList($params); $pages = $controller->getList($params);
$this->assertEquals(1, $pages->count()); $this->assertEquals(1, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Page 1'), ['Page 1'],
$pages->column('Title') $pages->column('Title')
); );
// Test live, but not on draft filter // Test live, but not on draft filter
$params = array( $params = [
'FilterClass' => 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_StatusRemovedFromDraftPages' 'FilterClass' => 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_StatusRemovedFromDraftPages'
); ];
$pages = $controller->getList($params); $pages = $controller->getList($params);
$this->assertEquals(1, $pages->count()); $this->assertEquals(1, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Page 12'), ['Page 12'],
$pages->column('Title') $pages->column('Title')
); );
// Test live pages filter // Test live pages filter
$params = array( $params = [
'FilterClass' => 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_PublishedPages' 'FilterClass' => 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_PublishedPages'
); ];
$pages = $controller->getList($params); $pages = $controller->getList($params);
$this->assertEquals(2, $pages->count()); $this->assertEquals(2, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Page 11', 'Page 12'), ['Page 11', 'Page 12'],
$pages->column('Title') $pages->column('Title')
); );
@ -508,15 +508,15 @@ class CMSMainTest extends FunctionalTest
$pages = $controller->getList($params, $page3->ID); $pages = $controller->getList($params, $page3->ID);
$this->assertEquals(2, $pages->count()); $this->assertEquals(2, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Page 11', 'Page 12'), ['Page 11', 'Page 12'],
$pages->column('Title') $pages->column('Title')
); );
// Test that parentID is respected when not filtering // Test that parentID is respected when not filtering
$pages = $controller->getList(array(), $page3->ID); $pages = $controller->getList([], $page3->ID);
$this->assertEquals(2, $pages->count()); $this->assertEquals(2, $pages->count());
$this->assertEquals( $this->assertEquals(
array('Page 3.1', 'Page 3.2'), ['Page 3.1', 'Page 3.2'],
$pages->column('Title') $pages->column('Title')
); );
} }

View File

@ -10,7 +10,7 @@ class CMSMainTest_ClassA extends Page implements TestOnly
{ {
private static $table_name = 'CMSMainTest_ClassA'; private static $table_name = 'CMSMainTest_ClassA';
private static $allowed_children = array(CMSMainTest_ClassB::class); private static $allowed_children = [CMSMainTest_ClassB::class];
protected function onBeforeWrite() protected function onBeforeWrite()
{ {

View File

@ -131,12 +131,12 @@ class CMSPageHistoryControllerTest extends FunctionalTest
$form = $this->cssParser()->getBySelector('#Form_VersionsForm'); $form = $this->cssParser()->getBySelector('#Form_VersionsForm');
$rows = $form[0]->xpath("fieldset/table/tbody/tr"); $rows = $form[0]->xpath("fieldset/table/tbody/tr");
$expected = array( $expected = [
array('version' => $this->versionPublishCheck2, 'status' => 'published'), ['version' => $this->versionPublishCheck2, 'status' => 'published'],
array('version' => $this->versionUnpublishedCheck2, 'status' => 'internal'), ['version' => $this->versionUnpublishedCheck2, 'status' => 'internal'],
array('version' => $this->versionPublishCheck, 'status' => 'published'), ['version' => $this->versionPublishCheck, 'status' => 'published'],
array('version' => $this->versionUnpublishedCheck, 'status' => 'internal') ['version' => $this->versionUnpublishedCheck, 'status' => 'internal']
); ];
// goes the reverse order that we created in setUp() // goes the reverse order that we created in setUp()
$i = 0; $i = 0;

View File

@ -35,14 +35,14 @@ class CMSSiteTreeFilterTest extends SapphireTest
$page1 = $this->objFromFixture('Page', 'page1'); $page1 = $this->objFromFixture('Page', 'page1');
$page2 = $this->objFromFixture('Page', 'page2'); $page2 = $this->objFromFixture('Page', 'page2');
$f = new CMSSiteTreeFilter_Search(array('Title' => 'Page 1')); $f = new CMSSiteTreeFilter_Search(['Title' => 'Page 1']);
$results = $f->pagesIncluded(); $results = $f->pagesIncluded();
$this->assertTrue($f->isPageIncluded($page1)); $this->assertTrue($f->isPageIncluded($page1));
$this->assertFalse($f->isPageIncluded($page2)); $this->assertFalse($f->isPageIncluded($page2));
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals( $this->assertEquals(
array('ID' => $page1->ID, 'ParentID' => 0), ['ID' => $page1->ID, 'ParentID' => 0],
$results[0] $results[0]
); );
} }
@ -52,14 +52,14 @@ class CMSSiteTreeFilterTest extends SapphireTest
$parent = $this->objFromFixture('Page', 'page3'); $parent = $this->objFromFixture('Page', 'page3');
$child = $this->objFromFixture('Page', 'page3b'); $child = $this->objFromFixture('Page', 'page3b');
$f = new CMSSiteTreeFilter_Search(array('Title' => 'Page 3b')); $f = new CMSSiteTreeFilter_Search(['Title' => 'Page 3b']);
$results = $f->pagesIncluded(); $results = $f->pagesIncluded();
$this->assertTrue($f->isPageIncluded($parent)); $this->assertTrue($f->isPageIncluded($parent));
$this->assertTrue($f->isPageIncluded($child)); $this->assertTrue($f->isPageIncluded($child));
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals( $this->assertEquals(
array('ID' => $child->ID, 'ParentID' => $parent->ID), ['ID' => $child->ID, 'ParentID' => $parent->ID],
$results[0] $results[0]
); );
} }
@ -79,19 +79,19 @@ class CMSSiteTreeFilterTest extends SapphireTest
$changedPageVersion = $changedPage->Version; $changedPageVersion = $changedPage->Version;
// Check that only changed pages are returned // Check that only changed pages are returned
$f = new CMSSiteTreeFilter_ChangedPages(array('Term' => 'Changed')); $f = new CMSSiteTreeFilter_ChangedPages(['Term' => 'Changed']);
$results = $f->pagesIncluded(); $results = $f->pagesIncluded();
$this->assertTrue($f->isPageIncluded($changedPage)); $this->assertTrue($f->isPageIncluded($changedPage));
$this->assertFalse($f->isPageIncluded($unchangedPage)); $this->assertFalse($f->isPageIncluded($unchangedPage));
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals( $this->assertEquals(
array('ID' => $changedPage->ID, 'ParentID' => 0), ['ID' => $changedPage->ID, 'ParentID' => 0],
$results[0] $results[0]
); );
// Check that only changed pages are returned // Check that only changed pages are returned
$f = new CMSSiteTreeFilter_ChangedPages(array('Term' => 'No Matches')); $f = new CMSSiteTreeFilter_ChangedPages(['Term' => 'No Matches']);
$results = $f->pagesIncluded(); $results = $f->pagesIncluded();
$this->assertEquals(0, count($results)); $this->assertEquals(0, count($results));
@ -101,11 +101,11 @@ class CMSSiteTreeFilterTest extends SapphireTest
$changedPage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $changedPage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$changedPage->doRollbackTo($changedPageVersion); $changedPage->doRollbackTo($changedPageVersion);
$f = new CMSSiteTreeFilter_ChangedPages(array('Term' => 'Changed')); $f = new CMSSiteTreeFilter_ChangedPages(['Term' => 'Changed']);
$results = $f->pagesIncluded(); $results = $f->pagesIncluded();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals(array('ID' => $changedPage->ID, 'ParentID' => 0), $results[0]); $this->assertEquals(['ID' => $changedPage->ID, 'ParentID' => 0], $results[0]);
} }
public function testDeletedPagesFilter() public function testDeletedPagesFilter()
@ -117,14 +117,14 @@ class CMSSiteTreeFilterTest extends SapphireTest
$deletedPage = Versioned::get_one_by_stage( $deletedPage = Versioned::get_one_by_stage(
SiteTree::class, SiteTree::class,
'Live', 'Live',
array('"SiteTree_Live"."ID"' => $deletedPageID) ['"SiteTree_Live"."ID"' => $deletedPageID]
); );
$f = new CMSSiteTreeFilter_DeletedPages(array('Term' => 'Page')); $f = new CMSSiteTreeFilter_DeletedPages(['Term' => 'Page']);
$this->assertTrue($f->isPageIncluded($deletedPage)); $this->assertTrue($f->isPageIncluded($deletedPage));
// Check that only changed pages are returned // Check that only changed pages are returned
$f = new CMSSiteTreeFilter_DeletedPages(array('Term' => 'No Matches')); $f = new CMSSiteTreeFilter_DeletedPages(['Term' => 'No Matches']);
$this->assertFalse($f->isPageIncluded($deletedPage)); $this->assertFalse($f->isPageIncluded($deletedPage));
} }
@ -138,11 +138,11 @@ class CMSSiteTreeFilterTest extends SapphireTest
); );
// Check draft page is shown // Check draft page is shown
$f = new CMSSiteTreeFilter_StatusDraftPages(array('Term' => 'Page')); $f = new CMSSiteTreeFilter_StatusDraftPages(['Term' => 'Page']);
$this->assertTrue($f->isPageIncluded($draftPage)); $this->assertTrue($f->isPageIncluded($draftPage));
// Check filter respects parameters // Check filter respects parameters
$f = new CMSSiteTreeFilter_StatusDraftPages(array('Term' => 'No Match')); $f = new CMSSiteTreeFilter_StatusDraftPages(['Term' => 'No Match']);
$this->assertEmpty($f->isPageIncluded($draftPage)); $this->assertEmpty($f->isPageIncluded($draftPage));
// Ensures empty array returned if no data to show // Ensures empty array returned if no data to show
@ -157,10 +157,10 @@ class CMSSiteTreeFilterTest extends SapphireTest
// Grab the date // Grab the date
$date = substr($draftPage->LastEdited, 0, 10); $date = substr($draftPage->LastEdited, 0, 10);
// Filter with that date // Filter with that date
$filter = new CMSSiteTreeFilter_Search(array( $filter = new CMSSiteTreeFilter_Search([
'LastEditedFrom' => $date, 'LastEditedFrom' => $date,
'LastEditedTo' => $date 'LastEditedTo' => $date
)); ]);
$this->assertTrue($filter->isPageIncluded($draftPage), 'Using the same date for from and to should show find that page'); $this->assertTrue($filter->isPageIncluded($draftPage), 'Using the same date for from and to should show find that page');
} }
@ -176,11 +176,11 @@ class CMSSiteTreeFilterTest extends SapphireTest
); );
// Check live-only page is included // Check live-only page is included
$f = new CMSSiteTreeFilter_StatusRemovedFromDraftPages(array('LastEditedFrom' => '2000-01-01 00:00')); $f = new CMSSiteTreeFilter_StatusRemovedFromDraftPages(['LastEditedFrom' => '2000-01-01 00:00']);
$this->assertTrue($f->isPageIncluded($removedDraftPage)); $this->assertTrue($f->isPageIncluded($removedDraftPage));
// Check filter is respected // Check filter is respected
$f = new CMSSiteTreeFilter_StatusRemovedFromDraftPages(array('LastEditedTo' => '1999-01-01 00:00')); $f = new CMSSiteTreeFilter_StatusRemovedFromDraftPages(['LastEditedTo' => '1999-01-01 00:00']);
$this->assertEmpty($f->isPageIncluded($removedDraftPage)); $this->assertEmpty($f->isPageIncluded($removedDraftPage));
// Ensures empty array returned if no data to show // Ensures empty array returned if no data to show
@ -201,11 +201,11 @@ class CMSSiteTreeFilterTest extends SapphireTest
$checkParentExists = Versioned::get_latest_version(SiteTree::class, $deletedPageID); $checkParentExists = Versioned::get_latest_version(SiteTree::class, $deletedPageID);
// Check deleted page is included // Check deleted page is included
$f = new CMSSiteTreeFilter_StatusDeletedPages(array('Title' => 'Page')); $f = new CMSSiteTreeFilter_StatusDeletedPages(['Title' => 'Page']);
$this->assertTrue($f->isPageIncluded($checkParentExists)); $this->assertTrue($f->isPageIncluded($checkParentExists));
// Check filter is respected // Check filter is respected
$f = new CMSSiteTreeFilter_StatusDeletedPages(array('Title' => 'Bobby')); $f = new CMSSiteTreeFilter_StatusDeletedPages(['Title' => 'Bobby']);
$this->assertFalse($f->isPageIncluded($checkParentExists)); $this->assertFalse($f->isPageIncluded($checkParentExists));
} }
} }

View File

@ -29,11 +29,11 @@ class CMSTreeTest extends FunctionalTest
// Move page2 before page1 // Move page2 before page1
$siblingIDs[0] = $page2->ID; $siblingIDs[0] = $page2->ID;
$siblingIDs[1] = $page1->ID; $siblingIDs[1] = $page1->ID;
$data = array( $data = [
'SiblingIDs' => $siblingIDs, 'SiblingIDs' => $siblingIDs,
'ID' => $page2->ID, 'ID' => $page2->ID,
'ParentID' => 0 'ParentID' => 0
); ];
$response = $this->post('admin/pages/edit/savetreenode', $data); $response = $this->post('admin/pages/edit/savetreenode', $data);
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
@ -59,16 +59,16 @@ class CMSTreeTest extends FunctionalTest
$page32 = $this->objFromFixture(SiteTree::class, 'page32'); $page32 = $this->objFromFixture(SiteTree::class, 'page32');
// Move page2 into page3, between page3.1 and page 3.2 // Move page2 into page3, between page3.1 and page 3.2
$siblingIDs = array( $siblingIDs = [
$page31->ID, $page31->ID,
$page2->ID, $page2->ID,
$page32->ID $page32->ID
); ];
$data = array( $data = [
'SiblingIDs' => $siblingIDs, 'SiblingIDs' => $siblingIDs,
'ID' => $page2->ID, 'ID' => $page2->ID,
'ParentID' => $page3->ID 'ParentID' => $page3->ID
); ];
$response = $this->post('admin/pages/edit/savetreenode', $data); $response = $this->post('admin/pages/edit/savetreenode', $data);
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$page2 = DataObject::get_by_id(SiteTree::class, $page2->ID, false); $page2 = DataObject::get_by_id(SiteTree::class, $page2->ID, false);

View File

@ -12,11 +12,11 @@ use Page;
class ContentControllerSearchExtensionTest extends SapphireTest class ContentControllerSearchExtensionTest extends SapphireTest
{ {
protected static $required_extensions = array( protected static $required_extensions = [
ContentController::class => [ ContentController::class => [
ContentControllerSearchExtension::class, ContentControllerSearchExtension::class,
] ]
); ];
public function testCustomSearchFormClassesToTest() public function testCustomSearchFormClassesToTest()
{ {

View File

@ -7,13 +7,13 @@ use PageController;
class ContentControllerTestPageController extends PageController implements TestOnly class ContentControllerTestPageController extends PageController implements TestOnly
{ {
private static $allowed_actions = array( private static $allowed_actions = [
'test', 'test',
'testwithouttemplate' 'testwithouttemplate'
); ];
public function testwithouttemplate() public function testwithouttemplate()
{ {
return array(); return [];
} }
} }

View File

@ -8,9 +8,9 @@ use PageController;
class ContentControllerTest_PageController extends PageController implements TestOnly class ContentControllerTest_PageController extends PageController implements TestOnly
{ {
private static $allowed_actions = array( private static $allowed_actions = [
'second_index' 'second_index'
); ];
public function index() public function index()
{ {

View File

@ -188,9 +188,9 @@ class ModelAsControllerTest extends FunctionalTest
{ {
$this->generateNestedPagesFixture(); $this->generateNestedPagesFixture();
$otherParent = new Page(array( $otherParent = new Page([
'URLSegment' => 'otherparent' 'URLSegment' => 'otherparent'
)); ]);
$otherParent->write(); $otherParent->write();
$otherParent->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $otherParent->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
@ -232,10 +232,10 @@ class ModelAsControllerTest extends FunctionalTest
{ {
$this->generateNestedPagesFixture(); $this->generateNestedPagesFixture();
$otherLevel1 = new Page(array( $otherLevel1 = new Page([
'Title' => "Other Level 1", 'Title' => "Other Level 1",
'URLSegment' => 'level1' 'URLSegment' => 'level1'
)); ]);
$otherLevel1->write(); $otherLevel1->write();
$otherLevel1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $otherLevel1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);

View File

@ -79,15 +79,15 @@ class RedirectorPageTest extends FunctionalTest
public function testAllowsProtocolRelative() public function testAllowsProtocolRelative()
{ {
$noProtocol = new RedirectorPage(array('ExternalURL' => 'mydomain.com')); $noProtocol = new RedirectorPage(['ExternalURL' => 'mydomain.com']);
$noProtocol->write(); $noProtocol->write();
$this->assertEquals('http://mydomain.com', $noProtocol->ExternalURL); $this->assertEquals('http://mydomain.com', $noProtocol->ExternalURL);
$protocolAbsolute = new RedirectorPage(array('ExternalURL' => 'http://mydomain.com')); $protocolAbsolute = new RedirectorPage(['ExternalURL' => 'http://mydomain.com']);
$protocolAbsolute->write(); $protocolAbsolute->write();
$this->assertEquals('http://mydomain.com', $protocolAbsolute->ExternalURL); $this->assertEquals('http://mydomain.com', $protocolAbsolute->ExternalURL);
$protocolRelative = new RedirectorPage(array('ExternalURL' => '//mydomain.com')); $protocolRelative = new RedirectorPage(['ExternalURL' => '//mydomain.com']);
$protocolRelative->write(); $protocolRelative->write();
$this->assertEquals('//mydomain.com', $protocolRelative->ExternalURL); $this->assertEquals('//mydomain.com', $protocolRelative->ExternalURL);
} }

View File

@ -9,10 +9,10 @@ class SiteTreeBacklinksTestContentObject extends DataObject implements TestOnly
{ {
private static $table_name = 'BacklinkContent'; private static $table_name = 'BacklinkContent';
private static $db = array( private static $db = [
'Title' => 'Text', 'Title' => 'Text',
'Content' => 'HTMLText', 'Content' => 'HTMLText',
); ];
private static $singular_name = 'Backlink test content object'; private static $singular_name = 'Backlink test content object';
} }

View File

@ -9,9 +9,9 @@ use SilverStripe\ORM\DataExtension;
class SiteTreeBacklinksTest_DOD extends DataExtension implements TestOnly class SiteTreeBacklinksTest_DOD extends DataExtension implements TestOnly
{ {
private static $db = array( private static $db = [
'ExtraContent' => 'HTMLText', 'ExtraContent' => 'HTMLText',
); ];
public function updateCMSFields(FieldList $fields) public function updateCMSFields(FieldList $fields)
{ {

View File

@ -55,7 +55,7 @@ class SiteTreeHTMLEditorFieldTest extends FunctionalTest
$editor->setValue("<a href=\"[sitetree_link,id=$aboutID]\">Example Link</a>"); $editor->setValue("<a href=\"[sitetree_link,id=$aboutID]\">Example Link</a>");
$editor->saveInto($sitetree); $editor->saveInto($sitetree);
$sitetree->write(); $sitetree->write();
$this->assertEquals(array($aboutID => $aboutID), $sitetree->LinkTracking()->getIdList(), 'Basic link tracking works.'); $this->assertEquals([$aboutID => $aboutID], $sitetree->LinkTracking()->getIdList(), 'Basic link tracking works.');
$editor->setValue( $editor->setValue(
"<a href=\"[sitetree_link,id=$aboutID]\"></a><a href=\"[sitetree_link,id=$contactID]\"></a>" "<a href=\"[sitetree_link,id=$aboutID]\"></a><a href=\"[sitetree_link,id=$contactID]\"></a>"
@ -63,7 +63,7 @@ class SiteTreeHTMLEditorFieldTest extends FunctionalTest
$editor->saveInto($sitetree); $editor->saveInto($sitetree);
$sitetree->write(); $sitetree->write();
$this->assertEquals( $this->assertEquals(
array($aboutID => $aboutID, $contactID => $contactID), [$aboutID => $aboutID, $contactID => $contactID],
$sitetree->LinkTracking()->getIdList(), $sitetree->LinkTracking()->getIdList(),
'Tracking works on multiple links' 'Tracking works on multiple links'
); );
@ -71,14 +71,14 @@ class SiteTreeHTMLEditorFieldTest extends FunctionalTest
$editor->setValue(null); $editor->setValue(null);
$editor->saveInto($sitetree); $editor->saveInto($sitetree);
$sitetree->write(); $sitetree->write();
$this->assertEquals(array(), $sitetree->LinkTracking()->getIdList(), 'Link tracking is removed when links are.'); $this->assertEquals([], $sitetree->LinkTracking()->getIdList(), 'Link tracking is removed when links are.');
// Legacy support - old CMS versions added link shortcodes with spaces instead of commas // Legacy support - old CMS versions added link shortcodes with spaces instead of commas
$editor->setValue("<a href=\"[sitetree_link id=$aboutID]\">Example Link</a>"); $editor->setValue("<a href=\"[sitetree_link id=$aboutID]\">Example Link</a>");
$editor->saveInto($sitetree); $editor->saveInto($sitetree);
$sitetree->write(); $sitetree->write();
$this->assertEquals( $this->assertEquals(
array($aboutID => $aboutID), [$aboutID => $aboutID],
$sitetree->LinkTracking()->getIdList(), $sitetree->LinkTracking()->getIdList(),
'Link tracking with space instead of comma in shortcode works.' 'Link tracking with space instead of comma in shortcode works.'
); );

View File

@ -9,5 +9,5 @@ class SiteTreeTest_ClassC extends Page implements TestOnly
{ {
private static $table_name = 'SiteTreeTest_ClassC'; private static $table_name = 'SiteTreeTest_ClassC';
private static $allowed_children = array(); private static $allowed_children = [];
} }

View File

@ -7,9 +7,9 @@ use PageController;
class SiteTreeTest_ConflictedController extends PageController implements TestOnly class SiteTreeTest_ConflictedController extends PageController implements TestOnly
{ {
private static $allowed_actions = array( private static $allowed_actions = [
'conflicted-action' 'conflicted-action'
); ];
public function hasActionTemplate($template) public function hasActionTemplate($template)
{ {

View File

@ -9,12 +9,12 @@ class VirtualPageTest_ClassA extends Page implements TestOnly
{ {
private static $table_name = 'VirtualPageTest_ClassA'; private static $table_name = 'VirtualPageTest_ClassA';
private static $db = array( private static $db = [
'MyInitiallyCopiedField' => 'Text', 'MyInitiallyCopiedField' => 'Text',
'MyVirtualField' => 'Text', 'MyVirtualField' => 'Text',
'MyNonVirtualField' => 'Text', 'MyNonVirtualField' => 'Text',
'CastingTest' => VirtualPageTest_TestDBField::class, 'CastingTest' => VirtualPageTest_TestDBField::class,
); ];
private static $allowed_children = [ private static $allowed_children = [
VirtualPageTest_ClassB::class, VirtualPageTest_ClassB::class,

View File

@ -9,5 +9,5 @@ class VirtualPageTest_ClassC extends Page implements TestOnly
{ {
private static $table_name = 'VirtualPageTest_ClassC'; private static $table_name = 'VirtualPageTest_ClassC';
private static $allowed_children = array(); private static $allowed_children = [];
} }

View File

@ -7,10 +7,10 @@ use SilverStripe\ORM\DataExtension;
class VirtualPageTest_PageExtension extends DataExtension implements TestOnly class VirtualPageTest_PageExtension extends DataExtension implements TestOnly
{ {
private static $db = array( private static $db = [
// These fields are just on an extension to simulate shared properties between Page and VirtualPage. // These fields are just on an extension to simulate shared properties between Page and VirtualPage.
// Not possible through direct $db definitions due to VirtualPage inheriting from Page, and Page being defined elsewhere. // Not possible through direct $db definitions due to VirtualPage inheriting from Page, and Page being defined elsewhere.
'MySharedVirtualField' => 'Text', 'MySharedVirtualField' => 'Text',
'MySharedNonVirtualField' => 'Text', 'MySharedNonVirtualField' => 'Text',
); ];
} }

View File

@ -10,8 +10,8 @@ class VirtualPageTest_PageWithAllowedChildren extends Page implements TestOnly
{ {
private static $table_name = 'VirtualPageTest_PageWithAllowedChildren'; private static $table_name = 'VirtualPageTest_PageWithAllowedChildren';
private static $allowed_children = array( private static $allowed_children = [
VirtualPageTest_ClassA::class, VirtualPageTest_ClassA::class,
VirtualPage::class, VirtualPage::class,
); ];
} }

View File

@ -9,7 +9,7 @@ class VirtualPageTest_VirtualPageSub extends VirtualPage implements TestOnly
{ {
private static $table_name = 'VirtualPageTest_VirtualPageSub'; private static $table_name = 'VirtualPageTest_VirtualPageSub';
private static $db = array( private static $db = [
'MyProperty' => 'Varchar', 'MyProperty' => 'Varchar',
); ];
} }

View File

@ -51,12 +51,12 @@ class CmsReportsTest extends SapphireTest
$class = get_class($report); $class = get_class($report);
// ASSERT that the "draft" report is returning the correct results. // ASSERT that the "draft" report is returning the correct results.
$parameters = array('CheckSite' => 'Draft'); $parameters = ['CheckSite' => 'Draft'];
$results = count($report->sourceRecords($parameters, null, null)) > 0; $results = count($report->sourceRecords($parameters, null, null)) > 0;
$isDraftBroken ? $this->assertTrue($results, "{$class} has NOT returned the correct DRAFT results, as NO pages were found.") : $this->assertFalse($results, "{$class} has NOT returned the correct DRAFT results, as pages were found."); $isDraftBroken ? $this->assertTrue($results, "{$class} has NOT returned the correct DRAFT results, as NO pages were found.") : $this->assertFalse($results, "{$class} has NOT returned the correct DRAFT results, as pages were found.");
// ASSERT that the "published" report is returning the correct results. // ASSERT that the "published" report is returning the correct results.
$parameters = array('CheckSite' => 'Published', 'OnLive' => 1); $parameters = ['CheckSite' => 'Published', 'OnLive' => 1];
$results = count($report->sourceRecords($parameters, null, null)) > 0; $results = count($report->sourceRecords($parameters, null, null)) > 0;
$isPublishedBroken ? $this->assertTrue($results, "{$class} has NOT returned the correct PUBLISHED results, as NO pages were found.") : $this->assertFalse($results, "{$class} has NOT returned the correct PUBLISHED results, as pages were found."); $isPublishedBroken ? $this->assertTrue($results, "{$class} has NOT returned the correct PUBLISHED results, as NO pages were found.") : $this->assertFalse($results, "{$class} has NOT returned the correct PUBLISHED results, as pages were found.");
} }
@ -71,9 +71,9 @@ class CmsReportsTest extends SapphireTest
$r = new RecentlyEditedReport(); $r = new RecentlyEditedReport();
// check if contains only elements not older than $daysAgo days // check if contains only elements not older than $daysAgo days
$this->assertNotNull($r->records(array())); $this->assertNotNull($r->records([]));
$this->assertContains($after->ID, $r->records(array())->column('ID')); $this->assertContains($after->ID, $r->records([])->column('ID'));
$this->assertNotContains($before->ID, $r->records(array())->column('ID')); $this->assertNotContains($before->ID, $r->records([])->column('ID'));
DBDatetime::clear_mock_now(); DBDatetime::clear_mock_now();
} }

View File

@ -16,12 +16,12 @@ class CMSMainSearchFormTest extends FunctionalTest
$this->get( $this->get(
'admin/pages/?' . 'admin/pages/?' .
http_build_query(array( http_build_query([
'q' => array( 'q' => [
'Term' => 'Page 10', 'Term' => 'Page 10',
'FilterClass' => CMSSiteTreeFilter_Search::class, 'FilterClass' => CMSSiteTreeFilter_Search::class,
) ]
)) ])
); );
$titles = $this->getPageTitles(); $titles = $this->getPageTitles();
@ -33,7 +33,7 @@ class CMSMainSearchFormTest extends FunctionalTest
protected function getPageTitles() protected function getPageTitles()
{ {
$titles = array(); $titles = [];
$links = $this->cssParser()->getBySelector('.col-getTreeTitle span.item'); $links = $this->cssParser()->getBySelector('.col-getTreeTitle span.item');
if ($links) { if ($links) {
foreach ($links as $link) { foreach ($links as $link) {

View File

@ -95,13 +95,13 @@ class RemoveOrphanedPagesTaskTest extends FunctionalTest
$orphans = $task->getOrphanedPages(); $orphans = $task->getOrphanedPages();
$orphanIDs = $orphans->column('ID'); $orphanIDs = $orphans->column('ID');
sort($orphanIDs); sort($orphanIDs);
$compareIDs = array( $compareIDs = [
$child1_3_orphaned->ID, $child1_3_orphaned->ID,
$child1_4_orphaned_published->ID, $child1_4_orphaned_published->ID,
$grandchild1_1_3_orphaned->ID, $grandchild1_1_3_orphaned->ID,
$grandchild1_1_4_orphaned_published->ID, $grandchild1_1_4_orphaned_published->ID,
$child2_1_published_orphaned->ID $child2_1_published_orphaned->ID
); ];
sort($compareIDs); sort($compareIDs);
$this->assertEquals($orphanIDs, $compareIDs); $this->assertEquals($orphanIDs, $compareIDs);