diff --git a/core/modules/action/action.module b/core/modules/action/action.module index 7461302d17..5004a84b11 100644 --- a/core/modules/action/action.module +++ b/core/modules/action/action.module @@ -15,13 +15,13 @@ function action_help($route_name, RouteMatchInterface $route_match) { case 'help.page.action': $output = ''; $output .= '

' . t('About') . '

'; - $output .= '

' . t('The Actions module provides tasks that can be executed by the site such as unpublishing content, sending email messages, or blocking a user. Other modules can trigger these actions when specific system events happen; for example, when new content is posted or when a user logs in. Modules can also provide additional actions. For more information, see the online documentation for the Actions module.', array(':documentation' => 'https://www.drupal.org/documentation/modules/action')) . '

'; + $output .= '

' . t('The Actions module provides tasks that can be executed by the site such as unpublishing content, sending email messages, or blocking a user. Other modules can trigger these actions when specific system events happen; for example, when new content is posted or when a user logs in. Modules can also provide additional actions. For more information, see the online documentation for the Actions module.', [':documentation' => 'https://www.drupal.org/documentation/modules/action']) . '

'; $output .= '

' . t('Uses') . '

'; $output .= '
'; $output .= '
' . t('Using simple actions') . '
'; - $output .= '
' . t('Simple actions do not require configuration and are listed automatically as available on the Actions page.', array(':actions' => \Drupal::url('entity.action.collection'))) . '
'; + $output .= '
' . t('Simple actions do not require configuration and are listed automatically as available on the Actions page.', [':actions' => \Drupal::url('entity.action.collection')]) . '
'; $output .= '
' . t('Creating and configuring advanced actions') . '
'; - $output .= '
' . t('Advanced actions are user-created and have to be configured individually. Create an advanced action on the Actions page by selecting an action type from the drop-down list. Then configure your action, for example by specifying the recipient of an automated email message.', array(':actions' => \Drupal::url('entity.action.collection'))) . '
'; + $output .= '
' . t('Advanced actions are user-created and have to be configured individually. Create an advanced action on the Actions page by selecting an action type from the drop-down list. Then configure your action, for example by specifying the recipient of an automated email message.', [':actions' => \Drupal::url('entity.action.collection')]) . '
'; $output .= '
'; return $output; diff --git a/core/modules/action/action.views_execution.inc b/core/modules/action/action.views_execution.inc index 5b4f71f811..71b8eebe42 100644 --- a/core/modules/action/action.views_execution.inc +++ b/core/modules/action/action.views_execution.inc @@ -9,12 +9,12 @@ * Implements hook_views_form_substitutions(). */ function action_views_form_substitutions() { - $select_all = array( + $select_all = [ '#type' => 'checkbox', '#default_value' => FALSE, - '#attributes' => array('class' => array('action-table-select-all')), - ); - return array( + '#attributes' => ['class' => ['action-table-select-all']], + ]; + return [ '' => drupal_render($select_all), - ); + ]; } diff --git a/core/modules/action/src/ActionFormBase.php b/core/modules/action/src/ActionFormBase.php index 7a5746a36a..3fafd035ee 100644 --- a/core/modules/action/src/ActionFormBase.php +++ b/core/modules/action/src/ActionFormBase.php @@ -58,32 +58,32 @@ public function buildForm(array $form, FormStateInterface $form_state) { * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { - $form['label'] = array( + $form['label'] = [ '#type' => 'textfield', '#title' => $this->t('Label'), '#default_value' => $this->entity->label(), '#maxlength' => '255', '#description' => $this->t('A unique label for this advanced action. This label will be displayed in the interface of modules that integrate with actions.'), - ); + ]; - $form['id'] = array( + $form['id'] = [ '#type' => 'machine_name', '#default_value' => $this->entity->id(), '#disabled' => !$this->entity->isNew(), '#maxlength' => 64, '#description' => $this->t('A unique name for this action. It must only contain lowercase letters, numbers and underscores.'), - '#machine_name' => array( - 'exists' => array($this, 'exists'), - ), - ); - $form['plugin'] = array( + '#machine_name' => [ + 'exists' => [$this, 'exists'], + ], + ]; + $form['plugin'] = [ '#type' => 'value', '#value' => $this->entity->get('plugin'), - ); - $form['type'] = array( + ]; + $form['type'] = [ '#type' => 'value', '#value' => $this->entity->getType(), - ); + ]; if ($this->plugin instanceof PluginFormInterface) { $form += $this->plugin->buildConfigurationForm($form, $form_state); diff --git a/core/modules/action/src/ActionListBuilder.php b/core/modules/action/src/ActionListBuilder.php index 0a54cd6527..2167d8e094 100644 --- a/core/modules/action/src/ActionListBuilder.php +++ b/core/modules/action/src/ActionListBuilder.php @@ -86,10 +86,10 @@ public function buildRow(EntityInterface $entity) { * {@inheritdoc} */ public function buildHeader() { - $header = array( + $header = [ 'type' => t('Action type'), 'label' => t('Label'), - ) + parent::buildHeader(); + ] + parent::buildHeader(); return $header; } @@ -97,7 +97,7 @@ public function buildHeader() { * {@inheritdoc} */ public function getDefaultOperations(EntityInterface $entity) { - $operations = $entity->isConfigurable() ? parent::getDefaultOperations($entity) : array(); + $operations = $entity->isConfigurable() ? parent::getDefaultOperations($entity) : []; if (isset($operations['edit'])) { $operations['edit']['title'] = t('Configure'); } diff --git a/core/modules/action/src/Form/ActionAdminManageForm.php b/core/modules/action/src/Form/ActionAdminManageForm.php index de487557d1..478e919be0 100644 --- a/core/modules/action/src/Form/ActionAdminManageForm.php +++ b/core/modules/action/src/Form/ActionAdminManageForm.php @@ -50,33 +50,33 @@ public function getFormId() { * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { - $actions = array(); + $actions = []; foreach ($this->manager->getDefinitions() as $id => $definition) { if (is_subclass_of($definition['class'], '\Drupal\Core\Plugin\PluginFormInterface')) { $key = Crypt::hashBase64($id); $actions[$key] = $definition['label'] . '...'; } } - $form['parent'] = array( + $form['parent'] = [ '#type' => 'details', '#title' => $this->t('Create an advanced action'), - '#attributes' => array('class' => array('container-inline')), + '#attributes' => ['class' => ['container-inline']], '#open' => TRUE, - ); - $form['parent']['action'] = array( + ]; + $form['parent']['action'] = [ '#type' => 'select', '#title' => $this->t('Action'), '#title_display' => 'invisible', '#options' => $actions, '#empty_option' => $this->t('Choose an advanced action'), - ); - $form['parent']['actions'] = array( + ]; + $form['parent']['actions'] = [ '#type' => 'actions' - ); - $form['parent']['actions']['submit'] = array( + ]; + $form['parent']['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Create'), - ); + ]; return $form; } @@ -87,7 +87,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getValue('action')) { $form_state->setRedirect( 'action.admin_add', - array('action_id' => $form_state->getValue('action')) + ['action_id' => $form_state->getValue('action')] ); } } diff --git a/core/modules/action/src/Plugin/Action/EmailAction.php b/core/modules/action/src/Plugin/Action/EmailAction.php index f23827975d..0f469ec6bf 100644 --- a/core/modules/action/src/Plugin/Action/EmailAction.php +++ b/core/modules/action/src/Plugin/Action/EmailAction.php @@ -129,7 +129,7 @@ public function execute($entity = NULL) { // If the recipient is a registered user with a language preference, use // the recipient's preferred language. Otherwise, use the system default // language. - $recipient_accounts = $this->storage->loadByProperties(array('mail' => $recipient)); + $recipient_accounts = $this->storage->loadByProperties(['mail' => $recipient]); $recipient_account = reset($recipient_accounts); if ($recipient_account) { $langcode = $recipient_account->getPreferredLangcode(); @@ -137,13 +137,13 @@ public function execute($entity = NULL) { else { $langcode = $this->languageManager->getDefaultLanguage()->getId(); } - $params = array('context' => $this->configuration); + $params = ['context' => $this->configuration]; if ($this->mailManager->mail('system', 'action_send_email', $recipient, $langcode, $params)) { - $this->logger->notice('Sent email to %recipient', array('%recipient' => $recipient)); + $this->logger->notice('Sent email to %recipient', ['%recipient' => $recipient]); } else { - $this->logger->error('Unable to send email to %recipient', array('%recipient' => $recipient)); + $this->logger->error('Unable to send email to %recipient', ['%recipient' => $recipient]); } } @@ -151,39 +151,39 @@ public function execute($entity = NULL) { * {@inheritdoc} */ public function defaultConfiguration() { - return array( + return [ 'recipient' => '', 'subject' => '', 'message' => '', - ); + ]; } /** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { - $form['recipient'] = array( + $form['recipient'] = [ '#type' => 'textfield', '#title' => t('Recipient email address'), '#default_value' => $this->configuration['recipient'], '#maxlength' => '254', '#description' => t('You may also use tokens: [node:author:mail], [comment:author:mail], etc. Separate recipients with a comma.'), - ); - $form['subject'] = array( + ]; + $form['subject'] = [ '#type' => 'textfield', '#title' => t('Subject'), '#default_value' => $this->configuration['subject'], '#maxlength' => '254', '#description' => t('The subject of the message.'), - ); - $form['message'] = array( + ]; + $form['message'] = [ '#type' => 'textarea', '#title' => t('Message'), '#default_value' => $this->configuration['message'], '#cols' => '80', '#rows' => '20', '#description' => t('The message that should be sent. You may include placeholders like [node:title], [user:account-name], [user:display-name] and [comment:body] to represent data that will be different each time message is sent. Not all placeholders will be available in all contexts.'), - ); + ]; return $form; } @@ -193,7 +193,7 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta public function validateConfigurationForm(array &$form, FormStateInterface $form_state) { if (!$this->emailValidator->isValid($form_state->getValue('recipient')) && strpos($form_state->getValue('recipient'), ':mail') === FALSE) { // We want the literal %author placeholder to be emphasized in the error message. - $form_state->setErrorByName('recipient', t('Enter a valid email address or use a token email address such as %author.', array('%author' => '[node:author:mail]'))); + $form_state->setErrorByName('recipient', t('Enter a valid email address or use a token email address such as %author.', ['%author' => '[node:author:mail]'])); } } diff --git a/core/modules/action/src/Plugin/Action/GotoAction.php b/core/modules/action/src/Plugin/Action/GotoAction.php index 5c1b552200..44e871b92a 100644 --- a/core/modules/action/src/Plugin/Action/GotoAction.php +++ b/core/modules/action/src/Plugin/Action/GotoAction.php @@ -103,22 +103,22 @@ public function execute($object = NULL) { * {@inheritdoc} */ public function defaultConfiguration() { - return array( + return [ 'url' => '', - ); + ]; } /** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { - $form['url'] = array( + $form['url'] = [ '#type' => 'textfield', '#title' => t('URL'), - '#description' => t('The URL to which the user should be redirected. This can be an internal URL like /node/1234 or an external URL like @url.', array('@url' => 'http://example.com')), + '#description' => t('The URL to which the user should be redirected. This can be an internal URL like /node/1234 or an external URL like @url.', ['@url' => 'http://example.com']), '#default_value' => $this->configuration['url'], '#required' => TRUE, - ); + ]; return $form; } diff --git a/core/modules/action/src/Plugin/Action/MessageAction.php b/core/modules/action/src/Plugin/Action/MessageAction.php index ab32b4c9fc..c85d249b08 100644 --- a/core/modules/action/src/Plugin/Action/MessageAction.php +++ b/core/modules/action/src/Plugin/Action/MessageAction.php @@ -84,23 +84,23 @@ public function execute($entity = NULL) { * {@inheritdoc} */ public function defaultConfiguration() { - return array( + return [ 'message' => '', - ); + ]; } /** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { - $form['message'] = array( + $form['message'] = [ '#type' => 'textarea', '#title' => t('Message'), '#default_value' => $this->configuration['message'], '#required' => TRUE, '#rows' => '8', '#description' => t('The message to be displayed to the current user. You may include placeholders like [node:title], [user:account-name], [user:display-name] and [comment:body] to represent data that will be different each time message is sent. Not all placeholders will be available in all contexts.'), - ); + ]; return $form; } diff --git a/core/modules/action/src/Plugin/migrate/source/Action.php b/core/modules/action/src/Plugin/migrate/source/Action.php index e983b00139..ac14a44b47 100644 --- a/core/modules/action/src/Plugin/migrate/source/Action.php +++ b/core/modules/action/src/Plugin/migrate/source/Action.php @@ -27,12 +27,12 @@ public function query() { * {@inheritdoc} */ public function fields() { - $fields = array( + $fields = [ 'aid' => $this->t('Action ID'), 'type' => $this->t('Module'), 'callback' => $this->t('Callback function'), 'parameters' => $this->t('Action configuration'), - ); + ]; if ($this->getModuleSchemaVersion('system') >= 7000) { $fields['label'] = $this->t('Label of the action'); } diff --git a/core/modules/action/tests/src/Functional/ActionListTest.php b/core/modules/action/tests/src/Functional/ActionListTest.php index 2510e86ef1..309160f4be 100644 --- a/core/modules/action/tests/src/Functional/ActionListTest.php +++ b/core/modules/action/tests/src/Functional/ActionListTest.php @@ -16,7 +16,7 @@ class ActionListTest extends BrowserTestBase { * * @var array */ - public static $modules = array('action'); + public static $modules = ['action']; /** * Tests the behavior when there are no actions to list in the admin page. diff --git a/core/modules/action/tests/src/Functional/ActionUninstallTest.php b/core/modules/action/tests/src/Functional/ActionUninstallTest.php index 93e0bc0c26..6b52643bc5 100644 --- a/core/modules/action/tests/src/Functional/ActionUninstallTest.php +++ b/core/modules/action/tests/src/Functional/ActionUninstallTest.php @@ -17,19 +17,19 @@ class ActionUninstallTest extends BrowserTestBase { * * @var array */ - public static $modules = array('views', 'action'); + public static $modules = ['views', 'action']; /** * Tests Action uninstall. */ public function testActionUninstall() { - \Drupal::service('module_installer')->uninstall(array('action')); + \Drupal::service('module_installer')->uninstall(['action']); $storage = $this->container->get('entity_type.manager')->getStorage('action'); $storage->resetCache(['user_block_user_action']); $this->assertTrue($storage->load('user_block_user_action'), 'Configuration entity \'user_block_user_action\' still exists after uninstalling action module.' ); - $admin_user = $this->drupalCreateUser(array('administer users')); + $admin_user = $this->drupalCreateUser(['administer users']); $this->drupalLogin($admin_user); $this->drupalGet('admin/people'); diff --git a/core/modules/action/tests/src/Functional/BulkFormTest.php b/core/modules/action/tests/src/Functional/BulkFormTest.php index 7d32b94711..439ffe4d6d 100644 --- a/core/modules/action/tests/src/Functional/BulkFormTest.php +++ b/core/modules/action/tests/src/Functional/BulkFormTest.php @@ -18,7 +18,7 @@ class BulkFormTest extends BrowserTestBase { * * @var array */ - public static $modules = array('node', 'action_bulk_test'); + public static $modules = ['node', 'action_bulk_test']; /** * Tests the bulk form. @@ -31,30 +31,30 @@ public function testBulkForm() { $this->drupalGet('test_bulk_form_empty'); $this->assertText(t('This view is empty.'), 'Empty text found on empty bulk form.'); - $nodes = array(); + $nodes = []; for ($i = 0; $i < 10; $i++) { // Ensure nodes are sorted in the same order they are inserted in the // array. $timestamp = REQUEST_TIME - $i; - $nodes[] = $this->drupalCreateNode(array( + $nodes[] = $this->drupalCreateNode([ 'sticky' => FALSE, 'created' => $timestamp, 'changed' => $timestamp, - )); + ]); } $this->drupalGet('test_bulk_form'); // Test that the views edit header appears first. - $first_form_element = $this->xpath('//form/div[1][@id = :id]', array(':id' => 'edit-header')); + $first_form_element = $this->xpath('//form/div[1][@id = :id]', [':id' => 'edit-header']); $this->assertTrue($first_form_element, 'The views form edit header appears first.'); $this->assertFieldById('edit-action', NULL, 'The action select field appears.'); // Make sure a checkbox appears on all rows. - $edit = array(); + $edit = []; for ($i = 0; $i < 10; $i++) { - $this->assertFieldById('edit-node-bulk-form-' . $i, NULL, format_string('The checkbox on row @row appears.', array('@row' => $i))); + $this->assertFieldById('edit-node-bulk-form-' . $i, NULL, format_string('The checkbox on row @row appears.', ['@row' => $i])); $edit["node_bulk_form[$i]"] = TRUE; } @@ -67,12 +67,12 @@ public function testBulkForm() { $this->drupalGet('test_bulk_form'); // Set all nodes to sticky and check that. - $edit += array('action' => 'node_make_sticky_action'); + $edit += ['action' => 'node_make_sticky_action']; $this->drupalPostForm(NULL, $edit, t('Apply to selected items')); foreach ($nodes as $node) { $changed_node = $node_storage->load($node->id()); - $this->assertTrue($changed_node->isSticky(), format_string('Node @nid got marked as sticky.', array('@nid' => $node->id()))); + $this->assertTrue($changed_node->isSticky(), format_string('Node @nid got marked as sticky.', ['@nid' => $node->id()])); } $this->assertText('Make content sticky was applied to 10 items.'); @@ -81,18 +81,18 @@ public function testBulkForm() { $node = $node_storage->load($nodes[0]->id()); $this->assertTrue($node->isPublished(), 'The node is published.'); - $edit = array('node_bulk_form[0]' => TRUE, 'action' => 'node_unpublish_action'); + $edit = ['node_bulk_form[0]' => TRUE, 'action' => 'node_unpublish_action']; $this->drupalPostForm(NULL, $edit, t('Apply to selected items')); $this->assertText('Unpublish content was applied to 1 item.'); // Load the node again. - $node_storage->resetCache(array($node->id())); + $node_storage->resetCache([$node->id()]); $node = $node_storage->load($node->id()); $this->assertFalse($node->isPublished(), 'A single node has been unpublished.'); // The second node should still be published. - $node_storage->resetCache(array($nodes[1]->id())); + $node_storage->resetCache([$nodes[1]->id()]); $node = $node_storage->load($nodes[1]->id()); $this->assertTrue($node->isPublished(), 'An unchecked node is still published.'); @@ -105,7 +105,7 @@ public function testBulkForm() { $view->save(); $this->drupalGet('test_bulk_form'); - $options = $this->xpath('//select[@id=:id]/option', array(':id' => 'edit-action')); + $options = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-action']); $this->assertEqual(count($options), 2); $this->assertOption('edit-action', 'node_make_sticky_action'); $this->assertOption('edit-action', 'node_make_unsticky_action'); @@ -137,17 +137,17 @@ public function testBulkForm() { $this->drupalGet('test_bulk_form'); // Call the node delete action. - $edit = array(); + $edit = []; for ($i = 0; $i < 5; $i++) { $edit["node_bulk_form[$i]"] = TRUE; } - $edit += array('action' => 'node_delete_action'); + $edit += ['action' => 'node_delete_action']; $this->drupalPostForm(NULL, $edit, t('Apply to selected items')); // Make sure we don't show an action message while we are still on the // confirmation page. $errors = $this->xpath('//div[contains(@class, "messages--status")]'); $this->assertFalse($errors, 'No action message shown.'); - $this->drupalPostForm(NULL, array(), t('Delete')); + $this->drupalPostForm(NULL, [], t('Delete')); $this->assertText(t('Deleted 5 posts.')); // Check if we got redirected to the original page. $this->assertUrl('test_bulk_form'); diff --git a/core/modules/action/tests/src/Functional/ConfigurationTest.php b/core/modules/action/tests/src/Functional/ConfigurationTest.php index 23d0a38191..063e4a89eb 100644 --- a/core/modules/action/tests/src/Functional/ConfigurationTest.php +++ b/core/modules/action/tests/src/Functional/ConfigurationTest.php @@ -19,24 +19,24 @@ class ConfigurationTest extends BrowserTestBase { * * @var array */ - public static $modules = array('action'); + public static $modules = ['action']; /** * Tests configuration of advanced actions through administration interface. */ function testActionConfiguration() { // Create a user with permission to view the actions administration pages. - $user = $this->drupalCreateUser(array('administer actions')); + $user = $this->drupalCreateUser(['administer actions']); $this->drupalLogin($user); // Make a POST request to admin/config/system/actions. - $edit = array(); + $edit = []; $edit['action'] = Crypt::hashBase64('action_goto_action'); $this->drupalPostForm('admin/config/system/actions', $edit, t('Create')); $this->assertResponse(200); // Make a POST request to the individual action configuration page. - $edit = array(); + $edit = []; $action_label = $this->randomMachineName(); $edit['label'] = $action_label; $edit['id'] = strtolower($action_label); @@ -52,7 +52,7 @@ function testActionConfiguration() { $this->clickLink(t('Configure')); preg_match('|admin/config/system/actions/configure/(.+)|', $this->getUrl(), $matches); $aid = $matches[1]; - $edit = array(); + $edit = []; $new_action_label = $this->randomMachineName(); $edit['label'] = $new_action_label; $edit['url'] = 'admin'; @@ -72,12 +72,12 @@ function testActionConfiguration() { $this->drupalGet('admin/config/system/actions'); $this->clickLink(t('Delete')); $this->assertResponse(200); - $edit = array(); + $edit = []; $this->drupalPostForm("admin/config/system/actions/configure/$aid/delete", $edit, t('Delete')); $this->assertResponse(200); // Make sure that the action was actually deleted. - $this->assertRaw(t('The action %action has been deleted.', array('%action' => $new_action_label)), 'Make sure that we get a delete confirmation message.'); + $this->assertRaw(t('The action %action has been deleted.', ['%action' => $new_action_label]), 'Make sure that we get a delete confirmation message.'); $this->drupalGet('admin/config/system/actions'); $this->assertResponse(200); $this->assertNoText($new_action_label, "Make sure the action label does not appear on the overview page after we've deleted the action."); diff --git a/core/modules/action/tests/src/Unit/Menu/ActionLocalTasksTest.php b/core/modules/action/tests/src/Unit/Menu/ActionLocalTasksTest.php index 34d24b1ce1..1959f6510a 100644 --- a/core/modules/action/tests/src/Unit/Menu/ActionLocalTasksTest.php +++ b/core/modules/action/tests/src/Unit/Menu/ActionLocalTasksTest.php @@ -12,7 +12,7 @@ class ActionLocalTasksTest extends LocalTaskIntegrationTestBase { protected function setUp() { - $this->directoryList = array('action' => 'core/modules/action'); + $this->directoryList = ['action' => 'core/modules/action']; parent::setUp(); } @@ -20,7 +20,7 @@ protected function setUp() { * Tests local task existence. */ public function testActionLocalTasks() { - $this->assertLocalTasks('entity.action.collection', array(array('action.admin'))); + $this->assertLocalTasks('entity.action.collection', [['action.admin']]); } } diff --git a/core/modules/aggregator/aggregator.install b/core/modules/aggregator/aggregator.install index 5edc503181..9e05400b8c 100644 --- a/core/modules/aggregator/aggregator.install +++ b/core/modules/aggregator/aggregator.install @@ -10,11 +10,11 @@ */ function aggregator_requirements($phase) { $has_curl = function_exists('curl_init'); - $requirements = array(); - $requirements['curl'] = array( + $requirements = []; + $requirements['curl'] = [ 'title' => t('cURL'), 'value' => $has_curl ? t('Enabled') : t('Not found'), - ); + ]; if (!$has_curl) { $requirements['curl']['severity'] = REQUIREMENT_ERROR; $requirements['curl']['description'] = t('The Aggregator module requires the PHP cURL library. For more information, see the online information on installing the PHP cURL extension.'); diff --git a/core/modules/aggregator/aggregator.module b/core/modules/aggregator/aggregator.module index cf32734a30..0f856e3125 100644 --- a/core/modules/aggregator/aggregator.module +++ b/core/modules/aggregator/aggregator.module @@ -25,35 +25,35 @@ function aggregator_help($route_name, RouteMatchInterface $route_match) { $path_validator = \Drupal::pathValidator(); $output = ''; $output .= '

' . t('About') . '

'; - $output .= '

' . t('The Aggregator module is an on-site syndicator and news reader that gathers and displays fresh content from RSS-, RDF-, and Atom-based feeds made available across the web. Thousands of sites (particularly news sites and blogs) publish their latest headlines in feeds, using a number of standardized XML-based formats. For more information, see the online documentation for the Aggregator module.', array(':aggregator-module' => 'https://www.drupal.org/documentation/modules/aggregator')) . '

'; + $output .= '

' . t('The Aggregator module is an on-site syndicator and news reader that gathers and displays fresh content from RSS-, RDF-, and Atom-based feeds made available across the web. Thousands of sites (particularly news sites and blogs) publish their latest headlines in feeds, using a number of standardized XML-based formats. For more information, see the online documentation for the Aggregator module.', [':aggregator-module' => 'https://www.drupal.org/documentation/modules/aggregator']) . '

'; $output .= '

' . t('Uses') . '

'; $output .= '
'; // Check if the aggregator sources View is enabled. if ($url = $path_validator->getUrlIfValid('aggregator/sources')) { $output .= '
' . t('Viewing feeds') . '
'; - $output .= '
' . t('Users view feed content in the main aggregator display, or by their source (usually via an RSS feed reader). The most recent content in a feed can be displayed as a block through the Blocks administration page.', array(':aggregator' => \Drupal::url('aggregator.page_last'), ':aggregator-sources' => $url->toString(), ':admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '
'; + $output .= '
' . t('Users view feed content in the main aggregator display, or by their source (usually via an RSS feed reader). The most recent content in a feed can be displayed as a block through the Blocks administration page.', [':aggregator' => \Drupal::url('aggregator.page_last'), ':aggregator-sources' => $url->toString(), ':admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '
'; } $output .= '
' . t('Adding, editing, and deleting feeds') . '
'; - $output .= '
' . t('Administrators can add, edit, and delete feeds, and choose how often to check each feed for newly updated items on the Aggregator administration page.', array(':feededit' => \Drupal::url('aggregator.admin_overview'))) . '
'; + $output .= '
' . t('Administrators can add, edit, and delete feeds, and choose how often to check each feed for newly updated items on the Aggregator administration page.', [':feededit' => \Drupal::url('aggregator.admin_overview')]) . '
'; $output .= '
' . t('Configuring the display of feed items') . '
'; - $output .= '
' . t('Administrators can choose how many items are displayed in the listing pages, which HTML tags are allowed in the content of feed items, and whether they should be trimmed to a maximum number of characters on the Aggregator settings page.', array(':settings' => \Drupal::url('aggregator.admin_settings'))) . '
'; + $output .= '
' . t('Administrators can choose how many items are displayed in the listing pages, which HTML tags are allowed in the content of feed items, and whether they should be trimmed to a maximum number of characters on the Aggregator settings page.', [':settings' => \Drupal::url('aggregator.admin_settings')]) . '
'; $output .= '
' . t('Discarding old feed items') . '
'; - $output .= '
' . t('Administrators can choose whether to discard feed items that are older than a specified period of time on the Aggregator settings page. This requires a correctly configured cron maintenance task (see below).', array(':settings' => \Drupal::url('aggregator.admin_settings'))) . '
'; + $output .= '
' . t('Administrators can choose whether to discard feed items that are older than a specified period of time on the Aggregator settings page. This requires a correctly configured cron maintenance task (see below).', [':settings' => \Drupal::url('aggregator.admin_settings')]) . '
'; $output .= '
' . t('OPML integration') . '
'; // Check if the aggregator opml View is enabled. if ($url = $path_validator->getUrlIfValid('aggregator/opml')) { - $output .= '
' . t('A machine-readable OPML file of all feeds is available. OPML is an XML-based file format used to share outline-structured information such as a list of RSS feeds. Feeds can also be imported via an OPML file.', array(':aggregator-opml' => $url->toString(), ':import-opml' => \Drupal::url('aggregator.opml_add'))) . '
'; + $output .= '
' . t('A machine-readable OPML file of all feeds is available. OPML is an XML-based file format used to share outline-structured information such as a list of RSS feeds. Feeds can also be imported via an OPML file.', [':aggregator-opml' => $url->toString(), ':import-opml' => \Drupal::url('aggregator.opml_add')]) . '
'; } $output .= '
' . t('Configuring cron') . '
'; - $output .= '
' . t('A working cron maintenance task is required to update feeds automatically.', array(':cron' => \Drupal::url('system.cron_settings'))) . '
'; + $output .= '
' . t('A working cron maintenance task is required to update feeds automatically.', [':cron' => \Drupal::url('system.cron_settings')]) . '
'; $output .= '
'; return $output; case 'aggregator.admin_overview': // Don't use placeholders for possibility to change URLs for translators. $output = '

' . t('Many sites publish their headlines and posts in feeds, using a number of standardized XML-based formats. The aggregator supports RSS, RDF, and Atom.') . '

'; - $output .= '

' . t('Current feeds are listed below, and new feeds may be added. For each feed, the latest items block may be enabled at the blocks administration page.', array(':addfeed' => \Drupal::url('aggregator.feed_add'), ':block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '

'; + $output .= '

' . t('Current feeds are listed below, and new feeds may be added. For each feed, the latest items block may be enabled at the blocks administration page.', [':addfeed' => \Drupal::url('aggregator.feed_add'), ':block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '

'; return $output; case 'aggregator.feed_add': @@ -68,66 +68,66 @@ function aggregator_help($route_name, RouteMatchInterface $route_match) { * Implements hook_theme(). */ function aggregator_theme() { - return array( - 'aggregator_feed' => array( + return [ + 'aggregator_feed' => [ 'render element' => 'elements', 'file' => 'aggregator.theme.inc', - ), - 'aggregator_item' => array( + ], + 'aggregator_item' => [ 'render element' => 'elements', 'file' => 'aggregator.theme.inc', - ), - ); + ], + ]; } /** * Implements hook_entity_extra_field_info(). */ function aggregator_entity_extra_field_info() { - $extra = array(); + $extra = []; - $extra['aggregator_feed']['aggregator_feed'] = array( - 'display' => array( - 'items' => array( + $extra['aggregator_feed']['aggregator_feed'] = [ + 'display' => [ + 'items' => [ 'label' => t('Items'), 'description' => t('Items associated with this feed'), 'weight' => 0, - ), + ], // @todo Move to a formatter at https://www.drupal.org/node/2339917. - 'image' => array( + 'image' => [ 'label' => t('Image'), 'description' => t('The feed image'), 'weight' => 2, - ), + ], // @todo Move to a formatter at https://www.drupal.org/node/2149845. - 'description' => array( + 'description' => [ 'label' => t('Description'), 'description' => t('The description of this feed'), 'weight' => 3, - ), - 'more_link' => array( + ], + 'more_link' => [ 'label' => t('More link'), 'description' => t('A more link to the feed detail page'), 'weight' => 5, - ), - 'feed_icon' => array( + ], + 'feed_icon' => [ 'label' => t('Feed icon'), 'description' => t('An icon that links to the feed URL'), 'weight' => 6, - ), - ), - ); + ], + ], + ]; - $extra['aggregator_item']['aggregator_item'] = array( - 'display' => array( + $extra['aggregator_item']['aggregator_item'] = [ + 'display' => [ // @todo Move to a formatter at https://www.drupal.org/node/2149845. - 'description' => array( + 'description' => [ 'label' => t('Description'), 'description' => t('The description of this feed item'), 'weight' => 2, - ), - ), - ); + ], + ], + ]; return $extra; } diff --git a/core/modules/aggregator/src/AggregatorFeedViewsData.php b/core/modules/aggregator/src/AggregatorFeedViewsData.php index 2eb0d344f4..b47f837dbd 100644 --- a/core/modules/aggregator/src/AggregatorFeedViewsData.php +++ b/core/modules/aggregator/src/AggregatorFeedViewsData.php @@ -15,12 +15,12 @@ class AggregatorFeedViewsData extends EntityViewsData { public function getViewsData() { $data = parent::getViewsData(); - $data['aggregator_feed']['table']['join'] = array( - 'aggregator_item' => array( + $data['aggregator_feed']['table']['join'] = [ + 'aggregator_item' => [ 'left_field' => 'fid', 'field' => 'fid', - ), - ); + ], + ]; $data['aggregator_feed']['fid']['help'] = $this->t('The unique ID of the aggregator feed.'); $data['aggregator_feed']['fid']['argument']['id'] = 'aggregator_fid'; diff --git a/core/modules/aggregator/src/Controller/AggregatorController.php b/core/modules/aggregator/src/Controller/AggregatorController.php index c84fb18b63..021e4d10a2 100644 --- a/core/modules/aggregator/src/Controller/AggregatorController.php +++ b/core/modules/aggregator/src/Controller/AggregatorController.php @@ -48,9 +48,9 @@ public static function create(ContainerInterface $container) { */ public function feedAdd() { $feed = $this->entityManager()->getStorage('aggregator_feed') - ->create(array( + ->create([ 'refresh' => 3600, - )); + ]); return $this->entityFormBuilder()->getForm($feed); } @@ -67,15 +67,15 @@ public function feedAdd() { */ protected function buildPageList(array $items, $feed_source = '') { // Assemble output. - $build = array( + $build = [ '#type' => 'container', - '#attributes' => array('class' => array('aggregator-wrapper')), - ); - $build['feed_source'] = is_array($feed_source) ? $feed_source : array('#markup' => $feed_source); + '#attributes' => ['class' => ['aggregator-wrapper']], + ]; + $build['feed_source'] = is_array($feed_source) ? $feed_source : ['#markup' => $feed_source]; if ($items) { $build['items'] = $this->entityManager()->getViewBuilder('aggregator_item') ->viewMultiple($items, 'default'); - $build['pager'] = array('#type' => 'pager'); + $build['pager'] = ['#type' => 'pager']; } return $build; } @@ -94,8 +94,8 @@ protected function buildPageList(array $items, $feed_source = '') { */ public function feedRefresh(FeedInterface $aggregator_feed) { $message = $aggregator_feed->refreshItems() - ? $this->t('There is new syndicated content from %site.', array('%site' => $aggregator_feed->label())) - : $this->t('There is no new syndicated content from %site.', array('%site' => $aggregator_feed->label())); + ? $this->t('There is new syndicated content from %site.', ['%site' => $aggregator_feed->label()]) + : $this->t('There is no new syndicated content from %site.', ['%site' => $aggregator_feed->label()]); drupal_set_message($message); return $this->redirect('aggregator.admin_overview'); } @@ -111,22 +111,22 @@ public function adminOverview() { $feeds = $entity_manager->getStorage('aggregator_feed') ->loadMultiple(); - $header = array($this->t('Title'), $this->t('Items'), $this->t('Last update'), $this->t('Next update'), $this->t('Operations')); - $rows = array(); + $header = [$this->t('Title'), $this->t('Items'), $this->t('Last update'), $this->t('Next update'), $this->t('Operations')]; + $rows = []; /** @var \Drupal\aggregator\FeedInterface[] $feeds */ foreach ($feeds as $feed) { - $row = array(); + $row = []; $row[] = $feed->link(); $row[] = $this->formatPlural($entity_manager->getStorage('aggregator_item')->getItemCount($feed), '1 item', '@count items'); $last_checked = $feed->getLastCheckedTime(); $refresh_rate = $feed->getRefreshRate(); - $row[] = ($last_checked ? $this->t('@time ago', array('@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked))) : $this->t('never')); + $row[] = ($last_checked ? $this->t('@time ago', ['@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked)]) : $this->t('never')); if (!$last_checked && $refresh_rate) { $next_update = $this->t('imminently'); } elseif ($last_checked && $refresh_rate) { - $next_update = $next = $this->t('%time left', array('%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME))); + $next_update = $next = $this->t('%time left', ['%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME)]); } else { $next_update = $this->t('never'); @@ -136,33 +136,33 @@ public function adminOverview() { 'title' => $this->t('Edit'), 'url' => Url::fromRoute('entity.aggregator_feed.edit_form', ['aggregator_feed' => $feed->id()]), ]; - $links['delete'] = array( + $links['delete'] = [ 'title' => $this->t('Delete'), 'url' => Url::fromRoute('entity.aggregator_feed.delete_form', ['aggregator_feed' => $feed->id()]), - ); - $links['delete_items'] = array( + ]; + $links['delete_items'] = [ 'title' => $this->t('Delete items'), 'url' => Url::fromRoute('aggregator.feed_items_delete', ['aggregator_feed' => $feed->id()]), - ); - $links['update'] = array( + ]; + $links['update'] = [ 'title' => $this->t('Update items'), 'url' => Url::fromRoute('aggregator.feed_refresh', ['aggregator_feed' => $feed->id()]), - ); - $row[] = array( - 'data' => array( + ]; + $row[] = [ + 'data' => [ '#type' => 'operations', '#links' => $links, - ), - ); + ], + ]; $rows[] = $row; } - $build['feeds'] = array( + $build['feeds'] = [ '#prefix' => '

' . $this->t('Feed overview') . '

', '#type' => 'table', '#header' => $header, '#rows' => $rows, - '#empty' => $this->t('No feeds available. Add feed.', array(':link' => $this->url('aggregator.feed_add'))), - ); + '#empty' => $this->t('No feeds available. Add feed.', [':link' => $this->url('aggregator.feed_add')]), + ]; return $build; } @@ -176,7 +176,7 @@ public function adminOverview() { public function pageLast() { $items = $this->entityManager()->getStorage('aggregator_item')->loadAll(20); $build = $this->buildPageList($items); - $build['#attached']['feed'][] = array('aggregator/rss', $this->config('system.site')->get('name') . ' ' . $this->t('aggregator')); + $build['#attached']['feed'][] = ['aggregator/rss', $this->config('system.site')->get('name') . ' ' . $this->t('aggregator')]; return $build; } diff --git a/core/modules/aggregator/src/Entity/Feed.php b/core/modules/aggregator/src/Entity/Feed.php index 834a55e9a8..3b14e8c24e 100644 --- a/core/modules/aggregator/src/Entity/Feed.php +++ b/core/modules/aggregator/src/Entity/Feed.php @@ -88,11 +88,11 @@ public function refreshItems() { * {@inheritdoc} */ public static function preCreate(EntityStorageInterface $storage, array &$values) { - $values += array( + $values += [ 'link' => '', 'description' => '', 'image' => '', - ); + ]; } /** @@ -143,10 +143,10 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setDescription(t('The name of the feed (or the name of the website providing the feed).')) ->setRequired(TRUE) ->setSetting('max_length', 255) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'string_textfield', 'weight' => -5, - )) + ]) ->setDisplayConfigurable('form', TRUE) ->addConstraint('FeedTitle'); @@ -154,15 +154,15 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setLabel(t('URL')) ->setDescription(t('The fully-qualified URL of the feed.')) ->setRequired(TRUE) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'uri', 'weight' => -3, - )) + ]) ->setDisplayConfigurable('form', TRUE) ->addConstraint('FeedUrl'); - $intervals = array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200); - $period = array_map(array(\Drupal::service('date.formatter'), 'formatInterval'), array_combine($intervals, $intervals)); + $intervals = [900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200]; + $period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals)); $period[AGGREGATOR_CLEAR_NEVER] = t('Never'); $fields['refresh'] = BaseFieldDefinition::create('list_integer') @@ -171,21 +171,21 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setSetting('unsigned', TRUE) ->setRequired(TRUE) ->setSetting('allowed_values', $period) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'options_select', 'weight' => -2, - )) + ]) ->setDisplayConfigurable('form', TRUE); $fields['checked'] = BaseFieldDefinition::create('timestamp') ->setLabel(t('Checked')) ->setDescription(t('Last time feed was checked for new items, as Unix timestamp.')) ->setDefaultValue(0) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'label' => 'inline', 'type' => 'timestamp_ago', 'weight' => 1, - )) + ]) ->setDisplayConfigurable('view', TRUE); $fields['queued'] = BaseFieldDefinition::create('timestamp') @@ -196,15 +196,15 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields['link'] = BaseFieldDefinition::create('uri') ->setLabel(t('URL')) ->setDescription(t('The link of the feed.')) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'label' => 'inline', 'weight' => 4, - )) + ]) ->setDisplayConfigurable('view', TRUE); $fields['description'] = BaseFieldDefinition::create('string_long') ->setLabel(t('Description')) - ->setDescription(t("The parent website's description that comes from the @description element in the feed.", array('@description' => ''))); + ->setDescription(t("The parent website's description that comes from the @description element in the feed.", ['@description' => ''])); $fields['image'] = BaseFieldDefinition::create('uri') ->setLabel(t('Image')) diff --git a/core/modules/aggregator/src/Entity/Item.php b/core/modules/aggregator/src/Entity/Item.php index 969e4e40bd..ef0c6d2451 100644 --- a/core/modules/aggregator/src/Entity/Item.php +++ b/core/modules/aggregator/src/Entity/Item.php @@ -61,11 +61,11 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setRequired(TRUE) ->setDescription(t('The aggregator feed entity associated with this item.')) ->setSetting('target_type', 'aggregator_feed') - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'label' => 'hidden', 'type' => 'entity_reference_label', 'weight' => 0, - )) + ]) ->setDisplayConfigurable('form', TRUE); $fields['title'] = BaseFieldDefinition::create('string') @@ -75,18 +75,18 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields['link'] = BaseFieldDefinition::create('uri') ->setLabel(t('Link')) ->setDescription(t('The link of the feed item.')) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'region' => 'hidden', - )) + ]) ->setDisplayConfigurable('view', TRUE); $fields['author'] = BaseFieldDefinition::create('string') ->setLabel(t('Author')) ->setDescription(t('The author of the feed item.')) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'label' => 'hidden', 'weight' => 3, - )) + ]) ->setDisplayConfigurable('view', TRUE); $fields['description'] = BaseFieldDefinition::create('string_long') @@ -96,11 +96,11 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields['timestamp'] = BaseFieldDefinition::create('created') ->setLabel(t('Posted on')) ->setDescription(t('Posted date of the feed item, as a Unix timestamp.')) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'label' => 'hidden', 'type' => 'timestamp_ago', 'weight' => 1, - )) + ]) ->setDisplayConfigurable('view', TRUE); // @todo Convert to a real UUID field in diff --git a/core/modules/aggregator/src/FeedForm.php b/core/modules/aggregator/src/FeedForm.php index 3447cc8c0f..1580a307dc 100644 --- a/core/modules/aggregator/src/FeedForm.php +++ b/core/modules/aggregator/src/FeedForm.php @@ -20,12 +20,12 @@ public function save(array $form, FormStateInterface $form_state) { $label = $feed->label(); $view_link = $feed->link($label, 'canonical'); if ($status == SAVED_UPDATED) { - drupal_set_message($this->t('The feed %feed has been updated.', array('%feed' => $view_link))); + drupal_set_message($this->t('The feed %feed has been updated.', ['%feed' => $view_link])); $form_state->setRedirectUrl($feed->urlInfo('canonical')); } else { - $this->logger('aggregator')->notice('Feed %feed added.', array('%feed' => $feed->label(), 'link' => $this->l($this->t('View'), new Url('aggregator.admin_overview')))); - drupal_set_message($this->t('The feed %feed has been added.', array('%feed' => $view_link))); + $this->logger('aggregator')->notice('Feed %feed added.', ['%feed' => $feed->label(), 'link' => $this->l($this->t('View'), new Url('aggregator.admin_overview'))]); + drupal_set_message($this->t('The feed %feed has been added.', ['%feed' => $view_link])); } } diff --git a/core/modules/aggregator/src/FeedStorage.php b/core/modules/aggregator/src/FeedStorage.php index 5085e6d353..ded3531380 100644 --- a/core/modules/aggregator/src/FeedStorage.php +++ b/core/modules/aggregator/src/FeedStorage.php @@ -16,10 +16,10 @@ class FeedStorage extends SqlContentEntityStorage implements FeedStorageInterfac * {@inheritdoc} */ public function getFeedIdsToRefresh() { - return $this->database->query('SELECT fid FROM {aggregator_feed} WHERE queued = 0 AND checked + refresh < :time AND refresh <> :never', array( + return $this->database->query('SELECT fid FROM {aggregator_feed} WHERE queued = 0 AND checked + refresh < :time AND refresh <> :never', [ ':time' => REQUEST_TIME, ':never' => AGGREGATOR_CLEAR_NEVER, - ))->fetchCol(); + ])->fetchCol(); } } diff --git a/core/modules/aggregator/src/FeedViewBuilder.php b/core/modules/aggregator/src/FeedViewBuilder.php index 5ce69ffd87..1efaa3028c 100644 --- a/core/modules/aggregator/src/FeedViewBuilder.php +++ b/core/modules/aggregator/src/FeedViewBuilder.php @@ -68,65 +68,65 @@ public function buildComponents(array &$build, array $entities, array $displays, if ($view_mode == 'full') { // Also add the pager. - $build[$id]['pager'] = array('#type' => 'pager'); + $build[$id]['pager'] = ['#type' => 'pager']; } } if ($display->getComponent('description')) { - $build[$id]['description'] = array( + $build[$id]['description'] = [ '#markup' => $entity->getDescription(), '#allowed_tags' => _aggregator_allowed_tags(), '#prefix' => '
', '#suffix' => '
', - ); + ]; } if ($display->getComponent('image')) { - $image_link = array(); + $image_link = []; // Render the image as link if it is available. $image = $entity->getImage(); $label = $entity->label(); $link_href = $entity->getWebsiteUrl(); if ($image && $label && $link_href) { - $link_title = array( + $link_title = [ '#theme' => 'image', '#uri' => $image, '#alt' => $label, - ); - $image_link = array( + ]; + $image_link = [ '#type' => 'link', '#title' => $link_title, '#url' => Url::fromUri($link_href), - '#options' => array( - 'attributes' => array('class' => array('feed-image')), - ), - ); + '#options' => [ + 'attributes' => ['class' => ['feed-image']], + ], + ]; } $build[$id]['image'] = $image_link; } if ($display->getComponent('feed_icon')) { - $build[$id]['feed_icon'] = array( + $build[$id]['feed_icon'] = [ '#theme' => 'feed_icon', '#url' => $entity->getUrl(), - '#title' => t('@title feed', array('@title' => $entity->label())), - ); + '#title' => t('@title feed', ['@title' => $entity->label()]), + ]; } if ($display->getComponent('more_link')) { $title_stripped = strip_tags($entity->label()); - $build[$id]['more_link'] = array( + $build[$id]['more_link'] = [ '#type' => 'link', - '#title' => t('More posts about @title', array( + '#title' => t('More posts about @title', [ '@title' => $title_stripped, - )), + ]), '#url' => Url::fromRoute('entity.aggregator_feed.canonical', ['aggregator_feed' => $entity->id()]), - '#options' => array( - 'attributes' => array( + '#options' => [ + 'attributes' => [ 'title' => $title_stripped, - ), - ), - ); + ], + ], + ]; } } diff --git a/core/modules/aggregator/src/Form/FeedDeleteForm.php b/core/modules/aggregator/src/Form/FeedDeleteForm.php index bcf1a3273a..17a179864f 100644 --- a/core/modules/aggregator/src/Form/FeedDeleteForm.php +++ b/core/modules/aggregator/src/Form/FeedDeleteForm.php @@ -28,9 +28,9 @@ protected function getRedirectUrl() { * {@inheritdoc} */ protected function getDeletionMessage() { - return $this->t('The feed %label has been deleted.', array( + return $this->t('The feed %label has been deleted.', [ '%label' => $this->entity->label(), - )); + ]); } } diff --git a/core/modules/aggregator/src/Form/FeedItemsDeleteForm.php b/core/modules/aggregator/src/Form/FeedItemsDeleteForm.php index 1117359c0d..48c83dc838 100644 --- a/core/modules/aggregator/src/Form/FeedItemsDeleteForm.php +++ b/core/modules/aggregator/src/Form/FeedItemsDeleteForm.php @@ -15,7 +15,7 @@ class FeedItemsDeleteForm extends ContentEntityConfirmFormBase { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to delete all items from the feed %feed?', array('%feed' => $this->entity->label())); + return $this->t('Are you sure you want to delete all items from the feed %feed?', ['%feed' => $this->entity->label()]); } /** diff --git a/core/modules/aggregator/src/Form/OpmlFeedAdd.php b/core/modules/aggregator/src/Form/OpmlFeedAdd.php index c78a8b73ac..59e70d9727 100644 --- a/core/modules/aggregator/src/Form/OpmlFeedAdd.php +++ b/core/modules/aggregator/src/Form/OpmlFeedAdd.php @@ -63,33 +63,33 @@ public function getFormId() { * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { - $intervals = array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200); - $period = array_map(array(\Drupal::service('date.formatter'), 'formatInterval'), array_combine($intervals, $intervals)); + $intervals = [900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200]; + $period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals)); - $form['upload'] = array( + $form['upload'] = [ '#type' => 'file', '#title' => $this->t('OPML File'), '#description' => $this->t('Upload an OPML file containing a list of feeds to be imported.'), - ); - $form['remote'] = array( + ]; + $form['remote'] = [ '#type' => 'url', '#title' => $this->t('OPML Remote URL'), '#maxlength' => 1024, '#description' => $this->t('Enter the URL of an OPML file. This file will be downloaded and processed only once on submission of the form.'), - ); - $form['refresh'] = array( + ]; + $form['refresh'] = [ '#type' => 'select', '#title' => $this->t('Update interval'), '#default_value' => 3600, '#options' => $period, - '#description' => $this->t('The length of time between feed updates. Requires a correctly configured cron maintenance task.', array(':cron' => $this->url('system.status'))), - ); + '#description' => $this->t('The length of time between feed updates. Requires a correctly configured cron maintenance task.', [':cron' => $this->url('system.status')]), + ]; - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Import'), - ); + ]; return $form; } @@ -109,7 +109,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) { * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { - $validators = array('file_validate_extensions' => array('opml xml')); + $validators = ['file_validate_extensions' => ['opml xml']]; if ($file = file_save_upload('upload', $validators, FALSE, 0)) { $data = file_get_contents($file->getFileUri()); } @@ -120,8 +120,8 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $data = (string) $response->getBody(); } catch (RequestException $e) { - $this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', array('%error' => $e->getMessage())); - drupal_set_message($this->t('Failed to download OPML file due to "%error".', array('%error' => $e->getMessage()))); + $this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]); + drupal_set_message($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()])); return; } } @@ -136,7 +136,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { foreach ($feeds as $feed) { // Ensure URL is valid. if (!UrlHelper::isValid($feed['url'], TRUE)) { - drupal_set_message($this->t('The URL %url is invalid.', array('%url' => $feed['url'])), 'warning'); + drupal_set_message($this->t('The URL %url is invalid.', ['%url' => $feed['url']]), 'warning'); continue; } @@ -151,20 +151,20 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $result = $this->feedStorage->loadMultiple($ids); foreach ($result as $old) { if (strcasecmp($old->label(), $feed['title']) == 0) { - drupal_set_message($this->t('A feed named %title already exists.', array('%title' => $old->label())), 'warning'); + drupal_set_message($this->t('A feed named %title already exists.', ['%title' => $old->label()]), 'warning'); continue 2; } if (strcasecmp($old->getUrl(), $feed['url']) == 0) { - drupal_set_message($this->t('A feed with the URL %url already exists.', array('%url' => $old->getUrl())), 'warning'); + drupal_set_message($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]), 'warning'); continue 2; } } - $new_feed = $this->feedStorage->create(array( + $new_feed = $this->feedStorage->create([ 'title' => $feed['title'], 'url' => $feed['url'], 'refresh' => $form_state->getValue('refresh'), - )); + ]); $new_feed->save(); } @@ -189,7 +189,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { * @todo Move this to a parser in https://www.drupal.org/node/1963540. */ protected function parseOpml($opml) { - $feeds = array(); + $feeds = []; $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8'); if (xml_parse_into_struct($xml_parser, $opml, $values)) { @@ -197,7 +197,7 @@ protected function parseOpml($opml) { if ($entry['tag'] == 'OUTLINE' && isset($entry['attributes'])) { $item = $entry['attributes']; if (!empty($item['XMLURL']) && !empty($item['TEXT'])) { - $feeds[] = array('title' => $item['TEXT'], 'url' => $item['XMLURL']); + $feeds[] = ['title' => $item['TEXT'], 'url' => $item['XMLURL']]; } } } diff --git a/core/modules/aggregator/src/Form/SettingsForm.php b/core/modules/aggregator/src/Form/SettingsForm.php index edd574189d..48b2dfe87e 100644 --- a/core/modules/aggregator/src/Form/SettingsForm.php +++ b/core/modules/aggregator/src/Form/SettingsForm.php @@ -21,25 +21,25 @@ class SettingsForm extends ConfigFormBase { * * @var \Drupal\aggregator\Plugin\AggregatorPluginManager[] */ - protected $managers = array(); + protected $managers = []; /** * The instantiated plugin instances that have configuration forms. * * @var \Drupal\Core\Plugin\PluginFormInterface[] */ - protected $configurableInstances = array(); + protected $configurableInstances = []; /** * The aggregator plugin definitions. * * @var array */ - protected $definitions = array( - 'fetcher' => array(), - 'parser' => array(), - 'processor' => array(), - ); + protected $definitions = [ + 'fetcher' => [], + 'parser' => [], + 'processor' => [], + ]; /** * Constructs a \Drupal\aggregator\SettingsForm object. @@ -58,15 +58,15 @@ class SettingsForm extends ConfigFormBase { public function __construct(ConfigFactoryInterface $config_factory, AggregatorPluginManager $fetcher_manager, AggregatorPluginManager $parser_manager, AggregatorPluginManager $processor_manager, TranslationInterface $string_translation) { parent::__construct($config_factory); $this->stringTranslation = $string_translation; - $this->managers = array( + $this->managers = [ 'fetcher' => $fetcher_manager, 'parser' => $parser_manager, 'processor' => $processor_manager, - ); + ]; // Get all available fetcher, parser and processor definitions. - foreach (array('fetcher', 'parser', 'processor') as $type) { + foreach (['fetcher', 'parser', 'processor'] as $type) { foreach ($this->managers[$type]->getDefinitions() as $id => $definition) { - $this->definitions[$type][$id] = SafeMarkup::format('@title @description', array('@title' => $definition['title'], '@description' => $definition['description'])); + $this->definitions[$type][$id] = SafeMarkup::format('@title @description', ['@title' => $definition['title'], '@description' => $definition['description']]); } } } @@ -105,56 +105,56 @@ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('aggregator.settings'); // Global aggregator settings. - $form['aggregator_allowed_html_tags'] = array( + $form['aggregator_allowed_html_tags'] = [ '#type' => 'textfield', '#title' => $this->t('Allowed HTML tags'), '#size' => 80, '#maxlength' => 255, '#default_value' => $config->get('items.allowed_html'), '#description' => $this->t('A space-separated list of HTML tags allowed in the content of feed items. Disallowed tags are stripped from the content.'), - ); + ]; // Only show basic configuration if there are actually options. - $basic_conf = array(); + $basic_conf = []; if (count($this->definitions['fetcher']) > 1) { - $basic_conf['aggregator_fetcher'] = array( + $basic_conf['aggregator_fetcher'] = [ '#type' => 'radios', '#title' => $this->t('Fetcher'), '#description' => $this->t('Fetchers download data from an external source. Choose a fetcher suitable for the external source you would like to download from.'), '#options' => $this->definitions['fetcher'], '#default_value' => $config->get('fetcher'), - ); + ]; } if (count($this->definitions['parser']) > 1) { - $basic_conf['aggregator_parser'] = array( + $basic_conf['aggregator_parser'] = [ '#type' => 'radios', '#title' => $this->t('Parser'), '#description' => $this->t('Parsers transform downloaded data into standard structures. Choose a parser suitable for the type of feeds you would like to aggregate.'), '#options' => $this->definitions['parser'], '#default_value' => $config->get('parser'), - ); + ]; } if (count($this->definitions['processor']) > 1) { - $basic_conf['aggregator_processors'] = array( + $basic_conf['aggregator_processors'] = [ '#type' => 'checkboxes', '#title' => $this->t('Processors'), '#description' => $this->t('Processors act on parsed feed data, for example they store feed items. Choose the processors suitable for your task.'), '#options' => $this->definitions['processor'], '#default_value' => $config->get('processors'), - ); + ]; } if (count($basic_conf)) { - $form['basic_conf'] = array( + $form['basic_conf'] = [ '#type' => 'details', '#title' => $this->t('Basic configuration'), '#description' => $this->t('For most aggregation tasks, the default settings are fine.'), '#open' => TRUE, - ); + ]; $form['basic_conf'] += $basic_conf; } // Call buildConfigurationForm() on the active fetcher and parser. - foreach (array('fetcher', 'parser') as $type) { + foreach (['fetcher', 'parser'] as $type) { $active = $config->get($type); if (array_key_exists($active, $this->definitions[$type])) { $instance = $this->managers[$type]->createInstance($active); @@ -169,7 +169,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { } // Implementing processor plugins will expect an array at $form['processors']. - $form['processors'] = array(); + $form['processors'] = []; // Call buildConfigurationForm() for each active processor. foreach ($this->definitions['processor'] as $id => $definition) { if (in_array($id, $config->get('processors'))) { diff --git a/core/modules/aggregator/src/ItemViewBuilder.php b/core/modules/aggregator/src/ItemViewBuilder.php index feb0ffafb8..feb35b5835 100644 --- a/core/modules/aggregator/src/ItemViewBuilder.php +++ b/core/modules/aggregator/src/ItemViewBuilder.php @@ -20,12 +20,12 @@ public function buildComponents(array &$build, array $entities, array $displays, $display = $displays[$bundle]; if ($display->getComponent('description')) { - $build[$id]['description'] = array( + $build[$id]['description'] = [ '#markup' => $entity->getDescription(), '#allowed_tags' => _aggregator_allowed_tags(), '#prefix' => '
', '#suffix' => '
', - ); + ]; } } } diff --git a/core/modules/aggregator/src/ItemsImporter.php b/core/modules/aggregator/src/ItemsImporter.php index df02564080..aa18d65c9a 100644 --- a/core/modules/aggregator/src/ItemsImporter.php +++ b/core/modules/aggregator/src/ItemsImporter.php @@ -95,7 +95,7 @@ public function refresh(FeedInterface $feed) { } // Store instances in an array so we dont have to instantiate new objects. - $processor_instances = array(); + $processor_instances = []; foreach ($this->config->get('processors') as $processor) { try { $processor_instances[$processor] = $this->processorManager->createInstance($processor); @@ -124,10 +124,10 @@ public function refresh(FeedInterface $feed) { // Log if feed URL has changed. if ($feed->getUrl() != $feed_url) { - $this->logger->notice('Updated URL for feed %title to %url.', array('%title' => $feed->label(), '%url' => $feed->getUrl())); + $this->logger->notice('Updated URL for feed %title to %url.', ['%title' => $feed->label(), '%url' => $feed->getUrl()]); } - $this->logger->notice('There is new syndicated content from %site.', array('%site' => $feed->label())); + $this->logger->notice('There is new syndicated content from %site.', ['%site' => $feed->label()]); // If there are items on the feed, let enabled processors process them. if (!empty($feed->items)) { diff --git a/core/modules/aggregator/src/Plugin/AggregatorPluginManager.php b/core/modules/aggregator/src/Plugin/AggregatorPluginManager.php index cd8a6e3e1c..7310987988 100644 --- a/core/modules/aggregator/src/Plugin/AggregatorPluginManager.php +++ b/core/modules/aggregator/src/Plugin/AggregatorPluginManager.php @@ -34,16 +34,16 @@ class AggregatorPluginManager extends DefaultPluginManager { * The module handler. */ public function __construct($type, \Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) { - $type_annotations = array( + $type_annotations = [ 'fetcher' => 'Drupal\aggregator\Annotation\AggregatorFetcher', 'parser' => 'Drupal\aggregator\Annotation\AggregatorParser', 'processor' => 'Drupal\aggregator\Annotation\AggregatorProcessor', - ); - $plugin_interfaces = array( + ]; + $plugin_interfaces = [ 'fetcher' => 'Drupal\aggregator\Plugin\FetcherInterface', 'parser' => 'Drupal\aggregator\Plugin\ParserInterface', 'processor' => 'Drupal\aggregator\Plugin\ProcessorInterface', - ); + ]; parent::__construct("Plugin/aggregator/$type", $namespaces, $module_handler, $plugin_interfaces[$type], $type_annotations[$type]); $this->setCacheBackend($cache_backend, 'aggregator_' . $type . '_plugins'); diff --git a/core/modules/aggregator/src/Plugin/AggregatorPluginSettingsBase.php b/core/modules/aggregator/src/Plugin/AggregatorPluginSettingsBase.php index bc59ec5eb2..403e6a3490 100644 --- a/core/modules/aggregator/src/Plugin/AggregatorPluginSettingsBase.php +++ b/core/modules/aggregator/src/Plugin/AggregatorPluginSettingsBase.php @@ -25,7 +25,7 @@ * {@inheritdoc} */ public function defaultConfiguration() { - return array(); + return []; } /** @@ -38,7 +38,7 @@ public function validateConfigurationForm(array &$form, FormStateInterface $form * {@inheritdoc} */ public function calculateDependencies() { - return array(); + return []; } } diff --git a/core/modules/aggregator/src/Plugin/Block/AggregatorFeedBlock.php b/core/modules/aggregator/src/Plugin/Block/AggregatorFeedBlock.php index 72e7a30892..90d8f669dd 100644 --- a/core/modules/aggregator/src/Plugin/Block/AggregatorFeedBlock.php +++ b/core/modules/aggregator/src/Plugin/Block/AggregatorFeedBlock.php @@ -77,10 +77,10 @@ public static function create(ContainerInterface $container, array $configuratio */ public function defaultConfiguration() { // By default, the block will contain 10 feed items. - return array( + return [ 'block_count' => 10, 'feed' => NULL, - ); + ]; } /** @@ -96,23 +96,23 @@ protected function blockAccess(AccountInterface $account) { */ public function blockForm($form, FormStateInterface $form_state) { $feeds = $this->feedStorage->loadMultiple(); - $options = array(); + $options = []; foreach ($feeds as $feed) { $options[$feed->id()] = $feed->label(); } - $form['feed'] = array( + $form['feed'] = [ '#type' => 'select', '#title' => $this->t('Select the feed that should be displayed'), '#default_value' => $this->configuration['feed'], '#options' => $options, - ); + ]; $range = range(2, 20); - $form['block_count'] = array( + $form['block_count'] = [ '#type' => 'select', '#title' => $this->t('Number of news items in block'), '#default_value' => $this->configuration['block_count'], '#options' => array_combine($range, $range), - ); + ]; return $form; } diff --git a/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php b/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php index 99ec48d9ce..91c7ac36ed 100644 --- a/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php +++ b/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php @@ -112,8 +112,8 @@ public function fetch(FeedInterface $feed) { return TRUE; } catch (RequestException $e) { - $this->logger->warning('The feed from %site seems to be broken because of error "%error".', array('%site' => $feed->label(), '%error' => $e->getMessage())); - drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', array('%site' => $feed->label(), '%error' => $e->getMessage())), 'warning'); + $this->logger->warning('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]); + drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]), 'warning'); return FALSE; } } diff --git a/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php b/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php index 2fb36823d8..03fa55f01c 100644 --- a/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php +++ b/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php @@ -31,7 +31,7 @@ public function parse(FeedInterface $feed) { } catch (ExceptionInterface $e) { watchdog_exception('aggregator', $e); - drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', array('%site' => $feed->label(), '%error' => $e->getMessage())), 'error'); + drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]), 'error'); return FALSE; } @@ -42,10 +42,10 @@ public function parse(FeedInterface $feed) { $feed->setImage($image['uri']); } // Initialize items array. - $feed->items = array(); + $feed->items = []; foreach ($channel as $item) { // Reset the parsed item. - $parsed_item = array(); + $parsed_item = []; // Move the values to an array as expected by processors. $parsed_item['title'] = $item->getTitle(); $parsed_item['guid'] = $item->getId(); diff --git a/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php b/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php index 4469c51a6d..525ef34f13 100644 --- a/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php +++ b/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php @@ -105,53 +105,53 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta $config = $this->config('aggregator.settings'); $processors = $config->get('processors'); $info = $this->getPluginDefinition(); - $counts = array(3, 5, 10, 15, 20, 25); + $counts = [3, 5, 10, 15, 20, 25]; $items = array_map(function ($count) { return $this->formatPlural($count, '1 item', '@count items'); }, array_combine($counts, $counts)); - $intervals = array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800); - $period = array_map(array($this->dateFormatter, 'formatInterval'), array_combine($intervals, $intervals)); + $intervals = [3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800]; + $period = array_map([$this->dateFormatter, 'formatInterval'], array_combine($intervals, $intervals)); $period[AGGREGATOR_CLEAR_NEVER] = t('Never'); - $form['processors'][$info['id']] = array(); + $form['processors'][$info['id']] = []; // Only wrap into details if there is a basic configuration. if (isset($form['basic_conf'])) { - $form['processors'][$info['id']] = array( + $form['processors'][$info['id']] = [ '#type' => 'details', '#title' => t('Default processor settings'), '#description' => $info['description'], '#open' => in_array($info['id'], $processors), - ); + ]; } - $form['processors'][$info['id']]['aggregator_summary_items'] = array( + $form['processors'][$info['id']]['aggregator_summary_items'] = [ '#type' => 'select', '#title' => t('Number of items shown in listing pages'), '#default_value' => $config->get('source.list_max'), '#empty_value' => 0, '#options' => $items, - ); + ]; - $form['processors'][$info['id']]['aggregator_clear'] = array( + $form['processors'][$info['id']]['aggregator_clear'] = [ '#type' => 'select', '#title' => t('Discard items older than'), '#default_value' => $config->get('items.expire'), '#options' => $period, - '#description' => t('Requires a correctly configured cron maintenance task.', array(':cron' => $this->url('system.status'))), - ); + '#description' => t('Requires a correctly configured cron maintenance task.', [':cron' => $this->url('system.status')]), + ]; - $lengths = array(0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000); + $lengths = [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000]; $options = array_map(function($length) { return ($length == 0) ? t('Unlimited') : $this->formatPlural($length, '1 character', '@count characters'); }, array_combine($lengths, $lengths)); - $form['processors'][$info['id']]['aggregator_teaser_length'] = array( + $form['processors'][$info['id']]['aggregator_teaser_length'] = [ '#type' => 'select', '#title' => t('Length of trimmed description'), '#default_value' => $config->get('items.teaser_length'), '#options' => $options, '#description' => t('The maximum number of characters used in the trimmed version of content.'), - ); + ]; return $form; } @@ -185,13 +185,13 @@ public function process(FeedInterface $feed) { // we find a duplicate entry, we resolve it and pass along its ID is such // that we can update it if needed. if (!empty($item['guid'])) { - $values = array('fid' => $feed->id(), 'guid' => $item['guid']); + $values = ['fid' => $feed->id(), 'guid' => $item['guid']]; } elseif ($item['link'] && $item['link'] != $feed->link && $item['link'] != $feed->url) { - $values = array('fid' => $feed->id(), 'link' => $item['link']); + $values = ['fid' => $feed->id(), 'link' => $item['link']]; } else { - $values = array('fid' => $feed->id(), 'title' => $item['title']); + $values = ['fid' => $feed->id(), 'title' => $item['title']]; } // Try to load an existing entry. @@ -199,7 +199,7 @@ public function process(FeedInterface $feed) { $entry = reset($entry); } else { - $entry = Item::create(array('langcode' => $feed->language()->getId())); + $entry = Item::create(['langcode' => $feed->language()->getId()]); } if ($item['timestamp']) { $entry->setPostedTime($item['timestamp']); @@ -231,7 +231,7 @@ public function delete(FeedInterface $feed) { $this->itemStorage->delete($items); } // @todo This should be moved out to caller with a different message maybe. - drupal_set_message(t('The news items from %site have been deleted.', array('%site' => $feed->label()))); + drupal_set_message(t('The news items from %site have been deleted.', ['%site' => $feed->label()])); } /** diff --git a/core/modules/aggregator/src/Plugin/migrate/source/AggregatorFeed.php b/core/modules/aggregator/src/Plugin/migrate/source/AggregatorFeed.php index e623e5fd0b..59244d4e4a 100644 --- a/core/modules/aggregator/src/Plugin/migrate/source/AggregatorFeed.php +++ b/core/modules/aggregator/src/Plugin/migrate/source/AggregatorFeed.php @@ -26,7 +26,7 @@ public function query() { * {@inheritdoc} */ public function fields() { - $fields = array( + $fields = [ 'fid' => $this->t('The feed ID.'), 'title' => $this->t('Title of the feed.'), 'url' => $this->t('URL to the feed.'), @@ -38,7 +38,7 @@ public function fields() { 'etag' => $this->t('Entity tag HTTP response header.'), 'modified' => $this->t('When the feed was last modified.'), 'block' => $this->t("Number of items to display in the feed's block."), - ); + ]; if ($this->getModuleSchemaVersion('system') >= 7000) { $fields['queued'] = $this->t('Time when this feed was queued for refresh, 0 if not queued.'); } diff --git a/core/modules/aggregator/src/Plugin/migrate/source/AggregatorItem.php b/core/modules/aggregator/src/Plugin/migrate/source/AggregatorItem.php index fc1c5c6c71..428c558ea7 100644 --- a/core/modules/aggregator/src/Plugin/migrate/source/AggregatorItem.php +++ b/core/modules/aggregator/src/Plugin/migrate/source/AggregatorItem.php @@ -27,7 +27,7 @@ public function query() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'iid' => $this->t('Primary Key: Unique ID for feed item.'), 'fid' => $this->t('The {aggregator_feed}.fid to which this item belongs.'), 'title' => $this->t('Title of the feed item.'), @@ -36,7 +36,7 @@ public function fields() { 'description' => $this->t('Body of the feed item.'), 'timestamp' => $this->t('Post date of feed item, as a Unix timestamp.'), 'guid' => $this->t('Unique identifier for the feed item.'), - ); + ]; } /** diff --git a/core/modules/aggregator/src/Plugin/views/argument/Fid.php b/core/modules/aggregator/src/Plugin/views/argument/Fid.php index bb912e1ce6..90564d5bb6 100644 --- a/core/modules/aggregator/src/Plugin/views/argument/Fid.php +++ b/core/modules/aggregator/src/Plugin/views/argument/Fid.php @@ -50,7 +50,7 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function titleQuery() { - $titles = array(); + $titles = []; $feeds = $this->entityManager->getStorage('aggregator_feed')->loadMultiple($this->value); foreach ($feeds as $feed) { diff --git a/core/modules/aggregator/src/Plugin/views/argument/Iid.php b/core/modules/aggregator/src/Plugin/views/argument/Iid.php index 9468c9868c..44b4569779 100644 --- a/core/modules/aggregator/src/Plugin/views/argument/Iid.php +++ b/core/modules/aggregator/src/Plugin/views/argument/Iid.php @@ -50,7 +50,7 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function titleQuery() { - $titles = array(); + $titles = []; $items = $this->entityManager->getStorage('aggregator_item')->loadMultiple($this->value); foreach ($items as $feed) { diff --git a/core/modules/aggregator/src/Plugin/views/row/Rss.php b/core/modules/aggregator/src/Plugin/views/row/Rss.php index ef46466490..464a28592e 100644 --- a/core/modules/aggregator/src/Plugin/views/row/Rss.php +++ b/core/modules/aggregator/src/Plugin/views/row/Rss.php @@ -48,31 +48,31 @@ public function render($row) { $item->{$name} = $field->value; } - $item->elements = array( - array( + $item->elements = [ + [ 'key' => 'pubDate', // views_view_row_rss takes care about the escaping. 'value' => gmdate('r', $entity->timestamp->value), - ), - array( + ], + [ 'key' => 'dc:creator', // views_view_row_rss takes care about the escaping. 'value' => $entity->author->value, - ), - array( + ], + [ 'key' => 'guid', // views_view_row_rss takes care about the escaping. 'value' => $entity->guid->value, - 'attributes' => array('isPermaLink' => 'false'), - ), - ); + 'attributes' => ['isPermaLink' => 'false'], + ], + ]; - $build = array( + $build = [ '#theme' => $this->themeFunctions(), '#view' => $this->view, '#options' => $this->options, '#row' => $item, - ); + ]; return $build; } diff --git a/core/modules/aggregator/src/Tests/AddFeedTest.php b/core/modules/aggregator/src/Tests/AddFeedTest.php index b7ffe5fbc7..4dfeb95572 100644 --- a/core/modules/aggregator/src/Tests/AddFeedTest.php +++ b/core/modules/aggregator/src/Tests/AddFeedTest.php @@ -39,8 +39,8 @@ public function testAddFeed() { 'refresh' => '900', ]; $this->drupalPostForm('aggregator/sources/add', $edit, t('Save')); - $this->assertRaw(t('A feed named %feed already exists. Enter a unique title.', array('%feed' => $feed->label()))); - $this->assertRaw(t('A feed with this URL %url already exists. Enter a unique URL.', array('%url' => $feed->getUrl()))); + $this->assertRaw(t('A feed named %feed already exists. Enter a unique title.', ['%feed' => $feed->label()])); + $this->assertRaw(t('A feed with this URL %url already exists. Enter a unique URL.', ['%url' => $feed->getUrl()])); // Delete feed. $this->deleteFeed($feed); diff --git a/core/modules/aggregator/src/Tests/AggregatorAdminTest.php b/core/modules/aggregator/src/Tests/AggregatorAdminTest.php index 487e0ef921..3d09bbcac0 100644 --- a/core/modules/aggregator/src/Tests/AggregatorAdminTest.php +++ b/core/modules/aggregator/src/Tests/AggregatorAdminTest.php @@ -22,7 +22,7 @@ public function testSettingsPage() { $this->assertText('Test processor'); // Set new values and enable test plugins. - $edit = array( + $edit = [ 'aggregator_allowed_html_tags' => '', 'aggregator_summary_items' => 10, 'aggregator_clear' => 3600, @@ -30,27 +30,27 @@ public function testSettingsPage() { 'aggregator_fetcher' => 'aggregator_test_fetcher', 'aggregator_parser' => 'aggregator_test_parser', 'aggregator_processors[aggregator_test_processor]' => 'aggregator_test_processor', - ); + ]; $this->drupalPostForm('admin/config/services/aggregator/settings', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); foreach ($edit as $name => $value) { - $this->assertFieldByName($name, $value, format_string('"@name" has correct default value.', array('@name' => $name))); + $this->assertFieldByName($name, $value, format_string('"@name" has correct default value.', ['@name' => $name])); } // Check for our test processor settings form. $this->assertText(t('Dummy length setting')); // Change its value to ensure that settingsSubmit is called. - $edit = array( + $edit = [ 'dummy_length' => 100, - ); + ]; $this->drupalPostForm('admin/config/services/aggregator/settings', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); $this->assertFieldByName('dummy_length', 100, '"dummy_length" has correct default value.'); // Make sure settings form is still accessible even after uninstalling a module // that provides the selected plugins. - $this->container->get('module_installer')->uninstall(array('aggregator_test')); + $this->container->get('module_installer')->uninstall(['aggregator_test']); $this->resetAll(); $this->drupalGet('admin/config/services/aggregator/settings'); $this->assertResponse(200); diff --git a/core/modules/aggregator/src/Tests/AggregatorCronTest.php b/core/modules/aggregator/src/Tests/AggregatorCronTest.php index 34a4cb930c..9ebb2d25c0 100644 --- a/core/modules/aggregator/src/Tests/AggregatorCronTest.php +++ b/core/modules/aggregator/src/Tests/AggregatorCronTest.php @@ -16,30 +16,30 @@ public function testCron() { $this->createSampleNodes(); $feed = $this->createFeed(); $this->cronRun(); - $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField()); + $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField()); $this->deleteFeedItems($feed); - $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField()); + $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField()); $this->cronRun(); - $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField()); + $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField()); // Test feed locking when queued for update. $this->deleteFeedItems($feed); db_update('aggregator_feed') ->condition('fid', $feed->id()) - ->fields(array( + ->fields([ 'queued' => REQUEST_TIME, - )) + ]) ->execute(); $this->cronRun(); - $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField()); + $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField()); db_update('aggregator_feed') ->condition('fid', $feed->id()) - ->fields(array( + ->fields([ 'queued' => 0, - )) + ]) ->execute(); $this->cronRun(); - $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField()); + $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField()); } } diff --git a/core/modules/aggregator/src/Tests/AggregatorRenderingTest.php b/core/modules/aggregator/src/Tests/AggregatorRenderingTest.php index 888f1da567..de7e401058 100644 --- a/core/modules/aggregator/src/Tests/AggregatorRenderingTest.php +++ b/core/modules/aggregator/src/Tests/AggregatorRenderingTest.php @@ -17,7 +17,7 @@ class AggregatorRenderingTest extends AggregatorTestBase { * * @var array */ - public static $modules = array('block', 'test_page_test'); + public static $modules = ['block', 'test_page_test']; protected function setUp() { parent::setUp(); @@ -35,15 +35,15 @@ public function testBlockLinks() { $this->updateFeedItems($feed, $this->getDefaultFeedItemCount()); // Need admin user to be able to access block admin. - $admin_user = $this->drupalCreateUser(array( + $admin_user = $this->drupalCreateUser([ 'administer blocks', 'access administration pages', 'administer news feeds', 'access news feeds', - )); + ]); $this->drupalLogin($admin_user); - $block = $this->drupalPlaceBlock("aggregator_feed_block", array('label' => 'feed-' . $feed->label())); + $block = $this->drupalPlaceBlock("aggregator_feed_block", ['label' => 'feed-' . $feed->label()]); // Configure the feed that should be displayed. $block->getPlugin()->setConfigurationValue('feed', $feed->id()); @@ -56,20 +56,20 @@ public function testBlockLinks() { // Confirm items appear as links. $items = $this->container->get('entity.manager')->getStorage('aggregator_item')->loadByFeed($feed->id(), 1); - $links = $this->xpath('//a[@href = :href]', array(':href' => reset($items)->getLink())); + $links = $this->xpath('//a[@href = :href]', [':href' => reset($items)->getLink()]); $this->assert(isset($links[0]), 'Item link found.'); // Find the expected read_more link. $href = $feed->url(); - $links = $this->xpath('//a[@href = :href]', array(':href' => $href)); - $this->assert(isset($links[0]), format_string('Link to href %href found.', array('%href' => $href))); + $links = $this->xpath('//a[@href = :href]', [':href' => $href]); + $this->assert(isset($links[0]), format_string('Link to href %href found.', ['%href' => $href])); $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags'); $cache_tags = explode(' ', $cache_tags_header); $this->assertTrue(in_array('aggregator_feed:' . $feed->id(), $cache_tags)); // Visit that page. $this->drupalGet($feed->urlInfo()->getInternalPath()); - $correct_titles = $this->xpath('//h1[normalize-space(text())=:title]', array(':title' => $feed->label())); + $correct_titles = $this->xpath('//h1[normalize-space(text())=:title]', [':title' => $feed->label()]); $this->assertFalse(empty($correct_titles), 'Aggregator feed page is available and has the correct title.'); $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags')); $this->assertTrue(in_array('aggregator_feed:' . $feed->id(), $cache_tags)); @@ -103,18 +103,18 @@ public function testFeedPage() { // Check for presence of an aggregator pager. $this->drupalGet('aggregator'); - $elements = $this->xpath("//ul[contains(@class, :class)]", array(':class' => 'pager__items')); + $elements = $this->xpath("//ul[contains(@class, :class)]", [':class' => 'pager__items']); $this->assertTrue(!empty($elements), 'Individual source page contains a pager.'); // Check for sources page title. $this->drupalGet('aggregator/sources'); - $titles = $this->xpath('//h1[normalize-space(text())=:title]', array(':title' => 'Sources')); + $titles = $this->xpath('//h1[normalize-space(text())=:title]', [':title' => 'Sources']); $this->assertTrue(!empty($titles), 'Source page contains correct title.'); // Find the expected read_more link on the sources page. $href = $feed->url(); - $links = $this->xpath('//a[@href = :href]', array(':href' => $href)); - $this->assertTrue(isset($links[0]), SafeMarkup::format('Link to href %href found.', array('%href' => $href))); + $links = $this->xpath('//a[@href = :href]', [':href' => $href]); + $this->assertTrue(isset($links[0]), SafeMarkup::format('Link to href %href found.', ['%href' => $href])); $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags'); $cache_tags = explode(' ', $cache_tags_header); $this->assertTrue(in_array('aggregator_feed:' . $feed->id(), $cache_tags)); @@ -139,7 +139,7 @@ public function testFeedPage() { // Check for the presence of a pager. $this->drupalGet('aggregator/sources/' . $feed->id()); - $elements = $this->xpath("//ul[contains(@class, :class)]", array(':class' => 'pager__items')); + $elements = $this->xpath("//ul[contains(@class, :class)]", [':class' => 'pager__items']); $this->assertTrue(!empty($elements), 'Individual source page contains a pager.'); $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags')); $this->assertTrue(in_array('aggregator_feed:' . $feed->id(), $cache_tags)); diff --git a/core/modules/aggregator/src/Tests/AggregatorTestBase.php b/core/modules/aggregator/src/Tests/AggregatorTestBase.php index 35bd9a9689..f42248975a 100644 --- a/core/modules/aggregator/src/Tests/AggregatorTestBase.php +++ b/core/modules/aggregator/src/Tests/AggregatorTestBase.php @@ -37,10 +37,10 @@ protected function setUp() { // Create an Article node type. if ($this->profile != 'standard') { - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); } - $this->adminUser = $this->drupalCreateUser(array('access administration pages', 'administer news feeds', 'access news feeds', 'create article content')); + $this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer news feeds', 'access news feeds', 'create article content']); $this->drupalLogin($this->adminUser); $this->drupalPlaceBlock('local_tasks_block'); } @@ -61,16 +61,16 @@ protected function setUp() { * * @see getFeedEditArray() */ - public function createFeed($feed_url = NULL, array $edit = array()) { + public function createFeed($feed_url = NULL, array $edit = []) { $edit = $this->getFeedEditArray($feed_url, $edit); $this->drupalPostForm('aggregator/sources/add', $edit, t('Save')); - $this->assertText(t('The feed @name has been added.', array('@name' => $edit['title[0][value]'])), format_string('The feed @name has been added.', array('@name' => $edit['title[0][value]']))); + $this->assertText(t('The feed @name has been added.', ['@name' => $edit['title[0][value]']]), format_string('The feed @name has been added.', ['@name' => $edit['title[0][value]']])); // Verify that the creation message contains a link to a feed. - $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'aggregator/sources/')); + $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']); $this->assert(isset($view_link), 'The message area contains a link to a feed'); - $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']))->fetchField(); + $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']])->fetchField(); $this->assertTrue(!empty($fid), 'The feed found in database.'); return Feed::load($fid); } @@ -82,8 +82,8 @@ public function createFeed($feed_url = NULL, array $edit = array()) { * Feed object representing the feed. */ public function deleteFeed(FeedInterface $feed) { - $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', array(), t('Delete')); - $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->label())), 'Feed deleted successfully.'); + $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', [], t('Delete')); + $this->assertRaw(t('The feed %title has been deleted.', ['%title' => $feed->label()]), 'Feed deleted successfully.'); } /** @@ -98,19 +98,19 @@ public function deleteFeed(FeedInterface $feed) { * @return array * A feed array. */ - public function getFeedEditArray($feed_url = NULL, array $edit = array()) { + public function getFeedEditArray($feed_url = NULL, array $edit = []) { $feed_name = $this->randomMachineName(10); if (!$feed_url) { - $feed_url = \Drupal::url('view.frontpage.feed_1', array(), array( - 'query' => array('feed' => $feed_name), + $feed_url = \Drupal::url('view.frontpage.feed_1', [], [ + 'query' => ['feed' => $feed_name], 'absolute' => TRUE, - )); + ]); } - $edit += array( + $edit += [ 'title[0][value]' => $feed_name, 'url[0][value]' => $feed_url, 'refresh' => '900', - ); + ]; return $edit; } @@ -126,19 +126,19 @@ public function getFeedEditArray($feed_url = NULL, array $edit = array()) { * @return \Drupal\aggregator\FeedInterface * A feed object. */ - public function getFeedEditObject($feed_url = NULL, array $values = array()) { + public function getFeedEditObject($feed_url = NULL, array $values = []) { $feed_name = $this->randomMachineName(10); if (!$feed_url) { - $feed_url = \Drupal::url('view.frontpage.feed_1', array( - 'query' => array('feed' => $feed_name), + $feed_url = \Drupal::url('view.frontpage.feed_1', [ + 'query' => ['feed' => $feed_name], 'absolute' => TRUE, - )); + ]); } - $values += array( + $values += [ 'title' => $feed_name, 'url' => $feed_url, 'refresh' => '900', - ); + ]; return Feed::create($values); } @@ -168,7 +168,7 @@ public function getDefaultFeedItemCount() { public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) { // First, let's ensure we can get to the rss xml. $this->drupalGet($feed->getUrl()); - $this->assertResponse(200, format_string(':url is reachable.', array(':url' => $feed->getUrl()))); + $this->assertResponse(200, format_string(':url is reachable.', [':url' => $feed->getUrl()])); // Attempt to access the update link directly without an access token. $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id()); @@ -179,15 +179,15 @@ public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) { $this->clickLink('Update items'); // Ensure we have the right number of items. - $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id())); - $feed->items = array(); + $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()]); + $feed->items = []; foreach ($result as $item) { $feed->items[] = $item->iid; } if ($expected_count !== NULL) { $feed->item_count = count($feed->items); - $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (@val1 != @val2)', array('@val1' => $expected_count, '@val2' => $feed->item_count))); + $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (@val1 != @val2)', ['@val1' => $expected_count, '@val2' => $feed->item_count])); } } @@ -198,8 +198,8 @@ public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) { * Feed object representing the feed. */ public function deleteFeedItems(FeedInterface $feed) { - $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), array(), t('Delete items')); - $this->assertRaw(t('The news items from %title have been deleted.', array('%title' => $feed->label())), 'Feed items deleted.'); + $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), [], t('Delete items')); + $this->assertRaw(t('The news items from %title have been deleted.', ['%title' => $feed->label()]), 'Feed items deleted.'); } /** @@ -212,10 +212,10 @@ public function deleteFeedItems(FeedInterface $feed) { */ public function updateAndDelete(FeedInterface $feed, $expected_count) { $this->updateFeedItems($feed, $expected_count); - $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField(); + $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField(); $this->assertTrue($count); $this->deleteFeedItems($feed); - $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField(); + $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField(); $this->assertTrue($count == 0); } @@ -231,7 +231,7 @@ public function updateAndDelete(FeedInterface $feed, $expected_count) { * TRUE if feed is unique. */ public function uniqueFeed($feed_name, $feed_url) { - $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed_name, ':url' => $feed_url))->fetchField(); + $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $feed_name, ':url' => $feed_url])->fetchField(); return (1 == $result); } @@ -358,7 +358,7 @@ public function getHtmlEntitiesSample() { public function createSampleNodes($count = 5) { // Post $count article nodes. for ($i = 0; $i < $count; $i++) { - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $edit['body[0][value]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/article', $edit, t('Save')); @@ -372,10 +372,10 @@ public function enableTestPlugins() { $this->config('aggregator.settings') ->set('fetcher', 'aggregator_test_fetcher') ->set('parser', 'aggregator_test_parser') - ->set('processors', array( + ->set('processors', [ 'aggregator_test_processor' => 'aggregator_test_processor', 'aggregator' => 'aggregator', - )) + ]) ->save(); } diff --git a/core/modules/aggregator/src/Tests/FeedAdminDisplayTest.php b/core/modules/aggregator/src/Tests/FeedAdminDisplayTest.php index 0324e3b9a5..0dbb872b56 100644 --- a/core/modules/aggregator/src/Tests/FeedAdminDisplayTest.php +++ b/core/modules/aggregator/src/Tests/FeedAdminDisplayTest.php @@ -14,7 +14,7 @@ class FeedAdminDisplayTest extends AggregatorTestBase { */ public function testFeedUpdateFields() { // Create scheduled feed. - $scheduled_feed = $this->createFeed(NULL, array('refresh' => '900')); + $scheduled_feed = $this->createFeed(NULL, ['refresh' => '900']); $this->drupalGet('admin/config/services/aggregator'); $this->assertResponse(200, 'Aggregator feed overview page exists.'); @@ -40,7 +40,7 @@ public function testFeedUpdateFields() { $this->deleteFeed($scheduled_feed); // Create non-scheduled feed. - $non_scheduled_feed = $this->createFeed(NULL, array('refresh' => '0')); + $non_scheduled_feed = $this->createFeed(NULL, ['refresh' => '0']); $this->drupalGet('admin/config/services/aggregator'); // The non scheduled feed shows that it has not been updated yet. diff --git a/core/modules/aggregator/src/Tests/FeedLanguageTest.php b/core/modules/aggregator/src/Tests/FeedLanguageTest.php index af8335e10e..98d04fa5c1 100644 --- a/core/modules/aggregator/src/Tests/FeedLanguageTest.php +++ b/core/modules/aggregator/src/Tests/FeedLanguageTest.php @@ -16,14 +16,14 @@ class FeedLanguageTest extends AggregatorTestBase { * * @var array */ - public static $modules = array('language'); + public static $modules = ['language']; /** * List of langcodes. * * @var string[] */ - protected $langcodes = array(); + protected $langcodes = []; /** * {@inheritdoc} @@ -32,12 +32,12 @@ protected function setUp() { parent::setUp(); // Create test languages. - $this->langcodes = array(ConfigurableLanguage::load('en')); + $this->langcodes = [ConfigurableLanguage::load('en')]; for ($i = 1; $i < 3; ++$i) { - $language = ConfigurableLanguage::create(array( + $language = ConfigurableLanguage::create([ 'id' => 'l' . $i, 'label' => $this->randomString(), - )); + ]); $language->save(); $this->langcodes[$i] = $language->id(); } @@ -57,10 +57,10 @@ public function testFeedLanguage() { $this->drupalPostForm('admin/config/regional/content-language', $edit, t('Save configuration')); /** @var \Drupal\aggregator\FeedInterface[] $feeds */ - $feeds = array(); + $feeds = []; // Create feeds. - $feeds[1] = $this->createFeed(NULL, array('langcode[0][value]' => $this->langcodes[1])); - $feeds[2] = $this->createFeed(NULL, array('langcode[0][value]' => $this->langcodes[2])); + $feeds[1] = $this->createFeed(NULL, ['langcode[0][value]' => $this->langcodes[1]]); + $feeds[2] = $this->createFeed(NULL, ['langcode[0][value]' => $this->langcodes[2]]); // Make sure that the language has been assigned. $this->assertEqual($feeds[1]->language()->getId(), $this->langcodes[1]); @@ -74,7 +74,7 @@ public function testFeedLanguage() { // the one from the feed. foreach ($feeds as $feed) { /** @var \Drupal\aggregator\ItemInterface[] $items */ - $items = entity_load_multiple_by_properties('aggregator_item', array('fid' => $feed->id())); + $items = entity_load_multiple_by_properties('aggregator_item', ['fid' => $feed->id()]); $this->assertTrue(count($items) > 0, 'Feed items were created.'); foreach ($items as $item) { $this->assertEqual($item->language()->getId(), $feed->language()->getId()); diff --git a/core/modules/aggregator/src/Tests/UpdateFeedItemTest.php b/core/modules/aggregator/src/Tests/UpdateFeedItemTest.php index ae78205bcd..67e96f1726 100644 --- a/core/modules/aggregator/src/Tests/UpdateFeedItemTest.php +++ b/core/modules/aggregator/src/Tests/UpdateFeedItemTest.php @@ -26,47 +26,47 @@ public function testUpdateFeedItem() { $this->deleteFeed($feed); // Test updating feed items without valid timestamp information. - $edit = array( + $edit = [ 'title[0][value]' => "Feed without publish timestamp", 'url[0][value]' => $this->getRSS091Sample(), - ); + ]; $this->drupalGet($edit['url[0][value]']); $this->assertResponse(200); $this->drupalPostForm('aggregator/sources/add', $edit, t('Save')); - $this->assertText(t('The feed @name has been added.', array('@name' => $edit['title[0][value]'])), format_string('The feed @name has been added.', array('@name' => $edit['title[0][value]']))); + $this->assertText(t('The feed @name has been added.', ['@name' => $edit['title[0][value]']]), format_string('The feed @name has been added.', ['@name' => $edit['title[0][value]']])); // Verify that the creation message contains a link to a feed. - $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'aggregator/sources/')); + $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']); $this->assert(isset($view_link), 'The message area contains a link to a feed'); - $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE url = :url", array(':url' => $edit['url[0][value]']))->fetchField(); + $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE url = :url", [':url' => $edit['url[0][value]']])->fetchField(); $feed = Feed::load($fid); $feed->refreshItems(); - $before = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField(); + $before = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField(); // Sleep for 3 second. sleep(3); db_update('aggregator_feed') ->condition('fid', $feed->id()) - ->fields(array( + ->fields([ 'checked' => 0, 'hash' => '', 'etag' => '', 'modified' => 0, - )) + ]) ->execute(); $feed->refreshItems(); - $after = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField(); - $this->assertTrue($before === $after, format_string('Publish timestamp of feed item was not updated (@before === @after)', array('@before' => $before, '@after' => $after))); + $after = db_query('SELECT timestamp FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField(); + $this->assertTrue($before === $after, format_string('Publish timestamp of feed item was not updated (@before === @after)', ['@before' => $before, '@after' => $after])); // Make sure updating items works even after uninstalling a module // that provides the selected plugins. $this->enableTestPlugins(); - $this->container->get('module_installer')->uninstall(array('aggregator_test')); + $this->container->get('module_installer')->uninstall(['aggregator_test']); $this->updateFeedItems($feed); $this->assertResponse(200); } diff --git a/core/modules/aggregator/src/Tests/UpdateFeedTest.php b/core/modules/aggregator/src/Tests/UpdateFeedTest.php index 8c797a5e82..d2308744c2 100644 --- a/core/modules/aggregator/src/Tests/UpdateFeedTest.php +++ b/core/modules/aggregator/src/Tests/UpdateFeedTest.php @@ -12,7 +12,7 @@ class UpdateFeedTest extends AggregatorTestBase { * Creates a feed and attempts to update it. */ public function testUpdateFeed() { - $remaining_fields = array('title[0][value]', 'url[0][value]', ''); + $remaining_fields = ['title[0][value]', 'url[0][value]', '']; foreach ($remaining_fields as $same_field) { $feed = $this->createFeed(); @@ -24,10 +24,10 @@ public function testUpdateFeed() { $edit[$same_field] = $feed->{$same_field}->value; } $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/configure', $edit, t('Save')); - $this->assertText(t('The feed @name has been updated.', array('@name' => $edit['title[0][value]'])), format_string('The feed %name has been updated.', array('%name' => $edit['title[0][value]']))); + $this->assertText(t('The feed @name has been updated.', ['@name' => $edit['title[0][value]']]), format_string('The feed %name has been updated.', ['%name' => $edit['title[0][value]']])); // Verify that the creation message contains a link to a feed. - $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'aggregator/sources/')); + $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']); $this->assert(isset($view_link), 'The message area contains a link to a feed'); // Check feed data. diff --git a/core/modules/aggregator/tests/modules/aggregator_test/src/Plugin/aggregator/processor/TestProcessor.php b/core/modules/aggregator/tests/modules/aggregator_test/src/Plugin/aggregator/processor/TestProcessor.php index 2f73c5f4af..294697a2bc 100644 --- a/core/modules/aggregator/tests/modules/aggregator_test/src/Plugin/aggregator/processor/TestProcessor.php +++ b/core/modules/aggregator/tests/modules/aggregator_test/src/Plugin/aggregator/processor/TestProcessor.php @@ -75,20 +75,20 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta $processors = $this->config('aggregator.settings')->get('processors'); $info = $this->getPluginDefinition(); - $form['processors'][$info['id']] = array( + $form['processors'][$info['id']] = [ '#type' => 'details', '#title' => t('Test processor settings'), '#description' => $info['description'], '#open' => in_array($info['id'], $processors), - ); + ]; // Add some dummy settings to verify settingsForm is called. - $form['processors'][$info['id']]['dummy_length'] = array( + $form['processors'][$info['id']]['dummy_length'] = [ '#title' => t('Dummy length setting'), '#type' => 'number', '#min' => 1, '#max' => 1000, '#default_value' => $this->configuration['items']['dummy_length'], - ); + ]; return $form; } diff --git a/core/modules/aggregator/tests/src/Functional/AggregatorTestBase.php b/core/modules/aggregator/tests/src/Functional/AggregatorTestBase.php index 9a07135244..ddd98bb82f 100644 --- a/core/modules/aggregator/tests/src/Functional/AggregatorTestBase.php +++ b/core/modules/aggregator/tests/src/Functional/AggregatorTestBase.php @@ -34,10 +34,10 @@ protected function setUp() { // Create an Article node type. if ($this->profile != 'standard') { - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); } - $this->adminUser = $this->drupalCreateUser(array('access administration pages', 'administer news feeds', 'access news feeds', 'create article content')); + $this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer news feeds', 'access news feeds', 'create article content']); $this->drupalLogin($this->adminUser); $this->drupalPlaceBlock('local_tasks_block'); } @@ -58,16 +58,16 @@ protected function setUp() { * * @see getFeedEditArray() */ - public function createFeed($feed_url = NULL, array $edit = array()) { + public function createFeed($feed_url = NULL, array $edit = []) { $edit = $this->getFeedEditArray($feed_url, $edit); $this->drupalPostForm('aggregator/sources/add', $edit, t('Save')); - $this->assertText(t('The feed @name has been added.', array('@name' => $edit['title[0][value]'])), format_string('The feed @name has been added.', array('@name' => $edit['title[0][value]']))); + $this->assertText(t('The feed @name has been added.', ['@name' => $edit['title[0][value]']]), format_string('The feed @name has been added.', ['@name' => $edit['title[0][value]']])); // Verify that the creation message contains a link to a feed. - $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'aggregator/sources/')); + $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']); $this->assert(isset($view_link), 'The message area contains a link to a feed'); - $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']))->fetchField(); + $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']])->fetchField(); $this->assertTrue(!empty($fid), 'The feed found in database.'); return Feed::load($fid); } @@ -79,8 +79,8 @@ public function createFeed($feed_url = NULL, array $edit = array()) { * Feed object representing the feed. */ public function deleteFeed(FeedInterface $feed) { - $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', array(), t('Delete')); - $this->assertRaw(t('The feed %title has been deleted.', array('%title' => $feed->label())), 'Feed deleted successfully.'); + $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', [], t('Delete')); + $this->assertRaw(t('The feed %title has been deleted.', ['%title' => $feed->label()]), 'Feed deleted successfully.'); } /** @@ -95,19 +95,19 @@ public function deleteFeed(FeedInterface $feed) { * @return array * A feed array. */ - public function getFeedEditArray($feed_url = NULL, array $edit = array()) { + public function getFeedEditArray($feed_url = NULL, array $edit = []) { $feed_name = $this->randomMachineName(10); if (!$feed_url) { - $feed_url = \Drupal::url('view.frontpage.feed_1', array(), array( - 'query' => array('feed' => $feed_name), + $feed_url = \Drupal::url('view.frontpage.feed_1', [], [ + 'query' => ['feed' => $feed_name], 'absolute' => TRUE, - )); + ]); } - $edit += array( + $edit += [ 'title[0][value]' => $feed_name, 'url[0][value]' => $feed_url, 'refresh' => '900', - ); + ]; return $edit; } @@ -123,19 +123,19 @@ public function getFeedEditArray($feed_url = NULL, array $edit = array()) { * @return \Drupal\aggregator\FeedInterface * A feed object. */ - public function getFeedEditObject($feed_url = NULL, array $values = array()) { + public function getFeedEditObject($feed_url = NULL, array $values = []) { $feed_name = $this->randomMachineName(10); if (!$feed_url) { - $feed_url = \Drupal::url('view.frontpage.feed_1', array( - 'query' => array('feed' => $feed_name), + $feed_url = \Drupal::url('view.frontpage.feed_1', [ + 'query' => ['feed' => $feed_name], 'absolute' => TRUE, - )); + ]); } - $values += array( + $values += [ 'title' => $feed_name, 'url' => $feed_url, 'refresh' => '900', - ); + ]; return Feed::create($values); } @@ -165,7 +165,7 @@ public function getDefaultFeedItemCount() { public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) { // First, let's ensure we can get to the rss xml. $this->drupalGet($feed->getUrl()); - $this->assertResponse(200, format_string(':url is reachable.', array(':url' => $feed->getUrl()))); + $this->assertResponse(200, format_string(':url is reachable.', [':url' => $feed->getUrl()])); // Attempt to access the update link directly without an access token. $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id()); @@ -176,15 +176,15 @@ public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) { $this->clickLink('Update items'); // Ensure we have the right number of items. - $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id())); - $feed->items = array(); + $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()]); + $feed->items = []; foreach ($result as $item) { $feed->items[] = $item->iid; } if ($expected_count !== NULL) { $feed->item_count = count($feed->items); - $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (@val1 != @val2)', array('@val1' => $expected_count, '@val2' => $feed->item_count))); + $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (@val1 != @val2)', ['@val1' => $expected_count, '@val2' => $feed->item_count])); } } @@ -195,8 +195,8 @@ public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) { * Feed object representing the feed. */ public function deleteFeedItems(FeedInterface $feed) { - $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), array(), t('Delete items')); - $this->assertRaw(t('The news items from %title have been deleted.', array('%title' => $feed->label())), 'Feed items deleted.'); + $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), [], t('Delete items')); + $this->assertRaw(t('The news items from %title have been deleted.', ['%title' => $feed->label()]), 'Feed items deleted.'); } /** @@ -209,10 +209,10 @@ public function deleteFeedItems(FeedInterface $feed) { */ public function updateAndDelete(FeedInterface $feed, $expected_count) { $this->updateFeedItems($feed, $expected_count); - $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField(); + $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField(); $this->assertTrue($count); $this->deleteFeedItems($feed); - $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed->id()))->fetchField(); + $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField(); $this->assertTrue($count == 0); } @@ -228,7 +228,7 @@ public function updateAndDelete(FeedInterface $feed, $expected_count) { * TRUE if feed is unique. */ public function uniqueFeed($feed_name, $feed_url) { - $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed_name, ':url' => $feed_url))->fetchField(); + $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $feed_name, ':url' => $feed_url])->fetchField(); return (1 == $result); } @@ -355,7 +355,7 @@ public function getHtmlEntitiesSample() { public function createSampleNodes($count = 5) { // Post $count article nodes. for ($i = 0; $i < $count; $i++) { - $edit = array(); + $edit = []; $edit['title[0][value]'] = $this->randomMachineName(); $edit['body[0][value]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/article', $edit, t('Save')); @@ -369,10 +369,10 @@ public function enableTestPlugins() { $this->config('aggregator.settings') ->set('fetcher', 'aggregator_test_fetcher') ->set('parser', 'aggregator_test_parser') - ->set('processors', array( + ->set('processors', [ 'aggregator_test_processor' => 'aggregator_test_processor', 'aggregator' => 'aggregator', - )) + ]) ->save(); } diff --git a/core/modules/aggregator/tests/src/Functional/DeleteFeedItemTest.php b/core/modules/aggregator/tests/src/Functional/DeleteFeedItemTest.php index 95202b813c..a8527f6b1c 100644 --- a/core/modules/aggregator/tests/src/Functional/DeleteFeedItemTest.php +++ b/core/modules/aggregator/tests/src/Functional/DeleteFeedItemTest.php @@ -13,15 +13,15 @@ class DeleteFeedItemTest extends AggregatorTestBase { */ public function testDeleteFeedItem() { // Create a bunch of test feeds. - $feed_urls = array(); + $feed_urls = []; // No last-modified, no etag. - $feed_urls[] = \Drupal::url('aggregator_test.feed', array(), array('absolute' => TRUE)); + $feed_urls[] = \Drupal::url('aggregator_test.feed', [], ['absolute' => TRUE]); // Last-modified, but no etag. - $feed_urls[] = \Drupal::url('aggregator_test.feed', array('use_last_modified' => 1), array('absolute' => TRUE)); + $feed_urls[] = \Drupal::url('aggregator_test.feed', ['use_last_modified' => 1], ['absolute' => TRUE]); // No Last-modified, but etag. - $feed_urls[] = \Drupal::url('aggregator_test.feed', array('use_last_modified' => 0, 'use_etag' => 1), array('absolute' => TRUE)); + $feed_urls[] = \Drupal::url('aggregator_test.feed', ['use_last_modified' => 0, 'use_etag' => 1], ['absolute' => TRUE]); // Last-modified and etag. - $feed_urls[] = \Drupal::url('aggregator_test.feed', array('use_last_modified' => 1, 'use_etag' => 1), array('absolute' => TRUE)); + $feed_urls[] = \Drupal::url('aggregator_test.feed', ['use_last_modified' => 1, 'use_etag' => 1], ['absolute' => TRUE]); foreach ($feed_urls as $feed_url) { $feed = $this->createFeed($feed_url); diff --git a/core/modules/aggregator/tests/src/Functional/DeleteFeedTest.php b/core/modules/aggregator/tests/src/Functional/DeleteFeedTest.php index 5bf5bd3eef..7d75696281 100644 --- a/core/modules/aggregator/tests/src/Functional/DeleteFeedTest.php +++ b/core/modules/aggregator/tests/src/Functional/DeleteFeedTest.php @@ -14,7 +14,7 @@ class DeleteFeedTest extends AggregatorTestBase { * * @var array */ - public static $modules = array('block'); + public static $modules = ['block']; /** * Deletes a feed and ensures that all of its services are deleted. @@ -43,7 +43,7 @@ public function testDeleteFeed() { $this->assertResponse(404, 'Deleted feed source does not exists.'); // Check database for feed. - $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", array(':title' => $feed1->label(), ':url' => $feed1->getUrl()))->fetchField(); + $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $feed1->label(), ':url' => $feed1->getUrl()])->fetchField(); $this->assertFalse($result, 'Feed not found in database'); } diff --git a/core/modules/aggregator/tests/src/Functional/FeedCacheTagsTest.php b/core/modules/aggregator/tests/src/Functional/FeedCacheTagsTest.php index 1a30720137..dc0aab9263 100644 --- a/core/modules/aggregator/tests/src/Functional/FeedCacheTagsTest.php +++ b/core/modules/aggregator/tests/src/Functional/FeedCacheTagsTest.php @@ -17,7 +17,7 @@ class FeedCacheTagsTest extends EntityWithUriCacheTagsTestBase { /** * {@inheritdoc} */ - public static $modules = array('aggregator'); + public static $modules = ['aggregator']; /** * {@inheritdoc} @@ -37,13 +37,13 @@ protected function setUp() { */ protected function createEntity() { // Create a "Llama" feed. - $feed = Feed::create(array( + $feed = Feed::create([ 'title' => 'Llama', 'url' => 'https://www.drupal.org/', 'refresh' => 900, 'checked' => 1389919932, 'description' => 'Drupal.org', - )); + ]); $feed->save(); return $feed; diff --git a/core/modules/aggregator/tests/src/Functional/FeedParserTest.php b/core/modules/aggregator/tests/src/Functional/FeedParserTest.php index 00c7b70492..ecb2e50c76 100644 --- a/core/modules/aggregator/tests/src/Functional/FeedParserTest.php +++ b/core/modules/aggregator/tests/src/Functional/FeedParserTest.php @@ -30,7 +30,7 @@ public function testRSS091Sample() { $feed = $this->createFeed($this->getRSS091Sample()); $feed->refreshItems(); $this->drupalGet('aggregator/sources/' . $feed->id()); - $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->label()))); + $this->assertResponse(200, format_string('Feed %name exists.', ['%name' => $feed->label()])); $this->assertText('First example feed item title'); $this->assertLinkByHref('http://example.com/example-turns-one'); $this->assertText('First example feed item description.'); @@ -53,19 +53,19 @@ public function testAtomSample() { $feed = $this->createFeed($this->getAtomSample()); $feed->refreshItems(); $this->drupalGet('aggregator/sources/' . $feed->id()); - $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->label()))); + $this->assertResponse(200, format_string('Feed %name exists.', ['%name' => $feed->label()])); $this->assertText('Atom-Powered Robots Run Amok'); $this->assertLinkByHref('http://example.org/2003/12/13/atom03'); $this->assertText('Some text.'); - $this->assertEqual('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a', db_query('SELECT guid FROM {aggregator_item} WHERE link = :link', array(':link' => 'http://example.org/2003/12/13/atom03'))->fetchField(), 'Atom entry id element is parsed correctly.'); + $this->assertEqual('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a', db_query('SELECT guid FROM {aggregator_item} WHERE link = :link', [':link' => 'http://example.org/2003/12/13/atom03'])->fetchField(), 'Atom entry id element is parsed correctly.'); // Check for second feed entry. $this->assertText('We tried to stop them, but we failed.'); $this->assertLinkByHref('http://example.org/2003/12/14/atom03'); $this->assertText('Some other text.'); - $db_guid = db_query('SELECT guid FROM {aggregator_item} WHERE link = :link', array( + $db_guid = db_query('SELECT guid FROM {aggregator_item} WHERE link = :link', [ ':link' => 'http://example.org/2003/12/14/atom03', - ))->fetchField(); + ])->fetchField(); $this->assertEqual('urn:uuid:1225c695-cfb8-4ebb-bbbb-80da344efa6a', $db_guid, 'Atom entry id element is parsed correctly.'); } @@ -76,7 +76,7 @@ public function testHtmlEntitiesSample() { $feed = $this->createFeed($this->getHtmlEntitiesSample()); $feed->refreshItems(); $this->drupalGet('aggregator/sources/' . $feed->id()); - $this->assertResponse(200, format_string('Feed %name exists.', array('%name' => $feed->label()))); + $this->assertResponse(200, format_string('Feed %name exists.', ['%name' => $feed->label()])); $this->assertRaw("Quote" Amp&"); } @@ -85,12 +85,12 @@ public function testHtmlEntitiesSample() { */ public function testRedirectFeed() { $redirect_url = Url::fromRoute('aggregator_test.redirect')->setAbsolute()->toString(); - $feed = Feed::create(array('url' => $redirect_url, 'title' => $this->randomMachineName())); + $feed = Feed::create(['url' => $redirect_url, 'title' => $this->randomMachineName()]); $feed->save(); $feed->refreshItems(); // Make sure that the feed URL was updated correctly. - $this->assertEqual($feed->getUrl(), \Drupal::url('aggregator_test.feed', array(), array('absolute' => TRUE))); + $this->assertEqual($feed->getUrl(), \Drupal::url('aggregator_test.feed', [], ['absolute' => TRUE])); } /** @@ -99,13 +99,13 @@ public function testRedirectFeed() { public function testInvalidFeed() { // Simulate a typo in the URL to force a curl exception. $invalid_url = 'http:/www.drupal.org'; - $feed = Feed::create(array('url' => $invalid_url, 'title' => $this->randomMachineName())); + $feed = Feed::create(['url' => $invalid_url, 'title' => $this->randomMachineName()]); $feed->save(); // Update the feed. Use the UI to be able to check the message easily. $this->drupalGet('admin/config/services/aggregator'); $this->clickLink(t('Update items')); - $this->assertRaw(t('The feed from %title seems to be broken because of error', array('%title' => $feed->label()))); + $this->assertRaw(t('The feed from %title seems to be broken because of error', ['%title' => $feed->label()])); } } diff --git a/core/modules/aggregator/tests/src/Functional/FeedProcessorPluginTest.php b/core/modules/aggregator/tests/src/Functional/FeedProcessorPluginTest.php index 5527d95613..bdc63f56b0 100644 --- a/core/modules/aggregator/tests/src/Functional/FeedProcessorPluginTest.php +++ b/core/modules/aggregator/tests/src/Functional/FeedProcessorPluginTest.php @@ -45,7 +45,7 @@ public function testDelete() { $description = $feed->description->value ?: ''; $this->updateAndDelete($feed, NULL); // Make sure the feed title is changed. - $entities = entity_load_multiple_by_properties('aggregator_feed', array('description' => $description)); + $entities = entity_load_multiple_by_properties('aggregator_feed', ['description' => $description]); $this->assertTrue(empty($entities)); } @@ -53,11 +53,11 @@ public function testDelete() { * Test post-processing functionality. */ public function testPostProcess() { - $feed = $this->createFeed(NULL, array('refresh' => 1800)); + $feed = $this->createFeed(NULL, ['refresh' => 1800]); $this->updateFeedItems($feed); $feed_id = $feed->id(); // Reset entity cache manually. - \Drupal::entityManager()->getStorage('aggregator_feed')->resetCache(array($feed_id)); + \Drupal::entityManager()->getStorage('aggregator_feed')->resetCache([$feed_id]); // Reload the feed to get new values. $feed = Feed::load($feed_id); // Make sure its refresh rate doubled. diff --git a/core/modules/aggregator/tests/src/Functional/ImportOpmlTest.php b/core/modules/aggregator/tests/src/Functional/ImportOpmlTest.php index 8994e3fe87..2500b9ebb5 100644 --- a/core/modules/aggregator/tests/src/Functional/ImportOpmlTest.php +++ b/core/modules/aggregator/tests/src/Functional/ImportOpmlTest.php @@ -14,7 +14,7 @@ class ImportOpmlTest extends AggregatorTestBase { * * @var array */ - public static $modules = array('block', 'help'); + public static $modules = ['block', 'help']; /** * {@inheritdoc} @@ -22,7 +22,7 @@ class ImportOpmlTest extends AggregatorTestBase { protected function setUp() { parent::setUp(); - $admin_user = $this->drupalCreateUser(array('administer news feeds', 'access news feeds', 'create article content', 'administer blocks')); + $admin_user = $this->drupalCreateUser(['administer news feeds', 'access news feeds', 'create article content', 'administer blocks']); $this->drupalLogin($admin_user); } @@ -31,7 +31,7 @@ protected function setUp() { */ public function openImportForm() { // Enable the help block. - $this->drupalPlaceBlock('help_block', array('region' => 'help')); + $this->drupalPlaceBlock('help_block', ['region' => 'help']); $this->drupalGet('admin/config/services/aggregator/add/opml'); $this->assertText('A single OPML document may contain many feeds.', 'Found OPML help text.'); @@ -46,19 +46,19 @@ public function openImportForm() { public function validateImportFormFields() { $before = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField(); - $edit = array(); + $edit = []; $this->drupalPostForm('admin/config/services/aggregator/add/opml', $edit, t('Import')); $this->assertRaw(t('Either upload a file or enter a URL.'), 'Error if no fields are filled.'); $path = $this->getEmptyOpml(); - $edit = array( + $edit = [ 'files[upload]' => $path, 'remote' => file_create_url($path), - ); + ]; $this->drupalPostForm('admin/config/services/aggregator/add/opml', $edit, t('Import')); $this->assertRaw(t('Either upload a file or enter a URL.'), 'Error if both fields are filled.'); - $edit = array('remote' => 'invalidUrl://empty'); + $edit = ['remote' => 'invalidUrl://empty']; $this->drupalPostForm('admin/config/services/aggregator/add/opml', $edit, t('Import')); $this->assertText(t('The URL invalidUrl://empty is not valid.'), 'Error if the URL is invalid.'); @@ -76,7 +76,7 @@ protected function submitImportForm() { $this->drupalPostForm('admin/config/services/aggregator/add/opml', $form, t('Import')); $this->assertText(t('No new feed has been added.'), 'Attempting to upload invalid XML.'); - $edit = array('remote' => file_create_url($this->getEmptyOpml())); + $edit = ['remote' => file_create_url($this->getEmptyOpml())]; $this->drupalPostForm('admin/config/services/aggregator/add/opml', $edit, t('Import')); $this->assertText(t('No new feed has been added.'), 'Attempting to load empty OPML from remote URL.'); @@ -88,13 +88,13 @@ protected function submitImportForm() { $feeds[0] = $this->getFeedEditArray(); $feeds[1] = $this->getFeedEditArray(); $feeds[2] = $this->getFeedEditArray(); - $edit = array( + $edit = [ 'files[upload]' => $this->getValidOpml($feeds), 'refresh' => '900', - ); + ]; $this->drupalPostForm('admin/config/services/aggregator/add/opml', $edit, t('Import')); - $this->assertRaw(t('A feed with the URL %url already exists.', array('%url' => $feeds[0]['url[0][value]'])), 'Verifying that a duplicate URL was identified'); - $this->assertRaw(t('A feed named %title already exists.', array('%title' => $feeds[1]['title[0][value]'])), 'Verifying that a duplicate title was identified'); + $this->assertRaw(t('A feed with the URL %url already exists.', ['%url' => $feeds[0]['url[0][value]']]), 'Verifying that a duplicate URL was identified'); + $this->assertRaw(t('A feed named %title already exists.', ['%title' => $feeds[1]['title[0][value]']]), 'Verifying that a duplicate title was identified'); $after = db_query('SELECT COUNT(*) FROM {aggregator_feed}')->fetchField(); $this->assertEqual($after, 2, 'Verifying that two distinct feeds were added.'); diff --git a/core/modules/aggregator/tests/src/Functional/ItemCacheTagsTest.php b/core/modules/aggregator/tests/src/Functional/ItemCacheTagsTest.php index 46b076cb29..09da343682 100644 --- a/core/modules/aggregator/tests/src/Functional/ItemCacheTagsTest.php +++ b/core/modules/aggregator/tests/src/Functional/ItemCacheTagsTest.php @@ -19,7 +19,7 @@ class ItemCacheTagsTest extends EntityCacheTagsTestBase { /** * {@inheritdoc} */ - public static $modules = array('aggregator'); + public static $modules = ['aggregator']; /** * {@inheritdoc} @@ -39,21 +39,21 @@ protected function setUp() { */ protected function createEntity() { // Create a "Camelids" feed. - $feed = Feed::create(array( + $feed = Feed::create([ 'title' => 'Camelids', 'url' => 'https://groups.drupal.org/not_used/167169', 'refresh' => 900, 'checked' => 1389919932, 'description' => 'Drupal Core Group feed', - )); + ]); $feed->save(); // Create a "Llama" aggregator feed item. - $item = Item::create(array( + $item = Item::create([ 'fid' => $feed->id(), 'title' => t('Llama'), 'path' => 'https://www.drupal.org/', - )); + ]); $item->save(); return $item; @@ -67,14 +67,14 @@ public function testEntityCreation() { \Drupal::cache('render')->set('foo', 'bar', CacheBackendInterface::CACHE_PERMANENT, $this->entity->getCacheTags()); // Verify a cache hit. - $this->verifyRenderCache('foo', array('aggregator_feed:1')); + $this->verifyRenderCache('foo', ['aggregator_feed:1']); // Now create a feed item in that feed. - Item::create(array( + Item::create([ 'fid' => $this->entity->getFeedId(), 'title' => t('Llama 2'), 'path' => 'https://groups.drupal.org/', - ))->save(); + ])->save(); // Verify a cache miss. $this->assertFalse(\Drupal::cache('render')->get('foo'), 'Creating a new feed item invalidates the cache tag of the feed.'); diff --git a/core/modules/aggregator/tests/src/Kernel/FeedValidationTest.php b/core/modules/aggregator/tests/src/Kernel/FeedValidationTest.php index 81a501e3ba..d8804dd9c3 100644 --- a/core/modules/aggregator/tests/src/Kernel/FeedValidationTest.php +++ b/core/modules/aggregator/tests/src/Kernel/FeedValidationTest.php @@ -17,7 +17,7 @@ class FeedValidationTest extends EntityKernelTestBase { * * @var array */ - public static $modules = array('aggregator', 'options'); + public static $modules = ['aggregator', 'options']; /** * {@inheritdoc} diff --git a/core/modules/aggregator/tests/src/Kernel/Migrate/d6/MigrateAggregatorConfigsTest.php b/core/modules/aggregator/tests/src/Kernel/Migrate/d6/MigrateAggregatorConfigsTest.php index d8f1b6f876..280a103db8 100644 --- a/core/modules/aggregator/tests/src/Kernel/Migrate/d6/MigrateAggregatorConfigsTest.php +++ b/core/modules/aggregator/tests/src/Kernel/Migrate/d6/MigrateAggregatorConfigsTest.php @@ -34,7 +34,7 @@ public function testAggregatorSettings() { $config = $this->config('aggregator.settings'); $this->assertIdentical('aggregator', $config->get('fetcher')); $this->assertIdentical('aggregator', $config->get('parser')); - $this->assertIdentical(array('aggregator'), $config->get('processors')); + $this->assertIdentical(['aggregator'], $config->get('processors')); $this->assertIdentical(600, $config->get('items.teaser_length')); $this->assertIdentical('
      • ', $config->get('items.allowed_html')); $this->assertIdentical(9676800, $config->get('items.expire')); diff --git a/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php b/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php index a72da23c8b..39f57b2518 100644 --- a/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php +++ b/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php @@ -21,14 +21,14 @@ class IntegrationTest extends ViewsKernelTestBase { * * @var array */ - public static $modules = array('aggregator', 'aggregator_test_views', 'system', 'field', 'options', 'user'); + public static $modules = ['aggregator', 'aggregator_test_views', 'system', 'field', 'options', 'user']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_aggregator_items'); + public static $testViews = ['test_aggregator_items']; /** * The entity storage for aggregator items. @@ -53,7 +53,7 @@ protected function setUp($import_test_views = TRUE) { $this->installEntitySchema('aggregator_item'); $this->installEntitySchema('aggregator_feed'); - ViewTestData::createTestViews(get_class($this), array('aggregator_test_views')); + ViewTestData::createTestViews(get_class($this), ['aggregator_test_views']); $this->itemStorage = $this->container->get('entity.manager')->getStorage('aggregator_item'); $this->feedStorage = $this->container->get('entity.manager')->getStorage('aggregator_feed'); @@ -66,19 +66,19 @@ public function testAggregatorItemView() { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); - $feed = $this->feedStorage->create(array( + $feed = $this->feedStorage->create([ 'title' => $this->randomMachineName(), 'url' => 'https://www.drupal.org/', 'refresh' => 900, 'checked' => 123543535, 'description' => $this->randomMachineName(), - )); + ]); $feed->save(); - $items = array(); - $expected = array(); + $items = []; + $expected = []; for ($i = 0; $i < 10; $i++) { - $values = array(); + $values = []; $values['fid'] = $feed->id(); $values['timestamp'] = mt_rand(REQUEST_TIME - 10, REQUEST_TIME + 10); $values['title'] = $this->randomMachineName(); @@ -99,13 +99,13 @@ public function testAggregatorItemView() { $view = Views::getView('test_aggregator_items'); $this->executeView($view); - $column_map = array( + $column_map = [ 'iid' => 'iid', 'title' => 'title', 'aggregator_item_timestamp' => 'timestamp', 'description' => 'description', 'aggregator_item_author' => 'author', - ); + ]; $this->assertIdenticalResultset($view, $expected, $column_map); // Ensure that the rendering of the linked title works as expected. diff --git a/core/modules/aggregator/tests/src/Unit/Menu/AggregatorLocalTasksTest.php b/core/modules/aggregator/tests/src/Unit/Menu/AggregatorLocalTasksTest.php index c9f6906f66..7a78ad9fb4 100644 --- a/core/modules/aggregator/tests/src/Unit/Menu/AggregatorLocalTasksTest.php +++ b/core/modules/aggregator/tests/src/Unit/Menu/AggregatorLocalTasksTest.php @@ -15,7 +15,7 @@ class AggregatorLocalTasksTest extends LocalTaskIntegrationTestBase { * {@inheritdoc} */ protected function setUp() { - $this->directoryList = array('aggregator' => 'core/modules/aggregator'); + $this->directoryList = ['aggregator' => 'core/modules/aggregator']; parent::setUp(); } @@ -25,19 +25,19 @@ protected function setUp() { * @dataProvider getAggregatorAdminRoutes */ public function testAggregatorAdminLocalTasks($route) { - $this->assertLocalTasks($route, array( - 0 => array('aggregator.admin_overview', 'aggregator.admin_settings'), - )); + $this->assertLocalTasks($route, [ + 0 => ['aggregator.admin_overview', 'aggregator.admin_settings'], + ]); } /** * Provides a list of routes to test. */ public function getAggregatorAdminRoutes() { - return array( - array('aggregator.admin_overview'), - array('aggregator.admin_settings'), - ); + return [ + ['aggregator.admin_overview'], + ['aggregator.admin_settings'], + ]; } /** @@ -46,9 +46,9 @@ public function getAggregatorAdminRoutes() { * @dataProvider getAggregatorSourceRoutes */ public function testAggregatorSourceLocalTasks($route) { - $this->assertLocalTasks($route, array( - 0 => array('entity.aggregator_feed.canonical', 'entity.aggregator_feed.edit_form', 'entity.aggregator_feed.delete_form'), - )); + $this->assertLocalTasks($route, [ + 0 => ['entity.aggregator_feed.canonical', 'entity.aggregator_feed.edit_form', 'entity.aggregator_feed.delete_form'], + ]); ; } @@ -56,10 +56,10 @@ public function testAggregatorSourceLocalTasks($route) { * Provides a list of source routes to test. */ public function getAggregatorSourceRoutes() { - return array( - array('entity.aggregator_feed.canonical'), - array('entity.aggregator_feed.edit_form'), - ); + return [ + ['entity.aggregator_feed.canonical'], + ['entity.aggregator_feed.edit_form'], + ]; } } diff --git a/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php b/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php index 87a5d93432..926723702d 100644 --- a/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php +++ b/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php @@ -39,20 +39,20 @@ class AggregatorPluginSettingsBaseTest extends UnitTestCase { */ protected function setUp() { $this->configFactory = $this->getConfigFactoryStub( - array( - 'aggregator.settings' => array( - 'processors' => array('aggregator_test'), - ), - 'aggregator_test.settings' => array(), - ) + [ + 'aggregator.settings' => [ + 'processors' => ['aggregator_test'], + ], + 'aggregator_test.settings' => [], + ] ); - foreach (array('fetcher', 'parser', 'processor') as $type) { + foreach (['fetcher', 'parser', 'processor'] as $type) { $this->managers[$type] = $this->getMockBuilder('Drupal\aggregator\Plugin\AggregatorPluginManager') ->disableOriginalConstructor() ->getMock(); $this->managers[$type]->expects($this->once()) ->method('getDefinitions') - ->will($this->returnValue(array('aggregator_test' => array('title' => '', 'description' => '')))); + ->will($this->returnValue(['aggregator_test' => ['title' => '', 'description' => '']])); } $this->settingsForm = new SettingsForm( @@ -79,8 +79,8 @@ public function testSettingsForm() { $test_processor = $this->getMock( 'Drupal\aggregator_test\Plugin\aggregator\processor\TestProcessor', - array('buildConfigurationForm', 'validateConfigurationForm', 'submitConfigurationForm'), - array(array(), 'aggregator_test', array('description' => ''), $this->configFactory) + ['buildConfigurationForm', 'validateConfigurationForm', 'submitConfigurationForm'], + [[], 'aggregator_test', ['description' => ''], $this->configFactory] ); $test_processor->expects($this->at(0)) ->method('buildConfigurationForm') @@ -98,7 +98,7 @@ public function testSettingsForm() { ->with($this->equalTo('aggregator_test')) ->will($this->returnValue($test_processor)); - $form = $this->settingsForm->buildForm(array(), $form_state); + $form = $this->settingsForm->buildForm([], $form_state); $this->settingsForm->validateForm($form, $form_state); $this->settingsForm->submitForm($form, $form_state); } diff --git a/core/modules/ban/ban.install b/core/modules/ban/ban.install index b2ea1fe3d3..f3c003a91c 100644 --- a/core/modules/ban/ban.install +++ b/core/modules/ban/ban.install @@ -9,27 +9,27 @@ * Implements hook_schema(). */ function ban_schema() { - $schema['ban_ip'] = array( + $schema['ban_ip'] = [ 'description' => 'Stores banned IP addresses.', - 'fields' => array( - 'iid' => array( + 'fields' => [ + 'iid' => [ 'description' => 'Primary Key: unique ID for IP addresses.', 'type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE, - ), - 'ip' => array( + ], + 'ip' => [ 'description' => 'IP address', 'type' => 'varchar_ascii', 'length' => 40, 'not null' => TRUE, 'default' => '', - ), - ), - 'indexes' => array( - 'ip' => array('ip'), - ), - 'primary key' => array('iid'), - ); + ], + ], + 'indexes' => [ + 'ip' => ['ip'], + ], + 'primary key' => ['iid'], + ]; return $schema; } diff --git a/core/modules/ban/ban.module b/core/modules/ban/ban.module index a1ee23803b..b8b72c5035 100644 --- a/core/modules/ban/ban.module +++ b/core/modules/ban/ban.module @@ -15,11 +15,11 @@ function ban_help($route_name, RouteMatchInterface $route_match) { case 'help.page.ban': $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Ban module allows administrators to ban visits to their site from individual IP addresses. For more information, see the online documentation for the Ban module.', array(':url' => 'https://www.drupal.org/documentation/modules/ban')) . '

        '; + $output .= '

        ' . t('The Ban module allows administrators to ban visits to their site from individual IP addresses. For more information, see the online documentation for the Ban module.', [':url' => 'https://www.drupal.org/documentation/modules/ban']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Banning IP addresses') . '
        '; - $output .= '
        ' . t('Administrators can enter IP addresses to ban on the IP address bans page.', array(':bans' => \Drupal::url('ban.admin_page'))) . '
        '; + $output .= '
        ' . t('Administrators can enter IP addresses to ban on the IP address bans page.', [':bans' => \Drupal::url('ban.admin_page')]) . '
        '; $output .= '
        '; return $output; diff --git a/core/modules/ban/src/BanIpManager.php b/core/modules/ban/src/BanIpManager.php index a92731c288..d354f7a71c 100644 --- a/core/modules/ban/src/BanIpManager.php +++ b/core/modules/ban/src/BanIpManager.php @@ -30,7 +30,7 @@ public function __construct(Connection $connection) { * {@inheritdoc} */ public function isBanned($ip) { - return (bool) $this->connection->query("SELECT * FROM {ban_ip} WHERE ip = :ip", array(':ip' => $ip))->fetchField(); + return (bool) $this->connection->query("SELECT * FROM {ban_ip} WHERE ip = :ip", [':ip' => $ip])->fetchField(); } /** @@ -45,8 +45,8 @@ public function findAll() { */ public function banIp($ip) { $this->connection->merge('ban_ip') - ->key(array('ip' => $ip)) - ->fields(array('ip' => $ip)) + ->key(['ip' => $ip]) + ->fields(['ip' => $ip]) ->execute(); } @@ -63,7 +63,7 @@ public function unbanIp($id) { * {@inheritdoc} */ public function findById($ban_id) { - return $this->connection->query("SELECT ip FROM {ban_ip} WHERE iid = :iid", array(':iid' => $ban_id))->fetchField(); + return $this->connection->query("SELECT ip FROM {ban_ip} WHERE iid = :iid", [':iid' => $ban_id])->fetchField(); } } diff --git a/core/modules/ban/src/Form/BanAdmin.php b/core/modules/ban/src/Form/BanAdmin.php index a0c769fd47..731d06518c 100644 --- a/core/modules/ban/src/Form/BanAdmin.php +++ b/core/modules/ban/src/Form/BanAdmin.php @@ -52,47 +52,47 @@ public function getFormId() { * address form field. */ public function buildForm(array $form, FormStateInterface $form_state, $default_ip = '') { - $rows = array(); - $header = array($this->t('banned IP addresses'), $this->t('Operations')); + $rows = []; + $header = [$this->t('banned IP addresses'), $this->t('Operations')]; $result = $this->ipManager->findAll(); foreach ($result as $ip) { - $row = array(); + $row = []; $row[] = $ip->ip; - $links = array(); - $links['delete'] = array( + $links = []; + $links['delete'] = [ 'title' => $this->t('Delete'), 'url' => Url::fromRoute('ban.delete', ['ban_id' => $ip->iid]), - ); - $row[] = array( - 'data' => array( + ]; + $row[] = [ + 'data' => [ '#type' => 'operations', '#links' => $links, - ), - ); + ], + ]; $rows[] = $row; } - $form['ip'] = array( + $form['ip'] = [ '#title' => $this->t('IP address'), '#type' => 'textfield', '#size' => 48, '#maxlength' => 40, '#default_value' => $default_ip, '#description' => $this->t('Enter a valid IP address.'), - ); - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + ]; + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Add'), - ); + ]; - $form['ban_ip_banning_table'] = array( + $form['ban_ip_banning_table'] = [ '#type' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => $this->t('No blocked IP addresses available.'), '#weight' => 120, - ); + ]; return $form; } @@ -118,7 +118,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) { public function submitForm(array &$form, FormStateInterface $form_state) { $ip = trim($form_state->getValue('ip')); $this->ipManager->banIp($ip); - drupal_set_message($this->t('The IP address %ip has been banned.', array('%ip' => $ip))); + drupal_set_message($this->t('The IP address %ip has been banned.', ['%ip' => $ip])); $form_state->setRedirect('ban.admin_page'); } diff --git a/core/modules/ban/src/Form/BanDelete.php b/core/modules/ban/src/Form/BanDelete.php index a8a4962458..3d14ca3415 100644 --- a/core/modules/ban/src/Form/BanDelete.php +++ b/core/modules/ban/src/Form/BanDelete.php @@ -58,7 +58,7 @@ public function getFormId() { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to unblock %ip?', array('%ip' => $this->banIp)); + return $this->t('Are you sure you want to unblock %ip?', ['%ip' => $this->banIp]); } /** @@ -93,8 +93,8 @@ public function buildForm(array $form, FormStateInterface $form_state, $ban_id = */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->ipManager->unbanIp($this->banIp); - $this->logger('user')->notice('Deleted %ip', array('%ip' => $this->banIp)); - drupal_set_message($this->t('The IP address %ip was deleted.', array('%ip' => $this->banIp))); + $this->logger('user')->notice('Deleted %ip', ['%ip' => $this->banIp]); + drupal_set_message($this->t('The IP address %ip was deleted.', ['%ip' => $this->banIp])); $form_state->setRedirectUrl($this->getCancelUrl()); } diff --git a/core/modules/ban/src/Plugin/migrate/destination/BlockedIp.php b/core/modules/ban/src/Plugin/migrate/destination/BlockedIp.php index 94135fd3f6..7c570bb793 100644 --- a/core/modules/ban/src/Plugin/migrate/destination/BlockedIp.php +++ b/core/modules/ban/src/Plugin/migrate/destination/BlockedIp.php @@ -76,7 +76,7 @@ public function fields(MigrationInterface $migration = NULL) { /** * {@inheritdoc} */ - public function import(Row $row, array $old_destination_id_values = array()) { + public function import(Row $row, array $old_destination_id_values = []) { $this->banManager->banIp($row->getDestinationProperty('ip')); } diff --git a/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php b/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php index 9738915023..0a155fb471 100644 --- a/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php +++ b/core/modules/ban/tests/src/Functional/IpAddressBlockingTest.php @@ -18,55 +18,55 @@ class IpAddressBlockingTest extends BrowserTestBase { * * @var array */ - public static $modules = array('ban'); + public static $modules = ['ban']; /** * Tests various user input to confirm correct validation and saving of data. */ function testIPAddressValidation() { // Create user. - $admin_user = $this->drupalCreateUser(array('ban IP addresses')); + $admin_user = $this->drupalCreateUser(['ban IP addresses']); $this->drupalLogin($admin_user); $this->drupalGet('admin/config/people/ban'); // Ban a valid IP address. - $edit = array(); + $edit = []; $edit['ip'] = '1.2.3.3'; $this->drupalPostForm('admin/config/people/ban', $edit, t('Add')); - $ip = db_query("SELECT iid from {ban_ip} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField(); + $ip = db_query("SELECT iid from {ban_ip} WHERE ip = :ip", [':ip' => $edit['ip']])->fetchField(); $this->assertTrue($ip, 'IP address found in database.'); - $this->assertRaw(t('The IP address %ip has been banned.', array('%ip' => $edit['ip'])), 'IP address was banned.'); + $this->assertRaw(t('The IP address %ip has been banned.', ['%ip' => $edit['ip']]), 'IP address was banned.'); // Try to block an IP address that's already blocked. - $edit = array(); + $edit = []; $edit['ip'] = '1.2.3.3'; $this->drupalPostForm('admin/config/people/ban', $edit, t('Add')); $this->assertText(t('This IP address is already banned.')); // Try to block a reserved IP address. - $edit = array(); + $edit = []; $edit['ip'] = '255.255.255.255'; $this->drupalPostForm('admin/config/people/ban', $edit, t('Add')); $this->assertText(t('Enter a valid IP address.')); // Try to block a reserved IP address. - $edit = array(); + $edit = []; $edit['ip'] = 'test.example.com'; $this->drupalPostForm('admin/config/people/ban', $edit, t('Add')); $this->assertText(t('Enter a valid IP address.')); // Submit an empty form. - $edit = array(); + $edit = []; $edit['ip'] = ''; $this->drupalPostForm('admin/config/people/ban', $edit, t('Add')); $this->assertText(t('Enter a valid IP address.')); // Pass an IP address as a URL parameter and submit it. $submit_ip = '1.2.3.4'; - $this->drupalPostForm('admin/config/people/ban/' . $submit_ip, array(), t('Add')); - $ip = db_query("SELECT iid from {ban_ip} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchField(); + $this->drupalPostForm('admin/config/people/ban/' . $submit_ip, [], t('Add')); + $ip = db_query("SELECT iid from {ban_ip} WHERE ip = :ip", [':ip' => $submit_ip])->fetchField(); $this->assertTrue($ip, 'IP address found in database'); - $this->assertRaw(t('The IP address %ip has been banned.', array('%ip' => $submit_ip)), 'IP address was banned.'); + $this->assertRaw(t('The IP address %ip has been banned.', ['%ip' => $submit_ip]), 'IP address was banned.'); // Submit your own IP address. This fails, although it works when testing // manually. @@ -85,7 +85,7 @@ function testIPAddressValidation() { $banIp->banIp($ip); $banIp->banIp($ip); $query = db_select('ban_ip', 'bip'); - $query->fields('bip', array('iid')); + $query->fields('bip', ['iid']); $query->condition('bip.ip', $ip); $ip_count = $query->execute()->fetchAll(); $this->assertEqual(1, count($ip_count)); @@ -93,7 +93,7 @@ function testIPAddressValidation() { $banIp->banIp($ip); $banIp->banIp($ip); $query = db_select('ban_ip', 'bip'); - $query->fields('bip', array('iid')); + $query->fields('bip', ['iid']); $query->condition('bip.ip', $ip); $ip_count = $query->execute()->fetchAll(); $this->assertEqual(1, count($ip_count)); diff --git a/core/modules/basic_auth/basic_auth.module b/core/modules/basic_auth/basic_auth.module index ea64c5ba18..7d1d01f6b6 100644 --- a/core/modules/basic_auth/basic_auth.module +++ b/core/modules/basic_auth/basic_auth.module @@ -15,7 +15,7 @@ function basic_auth_help($route_name, RouteMatchInterface $route_match) { case 'help.page.basic_auth': $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The HTTP Basic Authentication module supplies an HTTP Basic authentication provider for web service requests. This authentication provider authenticates requests using the HTTP Basic Authentication username and password, as an alternative to using Drupal\'s standard cookie-based authentication system. It is only useful if your site provides web services configured to use this type of authentication (for instance, the RESTful Web Services module). For more information, see the online documentation for the HTTP Basic Authentication module.', array(':hba_do' => 'https://www.drupal.org/documentation/modules/basic_auth', ':rest_help' => (\Drupal::moduleHandler()->moduleExists('rest')) ? \Drupal::url('help.page', array('name' => 'rest')) : '#')) . '

        '; + $output .= '

        ' . t('The HTTP Basic Authentication module supplies an HTTP Basic authentication provider for web service requests. This authentication provider authenticates requests using the HTTP Basic Authentication username and password, as an alternative to using Drupal\'s standard cookie-based authentication system. It is only useful if your site provides web services configured to use this type of authentication (for instance, the RESTful Web Services module). For more information, see the online documentation for the HTTP Basic Authentication module.', [':hba_do' => 'https://www.drupal.org/documentation/modules/basic_auth', ':rest_help' => (\Drupal::moduleHandler()->moduleExists('rest')) ? \Drupal::url('help.page', ['name' => 'rest']) : '#']) . '

        '; return $output; } } diff --git a/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php b/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php index eac482c812..c72e3f0c01 100644 --- a/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php +++ b/core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php @@ -88,7 +88,7 @@ public function authenticate(Request $request) { // in to many different user accounts. We have a reasonably high limit // since there may be only one apparent IP for all users at an institution. if ($this->flood->isAllowed('basic_auth.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) { - $accounts = $this->entityManager->getStorage('user')->loadByProperties(array('name' => $username, 'status' => 1)); + $accounts = $this->entityManager->getStorage('user')->loadByProperties(['name' => $username, 'status' => 1]); $account = reset($accounts); if ($account) { if ($flood_config->get('uid_only')) { @@ -127,9 +127,9 @@ public function authenticate(Request $request) { */ public function challengeException(Request $request, \Exception $previous) { $site_name = $this->configFactory->get('system.site')->get('name'); - $challenge = SafeMarkup::format('Basic realm="@realm"', array( + $challenge = SafeMarkup::format('Basic realm="@realm"', [ '@realm' => !empty($site_name) ? $site_name : 'Access restricted', - )); + ]); return new UnauthorizedHttpException((string) $challenge, 'No authentication credentials provided.', $previous); } diff --git a/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php b/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php index 04bb0fdc99..45b9b356eb 100644 --- a/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php +++ b/core/modules/basic_auth/src/Tests/Authentication/BasicAuthTest.php @@ -22,7 +22,7 @@ class BasicAuthTest extends WebTestBase { * * @var array */ - public static $modules = array('basic_auth', 'router_test', 'locale', 'basic_auth_test'); + public static $modules = ['basic_auth', 'router_test', 'locale', 'basic_auth_test']; /** * Test http basic authentication. @@ -55,7 +55,7 @@ public function testBasicAuth() { $this->drupalGet('admin'); $this->assertResponse('403', 'No authentication prompt for routes not explicitly defining authentication providers.'); - $account = $this->drupalCreateUser(array('access administration pages')); + $account = $this->drupalCreateUser(['access administration pages']); $this->basicAuthGet(Url::fromRoute('system.admin'), $account->getUsername(), $account->pass_raw); $this->assertNoLink('Log out', 'User is not logged in'); @@ -82,7 +82,7 @@ function testGlobalLoginFloodControl() { ->set('user_limit', 4000) ->save(); - $user = $this->drupalCreateUser(array()); + $user = $this->drupalCreateUser([]); $incorrect_user = clone $user; $incorrect_user->pass_raw .= 'incorrect'; $url = Url::fromRoute('router_test.11'); @@ -107,10 +107,10 @@ function testPerUserLoginFloodControl() { ->set('user_limit', 2) ->save(); - $user = $this->drupalCreateUser(array()); + $user = $this->drupalCreateUser([]); $incorrect_user = clone $user; $incorrect_user->pass_raw .= 'incorrect'; - $user2 = $this->drupalCreateUser(array()); + $user2 = $this->drupalCreateUser([]); $url = Url::fromRoute('router_test.11'); // Try a failed login. diff --git a/core/modules/basic_auth/src/Tests/BasicAuthTestTrait.php b/core/modules/basic_auth/src/Tests/BasicAuthTestTrait.php index b5766fb64a..8a289b0037 100644 --- a/core/modules/basic_auth/src/Tests/BasicAuthTestTrait.php +++ b/core/modules/basic_auth/src/Tests/BasicAuthTestTrait.php @@ -51,7 +51,7 @@ protected function basicAuthGet($path, $username, $password, array $options = [] * * @see \Drupal\simpletest\WebTestBase::drupalPostForm() */ - protected function basicAuthPostForm($path, $edit, $submit, $username, $password, array $options = array(), $form_html_id = NULL, $extra_post = NULL) { + protected function basicAuthPostForm($path, $edit, $submit, $username, $password, array $options = [], $form_html_id = NULL, $extra_post = NULL) { return $this->drupalPostForm($path, $edit, $submit, $options, $this->getBasicAuthHeaders($username, $password), $form_html_id, $extra_post); } diff --git a/core/modules/big_pipe/tests/modules/big_pipe_test/src/Form/BigPipeTestForm.php b/core/modules/big_pipe/tests/modules/big_pipe_test/src/Form/BigPipeTestForm.php index ccb15b737c..c56ee32787 100644 --- a/core/modules/big_pipe/tests/modules/big_pipe_test/src/Form/BigPipeTestForm.php +++ b/core/modules/big_pipe/tests/modules/big_pipe_test/src/Form/BigPipeTestForm.php @@ -20,14 +20,14 @@ public function getFormId() { public function buildForm(array $form, FormStateInterface $form_state) { $form['#token'] = FALSE; - $form['big_pipe'] = array( + $form['big_pipe'] = [ '#type' => 'checkboxes', '#title' => $this->t('BigPipe works…'), '#options' => [ 'js' => $this->t('… with JavaScript'), 'nojs' => $this->t('… without JavaScript'), ], - ); + ]; return $form; } diff --git a/core/modules/block/block.module b/core/modules/block/block.module index 7e39da4006..ee6a4a11ea 100644 --- a/core/modules/block/block.module +++ b/core/modules/block/block.module @@ -18,24 +18,24 @@ function block_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.block': - $block_content = \Drupal::moduleHandler()->moduleExists('block_content') ? \Drupal::url('help.page', array('name' => 'block_content')) : '#'; + $block_content = \Drupal::moduleHandler()->moduleExists('block_content') ? \Drupal::url('help.page', ['name' => 'block_content']) : '#'; $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Block module allows you to place blocks in regions of your installed themes, and configure block settings. For more information, see the online documentation for the Block module.', array(':blocks-documentation' => 'https://www.drupal.org/documentation/modules/block/')) . '

        '; + $output .= '

        ' . t('The Block module allows you to place blocks in regions of your installed themes, and configure block settings. For more information, see the online documentation for the Block module.', [':blocks-documentation' => 'https://www.drupal.org/documentation/modules/block/']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Placing and moving blocks') . '
        '; - $output .= '
        ' . t('You can place a new block in a region by selecting Place block on the Block layout page. Once a block is placed, it can be moved to a different region by drag-and-drop or by using the Region drop-down list, and then clicking Save blocks.', array(':blocks' => \Drupal::url('block.admin_display'))) . '
        '; + $output .= '
        ' . t('You can place a new block in a region by selecting Place block on the Block layout page. Once a block is placed, it can be moved to a different region by drag-and-drop or by using the Region drop-down list, and then clicking Save blocks.', [':blocks' => \Drupal::url('block.admin_display')]) . '
        '; $output .= '
        ' . t('Toggling between different themes') . '
        '; $output .= '
        ' . t('Blocks are placed and configured specifically for each theme. The Block layout page opens with the default theme, but you can toggle to other installed themes.') . '
        '; $output .= '
        ' . t('Demonstrating block regions for a theme') . '
        '; - $output .= '
        ' . t('You can see where the regions are for the current theme by clicking the Demonstrate block regions link on the Block layout page. Regions are specific to each theme.', array(':blocks' => \Drupal::url('block.admin_display'))) . '
        '; + $output .= '
        ' . t('You can see where the regions are for the current theme by clicking the Demonstrate block regions link on the Block layout page. Regions are specific to each theme.', [':blocks' => \Drupal::url('block.admin_display')]) . '
        '; $output .= '
        ' . t('Configuring block settings') . '
        '; - $output .= '
        ' . t('To change the settings of an individual block click on the Configure link on the Block layout page. The available options vary depending on the module that provides the block. For all blocks you can change the block title and toggle whether to display it.', array(':blocks' => Drupal::url('block.admin_display'))) . '
        '; + $output .= '
        ' . t('To change the settings of an individual block click on the Configure link on the Block layout page. The available options vary depending on the module that provides the block. For all blocks you can change the block title and toggle whether to display it.', [':blocks' => Drupal::url('block.admin_display')]) . '
        '; $output .= '
        ' . t('Controlling visibility') . '
        '; $output .= '
        ' . t('You can control the visibility of a block by restricting it to specific pages, content types, and/or roles by setting the appropriate options under Visibility settings of the block configuration.') . '
        '; $output .= '
        ' . t('Adding custom blocks') . '
        '; - $output .= '
        ' . t('You can add custom blocks, if the Custom Block module is installed. For more information, see the Custom Block help page.', array(':blockcontent-help' => $block_content)) . '
        '; + $output .= '
        ' . t('You can add custom blocks, if the Custom Block module is installed. For more information, see the Custom Block help page.', [':blockcontent-help' => $block_content]) . '
        '; $output .= '
        '; return $output; } @@ -43,7 +43,7 @@ function block_help($route_name, RouteMatchInterface $route_match) { $demo_theme = $route_match->getParameter('theme') ?: \Drupal::config('system.theme')->get('default'); $themes = \Drupal::service('theme_handler')->listInfo(); $output = '

        ' . t('Block placement is specific to each theme on your site. Changes will not be saved until you click Save blocks at the bottom of the page.') . '

        '; - $output .= '

        ' . \Drupal::l(t('Demonstrate block regions (@theme)', array('@theme' => $themes[$demo_theme]->info['name'])), new Url('block.admin_demo', array('theme' => $demo_theme))) . '

        '; + $output .= '

        ' . \Drupal::l(t('Demonstrate block regions (@theme)', ['@theme' => $themes[$demo_theme]->info['name']]), new Url('block.admin_demo', ['theme' => $demo_theme])) . '

        '; return $output; } } @@ -52,11 +52,11 @@ function block_help($route_name, RouteMatchInterface $route_match) { * Implements hook_theme(). */ function block_theme() { - return array( - 'block' => array( + return [ + 'block' => [ 'render element' => 'elements', - ), - ); + ], + ]; } /** @@ -65,12 +65,12 @@ function block_theme() { function block_page_top(array &$page_top) { if (\Drupal::routeMatch()->getRouteName() === 'block.admin_demo') { $theme = \Drupal::theme()->getActiveTheme()->getName(); - $page_top['backlink'] = array( + $page_top['backlink'] = [ '#type' => 'link', '#title' => t('Exit block region demonstration'), - '#options' => array('attributes' => array('class' => array('block-demo-backlink'))), + '#options' => ['attributes' => ['class' => ['block-demo-backlink']]], '#weight' => -10, - ); + ]; if (\Drupal::config('system.theme')->get('default') == $theme) { $page_top['backlink']['#url'] = Url::fromRoute('block.admin_display'); } @@ -108,12 +108,12 @@ function block_themes_installed($theme_list) { */ function block_theme_initialize($theme) { // Initialize theme's blocks if none already registered. - $has_blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(array('theme' => $theme)); + $has_blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $theme]); if (!$has_blocks) { $default_theme = \Drupal::config('system.theme')->get('default'); // Apply only to new theme's visible regions. $regions = system_region_list($theme, REGIONS_VISIBLE); - $default_theme_blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(array('theme' => $default_theme)); + $default_theme_blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $default_theme]); foreach ($default_theme_blocks as $default_theme_block_id => $default_theme_block) { if (strpos($default_theme_block_id, $default_theme . '_') === 0) { $id = str_replace($default_theme, $theme, $default_theme_block_id); @@ -161,7 +161,7 @@ function block_rebuild() { * Implements hook_theme_suggestions_HOOK(). */ function block_theme_suggestions_block(array $variables) { - $suggestions = array(); + $suggestions = []; $suggestions[] = 'block__' . $variables['elements']['#configuration']['provider']; // Hyphens (-) and underscores (_) play a special role in theme suggestions. diff --git a/core/modules/block/block.post_update.php b/core/modules/block/block.post_update.php index d3544e8bd6..bd0a67c7d8 100644 --- a/core/modules/block/block.post_update.php +++ b/core/modules/block/block.post_update.php @@ -63,10 +63,10 @@ function block_post_update_disable_blocks_with_missing_contexts() { $message = t('Encountered an unknown context mapping key coming probably from a contributed or custom module: One or more mappings could not be updated. Please manually review your visibility settings for the following blocks, which are disabled now:'); $message .= '
          '; foreach ($blocks as $disabled_block_id => $disabled_block) { - $message .= '
        • ' . t('@label (Visibility: @plugin_ids)', array( + $message .= '
        • ' . t('@label (Visibility: @plugin_ids)', [ '@label' => $disabled_block->get('settings')['label'], '@plugin_ids' => implode(', ', array_intersect_key($condition_plugin_id_label_map, array_flip(array_keys($block_update_8001[$disabled_block_id]['missing_context_ids'])))) - )) . '
        • '; + ]) . ''; } $message .= '
        '; diff --git a/core/modules/block/src/BlockForm.php b/core/modules/block/src/BlockForm.php index 42dfbc3b2f..b2d180aa46 100644 --- a/core/modules/block/src/BlockForm.php +++ b/core/modules/block/src/BlockForm.php @@ -140,57 +140,57 @@ public function form(array $form, FormStateInterface $form_state) { $form['visibility'] = $this->buildVisibilityInterface([], $form_state); // If creating a new block, calculate a safe default machine name. - $form['id'] = array( + $form['id'] = [ '#type' => 'machine_name', '#maxlength' => 64, '#description' => $this->t('A unique name for this block instance. Must be alpha-numeric and underscore separated.'), '#default_value' => !$entity->isNew() ? $entity->id() : $this->getUniqueMachineName($entity), - '#machine_name' => array( + '#machine_name' => [ 'exists' => '\Drupal\block\Entity\Block::load', 'replace_pattern' => '[^a-z0-9_.]+', - 'source' => array('settings', 'label'), - ), + 'source' => ['settings', 'label'], + ], '#required' => TRUE, '#disabled' => !$entity->isNew(), - ); + ]; // Theme settings. if ($entity->getTheme()) { - $form['theme'] = array( + $form['theme'] = [ '#type' => 'value', '#value' => $theme, - ); + ]; } else { - $theme_options = array(); + $theme_options = []; foreach ($this->themeHandler->listInfo() as $theme_name => $theme_info) { if (!empty($theme_info->status)) { $theme_options[$theme_name] = $theme_info->info['name']; } } - $form['theme'] = array( + $form['theme'] = [ '#type' => 'select', '#options' => $theme_options, '#title' => t('Theme'), '#default_value' => $theme, - '#ajax' => array( + '#ajax' => [ 'callback' => '::themeSwitch', 'wrapper' => 'edit-block-region-wrapper', - ), - ); + ], + ]; } // Hidden weight setting. $weight = $entity->isNew() ? $this->getRequest()->query->get('weight', 0) : $entity->getWeight(); - $form['weight'] = array( + $form['weight'] = [ '#type' => 'hidden', '#default_value' => $weight, - ); + ]; // Region settings. $entity_region = $entity->getRegion(); $region = $entity->isNew() ? $this->getRequest()->query->get('region', $entity_region) : $entity_region; - $form['region'] = array( + $form['region'] = [ '#type' => 'select', '#title' => $this->t('Region'), '#description' => $this->t('Select the region where this block should be displayed.'), @@ -199,7 +199,7 @@ public function form(array $form, FormStateInterface $form_state) { '#options' => system_region_list($theme, REGIONS_VISIBLE), '#prefix' => '
        ', '#suffix' => '
        ', - ); + ]; $form['#attached']['library'][] = 'block/drupal.block.admin'; return $form; } @@ -360,10 +360,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message($this->t('The block configuration has been saved.')); $form_state->setRedirect( 'block.admin_display_theme', - array( + [ 'theme' => $form_state->getValue('theme'), - ), - array('query' => array('block-placement' => Html::getClass($this->entity->id()))) + ], + ['query' => ['block-placement' => Html::getClass($this->entity->id())]] ); } diff --git a/core/modules/block/src/BlockListBuilder.php b/core/modules/block/src/BlockListBuilder.php index 6e5c968b6c..37b2e8bfc3 100644 --- a/core/modules/block/src/BlockListBuilder.php +++ b/core/modules/block/src/BlockListBuilder.php @@ -125,15 +125,15 @@ public function buildForm(array $form, FormStateInterface $form_state) { // Build the form tree. $form['blocks'] = $this->buildBlocksForm(); - $form['actions'] = array( + $form['actions'] = [ '#tree' => FALSE, '#type' => 'actions', - ); - $form['actions']['submit'] = array( + ]; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save blocks'), '#button_type' => 'primary', - ); + ]; return $form; } @@ -150,29 +150,29 @@ protected function buildBlocksForm() { /** @var \Drupal\block\BlockInterface[] $entities */ foreach ($entities as $entity_id => $entity) { $definition = $entity->getPlugin()->getPluginDefinition(); - $blocks[$entity->getRegion()][$entity_id] = array( + $blocks[$entity->getRegion()][$entity_id] = [ 'label' => $entity->label(), 'entity_id' => $entity_id, 'weight' => $entity->getWeight(), 'entity' => $entity, 'category' => $definition['category'], 'status' => $entity->status(), - ); + ]; } - $form = array( + $form = [ '#type' => 'table', - '#header' => array( + '#header' => [ $this->t('Block'), $this->t('Category'), $this->t('Region'), $this->t('Weight'), $this->t('Operations'), - ), - '#attributes' => array( + ], + '#attributes' => [ 'id' => 'blocks', - ), - ); + ], + ]; // Weights range from -delta to +delta, so delta should be at least half // of the amount of blocks present. This makes sure all blocks in the same @@ -188,39 +188,39 @@ protected function buildBlocksForm() { // Loop over each region and build blocks. $regions = $this->systemRegionList($this->getThemeName(), REGIONS_VISIBLE); foreach ($regions as $region => $title) { - $form['#tabledrag'][] = array( + $form['#tabledrag'][] = [ 'action' => 'match', 'relationship' => 'sibling', 'group' => 'block-region-select', 'subgroup' => 'block-region-' . $region, 'hidden' => FALSE, - ); - $form['#tabledrag'][] = array( + ]; + $form['#tabledrag'][] = [ 'action' => 'order', 'relationship' => 'sibling', 'group' => 'block-weight', 'subgroup' => 'block-weight-' . $region, - ); + ]; - $form['region-' . $region] = array( - '#attributes' => array( - 'class' => array('region-title', 'region-title-' . $region), + $form['region-' . $region] = [ + '#attributes' => [ + 'class' => ['region-title', 'region-title-' . $region], 'no_striping' => TRUE, - ), - ); - $form['region-' . $region]['title'] = array( - '#theme_wrappers' => array( - 'container' => array( - '#attributes' => array('class' => 'region-title__action'), - ) - ), + ], + ]; + $form['region-' . $region]['title'] = [ + '#theme_wrappers' => [ + 'container' => [ + '#attributes' => ['class' => 'region-title__action'], + ] + ], '#prefix' => $title, '#type' => 'link', '#title' => $this->t('Place block in the %region region', ['%region' => $title]), '#url' => Url::fromRoute('block.admin_library', ['theme' => $this->getThemeName()], ['query' => ['region' => $region]]), - '#wrapper_attributes' => array( + '#wrapper_attributes' => [ 'colspan' => 5, - ), + ], '#attributes' => [ 'class' => ['use-ajax', 'button', 'button--small'], 'data-dialog-type' => 'modal', @@ -228,74 +228,74 @@ protected function buildBlocksForm() { 'width' => 700, ]), ], - ); + ]; - $form['region-' . $region . '-message'] = array( - '#attributes' => array( - 'class' => array( + $form['region-' . $region . '-message'] = [ + '#attributes' => [ + 'class' => [ 'region-message', 'region-' . $region . '-message', empty($blocks[$region]) ? 'region-empty' : 'region-populated', - ), - ), - ); - $form['region-' . $region . '-message']['message'] = array( + ], + ], + ]; + $form['region-' . $region . '-message']['message'] = [ '#markup' => '' . $this->t('No blocks in this region') . '', - '#wrapper_attributes' => array( + '#wrapper_attributes' => [ 'colspan' => 5, - ), - ); + ], + ]; if (isset($blocks[$region])) { foreach ($blocks[$region] as $info) { $entity_id = $info['entity_id']; - $form[$entity_id] = array( - '#attributes' => array( - 'class' => array('draggable'), - ), - ); + $form[$entity_id] = [ + '#attributes' => [ + 'class' => ['draggable'], + ], + ]; $form[$entity_id]['#attributes']['class'][] = $info['status'] ? 'block-enabled' : 'block-disabled'; if ($placement && $placement == Html::getClass($entity_id)) { $form[$entity_id]['#attributes']['class'][] = 'color-success'; $form[$entity_id]['#attributes']['class'][] = 'js-block-placed'; } - $form[$entity_id]['info'] = array( + $form[$entity_id]['info'] = [ '#plain_text' => $info['status'] ? $info['label'] : $this->t('@label (disabled)', ['@label' => $info['label']]), - '#wrapper_attributes' => array( - 'class' => array('block'), - ), - ); - $form[$entity_id]['type'] = array( + '#wrapper_attributes' => [ + 'class' => ['block'], + ], + ]; + $form[$entity_id]['type'] = [ '#markup' => $info['category'], - ); - $form[$entity_id]['region-theme']['region'] = array( + ]; + $form[$entity_id]['region-theme']['region'] = [ '#type' => 'select', '#default_value' => $region, '#required' => TRUE, - '#title' => $this->t('Region for @block block', array('@block' => $info['label'])), + '#title' => $this->t('Region for @block block', ['@block' => $info['label']]), '#title_display' => 'invisible', '#options' => $regions, - '#attributes' => array( - 'class' => array('block-region-select', 'block-region-' . $region), - ), - '#parents' => array('blocks', $entity_id, 'region'), - ); - $form[$entity_id]['region-theme']['theme'] = array( + '#attributes' => [ + 'class' => ['block-region-select', 'block-region-' . $region], + ], + '#parents' => ['blocks', $entity_id, 'region'], + ]; + $form[$entity_id]['region-theme']['theme'] = [ '#type' => 'hidden', '#value' => $this->getThemeName(), - '#parents' => array('blocks', $entity_id, 'theme'), - ); - $form[$entity_id]['weight'] = array( + '#parents' => ['blocks', $entity_id, 'theme'], + ]; + $form[$entity_id]['weight'] = [ '#type' => 'weight', '#default_value' => $info['weight'], '#delta' => $weight_delta, - '#title' => $this->t('Weight for @block block', array('@block' => $info['label'])), + '#title' => $this->t('Weight for @block block', ['@block' => $info['label']]), '#title_display' => 'invisible', - '#attributes' => array( - 'class' => array('block-weight', 'block-weight-' . $region), - ), - ); + '#attributes' => [ + 'class' => ['block-weight', 'block-weight-' . $region], + ], + ]; $form[$entity_id]['operations'] = $this->buildOperations($info['entity']); } } @@ -362,7 +362,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $entities = $this->storage->loadMultiple(array_keys($form_state->getValue('blocks'))); /** @var \Drupal\block\BlockInterface[] $entities */ foreach ($entities as $entity_id => $entity) { - $entity_values = $form_state->getValue(array('blocks', $entity_id)); + $entity_values = $form_state->getValue(['blocks', $entity_id]); $entity->setWeight($entity_values['weight']); $entity->setRegion($entity_values['region']); $entity->save(); diff --git a/core/modules/block/src/BlockRepository.php b/core/modules/block/src/BlockRepository.php index 53620a09f1..4cdd71071d 100644 --- a/core/modules/block/src/BlockRepository.php +++ b/core/modules/block/src/BlockRepository.php @@ -48,10 +48,10 @@ public function __construct(EntityManagerInterface $entity_manager, ThemeManager public function getVisibleBlocksPerRegion(array &$cacheable_metadata = []) { $active_theme = $this->themeManager->getActiveTheme(); // Build an array of the region names in the right order. - $empty = array_fill_keys($active_theme->getRegions(), array()); + $empty = array_fill_keys($active_theme->getRegions(), []); - $full = array(); - foreach ($this->blockStorage->loadByProperties(array('theme' => $active_theme->getName())) as $block_id => $block) { + $full = []; + foreach ($this->blockStorage->loadByProperties(['theme' => $active_theme->getName()]) as $block_id => $block) { /** @var \Drupal\block\BlockInterface $block */ $access = $block->access('view', NULL, TRUE); $region = $block->getRegion(); diff --git a/core/modules/block/src/BlockViewBuilder.php b/core/modules/block/src/BlockViewBuilder.php index d3f501bd7a..3b20d7b25c 100644 --- a/core/modules/block/src/BlockViewBuilder.php +++ b/core/modules/block/src/BlockViewBuilder.php @@ -68,16 +68,16 @@ public function buildComponents(array &$build, array $entities, array $displays, * {@inheritdoc} */ public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) { - $build = $this->viewMultiple(array($entity), $view_mode, $langcode); + $build = $this->viewMultiple([$entity], $view_mode, $langcode); return reset($build); } /** * {@inheritdoc} */ - public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL) { + public function viewMultiple(array $entities = [], $view_mode = 'full', $langcode = NULL) { /** @var \Drupal\block\BlockInterface[] $entities */ - $build = array(); + $build = []; foreach ($entities as $entity) { $entity_id = $entity->id(); $plugin = $entity->getPlugin(); @@ -87,7 +87,7 @@ public function viewMultiple(array $entities = array(), $view_mode = 'full', $la // Create the render array for the block as a whole. // @see template_preprocess_block(). - $build[$entity_id] = array( + $build[$entity_id] = [ '#cache' => [ 'keys' => ['entity_view', 'block', $entity->id()], 'contexts' => Cache::mergeContexts( @@ -98,7 +98,7 @@ public function viewMultiple(array $entities = array(), $view_mode = 'full', $la 'max-age' => $plugin->getCacheMaxAge(), ], '#weight' => $entity->getWeight(), - ); + ]; // Allow altering of cacheability metadata or setting #create_placeholder. $this->moduleHandler->alter(['block_build', "block_build_" . $plugin->getBaseId()], $build[$entity_id], $plugin); @@ -216,7 +216,7 @@ public static function preRender($build) { // #contextual_links is information about the *entire* block. Therefore, // we must move these properties from $content and merge them into the // top-level element. - foreach (array('#attributes', '#contextual_links') as $property) { + foreach (['#attributes', '#contextual_links'] as $property) { if (isset($content[$property])) { $build[$property] += $content[$property]; unset($content[$property]); @@ -231,10 +231,10 @@ public static function preRender($build) { // render cached, so we can avoid the work of having to repeatedly // determine whether the block is empty. For instance, modifying or adding // entities could cause the block to no longer be empty. - $build = array( + $build = [ '#markup' => '', '#cache' => $build['#cache'], - ); + ]; // If $content is not empty, then it contains cacheability metadata, and // we must merge it with the existing cacheability metadata. This allows // blocks to be empty, yet still bubble cacheability metadata, to indicate diff --git a/core/modules/block/src/Controller/BlockAddController.php b/core/modules/block/src/Controller/BlockAddController.php index f983763fcc..973a85995e 100644 --- a/core/modules/block/src/Controller/BlockAddController.php +++ b/core/modules/block/src/Controller/BlockAddController.php @@ -22,7 +22,7 @@ class BlockAddController extends ControllerBase { */ public function blockAddConfigureForm($plugin_id, $theme) { // Create a block entity. - $entity = $this->entityManager()->getStorage('block')->create(array('plugin' => $plugin_id, 'theme' => $theme)); + $entity = $this->entityManager()->getStorage('block')->create(['plugin' => $plugin_id, 'theme' => $theme]); return $this->entityFormBuilder()->getForm($entity); } diff --git a/core/modules/block/src/Controller/BlockController.php b/core/modules/block/src/Controller/BlockController.php index 58417d515f..7398ff98e1 100644 --- a/core/modules/block/src/Controller/BlockController.php +++ b/core/modules/block/src/Controller/BlockController.php @@ -74,7 +74,7 @@ public function demo($theme) { $page = [ '#title' => Html::escape($this->themeHandler->getName($theme)), '#type' => 'page', - '#attached' => array( + '#attached' => [ 'drupalSettings' => [ // The block demonstration page is not marked as an administrative // page by \Drupal::service('router.admin_context')->isAdminRoute() @@ -83,20 +83,20 @@ public function demo($theme) { // is an actual administrative page. 'path' => ['currentPathIsAdmin' => TRUE], ], - 'library' => array( + 'library' => [ 'block/drupal.block.admin', - ), - ), + ], + ], ]; // Show descriptions in each visible page region, nothing else. $visible_regions = $this->getVisibleRegionNames($theme); foreach (array_keys($visible_regions) as $region) { - $page[$region]['block_description'] = array( + $page[$region]['block_description'] = [ '#type' => 'inline_template', '#template' => '
        {{ region_name }}
        ', - '#context' => array('region_name' => $visible_regions[$region]), - ); + '#context' => ['region_name' => $visible_regions[$region]], + ]; } return $page; diff --git a/core/modules/block/src/Controller/CategoryAutocompleteController.php b/core/modules/block/src/Controller/CategoryAutocompleteController.php index a856670f6c..c95fd477e8 100644 --- a/core/modules/block/src/Controller/CategoryAutocompleteController.php +++ b/core/modules/block/src/Controller/CategoryAutocompleteController.php @@ -51,10 +51,10 @@ public static function create(ContainerInterface $container) { */ public function autocomplete(Request $request) { $typed_category = $request->query->get('q'); - $matches = array(); + $matches = []; foreach ($this->blockManager->getCategories() as $category) { if (stripos($category, $typed_category) === 0) { - $matches[] = array('value' => $category, 'label' => Html::escape($category)); + $matches[] = ['value' => $category, 'label' => Html::escape($category)]; } } return new JsonResponse($matches); diff --git a/core/modules/block/src/Entity/Block.php b/core/modules/block/src/Entity/Block.php index 63b5205433..a0bbd25c88 100644 --- a/core/modules/block/src/Entity/Block.php +++ b/core/modules/block/src/Entity/Block.php @@ -66,7 +66,7 @@ class Block extends ConfigEntityBase implements BlockInterface, EntityWithPlugin * * @var array */ - protected $settings = array(); + protected $settings = []; /** * The region this block is placed in. diff --git a/core/modules/block/src/EventSubscriber/BlockPageDisplayVariantSubscriber.php b/core/modules/block/src/EventSubscriber/BlockPageDisplayVariantSubscriber.php index 2c85587d27..5faf8b870a 100644 --- a/core/modules/block/src/EventSubscriber/BlockPageDisplayVariantSubscriber.php +++ b/core/modules/block/src/EventSubscriber/BlockPageDisplayVariantSubscriber.php @@ -27,7 +27,7 @@ public function onSelectPageDisplayVariant(PageDisplayVariantSelectionEvent $eve * {@inheritdoc} */ static function getSubscribedEvents() { - $events[RenderEvents::SELECT_PAGE_DISPLAY_VARIANT][] = array('onSelectPageDisplayVariant'); + $events[RenderEvents::SELECT_PAGE_DISPLAY_VARIANT][] = ['onSelectPageDisplayVariant']; return $events; } diff --git a/core/modules/block/src/Form/BlockDeleteForm.php b/core/modules/block/src/Form/BlockDeleteForm.php index 63cdb92258..5209b329bf 100644 --- a/core/modules/block/src/Form/BlockDeleteForm.php +++ b/core/modules/block/src/Form/BlockDeleteForm.php @@ -28,10 +28,10 @@ public function getConfirmText() { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to remove the @entity-type %label?', array( + return $this->t('Are you sure you want to remove the @entity-type %label?', [ '@entity-type' => $this->getEntity()->getEntityType()->getLowercaseLabel(), '%label' => $this->getEntity()->label(), - )); + ]); } /** @@ -39,10 +39,10 @@ public function getQuestion() { */ protected function getDeletionMessage() { $entity = $this->getEntity(); - return $this->t('The @entity-type %label has been removed.', array( + return $this->t('The @entity-type %label has been removed.', [ '@entity-type' => $entity->getEntityType()->getLowercaseLabel(), '%label' => $entity->label(), - )); + ]); } } diff --git a/core/modules/block/src/Plugin/Derivative/ThemeLocalTask.php b/core/modules/block/src/Plugin/Derivative/ThemeLocalTask.php index 74da932003..927cb6133f 100644 --- a/core/modules/block/src/Plugin/Derivative/ThemeLocalTask.php +++ b/core/modules/block/src/Plugin/Derivative/ThemeLocalTask.php @@ -48,7 +48,7 @@ public function getDerivativeDefinitions($base_plugin_definition) { if ($this->themeHandler->hasUi($theme_name)) { $this->derivatives[$theme_name] = $base_plugin_definition; $this->derivatives[$theme_name]['title'] = $theme->info['name']; - $this->derivatives[$theme_name]['route_parameters'] = array('theme' => $theme_name); + $this->derivatives[$theme_name]['route_parameters'] = ['theme' => $theme_name]; } // Default task! if ($default_theme == $theme_name) { diff --git a/core/modules/block/src/Plugin/migrate/destination/EntityBlock.php b/core/modules/block/src/Plugin/migrate/destination/EntityBlock.php index c904a377af..537b16073e 100644 --- a/core/modules/block/src/Plugin/migrate/destination/EntityBlock.php +++ b/core/modules/block/src/Plugin/migrate/destination/EntityBlock.php @@ -17,10 +17,10 @@ class EntityBlock extends EntityConfigBase { */ protected function getEntityId(Row $row) { // Try to find the block by its plugin ID and theme. - $properties = array( + $properties = [ 'plugin' => $row->getDestinationProperty('plugin'), 'theme' => $row->getDestinationProperty('theme'), - ); + ]; $blocks = array_keys($this->storage->loadByProperties($properties)); return reset($blocks); } diff --git a/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php b/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php index cd4bce57e3..08525674e3 100644 --- a/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php +++ b/core/modules/block/src/Plugin/migrate/process/BlockPluginId.php @@ -47,12 +47,12 @@ public function __construct(array $configuration, $plugin_id, array $plugin_defi */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) { $entity_manager = $container->get('entity.manager'); - $migration_configuration = array( - 'migration' => array( + $migration_configuration = [ + 'migration' => [ 'd6_custom_block', 'd7_custom_block', - ), - ); + ], + ]; return new static( $configuration, $plugin_id, diff --git a/core/modules/block/src/Plugin/migrate/process/BlockRegion.php b/core/modules/block/src/Plugin/migrate/process/BlockRegion.php index 8aba3ee84c..0eb984fd20 100644 --- a/core/modules/block/src/Plugin/migrate/process/BlockRegion.php +++ b/core/modules/block/src/Plugin/migrate/process/BlockRegion.php @@ -43,7 +43,7 @@ public function __construct(array $configuration, $plugin_id, $plugin_definition * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { - $regions = array(); + $regions = []; foreach ($container->get('theme_handler')->listInfo() as $key => $theme) { $regions[$key] = $theme->info['regions']; } diff --git a/core/modules/block/src/Plugin/migrate/process/BlockSettings.php b/core/modules/block/src/Plugin/migrate/process/BlockSettings.php index 9f11be852b..68e8f186ba 100644 --- a/core/modules/block/src/Plugin/migrate/process/BlockSettings.php +++ b/core/modules/block/src/Plugin/migrate/process/BlockSettings.php @@ -21,7 +21,7 @@ class BlockSettings extends ProcessPluginBase { */ public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { list($plugin, $delta, $old_settings, $title) = $value; - $settings = array(); + $settings = []; $settings['label'] = $title; if ($title) { $settings['label_display'] = BlockPluginInterface::BLOCK_LABEL_VISIBLE; diff --git a/core/modules/block/src/Plugin/migrate/process/BlockVisibility.php b/core/modules/block/src/Plugin/migrate/process/BlockVisibility.php index e38d60be99..8860791254 100644 --- a/core/modules/block/src/Plugin/migrate/process/BlockVisibility.php +++ b/core/modules/block/src/Plugin/migrate/process/BlockVisibility.php @@ -59,12 +59,12 @@ public function __construct(array $configuration, $plugin_id, $plugin_definition * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) { - $migration_configuration = array( - 'migration' => array( + $migration_configuration = [ + 'migration' => [ 'd6_user_role', 'd7_user_role', - ), - ); + ], + ]; return new static( $configuration, $plugin_id, @@ -80,18 +80,18 @@ public static function create(ContainerInterface $container, array $configuratio public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { list($old_visibility, $pages, $roles) = $value; - $visibility = array(); + $visibility = []; // If the block is assigned to specific roles, add the user_role condition. if ($roles) { - $visibility['user_role'] = array( + $visibility['user_role'] = [ 'id' => 'user_role', - 'roles' => array(), - 'context_mapping' => array( + 'roles' => [], + 'context_mapping' => [ 'user' => '@user.current_user_context:current_user', - ), + ], 'negate' => FALSE, - ); + ]; foreach ($roles as $key => $role_id) { $roles[$key] = $this->migrationPlugin->transform($role_id, $migrate_executable, $row, $destination_property); @@ -104,12 +104,12 @@ public function transform($value, MigrateExecutableInterface $migrate_executable if ($old_visibility == 2) { // If the PHP module is present, migrate the visibility code unaltered. if ($this->moduleHandler->moduleExists('php')) { - $visibility['php'] = array( + $visibility['php'] = [ 'id' => 'php', // PHP code visibility could not be negated in Drupal 6 or 7. 'negate' => FALSE, 'php' => $pages, - ); + ]; } // Skip the row if we're configured to. If not, we don't need to do // anything else -- the block will simply have no PHP or request_path @@ -123,11 +123,11 @@ public function transform($value, MigrateExecutableInterface $migrate_executable foreach ($paths as $key => $path) { $paths[$key] = $path === '' ? $path : '/' . ltrim($path, '/'); } - $visibility['request_path'] = array( + $visibility['request_path'] = [ 'id' => 'request_path', 'negate' => !$old_visibility, 'pages' => implode("\n", $paths), - ); + ]; } } diff --git a/core/modules/block/src/Plugin/migrate/source/Block.php b/core/modules/block/src/Plugin/migrate/source/Block.php index b69128369a..df4c0e9e19 100644 --- a/core/modules/block/src/Plugin/migrate/source/Block.php +++ b/core/modules/block/src/Plugin/migrate/source/Block.php @@ -81,7 +81,7 @@ protected function initializeIterator() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'bid' => $this->t('The block numeric identifier.'), 'module' => $this->t('The module providing the block.'), 'delta' => $this->t('The block\'s delta.'), @@ -93,7 +93,7 @@ public function fields() { 'pages' => $this->t('Pages list.'), 'title' => $this->t('Block title.'), 'cache' => $this->t('Cache rule.'), - ); + ]; } /** @@ -117,7 +117,7 @@ public function prepareRow(Row $row) { $delta = $row->getSourceProperty('delta'); $query = $this->select($this->blockRoleTable, 'br') - ->fields('br', array('rid')) + ->fields('br', ['rid']) ->condition('module', $module) ->condition('delta', $delta); $query->join($this->userRoleTable, 'ur', 'br.rid = ur.rid'); @@ -125,7 +125,7 @@ public function prepareRow(Row $row) { ->fetchCol(); $row->setSourceProperty('roles', $roles); - $settings = array(); + $settings = []; switch ($module) { case 'aggregator': list($type, $id) = explode('-', $delta); @@ -152,7 +152,7 @@ public function prepareRow(Row $row) { $settings['forum']['block_num'] = $this->variableGet('forum_block_num_' . $delta, 5); break; case 'statistics': - foreach (array('statistics_block_top_day_num', 'statistics_block_top_all_num', 'statistics_block_top_last_num') as $name) { + foreach (['statistics_block_top_day_num', 'statistics_block_top_all_num', 'statistics_block_top_last_num'] as $name) { $settings['statistics'][$name] = $this->variableGet($name, 0); } break; diff --git a/core/modules/block/src/Tests/BlockAdminThemeTest.php b/core/modules/block/src/Tests/BlockAdminThemeTest.php index ab444d5e34..7736e05362 100644 --- a/core/modules/block/src/Tests/BlockAdminThemeTest.php +++ b/core/modules/block/src/Tests/BlockAdminThemeTest.php @@ -16,14 +16,14 @@ class BlockAdminThemeTest extends WebTestBase { * * @var array */ - public static $modules = array('block', 'contextual'); + public static $modules = ['block', 'contextual']; /** * Check for the accessibility of the admin theme on the block admin page. */ function testAdminTheme() { // Create administrative user. - $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes')); + $admin_user = $this->drupalCreateUser(['administer blocks', 'administer themes']); $this->drupalLogin($admin_user); // Ensure that access to block admin page is denied when theme is not @@ -32,7 +32,7 @@ function testAdminTheme() { $this->assertResponse(403); // Install admin theme and confirm that tab is accessible. - \Drupal::service('theme_handler')->install(array('bartik')); + \Drupal::service('theme_handler')->install(['bartik']); $edit['admin_theme'] = 'bartik'; $this->drupalPostForm('admin/appearance', $edit, t('Save configuration')); $this->drupalGet('admin/structure/block/list/bartik'); diff --git a/core/modules/block/src/Tests/BlockLanguageCacheTest.php b/core/modules/block/src/Tests/BlockLanguageCacheTest.php index fd5871e3a1..269536d9ce 100644 --- a/core/modules/block/src/Tests/BlockLanguageCacheTest.php +++ b/core/modules/block/src/Tests/BlockLanguageCacheTest.php @@ -18,25 +18,25 @@ class BlockLanguageCacheTest extends WebTestBase { * * @var array */ - public static $modules = array('block', 'language', 'menu_ui'); + public static $modules = ['block', 'language', 'menu_ui']; /** * List of langcodes. * * @var array */ - protected $langcodes = array(); + protected $langcodes = []; protected function setUp() { parent::setUp(); // Create test languages. - $this->langcodes = array(ConfigurableLanguage::load('en')); + $this->langcodes = [ConfigurableLanguage::load('en')]; for ($i = 1; $i < 3; ++$i) { - $language = ConfigurableLanguage::create(array( + $language = ConfigurableLanguage::create([ 'id' => 'l' . $i, 'label' => $this->randomString(), - )); + ]); $language->save(); $this->langcodes[$i] = $language; } @@ -47,16 +47,16 @@ protected function setUp() { */ public function testBlockLinks() { // Create admin user to be able to access block admin. - $admin_user = $this->drupalCreateUser(array( + $admin_user = $this->drupalCreateUser([ 'administer blocks', 'access administration pages', 'administer menu', - )); + ]); $this->drupalLogin($admin_user); // Create the block cache for all languages. foreach ($this->langcodes as $langcode) { - $this->drupalGet('admin/structure/block', array('language' => $langcode)); + $this->drupalGet('admin/structure/block', ['language' => $langcode]); $this->clickLinkPartialName('Place block'); } @@ -64,11 +64,11 @@ public function testBlockLinks() { $edit['label'] = $this->randomMachineName(); $edit['id'] = Unicode::strtolower($edit['label']); $this->drupalPostForm('admin/structure/menu/add', $edit, t('Save')); - $this->assertText(t('Menu @label has been added.', array('@label' => $edit['label']))); + $this->assertText(t('Menu @label has been added.', ['@label' => $edit['label']])); // Check that the block is listed for all languages. foreach ($this->langcodes as $langcode) { - $this->drupalGet('admin/structure/block', array('language' => $langcode)); + $this->drupalGet('admin/structure/block', ['language' => $langcode]); $this->clickLinkPartialName('Place block'); $this->assertText($edit['label']); } diff --git a/core/modules/block/src/Tests/BlockRenderOrderTest.php b/core/modules/block/src/Tests/BlockRenderOrderTest.php index faf667ed80..d74a90afc4 100644 --- a/core/modules/block/src/Tests/BlockRenderOrderTest.php +++ b/core/modules/block/src/Tests/BlockRenderOrderTest.php @@ -17,14 +17,14 @@ class BlockRenderOrderTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'block'); + public static $modules = ['node', 'block']; protected function setUp() { parent::setUp(); // Create a test user. - $end_user = $this->drupalCreateUser(array( + $end_user = $this->drupalCreateUser([ 'access content', - )); + ]); $this->drupalLogin($end_user); } @@ -34,32 +34,32 @@ protected function setUp() { function testBlockRenderOrder() { // Enable test blocks and place them in the same region. $region = 'header'; - $test_blocks = array( - 'stark_powered' => array( + $test_blocks = [ + 'stark_powered' => [ 'weight' => '-3', 'id' => 'stark_powered', 'label' => 'Test block A', - ), - 'stark_by' => array( + ], + 'stark_by' => [ 'weight' => '3', 'id' => 'stark_by', 'label' => 'Test block C', - ), - 'stark_drupal' => array( + ], + 'stark_drupal' => [ 'weight' => '3', 'id' => 'stark_drupal', 'label' => 'Test block B', - ), - ); + ], + ]; // Place the test blocks. foreach ($test_blocks as $test_block) { - $this->drupalPlaceBlock('system_powered_by_block', array( + $this->drupalPlaceBlock('system_powered_by_block', [ 'label' => $test_block['label'], 'region' => $region, 'weight' => $test_block['weight'], 'id' => $test_block['id'], - )); + ]); } $this->drupalGet(''); diff --git a/core/modules/block/src/Tests/BlockSystemBrandingTest.php b/core/modules/block/src/Tests/BlockSystemBrandingTest.php index f3dfa3cdb4..b5025e8017 100644 --- a/core/modules/block/src/Tests/BlockSystemBrandingTest.php +++ b/core/modules/block/src/Tests/BlockSystemBrandingTest.php @@ -14,7 +14,7 @@ class BlockSystemBrandingTest extends BlockTestBase { * * @var array */ - public static $modules = array('block', 'system'); + public static $modules = ['block', 'system']; /** * {@inheritdoc} @@ -26,7 +26,7 @@ protected function setUp() { ->set('slogan', 'Community plumbing') ->save(); // Add the system branding block to the page. - $this->drupalPlaceBlock('system_branding_block', array('region' => 'header', 'id' => 'site-branding')); + $this->drupalPlaceBlock('system_branding_block', ['region' => 'header', 'id' => 'site-branding']); } /** diff --git a/core/modules/block/src/Tests/BlockTest.php b/core/modules/block/src/Tests/BlockTest.php index 57f4647644..e6066c4fd2 100644 --- a/core/modules/block/src/Tests/BlockTest.php +++ b/core/modules/block/src/Tests/BlockTest.php @@ -24,12 +24,12 @@ function testBlockVisibility() { $title = $this->randomMachineName(8); // Enable a standard block. $default_theme = $this->config('system.theme')->get('default'); - $edit = array( + $edit = [ 'id' => strtolower($this->randomMachineName(8)), 'region' => 'sidebar_first', 'settings[label]' => $title, 'settings[label_display]' => TRUE, - ); + ]; // Set the block to be hidden on any user path, and to be shown only to // authenticated users. $edit['visibility[request_path][pages]'] = '/user*'; @@ -69,11 +69,11 @@ public function testBlockToggleVisibility() { $title = $this->randomMachineName(8); // Enable a standard block. $default_theme = $this->config('system.theme')->get('default'); - $edit = array( + $edit = [ 'id' => strtolower($this->randomMachineName(8)), 'region' => 'sidebar_first', 'settings[label]' => $title, - ); + ]; $block_id = $edit['id']; // Set the block to be shown only to authenticated users. $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE; @@ -105,12 +105,12 @@ function testBlockVisibilityListedEmpty() { $title = $this->randomMachineName(8); // Enable a standard block. $default_theme = $this->config('system.theme')->get('default'); - $edit = array( + $edit = [ 'id' => strtolower($this->randomMachineName(8)), 'region' => 'sidebar_first', 'settings[label]' => $title, 'visibility[request_path][negate]' => TRUE, - ); + ]; // Set the block to be hidden on any user path, and to be shown only to // authenticated users. $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block')); @@ -185,7 +185,7 @@ function testBlock() { $this->clickLink('Disable'); // Select the 'Powered by Drupal' block to be configured and moved. - $block = array(); + $block = []; $block['id'] = 'system_powered_by_block'; $block['settings[label]'] = $this->randomMachineName(8); $block['settings[label_display]'] = TRUE; @@ -193,7 +193,7 @@ function testBlock() { $block['region'] = 'header'; // Set block title to confirm that interface works and override any custom titles. - $this->drupalPostForm('admin/structure/block/add/' . $block['id'] . '/' . $block['theme'], array('settings[label]' => $block['settings[label]'], 'settings[label_display]' => $block['settings[label_display]'], 'id' => $block['id'], 'region' => $block['region']), t('Save block')); + $this->drupalPostForm('admin/structure/block/add/' . $block['id'] . '/' . $block['theme'], ['settings[label]' => $block['settings[label]'], 'settings[label_display]' => $block['settings[label_display]'], 'id' => $block['id'], 'region' => $block['region']], t('Save block')); $this->assertText(t('The block configuration has been saved.'), 'Block title set.'); // Check to see if the block was created by checking its configuration. $instance = Block::load($block['id']); @@ -217,23 +217,23 @@ function testBlock() { $this->assertNoText(t($block['settings[label]'])); // Check for
        if the machine name // is my_block_instance_name. - $xpath = $this->buildXPathQuery('//div[@id=:id]/*', array(':id' => 'block-' . str_replace('_', '-', strtolower($block['id'])))); + $xpath = $this->buildXPathQuery('//div[@id=:id]/*', [':id' => 'block-' . str_replace('_', '-', strtolower($block['id']))]); $this->assertNoFieldByXPath($xpath, FALSE, 'Block found in no regions.'); // Test deleting the block from the edit form. $this->drupalGet('admin/structure/block/manage/' . $block['id']); $this->clickLink(t('Remove block')); - $this->assertRaw(t('Are you sure you want to remove the block @name?', array('@name' => $block['settings[label]']))); - $this->drupalPostForm(NULL, array(), t('Remove')); - $this->assertRaw(t('The block %name has been removed.', array('%name' => $block['settings[label]']))); + $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block['settings[label]']])); + $this->drupalPostForm(NULL, [], t('Remove')); + $this->assertRaw(t('The block %name has been removed.', ['%name' => $block['settings[label]']])); // Test deleting a block via "Configure block" link. $block = $this->drupalPlaceBlock('system_powered_by_block'); - $this->drupalGet('admin/structure/block/manage/' . $block->id(), array('query' => array('destination' => 'admin'))); + $this->drupalGet('admin/structure/block/manage/' . $block->id(), ['query' => ['destination' => 'admin']]); $this->clickLink(t('Remove block')); - $this->assertRaw(t('Are you sure you want to remove the block @name?', array('@name' => $block->label()))); - $this->drupalPostForm(NULL, array(), t('Remove')); - $this->assertRaw(t('The block %name has been removed.', array('%name' => $block->label()))); + $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block->label()])); + $this->drupalPostForm(NULL, [], t('Remove')); + $this->assertRaw(t('The block %name has been removed.', ['%name' => $block->label()])); $this->assertUrl('admin'); $this->assertNoRaw($block->id()); } @@ -249,7 +249,7 @@ public function testBlockThemeSelector() { $this->drupalGet('admin/structure/block/list/' . $theme); $this->assertTitle(t('Block layout') . ' | Drupal'); // Select the 'Powered by Drupal' block to be placed. - $block = array(); + $block = []; $block['id'] = strtolower($this->randomMachineName()); $block['theme'] = $theme; $block['region'] = 'content'; @@ -260,7 +260,7 @@ public function testBlockThemeSelector() { // Set the default theme and ensure the block is placed. $theme_settings->set('default', $theme)->save(); $this->drupalGet(''); - $elements = $this->xpath('//div[@id = :id]', array(':id' => Html::getUniqueId('block-' . $block['id']))); + $elements = $this->xpath('//div[@id = :id]', [':id' => Html::getUniqueId('block-' . $block['id'])]); $this->assertTrue(!empty($elements), 'The block was found.'); } } @@ -270,11 +270,11 @@ public function testBlockThemeSelector() { */ function testThemeName() { // Enable the help block. - $this->drupalPlaceBlock('help_block', array('region' => 'help')); + $this->drupalPlaceBlock('help_block', ['region' => 'help']); $this->drupalPlaceBlock('local_tasks_block'); // Explicitly set the default and admin themes. $theme = 'block_test_specialchars_theme'; - \Drupal::service('theme_handler')->install(array($theme)); + \Drupal::service('theme_handler')->install([$theme]); \Drupal::service('router.builder')->rebuild(); $this->drupalGet('admin/structure/block'); $this->assertEscaped('<"Cat" & \'Mouse\'>'); @@ -292,20 +292,20 @@ function testHideBlockTitle() { $id = strtolower($this->randomMachineName(8)); // Enable a standard block. $default_theme = $this->config('system.theme')->get('default'); - $edit = array( + $edit = [ 'id' => $id, 'region' => 'sidebar_first', 'settings[label]' => $title, - ); + ]; $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block')); $this->assertText('The block configuration has been saved.', 'Block was saved'); $this->drupalGet('user'); $this->assertNoText($title, 'Block title was not displayed by default.'); - $edit = array( + $edit = [ 'settings[label_display]' => TRUE, - ); + ]; $this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block')); $this->assertText('The block configuration has been saved.', 'Block was saved'); @@ -330,24 +330,24 @@ function testHideBlockTitle() { */ function moveBlockToRegion(array $block, $region) { // Set the created block to a specific region. - $block += array('theme' => $this->config('system.theme')->get('default')); - $edit = array(); + $block += ['theme' => $this->config('system.theme')->get('default')]; + $edit = []; $edit['blocks[' . $block['id'] . '][region]'] = $region; $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks')); // Confirm that the block was moved to the proper region. - $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', array( '%region_name' => $region))); + $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', [ '%region_name' => $region])); // Confirm that the block is being displayed. $this->drupalGet(''); $this->assertText(t($block['settings[label]']), 'Block successfully being displayed on the page.'); // Confirm that the custom block was found at the proper region. - $xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', array( + $xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', [ ':region-class' => 'region region-' . Html::getClass($region), ':block-id' => 'block-' . str_replace('_', '-', strtolower($block['id'])), - )); - $this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', array('%region_name' => Html::getClass($region)))); + ]); + $this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', ['%region_name' => Html::getClass($region)])); } /** @@ -367,7 +367,7 @@ public function testBlockCacheTags() { $config->save(); // Place the "Powered by Drupal" block. - $block = $this->drupalPlaceBlock('system_powered_by_block', array('id' => 'powered')); + $block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']); // Prime the page cache. $this->drupalGet(''); @@ -377,26 +377,26 @@ public function testBlockCacheTags() { // both the page and block caches. $this->drupalGet(''); $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT'); - $cid_parts = array(\Drupal::url('', array(), array('absolute' => TRUE)), 'html'); + $cid_parts = [\Drupal::url('', [], ['absolute' => TRUE]), 'html']; $cid = implode(':', $cid_parts); $cache_entry = \Drupal::cache('render')->get($cid); - $expected_cache_tags = array( + $expected_cache_tags = [ 'config:block_list', 'block_view', 'config:block.block.powered', 'config:user.role.anonymous', 'http_response', 'rendered', - ); + ]; sort($expected_cache_tags); $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys(); $this->assertIdentical($cache_entry->tags, $expected_cache_tags); $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys)); - $expected_cache_tags = array( + $expected_cache_tags = [ 'block_view', 'config:block.block.powered', 'rendered', - ); + ]; sort($expected_cache_tags); $this->assertIdentical($cache_entry->tags, $expected_cache_tags); @@ -411,17 +411,17 @@ public function testBlockCacheTags() { $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT'); // Place the "Powered by Drupal" block another time; verify a cache miss. - $block_2 = $this->drupalPlaceBlock('system_powered_by_block', array('id' => 'powered-2')); + $block_2 = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered-2']); $this->drupalGet(''); $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS'); // Verify a cache hit, but also the presence of the correct cache tags. $this->drupalGet(''); $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT'); - $cid_parts = array(\Drupal::url('', array(), array('absolute' => TRUE)), 'html'); + $cid_parts = [\Drupal::url('', [], ['absolute' => TRUE]), 'html']; $cid = implode(':', $cid_parts); $cache_entry = \Drupal::cache('render')->get($cid); - $expected_cache_tags = array( + $expected_cache_tags = [ 'config:block_list', 'block_view', 'config:block.block.powered', @@ -429,23 +429,23 @@ public function testBlockCacheTags() { 'config:user.role.anonymous', 'http_response', 'rendered', - ); + ]; sort($expected_cache_tags); $this->assertEqual($cache_entry->tags, $expected_cache_tags); - $expected_cache_tags = array( + $expected_cache_tags = [ 'block_view', 'config:block.block.powered', 'rendered', - ); + ]; sort($expected_cache_tags); $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys(); $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys)); $this->assertIdentical($cache_entry->tags, $expected_cache_tags); - $expected_cache_tags = array( + $expected_cache_tags = [ 'block_view', 'config:block.block.powered-2', 'rendered', - ); + ]; sort($expected_cache_tags); $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys(); $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys)); @@ -456,7 +456,7 @@ public function testBlockCacheTags() { $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT'); // Delete the "Powered by Drupal" blocks; verify a cache miss. - entity_delete_multiple('block', array('powered', 'powered-2')); + entity_delete_multiple('block', ['powered', 'powered-2']); $this->drupalGet(''); $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS'); } diff --git a/core/modules/block/src/Tests/BlockTestBase.php b/core/modules/block/src/Tests/BlockTestBase.php index 970de5266e..71f0ae6cff 100644 --- a/core/modules/block/src/Tests/BlockTestBase.php +++ b/core/modules/block/src/Tests/BlockTestBase.php @@ -15,7 +15,7 @@ * * @var array */ - public static $modules = array('block', 'filter', 'test_page_test', 'help', 'block_test'); + public static $modules = ['block', 'filter', 'test_page_test', 'help', 'block_test']; /** * A list of theme regions to test. @@ -38,31 +38,31 @@ protected function setUp() { $this->config('system.site')->set('page.front', '/test-page')->save(); // Create Full HTML text format. - $full_html_format = FilterFormat::create(array( + $full_html_format = FilterFormat::create([ 'format' => 'full_html', 'name' => 'Full HTML', - )); + ]); $full_html_format->save(); // Create and log in an administrative user having access to the Full HTML // text format. - $this->adminUser = $this->drupalCreateUser(array( + $this->adminUser = $this->drupalCreateUser([ 'administer blocks', $full_html_format->getPermissionName(), 'access administration pages', - )); + ]); $this->drupalLogin($this->adminUser); // Define the existing regions. - $this->regions = array( + $this->regions = [ 'header', 'sidebar_first', 'content', 'sidebar_second', 'footer', - ); + ]; $block_storage = $this->container->get('entity_type.manager')->getStorage('block'); - $blocks = $block_storage->loadByProperties(array('theme' => $this->config('system.theme')->get('default'))); + $blocks = $block_storage->loadByProperties(['theme' => $this->config('system.theme')->get('default')]); foreach ($blocks as $block) { $block->delete(); } diff --git a/core/modules/block/src/Tests/BlockUiTest.php b/core/modules/block/src/Tests/BlockUiTest.php index 65183cdce6..5f18ae162b 100644 --- a/core/modules/block/src/Tests/BlockUiTest.php +++ b/core/modules/block/src/Tests/BlockUiTest.php @@ -17,7 +17,7 @@ class BlockUiTest extends WebTestBase { * * @var array */ - public static $modules = array('block', 'block_test', 'help', 'condition_test'); + public static $modules = ['block', 'block_test', 'help', 'condition_test']; protected $regions; @@ -43,30 +43,30 @@ class BlockUiTest extends WebTestBase { protected function setUp() { parent::setUp(); // Create and log in an administrative user. - $this->adminUser = $this->drupalCreateUser(array( + $this->adminUser = $this->drupalCreateUser([ 'administer blocks', 'access administration pages', - )); + ]); $this->drupalLogin($this->adminUser); // Enable some test blocks. - $this->blockValues = array( - array( + $this->blockValues = [ + [ 'label' => 'Tools', 'tr' => '5', 'plugin_id' => 'system_menu_block:tools', - 'settings' => array('region' => 'sidebar_second', 'id' => 'tools'), + 'settings' => ['region' => 'sidebar_second', 'id' => 'tools'], 'test_weight' => '-1', - ), - array( + ], + [ 'label' => 'Powered by Drupal', 'tr' => '16', 'plugin_id' => 'system_powered_by_block', - 'settings' => array('region' => 'footer', 'id' => 'powered'), + 'settings' => ['region' => 'footer', 'id' => 'powered'], 'test_weight' => '0', - ), - ); - $this->blocks = array(); + ], + ]; + $this->blocks = []; foreach ($this->blockValues as $values) { $this->blocks[] = $this->drupalPlaceBlock($values['plugin_id'], $values['settings']); } @@ -76,13 +76,13 @@ protected function setUp() { * Test block demo page exists and functions correctly. */ public function testBlockDemoUiPage() { - $this->drupalPlaceBlock('help_block', array('region' => 'help')); + $this->drupalPlaceBlock('help_block', ['region' => 'help']); $this->drupalGet('admin/structure/block'); - $this->clickLink(t('Demonstrate block regions (@theme)', array('@theme' => 'Classy'))); - $elements = $this->xpath('//div[contains(@class, "region-highlighted")]/div[contains(@class, "block-region") and contains(text(), :title)]', array(':title' => 'Highlighted')); + $this->clickLink(t('Demonstrate block regions (@theme)', ['@theme' => 'Classy'])); + $elements = $this->xpath('//div[contains(@class, "region-highlighted")]/div[contains(@class, "block-region") and contains(text(), :title)]', [':title' => 'Highlighted']); $this->assertTrue(!empty($elements), 'Block demo regions are shown.'); - \Drupal::service('theme_handler')->install(array('test_theme')); + \Drupal::service('theme_handler')->install(['test_theme']); $this->drupalGet('admin/structure/block/demo/test_theme'); $this->assertEscaped('Test theme'); @@ -163,11 +163,11 @@ function testBlockAdminUiPage() { * Tests the block categories on the listing page. */ public function testCandidateBlockList() { - $arguments = array( + $arguments = [ ':title' => 'Display message', ':category' => 'Block test', ':href' => 'admin/structure/block/add/test_block_instantiation/classy', - ); + ]; $pattern = '//tr[.//td/div[text()=:title] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]'; $this->drupalGet('admin/structure/block'); @@ -190,11 +190,11 @@ public function testCandidateBlockList() { * Tests the behavior of unsatisfied context-aware blocks. */ public function testContextAwareUnsatisfiedBlocks() { - $arguments = array( + $arguments = [ ':category' => 'Block test', ':href' => 'admin/structure/block/add/test_context_aware_unsatisfied/classy', ':text' => 'Test context-aware unsatisfied block', - ); + ]; $this->drupalGet('admin/structure/block'); $this->clickLinkPartialName('Place block'); @@ -215,11 +215,11 @@ public function testContextAwareBlocks() { $this->assertNoRaw($expected_text); $block_url = 'admin/structure/block/add/test_context_aware/classy'; - $arguments = array( + $arguments = [ ':title' => 'Test context-aware block', ':category' => 'Block test', ':href' => $block_url, - ); + ]; $pattern = '//tr[.//td/div[text()=:title] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]'; $this->drupalGet('admin/structure/block'); @@ -282,7 +282,7 @@ public function testMachineNameSuggestion() { */ public function testBlockPlacementIndicator() { // Select the 'Powered by Drupal' block to be placed. - $block = array(); + $block = []; $block['id'] = strtolower($this->randomMachineName()); $block['theme'] = 'classy'; $block['region'] = 'content'; @@ -292,7 +292,7 @@ public function testBlockPlacementIndicator() { $this->assertUrl('admin/structure/block/list/classy?block-placement=' . Html::getClass($block['id'])); // Resaving the block page will remove the block indicator. - $this->drupalPostForm(NULL, array(), t('Save blocks')); + $this->drupalPostForm(NULL, [], t('Save blocks')); $this->assertUrl('admin/structure/block/list/classy'); } diff --git a/core/modules/block/src/Tests/NonDefaultBlockAdminTest.php b/core/modules/block/src/Tests/NonDefaultBlockAdminTest.php index 218832d6c8..9f3590c7fa 100644 --- a/core/modules/block/src/Tests/NonDefaultBlockAdminTest.php +++ b/core/modules/block/src/Tests/NonDefaultBlockAdminTest.php @@ -16,7 +16,7 @@ class NonDefaultBlockAdminTest extends WebTestBase { * * @var array */ - public static $modules = array('block'); + public static $modules = ['block']; /** * {@inheritdoc} @@ -31,10 +31,10 @@ protected function setUp() { * Test non-default theme admin. */ function testNonDefaultBlockAdmin() { - $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes')); + $admin_user = $this->drupalCreateUser(['administer blocks', 'administer themes']); $this->drupalLogin($admin_user); $new_theme = 'bartik'; - \Drupal::service('theme_handler')->install(array($new_theme)); + \Drupal::service('theme_handler')->install([$new_theme]); $this->drupalGet('admin/structure/block/list/' . $new_theme); $this->assertText('Bartik(' . t('active tab') . ')', 'Tab for non-default theme found.'); } diff --git a/core/modules/block/src/Tests/Views/DisplayBlockTest.php b/core/modules/block/src/Tests/Views/DisplayBlockTest.php index d87817526e..64f4851aa1 100644 --- a/core/modules/block/src/Tests/Views/DisplayBlockTest.php +++ b/core/modules/block/src/Tests/Views/DisplayBlockTest.php @@ -26,19 +26,19 @@ class DisplayBlockTest extends ViewTestBase { * * @var array */ - public static $modules = array('node', 'block_test_views', 'test_page_test', 'contextual', 'views_ui'); + public static $modules = ['node', 'block_test_views', 'test_page_test', 'contextual', 'views_ui']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_view_block', 'test_view_block2'); + public static $testViews = ['test_view_block', 'test_view_block2']; protected function setUp() { parent::setUp(); - ViewTestData::createTestViews(get_class($this), array('block_test_views')); + ViewTestData::createTestViews(get_class($this), ['block_test_views']); $this->enableViewsTestModule(); } @@ -46,10 +46,10 @@ protected function setUp() { * Tests default and custom block categories. */ public function testBlockCategory() { - $this->drupalLogin($this->drupalCreateUser(array('administer views', 'administer blocks'))); + $this->drupalLogin($this->drupalCreateUser(['administer views', 'administer blocks'])); // Create a new view in the UI. - $edit = array(); + $edit = []; $edit['label'] = $this->randomString(); $edit['id'] = strtolower($this->randomMachineName()); $edit['show[wizard_key]'] = 'standard:views_test_data'; @@ -62,20 +62,20 @@ public function testBlockCategory() { // Test that the block was given a default category corresponding to its // base table. - $arguments = array( - ':href' => \Drupal::Url('block.admin_add', array( + $arguments = [ + ':href' => \Drupal::Url('block.admin_add', [ 'plugin_id' => 'views_block:' . $edit['id'] . '-block_1', 'theme' => 'classy', - )), + ]), ':category' => t('Lists (Views)'), - ); + ]; $this->drupalGet('admin/structure/block'); $this->clickLinkPartialName('Place block'); $elements = $this->xpath($pattern, $arguments); $this->assertTrue(!empty($elements), 'The test block appears in the category for its base table.'); // Duplicate the block before changing the category. - $this->drupalPostForm('admin/structure/views/view/' . $edit['id'] . '/edit/block_1', array(), t('Duplicate @display_title', array('@display_title' => 'Block'))); + $this->drupalPostForm('admin/structure/views/view/' . $edit['id'] . '/edit/block_1', [], t('Duplicate @display_title', ['@display_title' => 'Block'])); $this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_2'); // Change the block category to a random string. @@ -84,13 +84,13 @@ public function testBlockCategory() { $this->assertTrue(!empty($link)); $this->clickLink(t('Lists (Views)')); $category = $this->randomString(); - $this->drupalPostForm(NULL, array('block_category' => $category), t('Apply')); + $this->drupalPostForm(NULL, ['block_category' => $category], t('Apply')); // Duplicate the block after changing the category. - $this->drupalPostForm(NULL, array(), t('Duplicate @display_title', array('@display_title' => 'Block'))); + $this->drupalPostForm(NULL, [], t('Duplicate @display_title', ['@display_title' => 'Block'])); $this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_3'); - $this->drupalPostForm(NULL, array(), t('Save')); + $this->drupalPostForm(NULL, [], t('Save')); // Test that the blocks are listed under the correct categories. $arguments[':category'] = $category; @@ -99,23 +99,23 @@ public function testBlockCategory() { $elements = $this->xpath($pattern, $arguments); $this->assertTrue(!empty($elements), 'The test block appears in the custom category.'); - $arguments = array( - ':href' => \Drupal::Url('block.admin_add', array( + $arguments = [ + ':href' => \Drupal::Url('block.admin_add', [ 'plugin_id' => 'views_block:' . $edit['id'] . '-block_2', 'theme' => 'classy', - )), + ]), ':category' => t('Lists (Views)'), - ); + ]; $elements = $this->xpath($pattern, $arguments); $this->assertTrue(!empty($elements), 'The first duplicated test block remains in the original category.'); - $arguments = array( - ':href' => \Drupal::Url('block.admin_add', array( + $arguments = [ + ':href' => \Drupal::Url('block.admin_add', [ 'plugin_id' => 'views_block:' . $edit['id'] . '-block_3', 'theme' => 'classy', - )), + ]), ':category' => $category, - ); + ]; $elements = $this->xpath($pattern, $arguments); $this->assertTrue(!empty($elements), 'The second duplicated test block appears in the custom category.'); } @@ -126,13 +126,13 @@ public function testBlockCategory() { public function testDeleteBlockDisplay() { // To test all combinations possible we first place create two instances // of the block display of the first view. - $block_1 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', array('label' => 'test_view_block-block_1:1')); - $block_2 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', array('label' => 'test_view_block-block_1:2')); + $block_1 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1']); + $block_2 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:2']); // Then we add one instance of blocks for each of the two displays of the // second view. - $block_3 = $this->drupalPlaceBlock('views_block:test_view_block2-block_1', array('label' => 'test_view_block2-block_1')); - $block_4 = $this->drupalPlaceBlock('views_block:test_view_block2-block_2', array('label' => 'test_view_block2-block_2')); + $block_3 = $this->drupalPlaceBlock('views_block:test_view_block2-block_1', ['label' => 'test_view_block2-block_1']); + $block_4 = $this->drupalPlaceBlock('views_block:test_view_block2-block_2', ['label' => 'test_view_block2-block_2']); $this->drupalGet('test-page'); $this->assertBlockAppears($block_1); @@ -177,7 +177,7 @@ public function testDeleteBlockDisplay() { * Test the block form for a Views block. */ public function testViewsBlockForm() { - $this->drupalLogin($this->drupalCreateUser(array('administer blocks'))); + $this->drupalLogin($this->drupalCreateUser(['administer blocks'])); $default_theme = $this->config('system.theme')->get('default'); $this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme); $elements = $this->xpath('//input[@name="label"]'); @@ -239,7 +239,7 @@ public function testViewsBlockForm() { */ public function testBlockRendering() { // Create a block and set a custom title. - $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', array('label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title')); + $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']); $this->drupalGet(''); $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2'); @@ -276,7 +276,7 @@ public function testBlockEmptyRendering() { $view = View::load('test_view_block'); $view->invalidateCaches(); - $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', array('label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title')); + $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']); $this->drupalGet(''); $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]'))); @@ -349,7 +349,7 @@ public function testBlockEmptyRendering() { * Tests the contextual links on a Views block. */ public function testBlockContextualLinks() { - $this->drupalLogin($this->drupalCreateUser(array('administer views', 'access contextual links', 'administer blocks'))); + $this->drupalLogin($this->drupalCreateUser(['administer views', 'access contextual links', 'administer blocks'])); $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1'); $cached_block = $this->drupalPlaceBlock('views_block:test_view_block-block_1'); $this->drupalGet('test-page'); @@ -357,13 +357,13 @@ public function testBlockContextualLinks() { $id = 'block:block=' . $block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en'; $cached_id = 'block:block=' . $cached_block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en'; // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder() - $this->assertRaw(' $id)) . '>
        ', format_string('Contextual link placeholder with id @id exists.', array('@id' => $id))); - $this->assertRaw(' $cached_id)) . '>', format_string('Contextual link placeholder with id @id exists.', array('@id' => $cached_id))); + $this->assertRaw(' $id]) . '>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $id])); + $this->assertRaw(' $cached_id]) . '>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $cached_id])); // Get server-rendered contextual links. // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks() - $post = array('ids[0]' => $id, 'ids[1]' => $cached_id); - $response = $this->drupalPostWithFormat('contextual/render', 'json', $post, array('query' => array('destination' => 'test-page'))); + $post = ['ids[0]' => $id, 'ids[1]' => $cached_id]; + $response = $this->drupalPostWithFormat('contextual/render', 'json', $post, ['query' => ['destination' => 'test-page']]); $this->assertResponse(200); $json = Json::decode($response); $this->assertIdentical($json[$id], ''); diff --git a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestBlockInstantiation.php b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestBlockInstantiation.php index e5ad8daecc..0d146390c5 100644 --- a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestBlockInstantiation.php +++ b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestBlockInstantiation.php @@ -21,9 +21,9 @@ class TestBlockInstantiation extends BlockBase { * {@inheritdoc} */ public function defaultConfiguration() { - return array( + return [ 'display_message' => 'no message set', - ); + ]; } /** @@ -37,11 +37,11 @@ protected function blockAccess(AccountInterface $account) { * {@inheritdoc} */ public function blockForm($form, FormStateInterface $form_state) { - $form['display_message'] = array( + $form['display_message'] = [ '#type' => 'textfield', '#title' => $this->t('Display message'), '#default_value' => $this->configuration['display_message'], - ); + ]; return $form; } @@ -56,9 +56,9 @@ public function blockSubmit($form, FormStateInterface $form_state) { * {@inheritdoc} */ public function build() { - return array( + return [ '#children' => $this->configuration['display_message'], - ); + ]; } } diff --git a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestCacheBlock.php b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestCacheBlock.php index b395b9266c..5fec14ccc7 100644 --- a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestCacheBlock.php +++ b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestCacheBlock.php @@ -20,7 +20,7 @@ class TestCacheBlock extends BlockBase { public function build() { $content = \Drupal::state()->get('block_test.content'); - $build = array(); + $build = []; if (!empty($content)) { $build['#markup'] = $content; } diff --git a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php index bc7f20b256..7db350da81 100644 --- a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php +++ b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php @@ -25,11 +25,11 @@ class TestContextAwareBlock extends BlockBase { public function build() { /** @var $user \Drupal\user\UserInterface */ $user = $this->getContextValue('user'); - return array( + return [ '#prefix' => '
        ', '#suffix' => '
        ', '#markup' => $user ? $user->getUsername() : 'No context mapping selected.' , - ); + ]; } /** diff --git a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestHtmlBlock.php b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestHtmlBlock.php index de90af4612..35f08c4b04 100644 --- a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestHtmlBlock.php +++ b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestHtmlBlock.php @@ -18,10 +18,10 @@ class TestHtmlBlock extends BlockBase { * {@inheritdoc} */ public function build() { - return array( + return [ '#attributes' => \Drupal::state()->get('block_test.attributes'), '#children' => \Drupal::state()->get('block_test.content'), - ); + ]; } } diff --git a/core/modules/block/tests/src/Functional/BlockCacheTest.php b/core/modules/block/tests/src/Functional/BlockCacheTest.php index 9285c644f0..4ea433f76a 100644 --- a/core/modules/block/tests/src/Functional/BlockCacheTest.php +++ b/core/modules/block/tests/src/Functional/BlockCacheTest.php @@ -17,7 +17,7 @@ class BlockCacheTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block', 'block_test', 'test_page_test'); + public static $modules = ['block', 'block_test', 'test_page_test']; /** * A user with permission to create and edit books and to administer blocks. @@ -51,7 +51,7 @@ protected function setUp() { parent::setUp(); // Create an admin user, log in and enable test blocks. - $this->adminUser = $this->drupalCreateUser(array('administer blocks', 'access administration pages')); + $this->adminUser = $this->drupalCreateUser(['administer blocks', 'access administration pages']); $this->drupalLogin($this->adminUser); // Create additional users to test caching modes. @@ -87,7 +87,7 @@ function testCachePerRole() { $this->assertText($old_content, 'Block is served from the cache.'); // Clear the cache and verify that the stale data is no longer there. - Cache::invalidateTags(array('block_view')); + Cache::invalidateTags(['block_view']); $this->drupalGet(''); $this->assertNoText($old_content, 'Block cache clear removes stale cache data.'); $this->assertText($current_content, 'Fresh block content is displayed after clearing the cache.'); diff --git a/core/modules/block/tests/src/Functional/BlockHiddenRegionTest.php b/core/modules/block/tests/src/Functional/BlockHiddenRegionTest.php index e2965dcdcb..c51551521a 100644 --- a/core/modules/block/tests/src/Functional/BlockHiddenRegionTest.php +++ b/core/modules/block/tests/src/Functional/BlockHiddenRegionTest.php @@ -22,17 +22,17 @@ class BlockHiddenRegionTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block', 'block_test', 'search'); + public static $modules = ['block', 'block_test', 'search']; protected function setUp() { parent::setUp(); // Create administrative user. - $this->adminUser = $this->drupalCreateUser(array( + $this->adminUser = $this->drupalCreateUser([ 'administer blocks', 'administer themes', 'search content', - ) + ] ); $this->drupalLogin($this->adminUser); @@ -53,7 +53,7 @@ public function testBlockNotInHiddenRegion() { $theme = 'block_test_theme'; // We need to install a non-hidden theme so that there is more than one // local task. - \Drupal::service('theme_handler')->install(array($theme, 'stark')); + \Drupal::service('theme_handler')->install([$theme, 'stark']); $this->config('system.theme') ->set('default', $theme) ->save(); diff --git a/core/modules/block/tests/src/Functional/BlockHookOperationTest.php b/core/modules/block/tests/src/Functional/BlockHookOperationTest.php index 9cb2272ce7..3a5c1ffbd5 100644 --- a/core/modules/block/tests/src/Functional/BlockHookOperationTest.php +++ b/core/modules/block/tests/src/Functional/BlockHookOperationTest.php @@ -17,14 +17,14 @@ class BlockHookOperationTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block', 'entity_test'); + public static $modules = ['block', 'entity_test']; protected function setUp() { parent::setUp(); - $permissions = array( + $permissions = [ 'administer blocks', - ); + ]; // Create and log in user. $admin_user = $this->drupalCreateUser($permissions); @@ -38,7 +38,7 @@ public function testBlockOperationAlter() { // Add a test block, any block will do. // Set the machine name so the test_operation link can be built later. $block_id = Unicode::strtolower($this->randomMachineName(16)); - $this->drupalPlaceBlock('system_powered_by_block', array('id' => $block_id)); + $this->drupalPlaceBlock('system_powered_by_block', ['id' => $block_id]); // Get the Block listing. $this->drupalGet('admin/structure/block'); diff --git a/core/modules/block/tests/src/Functional/BlockHtmlTest.php b/core/modules/block/tests/src/Functional/BlockHtmlTest.php index 89bbcf9ee7..9436990796 100644 --- a/core/modules/block/tests/src/Functional/BlockHtmlTest.php +++ b/core/modules/block/tests/src/Functional/BlockHtmlTest.php @@ -16,7 +16,7 @@ class BlockHtmlTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block', 'block_test'); + public static $modules = ['block', 'block_test']; protected function setUp() { parent::setUp(); @@ -24,9 +24,9 @@ protected function setUp() { $this->drupalLogin($this->rootUser); // Enable the test_html block, to test HTML ID and attributes. - \Drupal::state()->set('block_test.attributes', array('data-custom-attribute' => 'foo')); + \Drupal::state()->set('block_test.attributes', ['data-custom-attribute' => 'foo']); \Drupal::state()->set('block_test.content', $this->randomMachineName()); - $this->drupalPlaceBlock('test_html', array('id' => 'test_html_block')); + $this->drupalPlaceBlock('test_html', ['id' => 'test_html_block']); // Enable a menu block, to test more complicated HTML. $this->drupalPlaceBlock('system_menu_block:admin'); @@ -43,7 +43,7 @@ function testHtml() { $this->assertFieldByXPath('//div[@id="block-test-html-block" and @data-custom-attribute="foo"]', NULL, 'HTML ID and attributes for test block are valid and on the same DOM element.'); // Ensure expected markup for a menu block. - $elements = $this->xpath('//nav[contains(@class, :nav-class)]/ul[contains(@class, :ul-class)]/li', array(':nav-class' => 'block-menu', ':ul-class' => 'menu')); + $elements = $this->xpath('//nav[contains(@class, :nav-class)]/ul[contains(@class, :ul-class)]/li', [':nav-class' => 'block-menu', ':ul-class' => 'menu']); $this->assertTrue(!empty($elements), 'The proper block markup was found.'); } diff --git a/core/modules/block/tests/src/Functional/BlockInvalidRegionTest.php b/core/modules/block/tests/src/Functional/BlockInvalidRegionTest.php index b0e08b9e37..9b18633d67 100644 --- a/core/modules/block/tests/src/Functional/BlockInvalidRegionTest.php +++ b/core/modules/block/tests/src/Functional/BlockInvalidRegionTest.php @@ -18,16 +18,16 @@ class BlockInvalidRegionTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block', 'block_test'); + public static $modules = ['block', 'block_test']; protected function setUp() { parent::setUp(); // Create an admin user. - $admin_user = $this->drupalCreateUser(array( + $admin_user = $this->drupalCreateUser([ 'administer site configuration', 'access administration pages', 'administer blocks', - )); + ]); $this->drupalLogin($admin_user); } @@ -40,14 +40,14 @@ function testBlockInInvalidRegion() { \Drupal::configFactory()->getEditable('block.block.' . $block->id())->set('region', 'invalid_region')->save(); $block = Block::load($block->id()); - $warning_message = t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $block->id(), '%region' => 'invalid_region')); + $warning_message = t('The block %info was assigned to the invalid region %region and has been disabled.', ['%info' => $block->id(), '%region' => 'invalid_region']); // Clearing the cache should disable the test block placed in the invalid region. - $this->drupalPostForm('admin/config/development/performance', array(), 'Clear all caches'); + $this->drupalPostForm('admin/config/development/performance', [], 'Clear all caches'); $this->assertRaw($warning_message, 'Enabled block was in the invalid region and has been disabled.'); // Clear the cache to check if the warning message is not triggered. - $this->drupalPostForm('admin/config/development/performance', array(), 'Clear all caches'); + $this->drupalPostForm('admin/config/development/performance', [], 'Clear all caches'); $this->assertNoRaw($warning_message, 'Disabled block in the invalid region will not trigger the warning.'); // Place disabled test block in the invalid region of the default theme. @@ -55,7 +55,7 @@ function testBlockInInvalidRegion() { $block = Block::load($block->id()); // Clear the cache to check if the warning message is not triggered. - $this->drupalPostForm('admin/config/development/performance', array(), 'Clear all caches'); + $this->drupalPostForm('admin/config/development/performance', [], 'Clear all caches'); $this->assertNoRaw($warning_message, 'Disabled block in the invalid region will not trigger the warning.'); } diff --git a/core/modules/block/tests/src/Functional/BlockLanguageTest.php b/core/modules/block/tests/src/Functional/BlockLanguageTest.php index 7e0a0e1851..cf1b87720a 100644 --- a/core/modules/block/tests/src/Functional/BlockLanguageTest.php +++ b/core/modules/block/tests/src/Functional/BlockLanguageTest.php @@ -23,19 +23,19 @@ class BlockLanguageTest extends BrowserTestBase { * * @var array */ - public static $modules = array('language', 'block', 'content_translation'); + public static $modules = ['language', 'block', 'content_translation']; protected function setUp() { parent::setUp(); // Create a new user, allow him to manage the blocks and the languages. - $this->adminUser = $this->drupalCreateUser(array('administer blocks', 'administer languages')); + $this->adminUser = $this->drupalCreateUser(['administer blocks', 'administer languages']); $this->drupalLogin($this->adminUser); // Add predefined language. - $edit = array( + $edit = [ 'predefined_langcode' => 'fr', - ); + ]; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); $this->assertText('French', 'Language added successfully.'); } @@ -52,17 +52,17 @@ public function testLanguageBlockVisibility() { $this->assertNoField('visibility[language][context_mapping][language]', 'Language type field is not visible.'); // Enable a standard block and set the visibility setting for one language. - $edit = array( + $edit = [ 'visibility[language][langcodes][en]' => TRUE, 'id' => strtolower($this->randomMachineName(8)), 'region' => 'sidebar_first', - ); + ]; $this->drupalPostForm('admin/structure/block/add/system_powered_by_block' . '/' . $default_theme, $edit, t('Save block')); // Change the default language. - $edit = array( + $edit = [ 'site_default_language' => 'fr', - ); + ]; $this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration')); // Check that a page has a block. @@ -79,16 +79,16 @@ public function testLanguageBlockVisibility() { */ public function testLanguageBlockVisibilityLanguageDelete() { // Enable a standard block and set the visibility setting for one language. - $edit = array( - 'visibility' => array( - 'language' => array( - 'langcodes' => array( + $edit = [ + 'visibility' => [ + 'language' => [ + 'langcodes' => [ 'fr' => 'fr', - ), + ], 'context_mapping' => ['language' => '@language.current_language_context:language_interface'], - ), - ), - ); + ], + ], + ]; $block = $this->drupalPlaceBlock('system_powered_by_block', $edit); // Check that we have the language in config after saving the setting. @@ -96,7 +96,7 @@ public function testLanguageBlockVisibilityLanguageDelete() { $this->assertEqual('fr', $visibility['language']['langcodes']['fr'], 'Language is set in the block configuration.'); // Delete the language. - $this->drupalPostForm('admin/config/regional/language/delete/fr', array(), t('Delete')); + $this->drupalPostForm('admin/config/regional/language/delete/fr', [], t('Delete')); // Check that the language is no longer stored in the configuration after // it is deleted. diff --git a/core/modules/block/tests/src/Functional/BlockTemplateSuggestionsTest.php b/core/modules/block/tests/src/Functional/BlockTemplateSuggestionsTest.php index ca13c58b7d..61a3745420 100644 --- a/core/modules/block/tests/src/Functional/BlockTemplateSuggestionsTest.php +++ b/core/modules/block/tests/src/Functional/BlockTemplateSuggestionsTest.php @@ -17,7 +17,7 @@ class BlockTemplateSuggestionsTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block'); + public static $modules = ['block']; /** * Tests template suggestions from block_theme_suggestions_block(). @@ -27,22 +27,22 @@ function testBlockThemeHookSuggestions() { // an underscore (not transformed) and a hyphen (transformed to underscore), // and generates possibilities for each level of derivative. // @todo Clarify this comment. - $block = Block::create(array( + $block = Block::create([ 'plugin' => 'system_menu_block:admin', 'region' => 'footer', 'id' => 'machinename', - )); + ]); - $variables = array(); + $variables = []; $plugin = $block->getPlugin(); $variables['elements']['#configuration'] = $plugin->getConfiguration(); $variables['elements']['#plugin_id'] = $plugin->getPluginId(); $variables['elements']['#id'] = $block->id(); $variables['elements']['#base_plugin_id'] = $plugin->getBaseId(); $variables['elements']['#derivative_plugin_id'] = $plugin->getDerivativeId(); - $variables['elements']['content'] = array(); + $variables['elements']['content'] = []; $suggestions = block_theme_suggestions_block($variables); - $this->assertEqual($suggestions, array('block__system', 'block__system_menu_block', 'block__system_menu_block__admin', 'block__machinename')); + $this->assertEqual($suggestions, ['block__system', 'block__system_menu_block', 'block__system_menu_block__admin', 'block__machinename']); } } diff --git a/core/modules/block/tests/src/Functional/NewDefaultThemeBlocksTest.php b/core/modules/block/tests/src/Functional/NewDefaultThemeBlocksTest.php index 5c23a66042..767a7da590 100644 --- a/core/modules/block/tests/src/Functional/NewDefaultThemeBlocksTest.php +++ b/core/modules/block/tests/src/Functional/NewDefaultThemeBlocksTest.php @@ -16,7 +16,7 @@ class NewDefaultThemeBlocksTest extends BrowserTestBase { * * @var array */ - public static $modules = array('block'); + public static $modules = ['block']; /** * Check the enabled Bartik blocks are correctly copied over. @@ -25,22 +25,22 @@ function testNewDefaultThemeBlocks() { $default_theme = $this->config('system.theme')->get('default'); // Add two instances of the user login block. - $this->drupalPlaceBlock('user_login_block', array( + $this->drupalPlaceBlock('user_login_block', [ 'id' => $default_theme . '_' . strtolower($this->randomMachineName(8)), - )); - $this->drupalPlaceBlock('user_login_block', array( + ]); + $this->drupalPlaceBlock('user_login_block', [ 'id' => $default_theme . '_' . strtolower($this->randomMachineName(8)), - )); + ]); // Add an instance of a different block. - $this->drupalPlaceBlock('system_powered_by_block', array( + $this->drupalPlaceBlock('system_powered_by_block', [ 'id' => $default_theme . '_' . strtolower($this->randomMachineName(8)), - )); + ]); // Install a different theme. $new_theme = 'bartik'; $this->assertFalse($new_theme == $default_theme, 'The new theme is different from the previous default theme.'); - \Drupal::service('theme_handler')->install(array($new_theme)); + \Drupal::service('theme_handler')->install([$new_theme]); $this->config('system.theme') ->set('default', $new_theme) ->save(); diff --git a/core/modules/block/tests/src/Kernel/BlockConfigSchemaTest.php b/core/modules/block/tests/src/Kernel/BlockConfigSchemaTest.php index a401ea5136..2bf41e0f4c 100644 --- a/core/modules/block/tests/src/Kernel/BlockConfigSchemaTest.php +++ b/core/modules/block/tests/src/Kernel/BlockConfigSchemaTest.php @@ -18,7 +18,7 @@ class BlockConfigSchemaTest extends KernelTestBase { /** * {@inheritdoc} */ - public static $modules = array( + public static $modules = [ 'block', 'aggregator', 'book', @@ -32,7 +32,7 @@ class BlockConfigSchemaTest extends KernelTestBase { 'taxonomy', 'user', 'text', - ); + ]; /** * The typed config manager. @@ -59,7 +59,7 @@ protected function setUp() { $this->installEntitySchema('block_content'); $this->installEntitySchema('taxonomy_term'); $this->installEntitySchema('node'); - $this->installSchema('book', array('book')); + $this->installSchema('book', ['book']); } /** @@ -68,20 +68,20 @@ protected function setUp() { public function testBlockConfigSchema() { foreach ($this->blockManager->getDefinitions() as $block_id => $definition) { $id = strtolower($this->randomMachineName()); - $block = Block::create(array( + $block = Block::create([ 'id' => $id, 'theme' => 'classy', 'weight' => 00, 'status' => TRUE, 'region' => 'content', 'plugin' => $block_id, - 'settings' => array( + 'settings' => [ 'label' => $this->randomMachineName(), 'provider' => 'system', 'label_display' => FALSE, - ), - 'visibility' => array(), - )); + ], + 'visibility' => [], + ]); $block->save(); $config = $this->config("block.block.$id"); diff --git a/core/modules/block/tests/src/Kernel/BlockInterfaceTest.php b/core/modules/block/tests/src/Kernel/BlockInterfaceTest.php index 5959c0d6a8..48d63a302d 100644 --- a/core/modules/block/tests/src/Kernel/BlockInterfaceTest.php +++ b/core/modules/block/tests/src/Kernel/BlockInterfaceTest.php @@ -13,7 +13,7 @@ */ class BlockInterfaceTest extends KernelTestBase { - public static $modules = array('system', 'block', 'block_test', 'user'); + public static $modules = ['system', 'block', 'block_test', 'user']; /** * Test configuration and subsequent form() and build() method calls. @@ -31,16 +31,16 @@ class BlockInterfaceTest extends KernelTestBase { */ public function testBlockInterface() { $manager = $this->container->get('plugin.manager.block'); - $configuration = array( + $configuration = [ 'label' => 'Custom Display Message', - ); - $expected_configuration = array( + ]; + $expected_configuration = [ 'id' => 'test_block_instantiation', 'label' => 'Custom Display Message', 'provider' => 'block_test', 'label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE, 'display_message' => 'no message set', - ); + ]; // Initial configuration of the block at construction time. /** @var $display_block \Drupal\Core\Block\BlockPluginInterface */ $display_block = $manager->createInstance('test_block_instantiation', $configuration); @@ -52,46 +52,46 @@ public function testBlockInterface() { $this->assertIdentical($display_block->getConfiguration(), $expected_configuration, 'The block configuration was updated correctly.'); $definition = $display_block->getPluginDefinition(); - $expected_form = array( - 'provider' => array( + $expected_form = [ + 'provider' => [ '#type' => 'value', '#value' => 'block_test', - ), - 'admin_label' => array( + ], + 'admin_label' => [ '#type' => 'item', '#title' => t('Block description'), '#plain_text' => $definition['admin_label'], - ), - 'label' => array( + ], + 'label' => [ '#type' => 'textfield', '#title' => 'Title', '#maxlength' => 255, '#default_value' => 'Custom Display Message', '#required' => TRUE, - ), - 'label_display' => array( + ], + 'label_display' => [ '#type' => 'checkbox', '#title' => 'Display title', '#default_value' => TRUE, '#return_value' => 'visible', - ), - 'context_mapping' => array(), - 'display_message' => array( + ], + 'context_mapping' => [], + 'display_message' => [ '#type' => 'textfield', '#title' => t('Display message'), '#default_value' => 'My custom display message.', - ), - ); + ], + ]; $form_state = new FormState(); // Ensure there are no form elements that do not belong to the plugin. - $actual_form = $display_block->buildConfigurationForm(array(), $form_state); + $actual_form = $display_block->buildConfigurationForm([], $form_state); // Remove the visibility sections, as that just tests condition plugins. unset($actual_form['visibility'], $actual_form['visibility_tabs']); $this->assertIdentical($this->castSafeStrings($actual_form), $this->castSafeStrings($expected_form), 'Only the expected form elements were present.'); - $expected_build = array( + $expected_build = [ '#children' => 'My custom display message.', - ); + ]; // Ensure the build array is proper. $this->assertIdentical($display_block->build(), $expected_build, 'The plugin returned the appropriate build array.'); diff --git a/core/modules/block/tests/src/Kernel/BlockStorageUnitTest.php b/core/modules/block/tests/src/Kernel/BlockStorageUnitTest.php index d31c92c950..2a7c7710c3 100644 --- a/core/modules/block/tests/src/Kernel/BlockStorageUnitTest.php +++ b/core/modules/block/tests/src/Kernel/BlockStorageUnitTest.php @@ -21,7 +21,7 @@ class BlockStorageUnitTest extends KernelTestBase { * * @var array */ - public static $modules = array('block', 'block_test', 'system'); + public static $modules = ['block', 'block_test', 'system']; /** * The block storage. @@ -56,7 +56,7 @@ public function testBlockCRUD() { protected function createTests() { // Attempt to create a block without a plugin. try { - $entity = $this->controller->create(array()); + $entity = $this->controller->create([]); $entity->getPlugin(); $this->fail('A block without a plugin was created with no exception thrown.'); } @@ -65,12 +65,12 @@ protected function createTests() { } // Create a block with only required values. - $entity = $this->controller->create(array( + $entity = $this->controller->create([ 'id' => 'test_block', 'theme' => 'stark', 'region' => 'content', 'plugin' => 'test_html', - )); + ]); $entity->save(); $this->assertTrue($entity instanceof Block, 'The newly created entity is a Block.'); @@ -81,24 +81,24 @@ protected function createTests() { unset($actual_properties['uuid']); // Ensure that default values are filled in. - $expected_properties = array( + $expected_properties = [ 'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(), 'status' => TRUE, - 'dependencies' => array('module' => array('block_test'), 'theme' => array('stark')), + 'dependencies' => ['module' => ['block_test'], 'theme' => ['stark']], 'id' => 'test_block', 'theme' => 'stark', 'region' => 'content', 'weight' => NULL, 'provider' => NULL, 'plugin' => 'test_html', - 'settings' => array( + 'settings' => [ 'id' => 'test_html', 'label' => '', 'provider' => 'block_test', 'label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE, - ), - 'visibility' => array(), - ); + ], + 'visibility' => [], + ]; $this->assertIdentical($actual_properties, $expected_properties); @@ -148,7 +148,7 @@ public function testDefaultBlocks() { $this->assertTrue(empty($entities), 'There are no blocks initially.'); // Install the block_test.module, so that its default config is installed. - $this->installConfig(array('block_test')); + $this->installConfig(['block_test']); $entities = $this->controller->loadMultiple(); $entity = reset($entities); diff --git a/core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php b/core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php index 64b21096c0..71c4f55b8d 100644 --- a/core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php +++ b/core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php @@ -20,7 +20,7 @@ class BlockViewBuilderTest extends KernelTestBase { * * @var array */ - public static $modules = array('block', 'block_test', 'system', 'user'); + public static $modules = ['block', 'block_test', 'system', 'user']; /** * The block being tested. @@ -56,11 +56,11 @@ protected function setUp() { \Drupal::state()->set('block_test.content', 'Llamas > unicorns!'); // Create a block with only required values. - $this->block = $this->controller->create(array( + $this->block = $this->controller->create([ 'id' => 'test_block', 'theme' => 'stark', 'plugin' => 'test_cache', - )); + ]); $this->block->save(); $this->container->get('cache.render')->deleteAll(); @@ -74,17 +74,17 @@ protected function setUp() { public function testBasicRendering() { \Drupal::state()->set('block_test.content', ''); - $entity = $this->controller->create(array( + $entity = $this->controller->create([ 'id' => 'test_block1', 'theme' => 'stark', 'plugin' => 'test_html', - )); + ]); $entity->save(); // Test the rendering of a block. $entity = Block::load('test_block1'); $output = entity_view($entity, 'block'); - $expected = array(); + $expected = []; $expected[] = '
        '; $expected[] = ' '; $expected[] = ' '; @@ -98,17 +98,17 @@ public function testBasicRendering() { Html::resetSeenIds(); // Test the rendering of a block with a given title. - $entity = $this->controller->create(array( + $entity = $this->controller->create([ 'id' => 'test_block2', 'theme' => 'stark', 'plugin' => 'test_html', - 'settings' => array( + 'settings' => [ 'label' => 'Powered by Bananas', - ), - )); + ], + ]); $entity->save(); $output = entity_view($entity, 'block'); - $expected = array(); + $expected = []; $expected[] = '
        '; $expected[] = ' '; $expected[] = '

        Powered by Bananas

        '; @@ -128,11 +128,11 @@ public function testBlockViewBuilderCache() { $this->verifyRenderCacheHandling(); // Create an empty block. - $this->block = $this->controller->create(array( + $this->block = $this->controller->create([ 'id' => 'test_block', 'theme' => 'stark', 'plugin' => 'test_cache', - )); + ]); $this->block->save(); \Drupal::state()->set('block_test.content', NULL); diff --git a/core/modules/block/tests/src/Unit/BlockConfigEntityUnitTest.php b/core/modules/block/tests/src/Unit/BlockConfigEntityUnitTest.php index 453cdcc821..8df0e93a27 100644 --- a/core/modules/block/tests/src/Unit/BlockConfigEntityUnitTest.php +++ b/core/modules/block/tests/src/Unit/BlockConfigEntityUnitTest.php @@ -69,20 +69,20 @@ protected function setUp() { * @covers ::calculateDependencies */ public function testCalculateDependencies() { - $values = array('theme' => 'stark'); + $values = ['theme' => 'stark']; // Mock the entity under test so that we can mock getPluginCollections(). $entity = $this->getMockBuilder('\Drupal\block\Entity\Block') - ->setConstructorArgs(array($values, $this->entityTypeId)) - ->setMethods(array('getPluginCollections')) + ->setConstructorArgs([$values, $this->entityTypeId]) + ->setMethods(['getPluginCollections']) ->getMock(); // Create a configurable plugin that would add a dependency. $instance_id = $this->randomMachineName(); - $instance = new TestConfigurablePlugin(array(), $instance_id, array('provider' => 'test')); + $instance = new TestConfigurablePlugin([], $instance_id, ['provider' => 'test']); // Create a plugin collection to contain the instance. $plugin_collection = $this->getMockBuilder('\Drupal\Core\Plugin\DefaultLazyPluginCollection') ->disableOriginalConstructor() - ->setMethods(array('get')) + ->setMethods(['get']) ->getMock(); $plugin_collection->expects($this->atLeastOnce()) ->method('get') @@ -93,7 +93,7 @@ public function testCalculateDependencies() { // Return the mocked plugin collection. $entity->expects($this->once()) ->method('getPluginCollections') - ->will($this->returnValue(array($plugin_collection))); + ->will($this->returnValue([$plugin_collection])); $dependencies = $entity->calculateDependencies()->getDependencies(); $this->assertContains('test', $dependencies['module']); diff --git a/core/modules/block/tests/src/Unit/BlockFormTest.php b/core/modules/block/tests/src/Unit/BlockFormTest.php index d8efe2b791..b8463490bd 100644 --- a/core/modules/block/tests/src/Unit/BlockFormTest.php +++ b/core/modules/block/tests/src/Unit/BlockFormTest.php @@ -88,7 +88,7 @@ protected function setUp() { * @see \Drupal\block\BlockForm::getUniqueMachineName() */ public function testGetUniqueMachineName() { - $blocks = array(); + $blocks = []; $blocks['test'] = $this->getBlockMockWithMachineName('test'); $blocks['other_test'] = $this->getBlockMockWithMachineName('other_test'); @@ -102,7 +102,7 @@ public function testGetUniqueMachineName() { $query->expects($this->exactly(5)) ->method('execute') - ->will($this->returnValue(array('test', 'other_test', 'other_test_1', 'other_test_2'))); + ->will($this->returnValue(['test', 'other_test', 'other_test_1', 'other_test_2'])); $this->storage->expects($this->exactly(5)) ->method('getQuery') diff --git a/core/modules/block/tests/src/Unit/BlockRepositoryTest.php b/core/modules/block/tests/src/Unit/BlockRepositoryTest.php index aab11fe9fc..5584b0bfdd 100644 --- a/core/modules/block/tests/src/Unit/BlockRepositoryTest.php +++ b/core/modules/block/tests/src/Unit/BlockRepositoryTest.php @@ -116,25 +116,25 @@ public function testGetVisibleBlocksPerRegion(array $blocks_config, array $expec } public function providerBlocksConfig() { - $blocks_config = array( - 'block1' => array( + $blocks_config = [ + 'block1' => [ AccessResult::allowed(), 'top', 0 - ), + ], // Test a block without access. - 'block2' => array( + 'block2' => [ AccessResult::forbidden(), 'bottom', 0 - ), + ], // Test some blocks in the same region with specific weight. - 'block4' => array( + 'block4' => [ AccessResult::allowed(), 'bottom', 5 - ), - 'block3' => array( + ], + 'block3' => [ AccessResult::allowed(), 'bottom', 5 - ), - 'block5' => array( + ], + 'block5' => [ AccessResult::allowed(), 'bottom', -5 - ), - ); + ], + ]; $test_cases = []; $test_cases[] = [$blocks_config, diff --git a/core/modules/block/tests/src/Unit/CategoryAutocompleteTest.php b/core/modules/block/tests/src/Unit/CategoryAutocompleteTest.php index c47d65ab44..d91ebbcdbc 100644 --- a/core/modules/block/tests/src/Unit/CategoryAutocompleteTest.php +++ b/core/modules/block/tests/src/Unit/CategoryAutocompleteTest.php @@ -24,7 +24,7 @@ protected function setUp() { $block_manager = $this->getMock('Drupal\Core\Block\BlockManagerInterface'); $block_manager->expects($this->any()) ->method('getCategories') - ->will($this->returnValue(array('Comment', 'Node', 'None & Such', 'User'))); + ->will($this->returnValue(['Comment', 'Node', 'None & Such', 'User'])); $this->autocompleteController = new CategoryAutocompleteController($block_manager); } @@ -43,9 +43,9 @@ protected function setUp() { */ public function testAutocompleteSuggestions($string, $suggestions) { $suggestions = array_map(function ($suggestion) { - return array('value' => $suggestion, 'label' => Html::escape($suggestion)); + return ['value' => $suggestion, 'label' => Html::escape($suggestion)]; }, $suggestions); - $result = $this->autocompleteController->autocomplete(new Request(array('q' => $string))); + $result = $this->autocompleteController->autocomplete(new Request(['q' => $string])); $this->assertSame($suggestions, json_decode($result->getContent(), TRUE)); } @@ -55,30 +55,30 @@ public function testAutocompleteSuggestions($string, $suggestions) { * @return array */ public function providerTestAutocompleteSuggestions() { - $test_parameters = array(); - $test_parameters[] = array( + $test_parameters = []; + $test_parameters[] = [ 'string' => 'Com', - 'suggestions' => array( + 'suggestions' => [ 'Comment', - ), - ); - $test_parameters[] = array( + ], + ]; + $test_parameters[] = [ 'string' => 'No', - 'suggestions' => array( + 'suggestions' => [ 'Node', 'None & Such', - ), - ); - $test_parameters[] = array( + ], + ]; + $test_parameters[] = [ 'string' => 'us', - 'suggestions' => array( + 'suggestions' => [ 'User', - ), - ); - $test_parameters[] = array( + ], + ]; + $test_parameters[] = [ 'string' => 'Banana', - 'suggestions' => array(), - ); + 'suggestions' => [], + ]; return $test_parameters; } diff --git a/core/modules/block/tests/src/Unit/Menu/BlockLocalTasksTest.php b/core/modules/block/tests/src/Unit/Menu/BlockLocalTasksTest.php index a513c4ef75..6d7dbf2b9b 100644 --- a/core/modules/block/tests/src/Unit/Menu/BlockLocalTasksTest.php +++ b/core/modules/block/tests/src/Unit/Menu/BlockLocalTasksTest.php @@ -13,33 +13,33 @@ class BlockLocalTasksTest extends LocalTaskIntegrationTestBase { protected function setUp() { - $this->directoryList = array('block' => 'core/modules/block'); + $this->directoryList = ['block' => 'core/modules/block']; parent::setUp(); - $config_factory = $this->getConfigFactoryStub(array('system.theme' => array( + $config_factory = $this->getConfigFactoryStub(['system.theme' => [ 'default' => 'test_c', - ))); + ]]); - $themes = array(); - $themes['test_a'] = (object) array( + $themes = []; + $themes['test_a'] = (object) [ 'status' => 1, - 'info' => array( + 'info' => [ 'name' => 'test_a', 'hidden' => TRUE, - ), - ); - $themes['test_b'] = (object) array( + ], + ]; + $themes['test_b'] = (object) [ 'status' => 1, - 'info' => array( + 'info' => [ 'name' => 'test_b', - ), - ); - $themes['test_c'] = (object) array( + ], + ]; + $themes['test_c'] = (object) [ 'status' => 1, - 'info' => array( + 'info' => [ 'name' => 'test_c', - ), - ); + ], + ]; $theme_handler = $this->getMock('Drupal\Core\Extension\ThemeHandlerInterface'); $theme_handler->expects($this->any()) ->method('listInfo') @@ -63,7 +63,7 @@ protected function setUp() { * Tests the admin edit local task. */ public function testBlockAdminLocalTasks() { - $this->assertLocalTasks('entity.block.edit_form', array(array('entity.block.edit_form'))); + $this->assertLocalTasks('entity.block.edit_form', [['entity.block.edit_form']]); } /** @@ -79,10 +79,10 @@ public function testBlockAdminDisplay($route, $expected) { * Provides a list of routes to test. */ public function providerTestBlockAdminDisplay() { - return array( - array('block.admin_display', array(array('block.admin_display'), array('block.admin_display_theme:test_b', 'block.admin_display_theme:test_c'))), - array('block.admin_display_theme', array(array('block.admin_display'), array('block.admin_display_theme:test_b', 'block.admin_display_theme:test_c'))), - ); + return [ + ['block.admin_display', [['block.admin_display'], ['block.admin_display_theme:test_b', 'block.admin_display_theme:test_c']]], + ['block.admin_display_theme', [['block.admin_display'], ['block.admin_display_theme:test_b', 'block.admin_display_theme:test_c']]], + ]; } } diff --git a/core/modules/block/tests/src/Unit/Plugin/DisplayVariant/BlockPageVariantTest.php b/core/modules/block/tests/src/Unit/Plugin/DisplayVariant/BlockPageVariantTest.php index 7701ecac0b..1569411353 100644 --- a/core/modules/block/tests/src/Unit/Plugin/DisplayVariant/BlockPageVariantTest.php +++ b/core/modules/block/tests/src/Unit/Plugin/DisplayVariant/BlockPageVariantTest.php @@ -44,7 +44,7 @@ class BlockPageVariantTest extends UnitTestCase { * @return \Drupal\block\Plugin\DisplayVariant\BlockPageVariant|\PHPUnit_Framework_MockObject_MockObject * A mocked display variant plugin. */ - public function setUpDisplayVariant($configuration = array(), $definition = array()) { + public function setUpDisplayVariant($configuration = [], $definition = []) { $container = new Container(); $cache_context_manager = $this->getMockBuilder('Drupal\Core\Cache\CacheContextsManager') @@ -60,37 +60,37 @@ public function setUpDisplayVariant($configuration = array(), $definition = arra $this->blockViewBuilder = $this->getMock('Drupal\Core\Entity\EntityViewBuilderInterface'); return $this->getMockBuilder('Drupal\block\Plugin\DisplayVariant\BlockPageVariant') - ->setConstructorArgs(array($configuration, 'test', $definition, $this->blockRepository, $this->blockViewBuilder, ['config:block_list'])) - ->setMethods(array('getRegionNames')) + ->setConstructorArgs([$configuration, 'test', $definition, $this->blockRepository, $this->blockViewBuilder, ['config:block_list']]) + ->setMethods(['getRegionNames']) ->getMock(); } public function providerBuild() { - $blocks_config = array( - 'block1' => array( + $blocks_config = [ + 'block1' => [ // region, is main content block, is messages block, is title block 'top', FALSE, FALSE, FALSE, - ), + ], // Test multiple blocks in the same region. - 'block2' => array( + 'block2' => [ 'bottom', FALSE, FALSE, FALSE, - ), - 'block3' => array( + ], + 'block3' => [ 'bottom', FALSE, FALSE, FALSE, - ), + ], // Test a block implementing MainContentBlockPluginInterface. - 'block4' => array( + 'block4' => [ 'center', TRUE, FALSE, FALSE, - ), + ], // Test a block implementing MessagesBlockPluginInterface. - 'block5' => array( + 'block5' => [ 'center', FALSE, TRUE, FALSE, - ), + ], // Test a block implementing TitleBlockPluginInterface. - 'block6' => array( + 'block6' => [ 'center', FALSE, FALSE, TRUE, - ), - ); + ], + ]; $test_cases = []; $test_cases[] = [$blocks_config, 6, @@ -219,7 +219,7 @@ public function testBuild(array $blocks_config, $visible_block_count, array $exp } $this->blockViewBuilder->expects($this->exactly($visible_block_count)) ->method('view') - ->will($this->returnValue(array())); + ->will($this->returnValue([])); $this->blockRepository->expects($this->once()) ->method('getVisibleBlocksPerRegion') ->willReturnCallback(function (&$cacheable_metadata) use ($blocks) { diff --git a/core/modules/block_content/block_content.module b/core/modules/block_content/block_content.module index e0b5729561..1b32a52294 100644 --- a/core/modules/block_content/block_content.module +++ b/core/modules/block_content/block_content.module @@ -15,25 +15,25 @@ function block_content_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.block_content': - $field_ui = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#'; + $field_ui = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#'; $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Custom Block module allows you to create and manage custom block types and content-containing blocks from the Custom block library page. Custom block types have fields; see the Field module help for more information. Once created, custom blocks can be placed in regions just like blocks provided by other modules; see the Block module help page for details. For more information, see the online documentation for the Custom Block module.', array(':block-library' => \Drupal::url('entity.block_content.collection'), ':block-content' => \Drupal::url('entity.block_content.collection'), ':field-help' => \Drupal::url('help.page', array('name' => 'field')), ':blocks' => \Drupal::url('help.page', array('name' => 'block')), ':online-help' => 'https://www.drupal.org/documentation/modules/block_content')) . '

        '; + $output .= '

        ' . t('The Custom Block module allows you to create and manage custom block types and content-containing blocks from the Custom block library page. Custom block types have fields; see the Field module help for more information. Once created, custom blocks can be placed in regions just like blocks provided by other modules; see the Block module help page for details. For more information, see the online documentation for the Custom Block module.', [':block-library' => \Drupal::url('entity.block_content.collection'), ':block-content' => \Drupal::url('entity.block_content.collection'), ':field-help' => \Drupal::url('help.page', ['name' => 'field']), ':blocks' => \Drupal::url('help.page', ['name' => 'block']), ':online-help' => 'https://www.drupal.org/documentation/modules/block_content']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Creating and managing custom block types') . '
        '; - $output .= '
        ' . t('Users with the Administer blocks permission can create and edit custom block types with fields and display settings, from the Block types page in the Custom block library. For more information about managing fields and display settings, see the Field UI module help.', array(':types' => \Drupal::url('entity.block_content_type.collection'), ':field-ui' => $field_ui)) . '
        '; + $output .= '
        ' . t('Users with the Administer blocks permission can create and edit custom block types with fields and display settings, from the Block types page in the Custom block library. For more information about managing fields and display settings, see the Field UI module help.', [':types' => \Drupal::url('entity.block_content_type.collection'), ':field-ui' => $field_ui]) . '
        '; $output .= '
        ' . t('Creating custom blocks') . '
        '; - $output .= '
        ' . t('Users with the Administer blocks permission can create, edit, and delete custom blocks of each defined custom block type, from the Blocks page in the Custom block library. After creating a block, place it in a region from the Block layout page; see the Block module help for more information about placing blocks.', array(':blocks' => \Drupal::url('block.admin_display'), ':block-library' => \Drupal::url('entity.block_content.collection'), ':block_help' => \Drupal::url('help.page', array('name' => 'block')))) . '
        '; + $output .= '
        ' . t('Users with the Administer blocks permission can create, edit, and delete custom blocks of each defined custom block type, from the Blocks page in the Custom block library. After creating a block, place it in a region from the Block layout page; see the Block module help for more information about placing blocks.', [':blocks' => \Drupal::url('block.admin_display'), ':block-library' => \Drupal::url('entity.block_content.collection'), ':block_help' => \Drupal::url('help.page', ['name' => 'block'])]) . '
        '; $output .= '
        '; return $output; case 'entity.block_content.collection': - $output = '

        ' . t('Blocks in the block library belong to Custom block types, each with its own fields and display settings. After creating a block, place it in a region from the Block layout page.', array(':types' => \Drupal::url('entity.block_content_type.collection'), ':blocks' => \Drupal::url('block.admin_display'))) . '

        '; + $output = '

        ' . t('Blocks in the block library belong to Custom block types, each with its own fields and display settings. After creating a block, place it in a region from the Block layout page.', [':types' => \Drupal::url('entity.block_content_type.collection'), ':blocks' => \Drupal::url('block.admin_display')]) . '

        '; return $output; case 'entity.block_content_type.collection': - $output = '

        ' . t('Each block type has its own fields and display settings. Create blocks of each type on the Blocks page in the custom block library.', array(':block-library' => \Drupal::url('entity.block_content.collection'))) . '

        '; + $output = '

        ' . t('Each block type has its own fields and display settings. Create blocks of each type on the Blocks page in the custom block library.', [':block-library' => \Drupal::url('entity.block_content.collection')]) . '

        '; return $output; } @@ -43,12 +43,12 @@ function block_content_help($route_name, RouteMatchInterface $route_match) { * Implements hook_theme(). */ function block_content_theme($existing, $type, $theme, $path) { - return array( - 'block_content_add_list' => array( - 'variables' => array('content' => NULL), + return [ + 'block_content_add_list' => [ + 'variables' => ['content' => NULL], 'file' => 'block_content.pages.inc', - ), - ); + ], + ]; } /** @@ -83,23 +83,23 @@ function block_content_add_body_field($block_type_id, $label = 'Body') { 'field_storage' => FieldStorageConfig::loadByName('block_content', 'body'), 'bundle' => $block_type_id, 'label' => $label, - 'settings' => array('display_summary' => FALSE), + 'settings' => ['display_summary' => FALSE], ]); $field->save(); // Assign widget settings for the 'default' form mode. entity_get_form_display('block_content', $block_type_id, 'default') - ->setComponent('body', array( + ->setComponent('body', [ 'type' => 'text_textarea_with_summary', - )) + ]) ->save(); // Assign display settings for 'default' view mode. entity_get_display('block_content', $block_type_id, 'default') - ->setComponent('body', array( + ->setComponent('body', [ 'label' => 'hidden', 'type' => 'text_default', - )) + ]) ->save(); } diff --git a/core/modules/block_content/block_content.pages.inc b/core/modules/block_content/block_content.pages.inc index 86296900df..e50e71787b 100644 --- a/core/modules/block_content/block_content.pages.inc +++ b/core/modules/block_content/block_content.pages.inc @@ -19,18 +19,18 @@ * @see block_content_add_page() */ function template_preprocess_block_content_add_list(&$variables) { - $variables['types'] = array(); + $variables['types'] = []; $query = \Drupal::request()->query->all(); foreach ($variables['content'] as $type) { - $variables['types'][$type->id()] = array( - 'link' => \Drupal::l($type->label(), new Url('block_content.add_form', array('block_content_type' => $type->id()), array('query' => $query))), - 'description' => array( + $variables['types'][$type->id()] = [ + 'link' => \Drupal::l($type->label(), new Url('block_content.add_form', ['block_content_type' => $type->id()], ['query' => $query])), + 'description' => [ '#markup' => $type->getDescription(), - ), + ], 'title' => $type->label(), - 'localized_options' => array( + 'localized_options' => [ 'query' => $query, - ), - ); + ], + ]; } } diff --git a/core/modules/block_content/src/BlockContentForm.php b/core/modules/block_content/src/BlockContentForm.php index b3f50f7a95..eefd4e9790 100644 --- a/core/modules/block_content/src/BlockContentForm.php +++ b/core/modules/block_content/src/BlockContentForm.php @@ -27,7 +27,7 @@ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); if ($this->operation == 'edit') { - $form['#title'] = $this->t('Edit custom block %label', array('%label' => $block->label())); + $form['#title'] = $this->t('Edit custom block %label', ['%label' => $block->label()]); } // Override the default CSS class name, since the user-defined custom block // type name in 'TYPE-block-form' potentially clashes with third-party class @@ -45,10 +45,10 @@ public function save(array $form, FormStateInterface $form_state) { $insert = $block->isNew(); $block->save(); - $context = array('@type' => $block->bundle(), '%info' => $block->label()); + $context = ['@type' => $block->bundle(), '%info' => $block->label()]; $logger = $this->logger('block_content'); $block_type = $this->getBundleEntity(); - $t_args = array('@type' => $block_type->label(), '%info' => $block->label()); + $t_args = ['@type' => $block_type->label(), '%info' => $block->label()]; if ($insert) { $logger->notice('@type: added %info.', $context); @@ -68,10 +68,10 @@ public function save(array $form, FormStateInterface $form_state) { } $form_state->setRedirect( 'block.admin_add', - array( + [ 'plugin_id' => 'block_content:' . $block->uuid(), 'theme' => $theme, - ) + ] ); } else { diff --git a/core/modules/block_content/src/BlockContentTranslationHandler.php b/core/modules/block_content/src/BlockContentTranslationHandler.php index b446cde8c5..612613b376 100644 --- a/core/modules/block_content/src/BlockContentTranslationHandler.php +++ b/core/modules/block_content/src/BlockContentTranslationHandler.php @@ -16,7 +16,7 @@ class BlockContentTranslationHandler extends ContentTranslationHandler { */ protected function entityFormTitle(EntityInterface $entity) { $block_type = BlockContentType::load($entity->bundle()); - return t('Edit @type @title', array('@type' => $block_type->label(), '@title' => $entity->label())); + return t('Edit @type @title', ['@type' => $block_type->label(), '@title' => $entity->label()]); } } diff --git a/core/modules/block_content/src/BlockContentTypeForm.php b/core/modules/block_content/src/BlockContentTypeForm.php index d864e8d56f..4e140b1932 100644 --- a/core/modules/block_content/src/BlockContentTypeForm.php +++ b/core/modules/block_content/src/BlockContentTypeForm.php @@ -25,65 +25,65 @@ public function form(array $form, FormStateInterface $form_state) { $form['#title'] = $this->t('Add custom block type'); } else { - $form['#title'] = $this->t('Edit %label custom block type', array('%label' => $block_type->label())); + $form['#title'] = $this->t('Edit %label custom block type', ['%label' => $block_type->label()]); } - $form['label'] = array( + $form['label'] = [ '#type' => 'textfield', '#title' => t('Label'), '#maxlength' => 255, '#default_value' => $block_type->label(), '#description' => t("Provide a label for this block type to help identify it in the administration pages."), '#required' => TRUE, - ); - $form['id'] = array( + ]; + $form['id'] = [ '#type' => 'machine_name', '#default_value' => $block_type->id(), - '#machine_name' => array( + '#machine_name' => [ 'exists' => '\Drupal\block_content\Entity\BlockContentType::load', - ), + ], '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, - ); + ]; - $form['description'] = array( + $form['description'] = [ '#type' => 'textarea', '#default_value' => $block_type->getDescription(), '#description' => t('Enter a description for this block type.'), '#title' => t('Description'), - ); + ]; - $form['revision'] = array( + $form['revision'] = [ '#type' => 'checkbox', '#title' => t('Create new revision'), '#default_value' => $block_type->shouldCreateNewRevision(), '#description' => t('Create a new revision by default for this block type.'), - ); + ]; if ($this->moduleHandler->moduleExists('language')) { - $form['language'] = array( + $form['language'] = [ '#type' => 'details', '#title' => t('Language settings'), '#group' => 'additional_settings', - ); + ]; $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('block_content', $block_type->id()); - $form['language']['language_configuration'] = array( + $form['language']['language_configuration'] = [ '#type' => 'language_configuration', - '#entity_information' => array( + '#entity_information' => [ 'entity_type' => 'block_content', 'bundle' => $block_type->id(), - ), + ], '#default_value' => $language_configuration, - ); + ]; $form['#submit'][] = 'language_configuration_element_submit'; } - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => t('Save'), - ); + ]; return $this->protectBundleIdElement($form); } @@ -98,13 +98,13 @@ public function save(array $form, FormStateInterface $form_state) { $edit_link = $this->entity->link($this->t('Edit')); $logger = $this->logger('block_content'); if ($status == SAVED_UPDATED) { - drupal_set_message(t('Custom block type %label has been updated.', array('%label' => $block_type->label()))); - $logger->notice('Custom block type %label has been updated.', array('%label' => $block_type->label(), 'link' => $edit_link)); + drupal_set_message(t('Custom block type %label has been updated.', ['%label' => $block_type->label()])); + $logger->notice('Custom block type %label has been updated.', ['%label' => $block_type->label(), 'link' => $edit_link]); } else { block_content_add_body_field($block_type->id()); - drupal_set_message(t('Custom block type %label has been added.', array('%label' => $block_type->label()))); - $logger->notice('Custom block type %label has been added.', array('%label' => $block_type->label(), 'link' => $edit_link)); + drupal_set_message(t('Custom block type %label has been added.', ['%label' => $block_type->label()])); + $logger->notice('Custom block type %label has been added.', ['%label' => $block_type->label(), 'link' => $edit_link]); } $form_state->setRedirectUrl($this->entity->urlInfo('collection')); diff --git a/core/modules/block_content/src/BlockContentViewBuilder.php b/core/modules/block_content/src/BlockContentViewBuilder.php index 322a087d9f..29c668cd63 100644 --- a/core/modules/block_content/src/BlockContentViewBuilder.php +++ b/core/modules/block_content/src/BlockContentViewBuilder.php @@ -15,13 +15,13 @@ class BlockContentViewBuilder extends EntityViewBuilder { * {@inheritdoc} */ public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) { - return $this->viewMultiple(array($entity), $view_mode, $langcode)[0]; + return $this->viewMultiple([$entity], $view_mode, $langcode)[0]; } /** * {@inheritdoc} */ - public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL) { + public function viewMultiple(array $entities = [], $view_mode = 'full', $langcode = NULL) { $build_list = parent::viewMultiple($entities, $view_mode, $langcode); // Apply the buildMultiple() #pre_render callback immediately, to make // bubbling of attributes and contextual links to the actual block work. @@ -48,10 +48,10 @@ protected function alterBuild(array &$build, EntityInterface $entity, EntityView parent::alterBuild($build, $entity, $display, $view_mode); // Add contextual links for this custom block. if (!$entity->isNew()) { - $build['#contextual_links']['block_content'] = array( - 'route_parameters' => array('block_content' => $entity->id()), - 'metadata' => array('changed' => $entity->getChangedTime()), - ); + $build['#contextual_links']['block_content'] = [ + 'route_parameters' => ['block_content' => $entity->id()], + 'metadata' => ['changed' => $entity->getChangedTime()], + ]; } } diff --git a/core/modules/block_content/src/BlockContentViewsData.php b/core/modules/block_content/src/BlockContentViewsData.php index 1d5d46f5f0..010ede0ea5 100644 --- a/core/modules/block_content/src/BlockContentViewsData.php +++ b/core/modules/block_content/src/BlockContentViewsData.php @@ -23,13 +23,13 @@ public function getViewsData() { $data['block_content_field_data']['type']['field']['id'] = 'field'; - $data['block_content']['block_content_listing_empty'] = array( + $data['block_content']['block_content_listing_empty'] = [ 'title' => $this->t('Empty block library behavior'), 'help' => $this->t('Provides a link to add a new block.'), - 'area' => array( + 'area' => [ 'id' => 'block_content_listing_empty', - ), - ); + ], + ]; // Advertise this table as a possible base table. $data['block_content_field_revision']['table']['base']['help'] = $this->t('Block Content revision is a history of changes to block content.'); $data['block_content_field_revision']['table']['base']['defaults']['title'] = 'info'; diff --git a/core/modules/block_content/src/Controller/BlockContentController.php b/core/modules/block_content/src/Controller/BlockContentController.php index 1caad74153..7c1f8aac33 100644 --- a/core/modules/block_content/src/Controller/BlockContentController.php +++ b/core/modules/block_content/src/Controller/BlockContentController.php @@ -79,14 +79,14 @@ public function add(Request $request) { return $this->addForm($type, $request); } if (count($types) === 0) { - return array( + return [ '#markup' => $this->t('You have not created any block types yet. Go to the block type creation page to add a new block type.', [ ':url' => Url::fromRoute('block_content.type_add')->toString(), ]), - ); + ]; } - return array('#theme' => 'block_content_add_list', '#content' => $types); + return ['#theme' => 'block_content_add_list', '#content' => $types]; } /** @@ -101,9 +101,9 @@ public function add(Request $request) { * A form array as expected by drupal_render(). */ public function addForm(BlockContentTypeInterface $block_content_type, Request $request) { - $block = $this->blockContentStorage->create(array( + $block = $this->blockContentStorage->create([ 'type' => $block_content_type->id() - )); + ]); if (($theme = $request->query->get('theme')) && in_array($theme, array_keys($this->themeHandler->listInfo()))) { // We have navigated to this page from the block library and will keep track // of the theme for redirecting the user to the configuration page for the @@ -123,7 +123,7 @@ public function addForm(BlockContentTypeInterface $block_content_type, Request $ * The page title. */ public function getAddFormTitle(BlockContentTypeInterface $block_content_type) { - return $this->t('Add %type custom block', array('%type' => $block_content_type->label())); + return $this->t('Add %type custom block', ['%type' => $block_content_type->label()]); } } diff --git a/core/modules/block_content/src/Entity/BlockContent.php b/core/modules/block_content/src/Entity/BlockContent.php index 51ae6f679c..2726b138b8 100644 --- a/core/modules/block_content/src/Entity/BlockContent.php +++ b/core/modules/block_content/src/Entity/BlockContent.php @@ -121,7 +121,7 @@ public static function postDelete(EntityStorageInterface $storage, array $entiti * {@inheritdoc} */ public function getInstances() { - return \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(array('plugin' => 'block_content:' . $this->uuid())); + return \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['plugin' => 'block_content:' . $this->uuid()]); } /** @@ -173,10 +173,10 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setRevisionable(TRUE) ->setTranslatable(TRUE) ->setRequired(TRUE) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'string_textfield', 'weight' => -5, - )) + ]) ->setDisplayConfigurable('form', TRUE) ->addConstraint('UniqueField', []); @@ -184,13 +184,13 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setLabel(t('Revision log message')) ->setDescription(t('The log entry explaining the changes in this revision.')) ->setRevisionable(TRUE) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'string_textarea', 'weight' => 25, - 'settings' => array( + 'settings' => [ 'rows' => 4, - ), - )); + ], + ]); $fields['changed'] = BaseFieldDefinition::create('changed') ->setLabel(t('Changed')) diff --git a/core/modules/block_content/src/Form/BlockContentDeleteForm.php b/core/modules/block_content/src/Form/BlockContentDeleteForm.php index 3fe725daa8..035ec4c2fb 100644 --- a/core/modules/block_content/src/Form/BlockContentDeleteForm.php +++ b/core/modules/block_content/src/Form/BlockContentDeleteForm.php @@ -16,10 +16,10 @@ class BlockContentDeleteForm extends ContentEntityDeleteForm { public function buildForm(array $form, FormStateInterface $form_state) { $instances = $this->entity->getInstances(); - $form['message'] = array( + $form['message'] = [ '#markup' => $this->formatPlural(count($instances), 'This will also remove 1 placed block instance.', 'This will also remove @count placed block instances.'), '#access' => !empty($instances), - ); + ]; return parent::buildForm($form, $form_state); } diff --git a/core/modules/block_content/src/Form/BlockContentTypeDeleteForm.php b/core/modules/block_content/src/Form/BlockContentTypeDeleteForm.php index b68e695b38..aea4ab5e83 100644 --- a/core/modules/block_content/src/Form/BlockContentTypeDeleteForm.php +++ b/core/modules/block_content/src/Form/BlockContentTypeDeleteForm.php @@ -18,8 +18,8 @@ public function buildForm(array $form, FormStateInterface $form_state) { ->condition('type', $this->entity->id()) ->execute(); if (!empty($blocks)) { - $caption = '

        ' . $this->formatPlural(count($blocks), '%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', '%label is used by @count custom blocks on your site. You may not remove %label until you have removed all of the %label custom blocks.', array('%label' => $this->entity->label())) . '

        '; - $form['description'] = array('#markup' => $caption); + $caption = '

        ' . $this->formatPlural(count($blocks), '%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', '%label is used by @count custom blocks on your site. You may not remove %label until you have removed all of the %label custom blocks.', ['%label' => $this->entity->label()]) . '

        '; + $form['description'] = ['#markup' => $caption]; return $form; } else { diff --git a/core/modules/block_content/src/Plugin/Block/BlockContentBlock.php b/core/modules/block_content/src/Plugin/Block/BlockContentBlock.php index 2afd0402eb..e97e740187 100644 --- a/core/modules/block_content/src/Plugin/Block/BlockContentBlock.php +++ b/core/modules/block_content/src/Plugin/Block/BlockContentBlock.php @@ -105,11 +105,11 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function defaultConfiguration() { - return array( + return [ 'status' => TRUE, 'info' => '', 'view_mode' => 'full', - ); + ]; } /** @@ -122,14 +122,14 @@ public function blockForm($form, FormStateInterface $form_state) { $block = $this->entityManager->loadEntityByUuid('block_content', $uuid); $options = $this->entityManager->getViewModeOptionsByBundle('block_content', $block->bundle()); - $form['view_mode'] = array( + $form['view_mode'] = [ '#type' => 'select', '#options' => $options, '#title' => $this->t('View mode'), '#description' => $this->t('Output the block in this view mode.'), '#default_value' => $this->configuration['view_mode'], '#access' => (count($options) > 1), - ); + ]; $form['title']['#description'] = $this->t('The title of the block as shown to the user.'); return $form; } @@ -161,13 +161,13 @@ public function build() { return $this->entityManager->getViewBuilder($block->getEntityTypeId())->view($block, $this->configuration['view_mode']); } else { - return array( - '#markup' => $this->t('Block with uuid %uuid does not exist. Add custom block.', array( + return [ + '#markup' => $this->t('Block with uuid %uuid does not exist. Add custom block.', [ '%uuid' => $this->getDerivativeId(), ':url' => $this->urlGenerator->generate('block_content.add_page') - )), + ]), '#access' => $this->account->hasPermission('administer blocks') - ); + ]; } } diff --git a/core/modules/block_content/src/Plugin/Derivative/BlockContent.php b/core/modules/block_content/src/Plugin/Derivative/BlockContent.php index ab564451cb..25806c5f13 100644 --- a/core/modules/block_content/src/Plugin/Derivative/BlockContent.php +++ b/core/modules/block_content/src/Plugin/Derivative/BlockContent.php @@ -50,9 +50,9 @@ public function getDerivativeDefinitions($base_plugin_definition) { foreach ($block_contents as $block_content) { $this->derivatives[$block_content->uuid()] = $base_plugin_definition; $this->derivatives[$block_content->uuid()]['admin_label'] = $block_content->label(); - $this->derivatives[$block_content->uuid()]['config_dependencies']['content'] = array( + $this->derivatives[$block_content->uuid()]['config_dependencies']['content'] = [ $block_content->getConfigDependencyName() - ); + ]; } return parent::getDerivativeDefinitions($base_plugin_definition); } diff --git a/core/modules/block_content/src/Plugin/migrate/source/d6/Box.php b/core/modules/block_content/src/Plugin/migrate/source/d6/Box.php index 41352336b4..a28927bd58 100644 --- a/core/modules/block_content/src/Plugin/migrate/source/d6/Box.php +++ b/core/modules/block_content/src/Plugin/migrate/source/d6/Box.php @@ -18,7 +18,7 @@ class Box extends DrupalSqlBase { */ public function query() { $query = $this->select('boxes', 'b') - ->fields('b', array('bid', 'body', 'info', 'format')); + ->fields('b', ['bid', 'body', 'info', 'format']); $query->orderBy('b.bid'); return $query; @@ -28,12 +28,12 @@ public function query() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'bid' => $this->t('The numeric identifier of the block/box'), 'body' => $this->t('The block/box content'), 'info' => $this->t('Admin title of the block/box.'), 'format' => $this->t('Input format of the custom block/box content.'), - ); + ]; } /** diff --git a/core/modules/block_content/src/Plugin/migrate/source/d7/BlockCustom.php b/core/modules/block_content/src/Plugin/migrate/source/d7/BlockCustom.php index 4aee2a4599..ea336829bf 100644 --- a/core/modules/block_content/src/Plugin/migrate/source/d7/BlockCustom.php +++ b/core/modules/block_content/src/Plugin/migrate/source/d7/BlockCustom.php @@ -24,12 +24,12 @@ public function query() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'bid' => $this->t('The numeric identifier of the block/box'), 'body' => $this->t('The block/box content'), 'info' => $this->t('Admin title of the block/box.'), 'format' => $this->t('Input format of the custom block/box content.'), - ); + ]; } /** diff --git a/core/modules/block_content/src/Plugin/views/area/ListingEmpty.php b/core/modules/block_content/src/Plugin/views/area/ListingEmpty.php index d2bd026157..e412f182ec 100644 --- a/core/modules/block_content/src/Plugin/views/area/ListingEmpty.php +++ b/core/modules/block_content/src/Plugin/views/area/ListingEmpty.php @@ -71,19 +71,19 @@ public static function create(ContainerInterface $container, array $configuratio public function render($empty = FALSE) { if (!$empty || !empty($this->options['empty'])) { /** @var \Drupal\Core\Access\AccessResultInterface|\Drupal\Core\Cache\CacheableDependencyInterface $access_result */ - $access_result = $this->accessManager->checkNamedRoute('block_content.add_page', array(), $this->currentUser, TRUE); - $element = array( - '#markup' => $this->t('Add a custom block.', array(':url' => Url::fromRoute('block_content.add_page')->toString())), + $access_result = $this->accessManager->checkNamedRoute('block_content.add_page', [], $this->currentUser, TRUE); + $element = [ + '#markup' => $this->t('Add a custom block.', [':url' => Url::fromRoute('block_content.add_page')->toString()]), '#access' => $access_result->isAllowed(), '#cache' => [ 'contexts' => $access_result->getCacheContexts(), 'tags' => $access_result->getCacheTags(), 'max-age' => $access_result->getCacheMaxAge(), ], - ); + ]; return $element; } - return array(); + return []; } } diff --git a/core/modules/block_content/src/Tests/BlockContentCreationTest.php b/core/modules/block_content/src/Tests/BlockContentCreationTest.php index e45892c5c3..ac9e824d49 100644 --- a/core/modules/block_content/src/Tests/BlockContentCreationTest.php +++ b/core/modules/block_content/src/Tests/BlockContentCreationTest.php @@ -21,17 +21,17 @@ class BlockContentCreationTest extends BlockContentTestBase { * * @var array */ - public static $modules = array('block_content_test', 'dblog', 'field_ui'); + public static $modules = ['block_content_test', 'dblog', 'field_ui']; /** * Permissions to grant admin user. * * @var array */ - protected $permissions = array( + protected $permissions = [ 'administer blocks', 'administer block_content display' - ); + ]; /** * Sets the test up. @@ -48,22 +48,22 @@ public function testBlockContentCreation() { $this->drupalLogin($this->adminUser); // Create a block. - $edit = array(); + $edit = []; $edit['info[0][value]'] = 'Test Block'; $edit['body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm('block/add/basic', $edit, t('Save')); // Check that the Basic block has been created. - $this->assertRaw(format_string('@block %name has been created.', array( + $this->assertRaw(format_string('@block %name has been created.', [ '@block' => 'basic', '%name' => $edit['info[0][value]'] - )), 'Basic block created.'); + ]), 'Basic block created.'); // Check that the view mode setting is hidden because only one exists. $this->assertNoFieldByXPath('//select[@name="settings[view_mode]"]', NULL, 'View mode setting hidden because only one exists'); // Check that the block exists in the database. - $blocks = entity_load_multiple_by_properties('block_content', array('info' => $edit['info[0][value]'])); + $blocks = entity_load_multiple_by_properties('block_content', ['info' => $edit['info[0][value]']]); $block = reset($blocks); $this->assertTrue($block, 'Custom Block found in database.'); @@ -72,9 +72,9 @@ public function testBlockContentCreation() { $this->drupalPostForm('block/add/basic', $edit, t('Save')); // Check that the Basic block has been created. - $this->assertRaw(format_string('A custom block with block description %value already exists.', array( + $this->assertRaw(format_string('A custom block with block description %value already exists.', [ '%value' => $edit['info[0][value]'] - ))); + ])); $this->assertResponse(200); } @@ -83,28 +83,28 @@ public function testBlockContentCreation() { */ public function testBlockContentCreationMultipleViewModes() { // Add a new view mode and verify if it is selected as expected. - $this->drupalLogin($this->drupalCreateUser(array('administer display modes'))); + $this->drupalLogin($this->drupalCreateUser(['administer display modes'])); $this->drupalGet('admin/structure/display-modes/view/add/block_content'); - $edit = array( + $edit = [ 'id' => 'test_view_mode', 'label' => 'Test View Mode', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertRaw(t('Saved the %label view mode.', array('%label' => $edit['label']))); + $this->assertRaw(t('Saved the %label view mode.', ['%label' => $edit['label']])); $this->drupalLogin($this->adminUser); // Create a block. - $edit = array(); + $edit = []; $edit['info[0][value]'] = 'Test Block'; $edit['body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm('block/add/basic', $edit, t('Save')); // Check that the Basic block has been created. - $this->assertRaw(format_string('@block %name has been created.', array( + $this->assertRaw(format_string('@block %name has been created.', [ '@block' => 'basic', '%name' => $edit['info[0][value]'] - )), 'Basic block created.'); + ]), 'Basic block created.'); // Save our block permanently $this->drupalPostForm(NULL, ['region' => 'content'], t('Save block')); @@ -114,9 +114,9 @@ public function testBlockContentCreationMultipleViewModes() { $this->drupalGet('admin/structure/block/block-content/types'); $this->clickLink(t('Manage display')); $this->drupalGet('admin/structure/block/block-content/manage/basic/display'); - $custom_view_mode = array( + $custom_view_mode = [ 'display_modes_custom[test_view_mode]' => 1, - ); + ]; $this->drupalPostForm(NULL, $custom_view_mode, t('Save')); // Go to the configure page and change the view mode. @@ -143,7 +143,7 @@ public function testBlockContentCreationMultipleViewModes() { $this->assertFieldByXPath('//select[@name="settings[view_mode]"]/option[@selected="selected"]/@value', 'test_view_mode', 'View mode changed to Test View Mode'); // Check that the block exists in the database. - $blocks = entity_load_multiple_by_properties('block_content', array('info' => $edit['info[0][value]'])); + $blocks = entity_load_multiple_by_properties('block_content', ['info' => $edit['info[0][value]']]); $block = reset($blocks); $this->assertTrue($block, 'Custom Block found in database.'); @@ -152,9 +152,9 @@ public function testBlockContentCreationMultipleViewModes() { $this->drupalPostForm('block/add/basic', $edit, t('Save')); // Check that the Basic block has been created. - $this->assertRaw(format_string('A custom block with block description %value already exists.', array( + $this->assertRaw(format_string('A custom block with block description %value already exists.', [ '%value' => $edit['info[0][value]'] - ))); + ])); $this->assertResponse(200); } @@ -165,20 +165,20 @@ public function testBlockContentCreationMultipleViewModes() { * type is being used. */ public function testDefaultBlockContentCreation() { - $edit = array(); + $edit = []; $edit['info[0][value]'] = $this->randomMachineName(8); $edit['body[0][value]'] = $this->randomMachineName(16); // Don't pass the custom block type in the url so the default is forced. $this->drupalPostForm('block/add', $edit, t('Save')); // Check that the block has been created and that it is a basic block. - $this->assertRaw(format_string('@block %name has been created.', array( + $this->assertRaw(format_string('@block %name has been created.', [ '@block' => 'basic', '%name' => $edit['info[0][value]'], - )), 'Basic block created.'); + ]), 'Basic block created.'); // Check that the block exists in the database. - $blocks = entity_load_multiple_by_properties('block_content', array('info' => $edit['info[0][value]'])); + $blocks = entity_load_multiple_by_properties('block_content', ['info' => $edit['info[0][value]']]); $block = reset($blocks); $this->assertTrue($block, 'Default Custom Block found in database.'); } @@ -199,7 +199,7 @@ public function testFailedBlockCreation() { if (Database::getConnection()->supportsTransactions()) { // Check that the block does not exist in the database. $id = db_select('block_content_field_data', 'b') - ->fields('b', array('id')) + ->fields('b', ['id']) ->condition('info', 'fail_creation') ->execute() ->fetchField(); @@ -208,7 +208,7 @@ public function testFailedBlockCreation() { else { // Check that the block exists in the database. $id = db_select('block_content_field_data', 'b') - ->fields('b', array('id')) + ->fields('b', ['id']) ->condition('info', 'fail_creation') ->execute() ->fetchField(); @@ -225,18 +225,18 @@ public function testFailedBlockCreation() { */ public function testBlockDelete() { // Create a block. - $edit = array(); + $edit = []; $edit['info[0][value]'] = $this->randomMachineName(8); $body = $this->randomMachineName(16); $edit['body[0][value]'] = $body; $this->drupalPostForm('block/add/basic', $edit, t('Save')); // Place the block. - $instance = array( + $instance = [ 'id' => Unicode::strtolower($edit['info[0][value]']), 'settings[label]' => $edit['info[0][value]'], 'region' => 'sidebar_first', - ); + ]; $block = BlockContent::load(1); $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default'); $this->drupalPostForm($url, $instance, t('Save block')); @@ -254,11 +254,11 @@ public function testBlockDelete() { $this->drupalGet('block/1/delete'); $this->assertText(\Drupal::translation()->formatPlural(1, 'This will also remove 1 placed block instance.', 'This will also remove @count placed block instance.')); - $this->drupalPostForm(NULL, array(), 'Delete'); - $this->assertRaw(t('The custom block %name has been deleted.', array('%name' => $edit['info[0][value]']))); + $this->drupalPostForm(NULL, [], 'Delete'); + $this->assertRaw(t('The custom block %name has been deleted.', ['%name' => $edit['info[0][value]']])); // Create another block and force the plugin cache to flush. - $edit2 = array(); + $edit2 = []; $edit2['info[0][value]'] = $this->randomMachineName(8); $body2 = $this->randomMachineName(16); $edit2['body[0][value]'] = $body2; @@ -268,7 +268,7 @@ public function testBlockDelete() { // Create another block with no instances, and test we don't get a // confirmation message about deleting instances. - $edit3 = array(); + $edit3 = []; $edit3['info[0][value]'] = $this->randomMachineName(8); $body = $this->randomMachineName(16); $edit3['body[0][value]'] = $body; @@ -286,16 +286,16 @@ public function testConfigDependencies() { $block = $this->createBlockContent(); // Place the block. $block_placement_id = Unicode::strtolower($block->label()); - $instance = array( + $instance = [ 'id' => $block_placement_id, 'settings[label]' => $block->label(), 'region' => 'sidebar_first', - ); + ]; $block = BlockContent::load(1); $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default'); $this->drupalPostForm($url, $instance, t('Save block')); - $dependencies = \Drupal::service('config.manager')->findConfigEntityDependentsAsEntities('content', array($block->getConfigDependencyName())); + $dependencies = \Drupal::service('config.manager')->findConfigEntityDependentsAsEntities('content', [$block->getConfigDependencyName()]); $block_placement = reset($dependencies); $this->assertEqual($block_placement_id, $block_placement->id(), "The block placement config entity has a dependency on the block content entity."); } diff --git a/core/modules/block_content/src/Tests/BlockContentListTest.php b/core/modules/block_content/src/Tests/BlockContentListTest.php index be8ea5e4c8..e00706e9ff 100644 --- a/core/modules/block_content/src/Tests/BlockContentListTest.php +++ b/core/modules/block_content/src/Tests/BlockContentListTest.php @@ -18,13 +18,13 @@ class BlockContentListTest extends BlockContentTestBase { * * @var array */ - public static $modules = array('block', 'block_content', 'config_translation'); + public static $modules = ['block', 'block_content', 'config_translation']; /** * Tests the custom block listing page. */ public function testListing() { - $this->drupalLogin($this->drupalCreateUser(array('administer blocks', 'translate configuration'))); + $this->drupalLogin($this->drupalCreateUser(['administer blocks', 'translate configuration'])); $this->drupalGet('admin/structure/block/block-content'); // Test for the page title. @@ -39,7 +39,7 @@ public function testListing() { $this->assertEqual(count($elements), 2, 'Correct number of table header cells found.'); // Test the contents of each th cell. - $expected_items = array(t('Block description'), t('Operations')); + $expected_items = [t('Block description'), t('Operations')]; foreach ($elements as $key => $element) { $this->assertEqual($element[0], $expected_items[$key]); } @@ -51,7 +51,7 @@ public function testListing() { $this->assertLink($link_text); $this->clickLink($link_text); $this->assertResponse(200); - $edit = array(); + $edit = []; $edit['info[0][value]'] = $label; $edit['body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm(NULL, $edit, t('Save')); @@ -72,14 +72,14 @@ public function testListing() { $blocks = $this->container ->get('entity.manager') ->getStorage('block_content') - ->loadByProperties(array('info' => $label)); + ->loadByProperties(['info' => $label]); $block = reset($blocks); if (!empty($block)) { $this->assertLinkByHref('block/' . $block->id()); $this->clickLink(t('Edit')); $this->assertResponse(200); - $this->assertTitle(strip_tags(t('Edit custom block %label', array('%label' => $label)) . ' | Drupal')); - $edit = array('info[0][value]' => $new_label); + $this->assertTitle(strip_tags(t('Edit custom block %label', ['%label' => $label]) . ' | Drupal')); + $edit = ['info[0][value]' => $new_label]; $this->drupalPostForm(NULL, $edit, t('Save')); } else { @@ -95,8 +95,8 @@ public function testListing() { $delete_text = t('Delete'); $this->clickLink($delete_text); $this->assertResponse(200); - $this->assertTitle(strip_tags(t('Are you sure you want to delete the custom block %label?', array('%label' => $new_label)) . ' | Drupal')); - $this->drupalPostForm(NULL, array(), $delete_text); + $this->assertTitle(strip_tags(t('Are you sure you want to delete the custom block %label?', ['%label' => $new_label]) . ' | Drupal')); + $this->drupalPostForm(NULL, [], $delete_text); // Verify that the text of the label and machine name does not appear in // the list (though it may appear elsewhere on the page). diff --git a/core/modules/block_content/src/Tests/BlockContentListViewsTest.php b/core/modules/block_content/src/Tests/BlockContentListViewsTest.php index de0ff3bdeb..77117fb009 100644 --- a/core/modules/block_content/src/Tests/BlockContentListViewsTest.php +++ b/core/modules/block_content/src/Tests/BlockContentListViewsTest.php @@ -22,7 +22,7 @@ class BlockContentListViewsTest extends BlockContentTestBase { * Tests the custom block listing page. */ public function testListing() { - $this->drupalLogin($this->drupalCreateUser(array('administer blocks', 'translate configuration'))); + $this->drupalLogin($this->drupalCreateUser(['administer blocks', 'translate configuration'])); $this->drupalGet('admin/structure/block/block-content'); // Test for the page title. @@ -58,7 +58,7 @@ public function testListing() { $this->assertLink($link_text); $this->clickLink($link_text); $this->assertResponse(200); - $edit = array(); + $edit = []; $edit['info[0][value]'] = $label; $edit['body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm(NULL, $edit, t('Save')); @@ -79,14 +79,14 @@ public function testListing() { $blocks = $this->container ->get('entity.manager') ->getStorage('block_content') - ->loadByProperties(array('info' => $label)); + ->loadByProperties(['info' => $label]); $block = reset($blocks); if (!empty($block)) { $this->assertLinkByHref('block/' . $block->id()); $this->clickLink(t('Edit')); $this->assertResponse(200); - $this->assertTitle(strip_tags(t('Edit custom block %label', array('%label' => $label)) . ' | Drupal')); - $edit = array('info[0][value]' => $new_label); + $this->assertTitle(strip_tags(t('Edit custom block %label', ['%label' => $label]) . ' | Drupal')); + $edit = ['info[0][value]' => $new_label]; $this->drupalPostForm(NULL, $edit, t('Save')); } else { @@ -102,8 +102,8 @@ public function testListing() { $delete_text = t('Delete'); $this->clickLink($delete_text); $this->assertResponse(200); - $this->assertTitle(strip_tags(t('Are you sure you want to delete the custom block %label?', array('%label' => $new_label)) . ' | Drupal')); - $this->drupalPostForm(NULL, array(), $delete_text); + $this->assertTitle(strip_tags(t('Are you sure you want to delete the custom block %label?', ['%label' => $new_label]) . ' | Drupal')); + $this->drupalPostForm(NULL, [], $delete_text); // Verify that the text of the label and machine name does not appear in // the list (though it may appear elsewhere on the page). diff --git a/core/modules/block_content/src/Tests/BlockContentTestBase.php b/core/modules/block_content/src/Tests/BlockContentTestBase.php index 28c6e227ef..3794478d52 100644 --- a/core/modules/block_content/src/Tests/BlockContentTestBase.php +++ b/core/modules/block_content/src/Tests/BlockContentTestBase.php @@ -31,16 +31,16 @@ * * @var array */ - protected $permissions = array( + protected $permissions = [ 'administer blocks' - ); + ]; /** * Modules to enable. * * @var array */ - public static $modules = array('block', 'block_content'); + public static $modules = ['block', 'block_content']; /** * Whether or not to auto-create the basic block type during setup. @@ -78,11 +78,11 @@ protected function setUp() { */ protected function createBlockContent($title = FALSE, $bundle = 'basic', $save = TRUE) { $title = $title ?: $this->randomMachineName(); - $block_content = BlockContent::create(array( + $block_content = BlockContent::create([ 'info' => $title, 'type' => $bundle, 'langcode' => 'en' - )); + ]); if ($block_content && $save === TRUE) { $block_content->save(); } @@ -101,11 +101,11 @@ protected function createBlockContent($title = FALSE, $bundle = 'basic', $save = * Created custom block type. */ protected function createBlockContentType($label, $create_body = FALSE) { - $bundle = BlockContentType::create(array( + $bundle = BlockContentType::create([ 'id' => $label, 'label' => $label, 'revision' => FALSE, - )); + ]); $bundle->save(); if ($create_body) { block_content_add_body_field($bundle->id()); diff --git a/core/modules/block_content/src/Tests/BlockContentTranslationUITest.php b/core/modules/block_content/src/Tests/BlockContentTranslationUITest.php index 332bf3d734..198beee8fb 100644 --- a/core/modules/block_content/src/Tests/BlockContentTranslationUITest.php +++ b/core/modules/block_content/src/Tests/BlockContentTranslationUITest.php @@ -19,13 +19,13 @@ class BlockContentTranslationUITest extends ContentTranslationUITestBase { * * @var array */ - public static $modules = array( + public static $modules = [ 'language', 'content_translation', 'block', 'field_ui', 'block_content' - ); + ]; /** * {@inheritdoc} @@ -57,11 +57,11 @@ protected function setUp() { */ protected function setupBundle() { // Create the basic bundle since it is provided by standard. - $bundle = BlockContentType::create(array( + $bundle = BlockContentType::create([ 'id' => $this->bundle, 'label' => $this->bundle, 'revision' => FALSE - )); + ]); $bundle->save(); } @@ -69,12 +69,12 @@ protected function setupBundle() { * {@inheritdoc} */ public function getTranslatorPermissions() { - return array_merge(parent::getTranslatorPermissions(), array( + return array_merge(parent::getTranslatorPermissions(), [ 'translate any entity', 'access administration pages', 'administer blocks', 'administer block_content fields' - )); + ]); } /** @@ -93,11 +93,11 @@ public function getTranslatorPermissions() { protected function createBlockContent($title = FALSE, $bundle = FALSE) { $title = $title ?: $this->randomMachineName(); $bundle = $bundle ?: $this->bundle; - $block_content = BlockContent::create(array( + $block_content = BlockContent::create([ 'info' => $title, 'type' => $bundle, 'langcode' => 'en' - )); + ]); $block_content->save(); return $block_content; } @@ -106,7 +106,7 @@ protected function createBlockContent($title = FALSE, $bundle = FALSE) { * {@inheritdoc} */ protected function getNewEntityValues($langcode) { - return array('info' => Unicode::strtolower($this->randomMachineName())) + parent::getNewEntityValues($langcode); + return ['info' => Unicode::strtolower($this->randomMachineName())] + parent::getNewEntityValues($langcode); } /** @@ -135,7 +135,7 @@ protected function doTestBasicTranslation() { $values = $this->getNewEntityValues($default_langcode); $storage = \Drupal::entityManager()->getStorage($this->entityTypeId); /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ - $entity = $storage->create(array('type' => 'basic') + $values); + $entity = $storage->create(['type' => 'basic'] + $values); $entity->save(); $entity->addTranslation('it', $values); @@ -159,11 +159,11 @@ protected function doTestBasicTranslation() { public function testDisabledBundle() { // Create a bundle that does not have translation enabled. $disabled_bundle = $this->randomMachineName(); - $bundle = BlockContentType::create(array( + $bundle = BlockContentType::create([ 'id' => $disabled_bundle, 'label' => $disabled_bundle, 'revision' => FALSE - )); + ]); $bundle->save(); // Create a block content for each bundle. @@ -171,7 +171,7 @@ public function testDisabledBundle() { $disabled_block_content = $this->createBlockContent(FALSE, $bundle->id()); // Make sure that only a single row was inserted into the block table. - $rows = db_query('SELECT * FROM {block_content_field_data} WHERE id = :id', array(':id' => $enabled_block_content->id()))->fetchAll(); + $rows = db_query('SELECT * FROM {block_content_field_data} WHERE id = :id', [':id' => $enabled_block_content->id()])->fetchAll(); $this->assertEqual(1, count($rows)); } @@ -188,15 +188,15 @@ protected function doTestTranslationEdit() { foreach ($this->langcodes as $langcode) { // We only want to test the title for non-english translations. if ($langcode != 'en') { - $options = array('language' => $languages[$langcode]); + $options = ['language' => $languages[$langcode]]; $url = $entity->urlInfo('edit-form', $options); $this->drupalGet($url); - $title = t('Edit @type @title [%language translation]', array( + $title = t('Edit @type @title [%language translation]', [ '@type' => $entity->bundle(), '@title' => $entity->getTranslation($langcode)->label(), '%language' => $languages[$langcode]->getName(), - )); + ]); $this->assertRaw($title); } } diff --git a/core/modules/block_content/src/Tests/BlockContentTypeTest.php b/core/modules/block_content/src/Tests/BlockContentTypeTest.php index 8f6ffe19d8..e69394b883 100644 --- a/core/modules/block_content/src/Tests/BlockContentTypeTest.php +++ b/core/modules/block_content/src/Tests/BlockContentTypeTest.php @@ -17,17 +17,17 @@ class BlockContentTypeTest extends BlockContentTestBase { * * @var array */ - public static $modules = array('field_ui'); + public static $modules = ['field_ui']; /** * Permissions to grant admin user. * * @var array */ - protected $permissions = array( + protected $permissions = [ 'administer blocks', 'administer block_content fields' - ); + ]; /** * Whether or not to create an initial block type. @@ -56,10 +56,10 @@ public function testBlockContentTypeCreation() { $this->clickLink('block type creation page'); // Create a block type via the user interface. - $edit = array( + $edit = [ 'id' => 'foo', 'label' => 'title for foo', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); $block_type = BlockContentType::load('foo'); $this->assertTrue($block_type, 'The new block type has been created.'); @@ -107,9 +107,9 @@ public function testBlockContentTypeEditing() { $this->assertRaw('Body', 'Body field was found.'); // Change the block type name. - $edit = array( + $edit = [ 'label' => 'Bar', - ); + ]; $this->drupalGet('admin/structure/block/block-content/manage/basic'); $this->assertTitle(format_string('Edit @type custom block type | Drupal', ['@type' => 'basic'])); $this->drupalPostForm(NULL, $edit, t('Save')); @@ -121,9 +121,9 @@ public function testBlockContentTypeEditing() { $this->assertUrl(\Drupal::url('block_content.add_form', ['block_content_type' => 'basic'], ['absolute' => TRUE]), [], 'Original machine name was used in URL.'); // Remove the body field. - $this->drupalPostForm('admin/structure/block/block-content/manage/basic/fields/block_content.basic.body/delete', array(), t('Delete')); + $this->drupalPostForm('admin/structure/block/block-content/manage/basic/fields/block_content.basic.body/delete', [], t('Delete')); // Resave the settings for this type. - $this->drupalPostForm('admin/structure/block/block-content/manage/basic', array(), t('Save')); + $this->drupalPostForm('admin/structure/block/block-content/manage/basic', [], t('Save')); // Check that the body field doesn't exist. $this->drupalGet('block/add/basic'); $this->assertNoRaw('Body', 'Body field was not found.'); @@ -146,7 +146,7 @@ public function testBlockContentTypeDeletion() { // Attempt to delete the block type, which should not be allowed. $this->drupalGet('admin/structure/block/block-content/manage/' . $type->id() . '/delete'); $this->assertRaw( - t('%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', array('%label' => $type->label())), + t('%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', ['%label' => $type->label()]), 'The block type will not be deleted until all blocks of that type are removed.' ); $this->assertNoText(t('This action cannot be undone.'), 'The block type deletion confirmation form is not available.'); @@ -156,7 +156,7 @@ public function testBlockContentTypeDeletion() { // Attempt to delete the block type, which should now be allowed. $this->drupalGet('admin/structure/block/block-content/manage/' . $type->id() . '/delete'); $this->assertRaw( - t('Are you sure you want to delete the custom block type %type?', array('%type' => $type->id())), + t('Are you sure you want to delete the custom block type %type?', ['%type' => $type->id()]), 'The block type is available for deletion.' ); $this->assertText(t('This action cannot be undone.'), 'The custom block type deletion confirmation form is available.'); @@ -197,22 +197,22 @@ public function testsBlockContentAddTypes() { $this->clickLink(t('Add custom block')); // The seven theme has markup inside the link, we cannot use clickLink(). if ($default_theme == 'seven') { - $options = $theme != $default_theme ? array('query' => array('theme' => $theme)) : array(); - $this->assertLinkByHref(\Drupal::url('block_content.add_form', array('block_content_type' => 'foo'), $options)); + $options = $theme != $default_theme ? ['query' => ['theme' => $theme]] : []; + $this->assertLinkByHref(\Drupal::url('block_content.add_form', ['block_content_type' => 'foo'], $options)); $this->drupalGet('block/add/foo', $options); } else { $this->clickLink('foo'); } // Create a new block. - $edit = array('info[0][value]' => $this->randomMachineName(8)); + $edit = ['info[0][value]' => $this->randomMachineName(8)]; $this->drupalPostForm(NULL, $edit, t('Save')); - $blocks = $storage->loadByProperties(array('info' => $edit['info[0][value]'])); + $blocks = $storage->loadByProperties(['info' => $edit['info[0][value]']]); if (!empty($blocks)) { $block = reset($blocks); - $this->assertUrl(\Drupal::url('block.admin_add', array('plugin_id' => 'block_content:' . $block->uuid(), 'theme' => $theme), array('absolute' => TRUE))); + $this->assertUrl(\Drupal::url('block.admin_add', ['plugin_id' => 'block_content:' . $block->uuid(), 'theme' => $theme], ['absolute' => TRUE])); $this->drupalPostForm(NULL, ['region' => 'content'], t('Save block')); - $this->assertUrl(\Drupal::url('block.admin_display_theme', array('theme' => $theme), array('absolute' => TRUE, 'query' => array('block-placement' => Html::getClass($edit['info[0][value]']))))); + $this->assertUrl(\Drupal::url('block.admin_display_theme', ['theme' => $theme], ['absolute' => TRUE, 'query' => ['block-placement' => Html::getClass($edit['info[0][value]'])]])); } else { $this->fail('Could not load created block.'); @@ -225,11 +225,11 @@ public function testsBlockContentAddTypes() { $this->drupalGet('admin/structure/block/block-content'); $this->clickLink(t('Add custom block')); $this->clickLink('foo'); - $edit = array('info[0][value]' => $this->randomMachineName(8)); + $edit = ['info[0][value]' => $this->randomMachineName(8)]; $this->drupalPostForm(NULL, $edit, t('Save')); - $blocks = $storage->loadByProperties(array('info' => $edit['info[0][value]'])); + $blocks = $storage->loadByProperties(['info' => $edit['info[0][value]']]); if (!empty($blocks)) { - $this->assertUrl(\Drupal::url('entity.block_content.collection', array(), array('absolute' => TRUE))); + $this->assertUrl(\Drupal::url('entity.block_content.collection', [], ['absolute' => TRUE])); } else { $this->fail('Could not load created block.'); diff --git a/core/modules/block_content/src/Tests/Views/BlockContentFieldFilterTest.php b/core/modules/block_content/src/Tests/Views/BlockContentFieldFilterTest.php index 5a46dddd76..905a7a0053 100644 --- a/core/modules/block_content/src/Tests/Views/BlockContentFieldFilterTest.php +++ b/core/modules/block_content/src/Tests/Views/BlockContentFieldFilterTest.php @@ -15,14 +15,14 @@ class BlockContentFieldFilterTest extends BlockContentTestBase { /** * {@inheritdoc} */ - public static $modules = array('language'); + public static $modules = ['language']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_field_filters'); + public static $testViews = ['test_field_filters']; /** * List of block_content infos by language. @@ -49,15 +49,15 @@ function setUp() { $field_storage->save(); // Set up block_content infos. - $this->blockContentInfos = array( + $this->blockContentInfos = [ 'en' => 'Food in Paris', 'es' => 'Comida en Paris', 'fr' => 'Nouriture en Paris', - ); + ]; // Create block_content with translations. $block_content = $this->createBlockContent(['info' => $this->blockContentInfos['en'], 'langcode' => 'en', 'type' => 'basic', 'body' => [['value' => $this->blockContentInfos['en']]]]); - foreach (array('es', 'fr') as $langcode) { + foreach (['es', 'fr'] as $langcode) { $translation = $block_content->addTranslation($langcode, ['info' => $this->blockContentInfos[$langcode]]); $translation->body->value = $this->blockContentInfos[$langcode]; } @@ -70,19 +70,19 @@ function setUp() { public function testFilters() { // Test the info filter page, which filters for info contains 'Comida'. // Should show just the Spanish translation, once. - $this->assertPageCounts('test-info-filter', array('es' => 1, 'fr' => 0, 'en' => 0), 'Comida info filter'); + $this->assertPageCounts('test-info-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida info filter'); // Test the body filter page, which filters for body contains 'Comida'. // Should show just the Spanish translation, once. - $this->assertPageCounts('test-body-filter', array('es' => 1, 'fr' => 0, 'en' => 0), 'Comida body filter'); + $this->assertPageCounts('test-body-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida body filter'); // Test the info Paris filter page, which filters for info contains // 'Paris'. Should show each translation once. - $this->assertPageCounts('test-info-paris', array('es' => 1, 'fr' => 1, 'en' => 1), 'Paris info filter'); + $this->assertPageCounts('test-info-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris info filter'); // Test the body Paris filter page, which filters for body contains // 'Paris'. Should show each translation once. - $this->assertPageCounts('test-body-paris', array('es' => 1, 'fr' => 1, 'en' => 1), 'Paris body filter'); + $this->assertPageCounts('test-body-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris body filter'); } /** diff --git a/core/modules/block_content/src/Tests/Views/BlockContentIntegrationTest.php b/core/modules/block_content/src/Tests/Views/BlockContentIntegrationTest.php index d92c5beb4f..8ec17e2381 100644 --- a/core/modules/block_content/src/Tests/Views/BlockContentIntegrationTest.php +++ b/core/modules/block_content/src/Tests/Views/BlockContentIntegrationTest.php @@ -14,23 +14,23 @@ class BlockContentIntegrationTest extends BlockContentTestBase { * * @var array */ - public static $testViews = array('test_block_content_view'); + public static $testViews = ['test_block_content_view']; /** * Tests basic block_content view with a block_content_type argument. */ public function testBlockContentViewTypeArgument() { // Create two content types with three block_contents each. - $types = array(); - $all_ids = array(); - $block_contents = array(); + $types = []; + $all_ids = []; + $block_contents = []; for ($i = 0; $i < 2; $i++) { $type = $this->createBlockContentType(); $types[] = $type; for ($j = 0; $j < 5; $j++) { // Ensure the right order of the block_contents. - $block_content = $this->createBlockContent(array('type' => $type->id())); + $block_content = $this->createBlockContent(['type' => $type->id()]); $block_contents[$type->id()][$block_content->id()] = $block_content; $all_ids[] = $block_content->id(); } @@ -55,9 +55,9 @@ public function testBlockContentViewTypeArgument() { * @param array $expected_ids * An array of block_content IDs. */ - protected function assertIds(array $expected_ids = array()) { + protected function assertIds(array $expected_ids = []) { $result = $this->xpath('//span[@class="field-content"]'); - $ids = array(); + $ids = []; foreach ($result as $element) { $ids[] = (int) $element; } diff --git a/core/modules/block_content/src/Tests/Views/BlockContentRedirectTest.php b/core/modules/block_content/src/Tests/Views/BlockContentRedirectTest.php index ff80665b57..828aa8468b 100644 --- a/core/modules/block_content/src/Tests/Views/BlockContentRedirectTest.php +++ b/core/modules/block_content/src/Tests/Views/BlockContentRedirectTest.php @@ -21,18 +21,18 @@ class BlockContentRedirectTest extends BlockContentTestBase { * * @var array */ - public static $modules = array('block', 'block_content', 'views'); + public static $modules = ['block', 'block_content', 'views']; /** * Tests the redirect destination when editing block content. */ public function testRedirectDestination() { - $this->drupalLogin($this->drupalCreateUser(array('administer blocks'))); + $this->drupalLogin($this->drupalCreateUser(['administer blocks'])); $this->drupalGet('admin/structure/block/block-content'); // Create a custom block. $this->clickLink('custom block'); - $edit = array(); + $edit = []; $edit['info[0][value]'] = 'Test redirect destination'; $edit['body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm(NULL, $edit, 'Save'); diff --git a/core/modules/block_content/src/Tests/Views/BlockContentTestBase.php b/core/modules/block_content/src/Tests/Views/BlockContentTestBase.php index 65d33c88b1..db665c9e45 100644 --- a/core/modules/block_content/src/Tests/Views/BlockContentTestBase.php +++ b/core/modules/block_content/src/Tests/Views/BlockContentTestBase.php @@ -25,26 +25,26 @@ * * @var array */ - protected $permissions = array( + protected $permissions = [ 'administer blocks', - ); + ]; /** * Modules to enable. * * @var array */ - public static $modules = array('block', 'block_content', 'block_content_test_views'); + public static $modules = ['block', 'block_content', 'block_content_test_views']; protected function setUp($import_test_views = TRUE) { parent::setUp($import_test_views); // Ensure the basic bundle exists. This is provided by the standard profile. - $this->createBlockContentType(array('id' => 'basic')); + $this->createBlockContentType(['id' => 'basic']); $this->adminUser = $this->drupalCreateUser($this->permissions); if ($import_test_views) { - ViewTestData::createTestViews(get_class($this), array('block_content_test_views')); + ViewTestData::createTestViews(get_class($this), ['block_content_test_views']); } } @@ -58,17 +58,17 @@ protected function setUp($import_test_views = TRUE) { * @return \Drupal\block_content\Entity\BlockContent * Created custom block. */ - protected function createBlockContent(array $settings = array()) { + protected function createBlockContent(array $settings = []) { $status = 0; - $settings += array( + $settings += [ 'info' => $this->randomMachineName(), 'type' => 'basic', 'langcode' => 'en', - ); + ]; if ($block_content = BlockContent::create($settings)) { $status = $block_content->save(); } - $this->assertEqual($status, SAVED_NEW, SafeMarkup::format('Created block content %info.', array('%info' => $block_content->label()))); + $this->assertEqual($status, SAVED_NEW, SafeMarkup::format('Created block content %info.', ['%info' => $block_content->label()])); return $block_content; } @@ -81,7 +81,7 @@ protected function createBlockContent(array $settings = array()) { * @return \Drupal\block_content\Entity\BlockContentType * Created custom block type. */ - protected function createBlockContentType(array $values = array()) { + protected function createBlockContentType(array $values = []) { // Find a non-existent random type name. if (!isset($values['id'])) { do { @@ -91,16 +91,16 @@ protected function createBlockContentType(array $values = array()) { else { $id = $values['id']; } - $values += array( + $values += [ 'id' => $id, 'label' => $id, 'revision' => FALSE - ); + ]; $bundle = BlockContentType::create($values); $status = $bundle->save(); block_content_add_body_field($bundle->id()); - $this->assertEqual($status, SAVED_NEW, SafeMarkup::format('Created block content type %bundle.', array('%bundle' => $bundle->id()))); + $this->assertEqual($status, SAVED_NEW, SafeMarkup::format('Created block content type %bundle.', ['%bundle' => $bundle->id()])); return $bundle; } diff --git a/core/modules/block_content/src/Tests/Views/FieldTypeTest.php b/core/modules/block_content/src/Tests/Views/FieldTypeTest.php index f14653fea3..e9aa336985 100644 --- a/core/modules/block_content/src/Tests/Views/FieldTypeTest.php +++ b/core/modules/block_content/src/Tests/Views/FieldTypeTest.php @@ -16,18 +16,18 @@ class FieldTypeTest extends BlockContentTestBase { * * @var array */ - public static $testViews = array('test_field_type'); + public static $testViews = ['test_field_type']; public function testFieldType() { $block_content = $this->createBlockContent(); - $expected_result[] = array( + $expected_result[] = [ 'id' => $block_content->id(), 'type' => $block_content->bundle(), - ); - $column_map = array( + ]; + $column_map = [ 'id' => 'id', 'type:target_id' => 'type', - ); + ]; $view = Views::getView('test_field_type'); $this->executeView($view); diff --git a/core/modules/block_content/src/Tests/Views/RevisionRelationshipsTest.php b/core/modules/block_content/src/Tests/Views/RevisionRelationshipsTest.php index 516705d2b2..7bad093dd3 100644 --- a/core/modules/block_content/src/Tests/Views/RevisionRelationshipsTest.php +++ b/core/modules/block_content/src/Tests/Views/RevisionRelationshipsTest.php @@ -20,72 +20,72 @@ class RevisionRelationshipsTest extends ViewTestBase { * * @var array */ - public static $modules = array('block_content' , 'block_content_test_views'); + public static $modules = ['block_content' , 'block_content_test_views']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_block_content_revision_id', 'test_block_content_revision_revision_id'); + public static $testViews = ['test_block_content_revision_id', 'test_block_content_revision_revision_id']; protected function setUp() { parent::setUp(); - BlockContentType::create(array( + BlockContentType::create([ 'id' => 'basic', 'label' => 'basic', 'revision' => TRUE, - )); - ViewTestData::createTestViews(get_class($this), array('block_content_test_views')); + ]); + ViewTestData::createTestViews(get_class($this), ['block_content_test_views']); } /** * Create a block_content with revision and rest result count for both views. */ public function testBlockContentRevisionRelationship() { - $block_content = BlockContent::create(array( + $block_content = BlockContent::create([ 'info' => $this->randomMachineName(), 'type' => 'basic', 'langcode' => 'en', - )); + ]); $block_content->save(); // Create revision of the block_content. $block_content_revision = clone $block_content; $block_content_revision->setNewRevision(); $block_content_revision->save(); - $column_map = array( + $column_map = [ 'revision_id' => 'revision_id', 'id_1' => 'id_1', 'block_content_field_data_block_content_field_revision_id' => 'block_content_field_data_block_content_field_revision_id', - ); + ]; // Here should be two rows. $view_id = Views::getView('test_block_content_revision_id'); - $this->executeView($view_id, array($block_content->id())); - $resultset_id = array( - array( + $this->executeView($view_id, [$block_content->id()]); + $resultset_id = [ + [ 'revision_id' => '1', 'id_1' => '1', 'block_content_field_data_block_content_field_revision_id' => '1', - ), - array( + ], + [ 'revision_id' => '2', 'id_1' => '1', 'block_content_field_data_block_content_field_revision_id' => '1', - ), - ); + ], + ]; $this->assertIdenticalResultset($view_id, $resultset_id, $column_map); // There should be only one row with active revision 2. $view_revision_id = Views::getView('test_block_content_revision_revision_id'); - $this->executeView($view_revision_id, array($block_content->id())); - $resultset_revision_id = array( - array( + $this->executeView($view_revision_id, [$block_content->id()]); + $resultset_revision_id = [ + [ 'revision_id' => '2', 'id_1' => '1', 'block_content_field_data_block_content_field_revision_id' => '1', - ), - ); + ], + ]; $this->assertIdenticalResultset($view_revision_id, $resultset_revision_id, $column_map); } diff --git a/core/modules/block_content/tests/modules/block_content_test/block_content_test.module b/core/modules/block_content/tests/modules/block_content_test/block_content_test.module index 57ea2a6864..0489a617b6 100644 --- a/core/modules/block_content/tests/modules/block_content_test/block_content_test.module +++ b/core/modules/block_content/tests/modules/block_content_test/block_content_test.module @@ -15,9 +15,9 @@ */ function block_content_test_block_content_view(array &$build, BlockContent $block_content, $view_mode) { // Add extra content. - $build['extra_content'] = array( + $build['extra_content'] = [ '#markup' => 'Yowser', - ); + ]; } /** diff --git a/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php b/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php index f44a773bfd..e00de6b5a9 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php @@ -20,29 +20,29 @@ class BlockContentCacheTagsTest extends EntityCacheTagsTestBase { /** * {@inheritdoc} */ - public static $modules = array('block_content'); + public static $modules = ['block_content']; /** * {@inheritdoc} */ protected function createEntity() { - $block_content_type = BlockContentType::create(array( + $block_content_type = BlockContentType::create([ 'id' => 'basic', 'label' => 'basic', 'revision' => FALSE - )); + ]); $block_content_type->save(); block_content_add_body_field($block_content_type->id()); // Create a "Llama" custom block. - $block_content = BlockContent::create(array( + $block_content = BlockContent::create([ 'info' => 'Llama', 'type' => 'basic', - 'body' => array( + 'body' => [ 'value' => 'The name "llama" was adopted by European settlers from native Peruvians.', 'format' => 'plain_text', - ), - )); + ], + ]); $block_content->save(); return $block_content; diff --git a/core/modules/block_content/tests/src/Functional/BlockContentPageViewTest.php b/core/modules/block_content/tests/src/Functional/BlockContentPageViewTest.php index 8c55da3c0c..355faf1f0f 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentPageViewTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentPageViewTest.php @@ -14,7 +14,7 @@ class BlockContentPageViewTest extends BlockContentTestBase { * * @var array */ - public static $modules = array('block_content_test'); + public static $modules = ['block_content_test']; /** * Checks block edit and fallback functionality. diff --git a/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php b/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php index 33f75ed4fa..fa88c64c26 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php @@ -37,8 +37,8 @@ protected function setUp() { // Create initial block. $block = $this->createBlockContent('initial'); - $blocks = array(); - $logs = array(); + $blocks = []; + $logs = []; // Get original block. $blocks[] = $block->getRevisionId(); @@ -74,9 +74,9 @@ public function testRevisions() { ->getStorage('block_content') ->loadRevision($revision_id); // Verify revision log is the same. - $this->assertEqual($loaded->getRevisionLogMessage(), $logs[$delta], format_string('Correct log message found for revision @revision', array( + $this->assertEqual($loaded->getRevisionLogMessage(), $logs[$delta], format_string('Correct log message found for revision @revision', [ '@revision' => $loaded->getRevisionId(), - ))); + ])); if ($delta > 0) { $this->assertTrue($loaded->getRevisionUser() instanceof UserInterface, 'Revision User found.'); $this->assertTrue(is_numeric($loaded->getRevisionUserId()), 'Revision User ID found.'); diff --git a/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php b/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php index a68f4233df..0f7ae5a2e6 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php @@ -16,7 +16,7 @@ class BlockContentSaveTest extends BlockContentTestBase { * * @var array */ - public static $modules = array('block_content_test'); + public static $modules = ['block_content_test']; /** * Sets the test up. @@ -35,12 +35,12 @@ public function testImport() { $max_id = db_query('SELECT MAX(id) FROM {block_content}')->fetchField(); $test_id = $max_id + mt_rand(1000, 1000000); $info = $this->randomMachineName(8); - $block_array = array( + $block_array = [ 'info' => $info, - 'body' => array('value' => $this->randomMachineName(32)), + 'body' => ['value' => $this->randomMachineName(32)], 'type' => 'basic', 'id' => $test_id - ); + ]; $block = BlockContent::create($block_array); $block->enforceIsNew(TRUE); $block->save(); diff --git a/core/modules/block_content/tests/src/Functional/BlockContentTestBase.php b/core/modules/block_content/tests/src/Functional/BlockContentTestBase.php index e5e7736409..45c7e26999 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentTestBase.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentTestBase.php @@ -28,16 +28,16 @@ * * @var array */ - protected $permissions = array( + protected $permissions = [ 'administer blocks' - ); + ]; /** * Modules to enable. * * @var array */ - public static $modules = array('block', 'block_content'); + public static $modules = ['block', 'block_content']; /** * Whether or not to auto-create the basic block type during setup. @@ -75,11 +75,11 @@ protected function setUp() { */ protected function createBlockContent($title = FALSE, $bundle = 'basic', $save = TRUE) { $title = $title ?: $this->randomMachineName(); - $block_content = BlockContent::create(array( + $block_content = BlockContent::create([ 'info' => $title, 'type' => $bundle, 'langcode' => 'en' - )); + ]); if ($block_content && $save === TRUE) { $block_content->save(); } @@ -98,11 +98,11 @@ protected function createBlockContent($title = FALSE, $bundle = 'basic', $save = * Created custom block type. */ protected function createBlockContentType($label, $create_body = FALSE) { - $bundle = BlockContentType::create(array( + $bundle = BlockContentType::create([ 'id' => $label, 'label' => $label, 'revision' => FALSE, - )); + ]); $bundle->save(); if ($create_body) { block_content_add_body_field($bundle->id()); diff --git a/core/modules/block_content/tests/src/Functional/PageEditTest.php b/core/modules/block_content/tests/src/Functional/PageEditTest.php index bab2a2992b..41638bd2bc 100644 --- a/core/modules/block_content/tests/src/Functional/PageEditTest.php +++ b/core/modules/block_content/tests/src/Functional/PageEditTest.php @@ -27,7 +27,7 @@ public function testPageEdit() { $title_key = 'info[0][value]'; $body_key = 'body[0][value]'; // Create block to edit. - $edit = array(); + $edit = []; $edit['info[0][value]'] = Unicode::strtolower($this->randomMachineName(8)); $edit[$body_key] = $this->randomMachineName(16); $this->drupalPostForm('block/add/basic', $edit, t('Save')); @@ -43,7 +43,7 @@ public function testPageEdit() { $this->assertFieldByName($body_key, $edit[$body_key], 'Body field displayed.'); // Edit the content of the block. - $edit = array(); + $edit = []; $edit[$title_key] = $this->randomMachineName(8); $edit[$body_key] = $this->randomMachineName(16); // Stay on the current page, without reloading. @@ -51,21 +51,21 @@ public function testPageEdit() { // Edit the same block, creating a new revision. $this->drupalGet("block/" . $block->id()); - $edit = array(); + $edit = []; $edit['info[0][value]'] = $this->randomMachineName(8); $edit[$body_key] = $this->randomMachineName(16); $edit['revision'] = TRUE; $this->drupalPostForm(NULL, $edit, t('Save')); // Ensure that the block revision has been created. - \Drupal::entityManager()->getStorage('block_content')->resetCache(array($block->id())); + \Drupal::entityManager()->getStorage('block_content')->resetCache([$block->id()]); $revised_block = BlockContent::load($block->id()); $this->assertNotIdentical($block->getRevisionId(), $revised_block->getRevisionId(), 'A new revision has been created.'); // Test deleting the block. $this->drupalGet("block/" . $revised_block->id()); $this->clickLink(t('Delete')); - $this->assertText(format_string('Are you sure you want to delete the custom block @label?', array('@label' => $revised_block->label()))); + $this->assertText(format_string('Are you sure you want to delete the custom block @label?', ['@label' => $revised_block->label()])); } } diff --git a/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentBodyFieldTest.php b/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentBodyFieldTest.php index 0bf29fdc6a..7d343738c9 100644 --- a/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentBodyFieldTest.php +++ b/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentBodyFieldTest.php @@ -15,7 +15,7 @@ */ class MigrateBlockContentBodyFieldTest extends MigrateDrupal7TestBase { - public static $modules = array('block', 'block_content', 'filter', 'text'); + public static $modules = ['block', 'block_content', 'filter', 'text']; /** * {@inheritdoc} diff --git a/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentTypeTest.php b/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentTypeTest.php index 9a3cbf0466..4accc2040b 100644 --- a/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentTypeTest.php +++ b/core/modules/block_content/tests/src/Kernel/Migrate/MigrateBlockContentTypeTest.php @@ -13,7 +13,7 @@ */ class MigrateBlockContentTypeTest extends MigrateDrupal7TestBase { - public static $modules = array('block', 'block_content', 'filter', 'text'); + public static $modules = ['block', 'block_content', 'filter', 'text']; /** * {@inheritdoc} diff --git a/core/modules/block_content/tests/src/Kernel/Migrate/d7/MigrateCustomBlockTest.php b/core/modules/block_content/tests/src/Kernel/Migrate/d7/MigrateCustomBlockTest.php index 42990db760..706a7ccf05 100644 --- a/core/modules/block_content/tests/src/Kernel/Migrate/d7/MigrateCustomBlockTest.php +++ b/core/modules/block_content/tests/src/Kernel/Migrate/d7/MigrateCustomBlockTest.php @@ -13,11 +13,11 @@ */ class MigrateCustomBlockTest extends MigrateDrupal7TestBase { - public static $modules = array( + public static $modules = [ 'block_content', 'filter', 'text', - ); + ]; /** * {@inheritdoc} diff --git a/core/modules/block_content/tests/src/Unit/Menu/BlockContentLocalTasksTest.php b/core/modules/block_content/tests/src/Unit/Menu/BlockContentLocalTasksTest.php index 3ab934c0a2..ced7e84c30 100644 --- a/core/modules/block_content/tests/src/Unit/Menu/BlockContentLocalTasksTest.php +++ b/core/modules/block_content/tests/src/Unit/Menu/BlockContentLocalTasksTest.php @@ -13,32 +13,32 @@ class BlockContentLocalTasksTest extends LocalTaskIntegrationTestBase { protected function setUp() { - $this->directoryList = array( + $this->directoryList = [ 'block' => 'core/modules/block', 'block_content' => 'core/modules/block_content', - ); + ]; parent::setUp(); - $config_factory = $this->getConfigFactoryStub(array('system.theme' => array( + $config_factory = $this->getConfigFactoryStub(['system.theme' => [ 'default' => 'test_c', - ))); + ]]); - $themes = array(); - $themes['test_a'] = (object) array( + $themes = []; + $themes['test_a'] = (object) [ 'status' => 0, - ); - $themes['test_b'] = (object) array( + ]; + $themes['test_b'] = (object) [ 'status' => 1, - 'info' => array( + 'info' => [ 'name' => 'test_b', - ), - ); - $themes['test_c'] = (object) array( + ], + ]; + $themes['test_c'] = (object) [ 'status' => 1, - 'info' => array( + 'info' => [ 'name' => 'test_c', - ), - ); + ], + ]; $theme_handler = $this->getMock('Drupal\Core\Extension\ThemeHandlerInterface'); $theme_handler->expects($this->any()) ->method('listInfo') @@ -56,25 +56,25 @@ protected function setUp() { * @dataProvider getBlockContentListingRoutes */ public function testBlockContentListLocalTasks($route) { - $this->assertLocalTasks($route, array( - 0 => array( + $this->assertLocalTasks($route, [ + 0 => [ 'block.admin_display', 'entity.block_content.collection', - ), - 1 => array( + ], + 1 => [ 'block_content.list_sub', 'entity.block_content_type.collection', - ), - )); + ], + ]); } /** * Provides a list of routes to test. */ public function getBlockContentListingRoutes() { - return array( - array('entity.block_content.collection', 'entity.block_content_type.collection'), - ); + return [ + ['entity.block_content.collection', 'entity.block_content_type.collection'], + ]; } } diff --git a/core/modules/book/book.install b/core/modules/book/book.install index 76ddc81ed0..7704483365 100644 --- a/core/modules/book/book.install +++ b/core/modules/book/book.install @@ -17,119 +17,119 @@ function book_uninstall() { * Implements hook_schema(). */ function book_schema() { - $schema['book'] = array( + $schema['book'] = [ 'description' => 'Stores book outline information. Uniquely defines the location of each node in the book outline', - 'fields' => array( - 'nid' => array( + 'fields' => [ + 'nid' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => "The book page's {node}.nid.", - ), - 'bid' => array( + ], + 'bid' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => "The book ID is the {book}.nid of the top-level page.", - ), - 'pid' => array( + ], + 'pid' => [ 'description' => 'The parent ID (pid) is the id of the node above in the hierarchy, or zero if the node is at the top level in its outline.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'has_children' => array( + ], + 'has_children' => [ 'description' => 'Flag indicating whether any nodes have this node as a parent (1 = children exist, 0 = no children).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, 'size' => 'small', - ), - 'weight' => array( + ], + 'weight' => [ 'description' => 'Weight among book entries in the same book at the same depth.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, - ), - 'depth' => array( + ], + 'depth' => [ 'description' => 'The depth relative to the top level. A link with pid == 0 will have depth == 1.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, 'size' => 'small', - ), - 'p1' => array( + ], + 'p1' => [ 'description' => 'The first nid in the materialized path. If N = depth, then pN must equal the nid. If depth > 1 then p(N-1) must equal the pid. All pX where X > depth must equal zero. The columns p1 .. p9 are also called the parents.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p2' => array( + ], + 'p2' => [ 'description' => 'The second nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p3' => array( + ], + 'p3' => [ 'description' => 'The third nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p4' => array( + ], + 'p4' => [ 'description' => 'The fourth nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p5' => array( + ], + 'p5' => [ 'description' => 'The fifth nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p6' => array( + ], + 'p6' => [ 'description' => 'The sixth nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p7' => array( + ], + 'p7' => [ 'description' => 'The seventh nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p8' => array( + ], + 'p8' => [ 'description' => 'The eighth nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - 'p9' => array( + ], + 'p9' => [ 'description' => 'The ninth nid in the materialized path. See p1.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, - ), - ), - 'primary key' => array('nid'), - 'indexes' => array( - 'book_parents' => array('bid', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9'), - ), - ); + ], + ], + 'primary key' => ['nid'], + 'indexes' => [ + 'book_parents' => ['bid', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9'], + ], + ]; return $schema; } diff --git a/core/modules/book/book.module b/core/modules/book/book.module index ecccb74527..988201ee1e 100644 --- a/core/modules/book/book.module +++ b/core/modules/book/book.module @@ -25,17 +25,17 @@ function book_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.book': $output = '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Book module is used for creating structured, multi-page content, such as site resource guides, manuals, and wikis. It allows you to create content that has chapters, sections, subsections, or any similarly-tiered structure. Enabling the module creates a new content type Book page. For more information, see the online documentation for the Book module.', array(':book' => 'https://www.drupal.org/documentation/modules/book')) . '

        '; + $output .= '

        ' . t('The Book module is used for creating structured, multi-page content, such as site resource guides, manuals, and wikis. It allows you to create content that has chapters, sections, subsections, or any similarly-tiered structure. Enabling the module creates a new content type Book page. For more information, see the online documentation for the Book module.', [':book' => 'https://www.drupal.org/documentation/modules/book']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Adding and managing book content') . '
        '; $output .= '
        ' . t('Books have a hierarchical structure, called a book outline. Each book outline can have nested pages up to nine levels deep. Multiple content types can be configured to behave as a book outline. From the content edit form, it is possible to add a page to a book outline or create a new book.') . '
        '; - $output .= '
        ' . t('You can assign separate permissions for creating new books as well as creating, editing and deleting book content. Users with the Administer book outlines permission can add any type of content to a book by selecting the appropriate book outline while editing the content. They can also view a list of all books, and edit and rearrange section titles on the Book list page.', array(':admin-book' => \Drupal::url('book.admin'))) . '
        '; + $output .= '
        ' . t('You can assign separate permissions for creating new books as well as creating, editing and deleting book content. Users with the Administer book outlines permission can add any type of content to a book by selecting the appropriate book outline while editing the content. They can also view a list of all books, and edit and rearrange section titles on the Book list page.', [':admin-book' => \Drupal::url('book.admin')]) . '
        '; $output .= '
        ' . t('Configuring content types for books') . '
        '; - $output .= '
        ' . t('The Book page content type is the initial content type enabled for book outlines. On the Book settings page you can configure content types that can used in book outlines.', array(':admin-settings' => \Drupal::url('book.settings'))) . '
        '; - $output .= '
        ' . t('Users with the Add content and child pages to books permission will see a link to Add child page when viewing a content item that is part of a book outline. This link will allow users to create a new content item of the content type you select on the Book settings page. By default this is the Book page content type.', array(':admin-settings' => \Drupal::url('book.settings'))) . '
        '; + $output .= '
        ' . t('The Book page content type is the initial content type enabled for book outlines. On the Book settings page you can configure content types that can used in book outlines.', [':admin-settings' => \Drupal::url('book.settings')]) . '
        '; + $output .= '
        ' . t('Users with the Add content and child pages to books permission will see a link to Add child page when viewing a content item that is part of a book outline. This link will allow users to create a new content item of the content type you select on the Book settings page. By default this is the Book page content type.', [':admin-settings' => \Drupal::url('book.settings')]) . '
        '; $output .= '
        ' . t('Book navigation') . '
        '; - $output .= '
        ' . t("Book pages have a default book-specific navigation block. This navigation block contains links that lead to the previous and next pages in the book, and to the level above the current page in the book's structure. This block can be enabled on the Blocks layout page. For book pages to show up in the book navigation, they must be added to a book outline.", array(':admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '
        '; + $output .= '
        ' . t("Book pages have a default book-specific navigation block. This navigation block contains links that lead to the previous and next pages in the book, and to the level above the current page in the book's structure. This block can be enabled on the Blocks layout page. For book pages to show up in the book navigation, they must be added to a book outline.", [':admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '
        '; $output .= '
        ' . t('Collaboration') . '
        '; $output .= '
        ' . t('Books can be created collaboratively, as they allow users with appropriate permissions to add pages into existing books, and add those pages to a custom table of contents.') . '
        '; $output .= '
        ' . t('Printing books') . '
        '; @@ -47,7 +47,7 @@ function book_help($route_name, RouteMatchInterface $route_match) { return '

        ' . t('The book module offers a means to organize a collection of related content pages, collectively known as a book. When viewed, this content automatically displays links to adjacent book pages, providing a simple navigation system for creating and reviewing structured content.') . '

        '; case 'entity.node.book_outline_form': - return '

        ' . t('The outline feature allows you to include pages in the Book hierarchy, as well as move them within the hierarchy or to reorder an entire book.', array(':book' => \Drupal::url('book.render'), ':book-admin' => \Drupal::url('book.admin'))) . '

        '; + return '

        ' . t('The outline feature allows you to include pages in the Book hierarchy, as well as move them within the hierarchy or to reorder an entire book.', [':book' => \Drupal::url('book.render'), ':book-admin' => \Drupal::url('book.admin')]) . '

        '; } } @@ -55,23 +55,23 @@ function book_help($route_name, RouteMatchInterface $route_match) { * Implements hook_theme(). */ function book_theme() { - return array( - 'book_navigation' => array( - 'variables' => array('book_link' => NULL), - ), - 'book_tree' => array( - 'variables' => array('items' => array(), 'attributes' => array()), - ), - 'book_export_html' => array( - 'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL), - ), - 'book_all_books_block' => array( + return [ + 'book_navigation' => [ + 'variables' => ['book_link' => NULL], + ], + 'book_tree' => [ + 'variables' => ['items' => [], 'attributes' => []], + ], + 'book_export_html' => [ + 'variables' => ['title' => NULL, 'contents' => NULL, 'depth' => NULL], + ], + 'book_all_books_block' => [ 'render element' => 'book_menus', - ), - 'book_node_export_html' => array( - 'variables' => array('node' => NULL, 'content' => NULL, 'children' => NULL), - ), - ); + ], + 'book_node_export_html' => [ + 'variables' => ['node' => NULL, 'content' => NULL, 'children' => NULL], + ], + ]; } /** @@ -97,31 +97,31 @@ function book_node_links_alter(array &$links, NodeInterface $node, array &$conte $child_type = \Drupal::config('book.settings')->get('child_type'); $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node'); if (($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines')) && $access_control_handler->createAccess($child_type) && $node->isPublished() && $node->book['depth'] < BookManager::BOOK_MAX_DEPTH) { - $book_links['book_add_child'] = array( + $book_links['book_add_child'] = [ 'title' => t('Add child page'), 'url' => Url::fromRoute('node.add', ['node_type' => $child_type], ['query' => ['parent' => $node->id()]]), - ); + ]; } if ($account->hasPermission('access printer-friendly version')) { - $book_links['book_printer'] = array( + $book_links['book_printer'] = [ 'title' => t('Printer-friendly version'), 'url' => Url::fromRoute('book.export', [ 'type' => 'html', 'node' => $node->id(), ]), - 'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.')) - ); + 'attributes' => ['title' => t('Show a printer-friendly version of this book page and its sub-pages.')] + ]; } } } if (!empty($book_links)) { - $links['book'] = array( + $links['book'] = [ '#theme' => 'links__node__book', '#links' => $book_links, - '#attributes' => array('class' => array('links', 'inline')), - ); + '#attributes' => ['class' => ['links', 'inline']], + ]; } } } @@ -148,17 +148,17 @@ function book_form_node_form_alter(&$form, FormStateInterface $form_state, $form $collapsed = !($node->isNew() && !empty($node->book['pid'])); $form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account, $collapsed); // The "js-hide" class hides submit button when Javascript is enabled. - $form['book']['pick-book'] = array( + $form['book']['pick-book'] = [ '#type' => 'submit', '#value' => t('Change book (update list of parents)'), - '#submit' => array('book_pick_book_nojs_submit'), + '#submit' => ['book_pick_book_nojs_submit'], '#weight' => 20, - '#attributes' => array( - 'class' => array( + '#attributes' => [ + 'class' => [ 'js-hide', - ), - ), - ); + ], + ], + ]; $form['#entity_builders'][] = 'book_node_builder'; } } @@ -232,7 +232,7 @@ function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayI if (!$book_node->access()) { return; } - $build['book_navigation'] = array( + $build['book_navigation'] = [ '#theme' => 'book_navigation', '#book_link' => $node->book, '#weight' => 100, @@ -241,7 +241,7 @@ function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayI '#cache' => [ 'tags' => $node->getEntityType()->getListCacheTags(), ], - ); + ]; } } } @@ -295,7 +295,7 @@ function book_node_prepare_form(NodeInterface $node, $operation, FormStateInterf // Prepare defaults for the add/edit form. $account = \Drupal::currentUser(); if (empty($node->book) && ($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines'))) { - $node->book = array(); + $node->book = []; $query = \Drupal::request()->query; if ($node->isNew() && !is_null($query->get('parent')) && is_numeric($query->get('parent'))) { @@ -341,10 +341,10 @@ function book_form_node_confirm_form_alter(&$form, FormStateInterface $form_stat } if (isset($node->book) && $node->book['has_children']) { - $form['book_warning'] = array( - '#markup' => '

        ' . t('%title is part of a book outline, and has associated child pages. If you proceed with deletion, the child pages will be relocated automatically.', array('%title' => $node->label())) . '

        ', + $form['book_warning'] = [ + '#markup' => '

        ' . t('%title is part of a book outline, and has associated child pages. If you proceed with deletion, the child pages will be relocated automatically.', ['%title' => $node->label()]) . '

        ', '#weight' => -10, - ); + ]; } } @@ -365,13 +365,13 @@ function book_form_node_confirm_form_alter(&$form, FormStateInterface $form_stat function template_preprocess_book_all_books_block(&$variables) { // Remove all non-renderable elements. $elements = $variables['book_menus']; - $variables['book_menus'] = array(); + $variables['book_menus'] = []; foreach (Element::children($elements) as $index) { - $variables['book_menus'][] = array( + $variables['book_menus'][] = [ 'id' => $index, 'menu' => $elements[$index], 'title' => $elements[$index]['#book_title'], - ); + ]; } } @@ -391,7 +391,7 @@ function template_preprocess_book_navigation(&$variables) { // Provide extra variables for themers. Not needed by default. $variables['book_id'] = $book_link['bid']; $variables['book_title'] = $book_link['link_title']; - $variables['book_url'] = \Drupal::url('entity.node.canonical', array('node' => $book_link['bid'])); + $variables['book_url'] = \Drupal::url('entity.node.canonical', ['node' => $book_link['bid']]); $variables['current_depth'] = $book_link['depth']; $variables['tree'] = ''; @@ -401,14 +401,14 @@ function template_preprocess_book_navigation(&$variables) { if ($book_link['nid']) { $variables['tree'] = $book_outline->childrenLinks($book_link); - $build = array(); + $build = []; if ($prev = $book_outline->prevLink($book_link)) { - $prev_href = \Drupal::url('entity.node.canonical', array('node' => $prev['nid'])); - $build['#attached']['html_head_link'][][] = array( + $prev_href = \Drupal::url('entity.node.canonical', ['node' => $prev['nid']]); + $build['#attached']['html_head_link'][][] = [ 'rel' => 'prev', 'href' => $prev_href, - ); + ]; $variables['prev_url'] = $prev_href; $variables['prev_title'] = $prev['title']; } @@ -416,21 +416,21 @@ function template_preprocess_book_navigation(&$variables) { /** @var \Drupal\book\BookManagerInterface $book_manager */ $book_manager = \Drupal::service('book.manager'); if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) { - $parent_href = \Drupal::url('entity.node.canonical', array('node' => $book_link['pid'])); - $build['#attached']['html_head_link'][][] = array( + $parent_href = \Drupal::url('entity.node.canonical', ['node' => $book_link['pid']]); + $build['#attached']['html_head_link'][][] = [ 'rel' => 'up', 'href' => $parent_href, - ); + ]; $variables['parent_url'] = $parent_href; $variables['parent_title'] = $parent['title']; } if ($next = $book_outline->nextLink($book_link)) { - $next_href = \Drupal::url('entity.node.canonical', array('node' => $next['nid'])); - $build['#attached']['html_head_link'][][] = array( + $next_href = \Drupal::url('entity.node.canonical', ['node' => $next['nid']]); + $build['#attached']['html_head_link'][][] = [ 'rel' => 'next', 'href' => $next_href, - ); + ]; $variables['next_url'] = $next_href; $variables['next_title'] = $next['title']; } @@ -442,7 +442,7 @@ function template_preprocess_book_navigation(&$variables) { $variables['has_links'] = FALSE; // Link variables to filter for values and set state of the flag variable. - $links = array('prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title'); + $links = ['prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title']; foreach ($links as $link) { if (isset($variables[$link])) { // Flag when there is a value. @@ -475,7 +475,7 @@ function template_preprocess_book_export_html(&$variables) { $variables['language_rtl'] = ($language_interface->getDirection() == LanguageInterface::DIRECTION_RTL); // HTML element attributes. - $attributes = array(); + $attributes = []; $attributes['lang'] = $language_interface->getId(); $attributes['dir'] = $language_interface->getDirection(); $variables['html_attributes'] = new Attribute($attributes); diff --git a/core/modules/book/src/BookBreadcrumbBuilder.php b/core/modules/book/src/BookBreadcrumbBuilder.php index ed39a53d2e..90591d8d49 100644 --- a/core/modules/book/src/BookBreadcrumbBuilder.php +++ b/core/modules/book/src/BookBreadcrumbBuilder.php @@ -56,10 +56,10 @@ public function applies(RouteMatchInterface $route_match) { * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { - $book_nids = array(); + $book_nids = []; $breadcrumb = new Breadcrumb(); - $links = array(Link::createFromRoute($this->t('Home'), '')); + $links = [Link::createFromRoute($this->t('Home'), '')]; $book = $route_match->getParameter('node')->book; $depth = 1; // We skip the current node. @@ -76,7 +76,7 @@ public function build(RouteMatchInterface $route_match) { $breadcrumb->addCacheableDependency($access); if ($access->isAllowed()) { $breadcrumb->addCacheableDependency($parent_book); - $links[] = Link::createFromRoute($parent_book->label(), 'entity.node.canonical', array('node' => $parent_book->id())); + $links[] = Link::createFromRoute($parent_book->label(), 'entity.node.canonical', ['node' => $parent_book->id()]); } } $depth++; diff --git a/core/modules/book/src/BookExport.php b/core/modules/book/src/BookExport.php index 8261c42ea9..a323370051 100644 --- a/core/modules/book/src/BookExport.php +++ b/core/modules/book/src/BookExport.php @@ -73,8 +73,8 @@ public function bookExportHtml(NodeInterface $node) { } $tree = $this->bookManager->bookSubtreeData($node->book); - $contents = $this->exportTraverse($tree, array($this, 'bookNodeExport')); - return array( + $contents = $this->exportTraverse($tree, [$this, 'bookNodeExport']); + return [ '#theme' => 'book_export_html', '#title' => $node->label(), '#contents' => $contents, @@ -82,7 +82,7 @@ public function bookExportHtml(NodeInterface $node) { '#cache' => [ 'tags' => $node->getEntityType()->getListCacheTags(), ], - ); + ]; } /** @@ -101,9 +101,9 @@ public function bookExportHtml(NodeInterface $node) { */ protected function exportTraverse(array $tree, $callable) { // If there is no valid callable, use the default callback. - $callable = !empty($callable) ? $callable : array($this, 'bookNodeExport'); + $callable = !empty($callable) ? $callable : [$this, 'bookNodeExport']; - $build = array(); + $build = []; foreach ($tree as $data) { // Note- access checking is already performed when building the tree. if ($node = $this->nodeStorage->load($data['link']['nid'])) { @@ -133,12 +133,12 @@ protected function bookNodeExport(NodeInterface $node, $children = '') { $build = $this->viewBuilder->view($node, 'print', NULL); unset($build['#theme']); - return array( + return [ '#theme' => 'book_node_export_html', '#content' => $build, '#node' => $node, '#children' => $children, - ); + ]; } } diff --git a/core/modules/book/src/BookManager.php b/core/modules/book/src/BookManager.php index 60754be7bd..3e14c40076 100644 --- a/core/modules/book/src/BookManager.php +++ b/core/modules/book/src/BookManager.php @@ -92,7 +92,7 @@ public function getAllBooks() { * Loads Books Array. */ protected function loadBooks() { - $this->books = array(); + $this->books = []; $nids = $this->bookOutlineStorage->getBooks(); if ($nids) { @@ -117,15 +117,15 @@ protected function loadBooks() { * {@inheritdoc} */ public function getLinkDefaults($nid) { - return array( + return [ 'original_bid' => 0, 'nid' => $nid, 'bid' => 0, 'pid' => 0, 'has_children' => 0, 'weight' => 0, - 'options' => array(), - ); + 'options' => [], + ]; } /** @@ -159,40 +159,40 @@ public function addFormElements(array $form, FormStateInterface $form_state, Nod if ($form_state->hasValue('book')) { $node->book = $form_state->getValue('book'); } - $form['book'] = array( + $form['book'] = [ '#type' => 'details', '#title' => $this->t('Book outline'), '#weight' => 10, '#open' => !$collapsed, '#group' => 'advanced', - '#attributes' => array( - 'class' => array('book-outline-form'), - ), - '#attached' => array( - 'library' => array('book/drupal.book'), - ), + '#attributes' => [ + 'class' => ['book-outline-form'], + ], + '#attached' => [ + 'library' => ['book/drupal.book'], + ], '#tree' => TRUE, - ); - foreach (array('nid', 'has_children', 'original_bid', 'parent_depth_limit') as $key) { - $form['book'][$key] = array( + ]; + foreach (['nid', 'has_children', 'original_bid', 'parent_depth_limit'] as $key) { + $form['book'][$key] = [ '#type' => 'value', '#value' => $node->book[$key], - ); + ]; } $form['book']['pid'] = $this->addParentSelectFormElements($node->book); // @see \Drupal\book\Form\BookAdminEditForm::bookAdminTableTree(). The // weight may be larger than 15. - $form['book']['weight'] = array( + $form['book']['weight'] = [ '#type' => 'weight', '#title' => $this->t('Weight'), '#default_value' => $node->book['weight'], '#delta' => max(15, abs($node->book['weight'])), '#weight' => 5, '#description' => $this->t('Pages at a given level are ordered first by weight and then by title.'), - ); - $options = array(); + ]; + $options = []; $nid = !$node->isNew() ? $node->id() : 'new'; if ($node->id() && ($nid == $node->book['original_bid']) && ($node->book['parent_depth_limit'] == 0)) { // This is the top level node in a maximum depth book and thus cannot be @@ -207,15 +207,15 @@ public function addFormElements(array $form, FormStateInterface $form_state, Nod if ($account->hasPermission('create new books') && ($nid == 'new' || ($nid != $node->book['original_bid']))) { // The node can become a new book, if it is not one already. - $options = array($nid => $this->t('- Create a new book -')) + $options; + $options = [$nid => $this->t('- Create a new book -')] + $options; } if (!$node->book['bid']) { // The node is not currently in the hierarchy. - $options = array(0 => $this->t('- None -')) + $options; + $options = [0 => $this->t('- None -')] + $options; } // Add a drop-down to select the destination book. - $form['book']['bid'] = array( + $form['book']['bid'] = [ '#type' => 'select', '#title' => $this->t('Book'), '#default_value' => $node->book['bid'], @@ -223,14 +223,14 @@ public function addFormElements(array $form, FormStateInterface $form_state, Nod '#access' => (bool) $options, '#description' => $this->t('Your page will be a part of the selected book.'), '#weight' => -5, - '#attributes' => array('class' => array('book-title-select')), - '#ajax' => array( + '#attributes' => ['class' => ['book-title-select']], + '#ajax' => [ 'callback' => 'book_form_update', 'wrapper' => 'edit-book-plid-wrapper', 'effect' => 'fade', 'speed' => 'fast', - ), - ); + ], + ]; return $form; } @@ -281,8 +281,8 @@ public function updateOutline(NodeInterface $node) { /** * {@inheritdoc} */ - public function getBookParents(array $item, array $parent = array()) { - $book = array(); + public function getBookParents(array $item, array $parent = []) { + $book = []; if ($item['pid'] == 0) { $book['p1'] = $item['nid']; for ($i = 2; $i <= static::BOOK_MAX_DEPTH; $i++) { @@ -325,15 +325,15 @@ public function getBookParents(array $item, array $parent = array()) { protected function addParentSelectFormElements(array $book_link) { $config = $this->configFactory->get('book.settings'); if ($config->get('override_parent_selector')) { - return array(); + return []; } // Offer a message or a drop-down to choose a different parent page. - $form = array( + $form = [ '#type' => 'hidden', '#value' => -1, '#prefix' => '
        ', '#suffix' => '
        ', - ); + ]; if ($book_link['nid'] === $book_link['bid']) { // This is a book - at the top level. @@ -348,16 +348,16 @@ protected function addParentSelectFormElements(array $book_link) { $form['#prefix'] .= '' . $this->t('No book selected.') . ''; } else { - $form = array( + $form = [ '#type' => 'select', '#title' => $this->t('Parent item'), '#default_value' => $book_link['pid'], - '#description' => $this->t('The parent page in the book. The maximum depth for a book and all child pages is @maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', array('@maxdepth' => static::BOOK_MAX_DEPTH)), - '#options' => $this->getTableOfContents($book_link['bid'], $book_link['parent_depth_limit'], array($book_link['nid'])), - '#attributes' => array('class' => array('book-title-select')), + '#description' => $this->t('The parent page in the book. The maximum depth for a book and all child pages is @maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', ['@maxdepth' => static::BOOK_MAX_DEPTH]), + '#options' => $this->getTableOfContents($book_link['bid'], $book_link['parent_depth_limit'], [$book_link['nid']]), + '#attributes' => ['class' => ['book-title-select']], '#prefix' => '
        ', '#suffix' => '
        ', - ); + ]; } $this->renderer->addCacheableDependency($form, $config); @@ -388,7 +388,7 @@ protected function addParentSelectFormElements(array $book_link) { * children). */ protected function recurseTableOfContents(array $tree, $indent, array &$toc, array $exclude, $depth_limit) { - $nids = array(); + $nids = []; foreach ($tree as $data) { if ($data['link']['depth'] > $depth_limit) { // Don't iterate through any links on this level. @@ -417,9 +417,9 @@ protected function recurseTableOfContents(array $tree, $indent, array &$toc, arr /** * {@inheritdoc} */ - public function getTableOfContents($bid, $depth_limit, array $exclude = array()) { + public function getTableOfContents($bid, $depth_limit, array $exclude = []) { $tree = $this->bookTreeAllData($bid); - $toc = array(); + $toc = []; $this->recurseTableOfContents($tree, '', $toc, $exclude, $depth_limit); return $toc; @@ -443,14 +443,14 @@ public function deleteFromBook($nid) { } $this->updateOriginalParent($original); $this->books = NULL; - Cache::invalidateTags(array('bid:' . $original['bid'])); + Cache::invalidateTags(['bid:' . $original['bid']]); } /** * {@inheritdoc} */ public function bookTreeAllData($bid, $link = NULL, $max_depth = NULL) { - $tree = &drupal_static(__METHOD__, array()); + $tree = &drupal_static(__METHOD__, []); $language_interface = \Drupal::languageManager()->getCurrentLanguage(); // Use $nid as a flag for whether the data being loaded is for the whole @@ -462,10 +462,10 @@ public function bookTreeAllData($bid, $link = NULL, $max_depth = NULL) { if (!isset($tree[$cid])) { // If the tree data was not in the static cache, build $tree_parameters. - $tree_parameters = array( + $tree_parameters = [ 'min_depth' => 1, 'max_depth' => $max_depth, - ); + ]; if ($nid) { $active_trail = $this->getActiveTrailIds($bid, $link); $tree_parameters['expanded'] = $active_trail; @@ -486,7 +486,7 @@ public function bookTreeAllData($bid, $link = NULL, $max_depth = NULL) { public function getActiveTrailIds($bid, $link) { // The tree is for a single item, so we need to match the values in its // p columns and 0 (the top level) with the plid values of other links. - $active_trail = array(0); + $active_trail = [0]; for ($i = 1; $i < static::BOOK_MAX_DEPTH; $i++) { if (!empty($link["p$i"])) { $active_trail[] = $link["p$i"]; @@ -600,7 +600,7 @@ protected function buildItems(array $tree) { * @return array * A fully built book tree. */ - protected function bookTreeBuild($bid, array $parameters = array()) { + protected function bookTreeBuild($bid, array $parameters = []) { // Build the book tree. $data = $this->doBookTreeBuild($bid, $parameters); // Check access for the current user to each item in the tree. @@ -639,9 +639,9 @@ protected function bookTreeBuild($bid, array $parameters = array()) { * * @see \Drupal\book\BookOutlineStorageInterface::getBookMenuTree() */ - protected function doBookTreeBuild($bid, array $parameters = array()) { + protected function doBookTreeBuild($bid, array $parameters = []) { // Static cache of already built menu trees. - $trees = &drupal_static(__METHOD__, array()); + $trees = &drupal_static(__METHOD__, []); $language_interface = \Drupal::languageManager()->getCurrentLanguage(); // Build the cache id; sort parents to prevent duplicate storage and remove @@ -664,18 +664,18 @@ protected function doBookTreeBuild($bid, array $parameters = array()) { $result = $this->bookOutlineStorage->getBookMenuTree($bid, $parameters, $min_depth, static::BOOK_MAX_DEPTH); // Build an ordered array of links using the query result object. - $links = array(); + $links = []; foreach ($result as $link) { $link = (array) $link; $links[$link['nid']] = $link; } - $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : array()); + $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : []); $data['tree'] = $this->buildBookOutlineData($links, $active_trail, $min_depth); - $data['node_links'] = array(); + $data['node_links'] = []; $this->bookTreeCollectNodeLinks($data['tree'], $data['node_links']); // Cache the data, if it is not already in the cache. - \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, array('bid:' . $bid)); + \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, ['bid:' . $bid]); $trees[$tree_cid] = $data; } @@ -705,7 +705,7 @@ public function bookTreeGetFlat(array $book_link) { if (!isset($this->bookTreeFlattened[$book_link['nid']])) { // Call $this->bookTreeAllData() to take advantage of caching. $tree = $this->bookTreeAllData($book_link['bid'], $book_link, $book_link['depth'] + 1); - $this->bookTreeFlattened[$book_link['nid']] = array(); + $this->bookTreeFlattened[$book_link['nid']] = []; $this->flatBookTree($tree, $this->bookTreeFlattened[$book_link['nid']]); } @@ -735,7 +735,7 @@ protected function flatBookTree(array $tree, array &$flat) { * {@inheritdoc} */ public function loadBookLink($nid, $translate = TRUE) { - $links = $this->loadBookLinks(array($nid), $translate); + $links = $this->loadBookLinks([$nid], $translate); return isset($links[$nid]) ? $links[$nid] : FALSE; } @@ -744,7 +744,7 @@ public function loadBookLink($nid, $translate = TRUE) { */ public function loadBookLinks($nids, $translate = TRUE) { $result = $this->bookOutlineStorage->loadMultiple($nids, $translate); - $links = array(); + $links = []; foreach ($result as $link) { if ($translate) { $this->bookLinkTranslate($link); @@ -779,7 +779,7 @@ public function saveBookLink(array $link, $new) { // Update the bid for this page and all children. if ($link['pid'] == 0) { $link['depth'] = 1; - $parent = array(); + $parent = []; } // In case the form did not specify a proper PID we use the BID as new // parent. @@ -801,11 +801,11 @@ public function saveBookLink(array $link, $new) { $this->updateParent($link); } // Update the weight and pid. - $this->bookOutlineStorage->update($link['nid'], array( + $this->bookOutlineStorage->update($link['nid'], [ 'weight' => $link['weight'], 'pid' => $link['pid'], 'bid' => $link['bid'], - )); + ]); } $cache_tags = []; foreach ($affected_bids as $bid) { @@ -825,16 +825,16 @@ public function saveBookLink(array $link, $new) { */ protected function moveChildren(array $link, array $original) { $p = 'p1'; - $expressions = array(); + $expressions = []; for ($i = 1; $i <= $link['depth']; $p = 'p' . ++$i) { - $expressions[] = array($p, ":p_$i", array(":p_$i" => $link[$p])); + $expressions[] = [$p, ":p_$i", [":p_$i" => $link[$p]]]; } $j = $original['depth'] + 1; while ($i <= static::BOOK_MAX_DEPTH && $j <= static::BOOK_MAX_DEPTH) { - $expressions[] = array('p' . $i++, 'p' . $j++, array()); + $expressions[] = ['p' . $i++, 'p' . $j++, []]; } while ($i <= static::BOOK_MAX_DEPTH) { - $expressions[] = array('p' . $i++, 0, array()); + $expressions[] = ['p' . $i++, 0, []]; } $shift = $link['depth'] - $original['depth']; @@ -868,7 +868,7 @@ protected function updateParent(array $link) { // Nothing to update. return TRUE; } - return $this->bookOutlineStorage->update($link['pid'], array('has_children' => 1)); + return $this->bookOutlineStorage->update($link['pid'], ['has_children' => 1]); } /** @@ -897,7 +897,7 @@ protected function updateOriginalParent(array $original) { // Update the parent. If the original link did not have children, then the // parent now does not have children. If the original had children, then the // the parent has children now (still). - return $this->bookOutlineStorage->update($original['pid'], array('has_children' => $parent_has_children)); + return $this->bookOutlineStorage->update($original['pid'], ['has_children' => $parent_has_children]); } /** @@ -926,7 +926,7 @@ protected function setParents(array &$link, array $parent) { /** * {@inheritdoc} */ - public function bookTreeCheckAccess(&$tree, $node_links = array()) { + public function bookTreeCheckAccess(&$tree, $node_links = []) { if ($node_links) { // @todo Extract that into its own method. $nids = array_keys($node_links); @@ -954,7 +954,7 @@ public function bookTreeCheckAccess(&$tree, $node_links = array()) { * The book tree to operate on. */ protected function doBookTreeCheckAccess(&$tree) { - $new_tree = array(); + $new_tree = []; foreach ($tree as $key => $v) { $item = &$tree[$key]['link']; $this->bookLinkTranslate($item); @@ -993,7 +993,7 @@ public function bookLinkTranslate(&$link) { } // The node label will be the value for the current user's language. $link['title'] = $node->label(); - $link['options'] = array(); + $link['options'] = []; } return $link; } @@ -1021,7 +1021,7 @@ public function bookLinkTranslate(&$link) { * array will be empty if the book link has no items in its sub-tree * having a depth greater than or equal to $depth. */ - protected function buildBookOutlineData(array $links, array $parents = array(), $depth = 1) { + protected function buildBookOutlineData(array $links, array $parents = [], $depth = 1) { // Reverse the array so we can use the more efficient array_pop() function. $links = array_reverse($links); return $this->buildBookOutlineRecursive($links, $parents, $depth); @@ -1047,16 +1047,16 @@ protected function buildBookOutlineData(array $links, array $parents = array(), * Book tree. */ protected function buildBookOutlineRecursive(&$links, $parents, $depth) { - $tree = array(); + $tree = []; while ($item = array_pop($links)) { // We need to determine if we're on the path to root so we can later build // the correct active trail. $item['in_active_trail'] = in_array($item['nid'], $parents); // Add the current link to the tree. - $tree[$item['nid']] = array( + $tree[$item['nid']] = [ 'link' => $item, - 'below' => array(), - ); + 'below' => [], + ]; // Look ahead to the next link, but leave it on the array so it's // available to other recursive function calls if we return or build a // sub-tree. @@ -1080,7 +1080,7 @@ protected function buildBookOutlineRecursive(&$links, $parents, $depth) { * {@inheritdoc} */ public function bookSubtreeData($link) { - $tree = &drupal_static(__METHOD__, array()); + $tree = &drupal_static(__METHOD__, []); // Generate a cache ID (cid) specific for this $link. $cid = 'book-links:subtree-cid:' . $link['nid']; @@ -1101,23 +1101,23 @@ public function bookSubtreeData($link) { // If the subtree data was not in the cache, $data will be NULL. if (!isset($data)) { $result = $this->bookOutlineStorage->getBookSubtree($link, static::BOOK_MAX_DEPTH); - $links = array(); + $links = []; foreach ($result as $item) { $links[] = $item; } - $data['tree'] = $this->buildBookOutlineData($links, array(), $link['depth']); - $data['node_links'] = array(); + $data['tree'] = $this->buildBookOutlineData($links, [], $link['depth']); + $data['node_links'] = []; $this->bookTreeCollectNodeLinks($data['tree'], $data['node_links']); // Compute the real cid for book subtree data. $tree_cid = 'book-links:subtree-data:' . hash('sha256', serialize($data)); // Cache the data, if it is not already in the cache. if (!\Drupal::cache('data')->get($tree_cid)) { - \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, array('bid:' . $link['bid'])); + \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, ['bid:' . $link['bid']]); } // Cache the cid of the (shared) data using the book and item-specific // cid. - \Drupal::cache('data')->set($cid, $tree_cid, Cache::PERMANENT, array('bid:' . $link['bid'])); + \Drupal::cache('data')->set($cid, $tree_cid, Cache::PERMANENT, ['bid:' . $link['bid']]); } // Check access for the current user to each item in the tree. $this->bookTreeCheckAccess($data['tree'], $data['node_links']); diff --git a/core/modules/book/src/BookManagerInterface.php b/core/modules/book/src/BookManagerInterface.php index 70d0107c63..5402bf51d7 100644 --- a/core/modules/book/src/BookManagerInterface.php +++ b/core/modules/book/src/BookManagerInterface.php @@ -108,7 +108,7 @@ public function loadBookLinks($nids, $translate = TRUE); * An array of (menu link ID, title) pairs for use as options for selecting * a book page. */ - public function getTableOfContents($bid, $depth_limit, array $exclude = array()); + public function getTableOfContents($bid, $depth_limit, array $exclude = []); /** * Finds the depth limit for items in the parent select. @@ -207,7 +207,7 @@ public function saveBookLink(array $link, $new); */ public function getLinkDefaults($nid); - public function getBookParents(array $item, array $parent = array()); + public function getBookParents(array $item, array $parent = []); /** * Builds the common elements of the book form for the node and outline forms. @@ -262,7 +262,7 @@ public function bookTreeOutput(array $tree); * A collection of node link references generated from $tree by * menu_tree_collect_node_links(). */ - public function bookTreeCheckAccess(&$tree, $node_links = array()); + public function bookTreeCheckAccess(&$tree, $node_links = []); /** * Gets the data representing a subtree of the book hierarchy. diff --git a/core/modules/book/src/BookOutline.php b/core/modules/book/src/BookOutline.php index bc03b7c5a9..ec28d50c72 100644 --- a/core/modules/book/src/BookOutline.php +++ b/core/modules/book/src/BookOutline.php @@ -105,7 +105,7 @@ public function nextLink(array $book_link) { public function childrenLinks(array $book_link) { $flat = $this->bookManager->bookTreeGetFlat($book_link); - $children = array(); + $children = []; if ($book_link['has_children']) { // Walk through the array until we find the current page. diff --git a/core/modules/book/src/BookOutlineStorage.php b/core/modules/book/src/BookOutlineStorage.php index 92076cba3f..4f61b5c005 100644 --- a/core/modules/book/src/BookOutlineStorage.php +++ b/core/modules/book/src/BookOutlineStorage.php @@ -43,7 +43,7 @@ public function hasBooks() { * {@inheritdoc} */ public function loadMultiple($nids, $access = TRUE) { - $query = $this->connection->select('book', 'b', array('fetch' => \PDO::FETCH_ASSOC)); + $query = $this->connection->select('book', 'b', ['fetch' => \PDO::FETCH_ASSOC]); $query->fields('b'); $query->condition('b.nid', $nids, 'IN'); @@ -89,7 +89,7 @@ public function delete($nid) { */ public function loadBookChildren($pid) { return $this->connection - ->query("SELECT * FROM {book} WHERE pid = :pid", array(':pid' => $pid)) + ->query("SELECT * FROM {book} WHERE pid = :pid", [':pid' => $pid]) ->fetchAllAssoc('nid', \PDO::FETCH_ASSOC); } @@ -128,12 +128,12 @@ public function getBookMenuTree($bid, $parameters, $min_depth, $max_depth) { public function insert($link, $parents) { return $this->connection ->insert('book') - ->fields(array( + ->fields([ 'nid' => $link['nid'], 'bid' => $link['bid'], 'pid' => $link['pid'], 'weight' => $link['weight'], - ) + $parents + ] + $parents ) ->execute(); } @@ -154,13 +154,13 @@ public function update($nid, $fields) { */ public function updateMovedChildren($bid, $original, $expressions, $shift) { $query = $this->connection->update('book'); - $query->fields(array('bid' => $bid)); + $query->fields(['bid' => $bid]); foreach ($expressions as $expression) { $query->expression($expression[0], $expression[1], $expression[2]); } - $query->expression('depth', 'depth + :depth', array(':depth' => $shift)); + $query->expression('depth', 'depth + :depth', [':depth' => $shift]); $query->condition('bid', $original['bid']); $p = 'p1'; for ($i = 1; !empty($original[$p]); $p = 'p' . ++$i) { @@ -186,7 +186,7 @@ public function countOriginalLinkChildren($original) { * {@inheritdoc} */ public function getBookSubtree($link, $max_depth) { - $query = db_select('book', 'b', array('fetch' => \PDO::FETCH_ASSOC)); + $query = db_select('book', 'b', ['fetch' => \PDO::FETCH_ASSOC]); $query->fields('b'); $query->condition('b.bid', $link['bid']); diff --git a/core/modules/book/src/Controller/BookController.php b/core/modules/book/src/Controller/BookController.php index 920afeb2b1..b92c3e3fcf 100644 --- a/core/modules/book/src/Controller/BookController.php +++ b/core/modules/book/src/Controller/BookController.php @@ -73,9 +73,9 @@ public static function create(ContainerInterface $container) { * A render array representing the administrative page content. */ public function adminOverview() { - $rows = array(); + $rows = []; - $headers = array(t('Book'), t('Operations')); + $headers = [t('Book'), t('Operations')]; // Add any recognized books to the table list. foreach ($this->bookManager->getAllBooks() as $book) { /** @var \Drupal\Core\Url $url */ @@ -83,28 +83,28 @@ public function adminOverview() { if (isset($book['options'])) { $url->setOptions($book['options']); } - $row = array( + $row = [ $this->l($book['title'], $url), - ); - $links = array(); - $links['edit'] = array( + ]; + $links = []; + $links['edit'] = [ 'title' => t('Edit order and titles'), 'url' => Url::fromRoute('book.admin_edit', ['node' => $book['nid']]), - ); - $row[] = array( - 'data' => array( + ]; + $row[] = [ + 'data' => [ '#type' => 'operations', '#links' => $links, - ), - ); + ], + ]; $rows[] = $row; } - return array( + return [ '#type' => 'table', '#header' => $headers, '#rows' => $rows, '#empty' => t('No books available.'), - ); + ]; } /** @@ -114,17 +114,17 @@ public function adminOverview() { * A render array representing the listing of all books content. */ public function bookRender() { - $book_list = array(); + $book_list = []; foreach ($this->bookManager->getAllBooks() as $book) { $book_list[] = $this->l($book['title'], $book['url']); } - return array( + return [ '#theme' => 'item_list', '#items' => $book_list, '#cache' => [ 'tags' => \Drupal::entityManager()->getDefinition('node')->getListCacheTags(), ], - ); + ]; } /** diff --git a/core/modules/book/src/Form/BookAdminEditForm.php b/core/modules/book/src/Form/BookAdminEditForm.php index 175394422f..e91f52ea8b 100644 --- a/core/modules/book/src/Form/BookAdminEditForm.php +++ b/core/modules/book/src/Form/BookAdminEditForm.php @@ -70,10 +70,10 @@ public function buildForm(array $form, FormStateInterface $form_state, NodeInter $form['#title'] = $node->label(); $form['#node'] = $node; $this->bookAdminTable($node, $form); - $form['save'] = array( + $form['save'] = [ '#type' => 'submit', '#value' => $this->t('Save book pages'), - ); + ]; return $form; } @@ -101,7 +101,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { foreach (Element::children($form['table']) as $key) { if ($form['table'][$key]['#item']) { $row = $form['table'][$key]; - $values = $form_state->getValue(array('table', $key)); + $values = $form_state->getValue(['table', $key]); // Update menu item if moved. if ($row['parent']['pid']['#default_value'] != $values['pid'] || $row['weight']['#default_value'] != $values['weight']) { @@ -114,18 +114,18 @@ public function submitForm(array &$form, FormStateInterface $form_state) { // Update the title if changed. if ($row['title']['#default_value'] != $values['title']) { $node = $this->nodeStorage->load($values['nid']); - $node->revision_log = $this->t('Title changed from %original to %current.', array('%original' => $node->label(), '%current' => $values['title'])); + $node->revision_log = $this->t('Title changed from %original to %current.', ['%original' => $node->label(), '%current' => $values['title']]); $node->title = $values['title']; $node->book['link_title'] = $values['title']; $node->setNewRevision(); $node->save(); - $this->logger('content')->notice('book: updated %title.', array('%title' => $node->label(), 'link' => $node->link($this->t('View')))); + $this->logger('content')->notice('book: updated %title.', ['%title' => $node->label(), 'link' => $node->link($this->t('View'))]); } } } } - drupal_set_message($this->t('Updated book %title.', array('%title' => $form['#node']->label()))); + drupal_set_message($this->t('Updated book %title.', ['%title' => $form['#node']->label()])); } /** @@ -139,7 +139,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { * @see self::buildForm() */ protected function bookAdminTable(NodeInterface $node, array &$form) { - $form['table'] = array( + $form['table'] = [ '#type' => 'table', '#header' => [ $this->t('Title'), @@ -164,7 +164,7 @@ protected function bookAdminTable(NodeInterface $node, array &$form) { 'group' => 'book-weight', ], ], - ); + ]; $tree = $this->bookManager->bookSubtreeData($node->book); // Do not include the book item itself. @@ -173,14 +173,14 @@ protected function bookAdminTable(NodeInterface $node, array &$form) { $hash = Crypt::hashBase64(serialize($tree['below'])); // Store the hash value as a hidden form element so that we can detect // if another user changed the book hierarchy. - $form['tree_hash'] = array( + $form['tree_hash'] = [ '#type' => 'hidden', '#default_value' => $hash, - ); - $form['tree_current_hash'] = array( + ]; + $form['tree_current_hash'] = [ '#type' => 'value', '#value' => $hash, - ); + ]; $this->bookAdminTableTree($tree['below'], $form['table']); } } diff --git a/core/modules/book/src/Form/BookOutlineForm.php b/core/modules/book/src/Form/BookOutlineForm.php index 8b4e3640b7..1d63aacf0c 100644 --- a/core/modules/book/src/Form/BookOutlineForm.php +++ b/core/modules/book/src/Form/BookOutlineForm.php @@ -107,7 +107,7 @@ protected function actions(array $form, FormStateInterface $form_state) { public function save(array $form, FormStateInterface $form_state) { $form_state->setRedirect( 'entity.node.canonical', - array('node' => $this->entity->id()) + ['node' => $this->entity->id()] ); $book_link = $form_state->getValue('book'); if (!$book_link['bid']) { diff --git a/core/modules/book/src/Form/BookRemoveForm.php b/core/modules/book/src/Form/BookRemoveForm.php index 4848fa2943..e31c0940e8 100644 --- a/core/modules/book/src/Form/BookRemoveForm.php +++ b/core/modules/book/src/Form/BookRemoveForm.php @@ -65,7 +65,7 @@ public function buildForm(array $form, FormStateInterface $form_state, NodeInter * {@inheritdoc} */ public function getDescription() { - $title = array('%title' => $this->node->label()); + $title = ['%title' => $this->node->label()]; if ($this->node->book['has_children']) { return $this->t('%title has associated child pages, which will be relocated automatically to maintain their connection to the book. To recreate the hierarchy (as it was before removing this page), %title may be added again using the Outline tab, and each of its former child pages will need to be relocated manually.', $title); } @@ -85,7 +85,7 @@ public function getConfirmText() { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to remove %title from the book hierarchy?', array('%title' => $this->node->label())); + return $this->t('Are you sure you want to remove %title from the book hierarchy?', ['%title' => $this->node->label()]); } /** diff --git a/core/modules/book/src/Form/BookSettingsForm.php b/core/modules/book/src/Form/BookSettingsForm.php index 058d0cd063..29590ccdb5 100644 --- a/core/modules/book/src/Form/BookSettingsForm.php +++ b/core/modules/book/src/Form/BookSettingsForm.php @@ -30,22 +30,22 @@ protected function getEditableConfigNames() { public function buildForm(array $form, FormStateInterface $form_state) { $types = node_type_get_names(); $config = $this->config('book.settings'); - $form['book_allowed_types'] = array( + $form['book_allowed_types'] = [ '#type' => 'checkboxes', '#title' => $this->t('Content types allowed in book outlines'), '#default_value' => $config->get('allowed_types'), '#options' => $types, - '#description' => $this->t('Users with the %outline-perm permission can add all content types.', array('%outline-perm' => $this->t('Administer book outlines'))), + '#description' => $this->t('Users with the %outline-perm permission can add all content types.', ['%outline-perm' => $this->t('Administer book outlines')]), '#required' => TRUE, - ); - $form['book_child_type'] = array( + ]; + $form['book_child_type'] = [ '#type' => 'radios', '#title' => $this->t('Content type for the Add child page link'), '#default_value' => $config->get('child_type'), '#options' => $types, '#required' => TRUE, - ); - $form['array_filter'] = array('#type' => 'value', '#value' => TRUE); + ]; + $form['array_filter'] = ['#type' => 'value', '#value' => TRUE]; return parent::buildForm($form, $form_state); } @@ -55,8 +55,8 @@ public function buildForm(array $form, FormStateInterface $form_state) { */ public function validateForm(array &$form, FormStateInterface $form_state) { $child_type = $form_state->getValue('book_child_type'); - if ($form_state->isValueEmpty(array('book_allowed_types', $child_type))) { - $form_state->setErrorByName('book_child_type', $this->t('The content type for the %add-child link must be one of those selected as an allowed book outline type.', array('%add-child' => $this->t('Add child page')))); + if ($form_state->isValueEmpty(['book_allowed_types', $child_type])) { + $form_state->setErrorByName('book_child_type', $this->t('The content type for the %add-child link must be one of those selected as an allowed book outline type.', ['%add-child' => $this->t('Add child page')])); } parent::validateForm($form, $form_state); diff --git a/core/modules/book/src/Plugin/Block/BookNavigationBlock.php b/core/modules/book/src/Plugin/Block/BookNavigationBlock.php index a7b0f1e32a..7b0156f240 100644 --- a/core/modules/book/src/Plugin/Block/BookNavigationBlock.php +++ b/core/modules/book/src/Plugin/Block/BookNavigationBlock.php @@ -86,26 +86,26 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function defaultConfiguration() { - return array( + return [ 'block_mode' => "all pages", - ); + ]; } /** * {@inheritdoc} */ function blockForm($form, FormStateInterface $form_state) { - $options = array( + $options = [ 'all pages' => $this->t('Show block on all pages'), 'book pages' => $this->t('Show block only on book pages'), - ); - $form['book_block_mode'] = array( + ]; + $form['book_block_mode'] = [ '#type' => 'radios', '#title' => $this->t('Book navigation block display'), '#options' => $options, '#default_value' => $this->configuration['block_mode'], '#description' => $this->t("If Show block on all pages is selected, the block will contain the automatically generated menus for all of the site's books. If Show block only on book pages is selected, the block will contain only the one menu corresponding to the current page's book. In this case, if the current page is not in a book, no block will be displayed. The Page specific visibility settings or other visibility settings can be used in addition to selectively display this block."), - ); + ]; return $form; } @@ -127,8 +127,8 @@ public function build() { $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid']; } if ($this->configuration['block_mode'] == 'all pages') { - $book_menus = array(); - $pseudo_tree = array(0 => array('below' => FALSE)); + $book_menus = []; + $pseudo_tree = [0 => ['below' => FALSE]]; foreach ($this->bookManager->getAllBooks() as $book_id => $book) { if ($book['bid'] == $current_bid) { // If the current page is a node associated with a book, the menu @@ -146,14 +146,14 @@ public function build() { $pseudo_tree[0]['link'] = $book; $book_menus[$book_id] = $this->bookManager->bookTreeOutput($pseudo_tree); } - $book_menus[$book_id] += array( + $book_menus[$book_id] += [ '#book_title' => $book['title'], - ); + ]; } if ($book_menus) { - return array( + return [ '#theme' => 'book_all_books_block', - ) + $book_menus; + ] + $book_menus; } } elseif ($current_bid) { @@ -175,7 +175,7 @@ public function build() { } } } - return array(); + return []; } /** diff --git a/core/modules/book/src/Plugin/migrate/source/d6/Book.php b/core/modules/book/src/Plugin/migrate/source/d6/Book.php index 76833aa753..f41bb42dfa 100644 --- a/core/modules/book/src/Plugin/migrate/source/d6/Book.php +++ b/core/modules/book/src/Plugin/migrate/source/d6/Book.php @@ -17,9 +17,9 @@ class Book extends DrupalSqlBase { * {@inheritdoc} */ public function query() { - $query = $this->select('book', 'b')->fields('b', array('nid', 'bid')); + $query = $this->select('book', 'b')->fields('b', ['nid', 'bid']); $query->join('menu_links', 'ml', 'b.mlid = ml.mlid'); - $ml_fields = array('mlid', 'plid', 'weight', 'has_children', 'depth'); + $ml_fields = ['mlid', 'plid', 'weight', 'has_children', 'depth']; for ($i = 1; $i <= 9; $i++) { $field = "p$i"; $ml_fields[] = $field; @@ -42,7 +42,7 @@ public function getIds() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'nid' => $this->t('Node ID'), 'bid' => $this->t('Book ID'), 'mlid' => $this->t('Menu link ID'), @@ -57,7 +57,7 @@ public function fields() { 'p7' => $this->t('The seventh mlid in the materialized path. See p1.'), 'p8' => $this->t('The eighth mlid in the materialized path. See p1.'), 'p9' => $this->t('The ninth mlid in the materialized path. See p1.'), - ); + ]; } } diff --git a/core/modules/book/src/Tests/BookBreadcrumbTest.php b/core/modules/book/src/Tests/BookBreadcrumbTest.php index 57e1b3d6ce..d2f4d5d386 100644 --- a/core/modules/book/src/Tests/BookBreadcrumbTest.php +++ b/core/modules/book/src/Tests/BookBreadcrumbTest.php @@ -16,7 +16,7 @@ class BookBreadcrumbTest extends WebTestBase { * * @var array */ - public static $modules = array('book', 'block', 'book_breadcrumb_test'); + public static $modules = ['book', 'block', 'book_breadcrumb_test']; /** * A book node. @@ -48,8 +48,8 @@ protected function setUp() { $this->drupalPlaceBlock('page_title_block'); // Create users. - $this->bookAuthor = $this->drupalCreateUser(array('create new books', 'create book content', 'edit own book content', 'add content to books')); - $this->adminUser = $this->drupalCreateUser(array('create new books', 'create book content', 'edit any book content', 'delete any book content', 'add content to books', 'administer blocks', 'administer permissions', 'administer book outlines', 'administer content types', 'administer site configuration')); + $this->bookAuthor = $this->drupalCreateUser(['create new books', 'create book content', 'edit own book content', 'add content to books']); + $this->adminUser = $this->drupalCreateUser(['create new books', 'create book content', 'edit any book content', 'delete any book content', 'add content to books', 'administer blocks', 'administer permissions', 'administer book outlines', 'administer content types', 'administer site configuration']); } /** @@ -76,7 +76,7 @@ protected function createBreadcrumbBook() { * |- Node 5 * |- Node 6 */ - $nodes = array(); + $nodes = []; $nodes[0] = $this->createBookNode($book->id()); $nodes[1] = $this->createBookNode($book->id(), $nodes[0]->id()); $nodes[2] = $this->createBookNode($book->id(), $nodes[0]->id()); @@ -107,7 +107,7 @@ protected function createBookNode($book_nid, $parent = NULL) { // that when sorted nodes stay in same order. static $number = 0; - $edit = array(); + $edit = []; $edit['title[0][value]'] = str_pad($number, 2, '0', STR_PAD_LEFT) . ' - SimpleTest test node ' . $this->randomMachineName(10); $edit['body[0][value]'] = 'SimpleTest test body ' . $this->randomMachineName(32) . ' ' . $this->randomMachineName(32); $edit['book[bid]'] = $book_nid; @@ -146,7 +146,7 @@ public function testBreadcrumbTitleUpdates() { $this->drupalGet($nodes[4]->toUrl()); // Fetch each node title in the current breadcrumb. $links = $this->xpath('//nav[@class="breadcrumb"]/ol/li/a'); - $got_breadcrumb = array(); + $got_breadcrumb = []; foreach ($links as $link) { $got_breadcrumb[] = (string) $link; } @@ -160,7 +160,7 @@ public function testBreadcrumbTitleUpdates() { $this->drupalGet($nodes[4]->toUrl()); // Fetch each node title in the current breadcrumb. $links = $this->xpath('//nav[@class="breadcrumb"]/ol/li/a'); - $got_breadcrumb = array(); + $got_breadcrumb = []; foreach ($links as $link) { $got_breadcrumb[] = (string) $link; } @@ -181,7 +181,7 @@ public function testBreadcrumbAccessUpdates() { $this->drupalPostForm($nodes[3]->toUrl('edit-form'), $edit, 'Save'); $this->drupalGet($nodes[4]->toUrl()); $links = $this->xpath('//nav[@class="breadcrumb"]/ol/li/a'); - $got_breadcrumb = array(); + $got_breadcrumb = []; foreach ($links as $link) { $got_breadcrumb[] = (string) $link; } @@ -191,7 +191,7 @@ public function testBreadcrumbAccessUpdates() { $config->set('hide', TRUE)->save(); $this->drupalGet($nodes[4]->toUrl()); $links = $this->xpath('//nav[@class="breadcrumb"]/ol/li/a'); - $got_breadcrumb = array(); + $got_breadcrumb = []; foreach ($links as $link) { $got_breadcrumb[] = (string) $link; } diff --git a/core/modules/book/src/Tests/BookInstallTest.php b/core/modules/book/src/Tests/BookInstallTest.php index ba70a9bcd0..9933b1c5f8 100644 --- a/core/modules/book/src/Tests/BookInstallTest.php +++ b/core/modules/book/src/Tests/BookInstallTest.php @@ -17,7 +17,7 @@ class BookInstallTest extends WebTestBase { * * @var array */ - public static $modules = array('node'); + public static $modules = ['node']; /** * {@inheritdoc} diff --git a/core/modules/book/src/Tests/BookTest.php b/core/modules/book/src/Tests/BookTest.php index cdd61c60ab..183674fa4a 100644 --- a/core/modules/book/src/Tests/BookTest.php +++ b/core/modules/book/src/Tests/BookTest.php @@ -20,7 +20,7 @@ class BookTest extends WebTestBase { * * @var array */ - public static $modules = array('book', 'block', 'node_access_test', 'book_test'); + public static $modules = ['book', 'block', 'node_access_test', 'book_test']; /** * A book node. @@ -69,10 +69,10 @@ protected function setUp() { node_access_rebuild(); // Create users. - $this->bookAuthor = $this->drupalCreateUser(array('create new books', 'create book content', 'edit own book content', 'add content to books')); - $this->webUser = $this->drupalCreateUser(array('access printer-friendly version', 'node test view')); - $this->webUserWithoutNodeAccess = $this->drupalCreateUser(array('access printer-friendly version')); - $this->adminUser = $this->drupalCreateUser(array('create new books', 'create book content', 'edit any book content', 'delete any book content', 'add content to books', 'administer blocks', 'administer permissions', 'administer book outlines', 'node test view', 'administer content types', 'administer site configuration')); + $this->bookAuthor = $this->drupalCreateUser(['create new books', 'create book content', 'edit own book content', 'add content to books']); + $this->webUser = $this->drupalCreateUser(['access printer-friendly version', 'node test view']); + $this->webUserWithoutNodeAccess = $this->drupalCreateUser(['access printer-friendly version']); + $this->adminUser = $this->drupalCreateUser(['create new books', 'create book content', 'edit any book content', 'delete any book content', 'add content to books', 'administer blocks', 'administer permissions', 'administer book outlines', 'node test view', 'administer content types', 'administer site configuration']); } /** @@ -96,7 +96,7 @@ function createBook() { * |- Node 3 * |- Node 4 */ - $nodes = array(); + $nodes = []; $nodes[] = $this->createBookNode($book->id()); // Node 0. $nodes[] = $this->createBookNode($book->id(), $nodes[0]->book['nid']); // Node 1. $nodes[] = $this->createBookNode($book->id(), $nodes[0]->book['nid']); // Node 2. @@ -159,8 +159,8 @@ function testEmptyBook() { // Log in as a user with access to the book outline and save the form. $this->drupalLogin($this->adminUser); - $this->drupalPostForm('admin/structure/book/' . $book->id(), array(), t('Save book pages')); - $this->assertText(t('Updated book @book.', array('@book' => $book->label()))); + $this->drupalPostForm('admin/structure/book/' . $book->id(), [], t('Save book pages')); + $this->assertText(t('Updated book @book.', ['@book' => $book->label()])); } /** @@ -175,12 +175,12 @@ function testBook() { // Check that book pages display along with the correct outlines and // previous/next links. - $this->checkBookNode($book, array($nodes[0], $nodes[3], $nodes[4]), FALSE, FALSE, $nodes[0], array()); - $this->checkBookNode($nodes[0], array($nodes[1], $nodes[2]), $book, $book, $nodes[1], array($book)); - $this->checkBookNode($nodes[1], NULL, $nodes[0], $nodes[0], $nodes[2], array($book, $nodes[0])); - $this->checkBookNode($nodes[2], NULL, $nodes[1], $nodes[0], $nodes[3], array($book, $nodes[0])); - $this->checkBookNode($nodes[3], NULL, $nodes[2], $book, $nodes[4], array($book)); - $this->checkBookNode($nodes[4], NULL, $nodes[3], $book, FALSE, array($book)); + $this->checkBookNode($book, [$nodes[0], $nodes[3], $nodes[4]], FALSE, FALSE, $nodes[0], []); + $this->checkBookNode($nodes[0], [$nodes[1], $nodes[2]], $book, $book, $nodes[1], [$book]); + $this->checkBookNode($nodes[1], NULL, $nodes[0], $nodes[0], $nodes[2], [$book, $nodes[0]]); + $this->checkBookNode($nodes[2], NULL, $nodes[1], $nodes[0], $nodes[3], [$book, $nodes[0]]); + $this->checkBookNode($nodes[3], NULL, $nodes[2], $book, $nodes[4], [$book]); + $this->checkBookNode($nodes[4], NULL, $nodes[3], $book, FALSE, [$book]); $this->drupalLogout(); $this->drupalLogin($this->bookAuthor); @@ -203,14 +203,14 @@ function testBook() { $this->drupalLogout(); $this->drupalLogin($this->webUser); // Verify the new outline - make sure we don't get stale cached data. - $this->checkBookNode($nodes[3], array($nodes[5]), $nodes[2], $book, $nodes[5], array($book)); - $this->checkBookNode($nodes[4], NULL, $nodes[5], $book, FALSE, array($book)); + $this->checkBookNode($nodes[3], [$nodes[5]], $nodes[2], $book, $nodes[5], [$book]); + $this->checkBookNode($nodes[4], NULL, $nodes[5], $book, FALSE, [$book]); $this->drupalLogout(); // Create a second book, and move an existing book page into it. $this->drupalLogin($this->bookAuthor); $other_book = $this->createBookNode('new'); $node = $this->createBookNode($book->id()); - $edit = array('book[bid]' => $other_book->id()); + $edit = ['book[bid]' => $other_book->id()]; $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->drupalLogout(); @@ -220,8 +220,8 @@ function testBook() { // First we must set $this->book to the second book, so that the // correct regex will be generated for testing the outline. $this->book = $other_book; - $this->checkBookNode($other_book, array($node), FALSE, FALSE, $node, array()); - $this->checkBookNode($node, NULL, $other_book, $other_book, FALSE, array($other_book)); + $this->checkBookNode($other_book, [$node], FALSE, FALSE, $node, []); + $this->checkBookNode($node, NULL, $other_book, $other_book, FALSE, [$other_book]); // Test that we can save a book programatically. $this->drupalLogin($this->bookAuthor); @@ -255,38 +255,38 @@ function checkBookNode(EntityInterface $node, $nodes, $previous = FALSE, $up = F // Check outline structure. if ($nodes !== NULL) { - $this->assertPattern($this->generateOutlinePattern($nodes), format_string('Node @number outline confirmed.', array('@number' => $number))); + $this->assertPattern($this->generateOutlinePattern($nodes), format_string('Node @number outline confirmed.', ['@number' => $number])); } else { - $this->pass(format_string('Node %number does not have outline.', array('%number' => $number))); + $this->pass(format_string('Node %number does not have outline.', ['%number' => $number])); } // Check previous, up, and next links. if ($previous) { /** @var \Drupal\Core\Url $url */ $url = $previous->urlInfo(); - $url->setOptions(array('attributes' => array('rel' => array('prev'), 'title' => t('Go to previous page')))); - $text = SafeMarkup::format(' @label', array('@label' => $previous->label())); + $url->setOptions(['attributes' => ['rel' => ['prev'], 'title' => t('Go to previous page')]]); + $text = SafeMarkup::format(' @label', ['@label' => $previous->label()]); $this->assertRaw(\Drupal::l($text, $url), 'Previous page link found.'); } if ($up) { /** @var \Drupal\Core\Url $url */ $url = $up->urlInfo(); - $url->setOptions(array('attributes' => array('title' => t('Go to parent page')))); + $url->setOptions(['attributes' => ['title' => t('Go to parent page')]]); $this->assertRaw(\Drupal::l('Up', $url), 'Up page link found.'); } if ($next) { /** @var \Drupal\Core\Url $url */ $url = $next->urlInfo(); - $url->setOptions(array('attributes' => array('rel' => array('next'), 'title' => t('Go to next page')))); - $text = SafeMarkup::format('@label ', array('@label' => $next->label())); + $url->setOptions(['attributes' => ['rel' => ['next'], 'title' => t('Go to next page')]]); + $text = SafeMarkup::format('@label ', ['@label' => $next->label()]); $this->assertRaw(\Drupal::l($text, $url), 'Next page link found.'); } // Compute the expected breadcrumb. - $expected_breadcrumb = array(); + $expected_breadcrumb = []; $expected_breadcrumb[] = \Drupal::url(''); foreach ($breadcrumb as $a_node) { $expected_breadcrumb[] = $a_node->url(); @@ -294,7 +294,7 @@ function checkBookNode(EntityInterface $node, $nodes, $previous = FALSE, $up = F // Fetch links in the current breadcrumb. $links = $this->xpath('//nav[@class="breadcrumb"]/ol/li/a'); - $got_breadcrumb = array(); + $got_breadcrumb = []; foreach ($links as $link) { $got_breadcrumb[] = (string) $link['href']; } @@ -344,7 +344,7 @@ function createBookNode($book_nid, $parent = NULL) { // since it uniquely identifies each call to createBookNode(). static $number = 0; // Used to ensure that when sorted nodes stay in same order. - $edit = array(); + $edit = []; $edit['title[0][value]'] = str_pad($number, 2, '0', STR_PAD_LEFT) . ' - SimpleTest test node ' . $this->randomMachineName(10); $edit['body[0][value]'] = 'SimpleTest test body ' . $this->randomMachineName(32) . ' ' . $this->randomMachineName(32); $edit['book[bid]'] = $book_nid; @@ -410,7 +410,7 @@ function testBookExport() { // Now grant anonymous users permission to view the printer-friendly // version and verify that node access restrictions still prevent them from // seeing it. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access printer-friendly version')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access printer-friendly version']); $this->drupalGet('book/export/html/' . $this->book->id()); $this->assertResponse('403', 'Anonymous user properly forbidden from seeing the printer-friendly version when denied by node access.'); } @@ -425,7 +425,7 @@ function testBookNavigationBlock() { $block = $this->drupalPlaceBlock('book_navigation'); // Give anonymous users the permission 'node test view'. - $edit = array(); + $edit = []; $edit[RoleInterface::ANONYMOUS_ID . '[node test view]'] = TRUE; $this->drupalPostForm('admin/people/permissions/' . RoleInterface::ANONYMOUS_ID, $edit, t('Save permissions')); $this->assertText(t('The changes have been saved.'), "Permission 'node test view' successfully assigned to anonymous users."); @@ -434,7 +434,7 @@ function testBookNavigationBlock() { $nodes = $this->createBook(); $this->drupalGet(''); $this->assertText($block->label(), 'Book navigation block is displayed.'); - $this->assertText($this->book->label(), format_string('Link to book root (@title) is displayed.', array('@title' => $nodes[0]->label()))); + $this->assertText($this->book->label(), format_string('Link to book root (@title) is displayed.', ['@title' => $nodes[0]->label()])); $this->assertNoText($nodes[0]->label(), 'No links to individual book pages are displayed.'); } @@ -485,8 +485,8 @@ public function testGetTableOfContents() { $diff = array_diff($expected_nids, array_keys($options)); $this->assertTrue(empty($diff), 'Found all expected option keys'); // Exclude Node 3. - $options = $manager->getTableOfContents($book->id(), 3, array($nodes[3]->id())); - $expected_nids = array($book->id(), $nodes[0]->id(), $nodes[1]->id(), $nodes[2]->id(), $nodes[4]->id()); + $options = $manager->getTableOfContents($book->id(), 3, [$nodes[3]->id()]); + $expected_nids = [$book->id(), $nodes[0]->id(), $nodes[1]->id(), $nodes[2]->id(), $nodes[4]->id()]; $this->assertEqual(count($options), count($expected_nids)); $diff = array_diff($expected_nids, array_keys($options)); $this->assertTrue(empty($diff), 'Found all expected option keys after excluding Node 3'); @@ -497,10 +497,10 @@ public function testGetTableOfContents() { */ function testNavigationBlockOnAccessModuleInstalled() { $this->drupalLogin($this->adminUser); - $block = $this->drupalPlaceBlock('book_navigation', array('block_mode' => 'book pages')); + $block = $this->drupalPlaceBlock('book_navigation', ['block_mode' => 'book pages']); // Give anonymous users the permission 'node test view'. - $edit = array(); + $edit = []; $edit[RoleInterface::ANONYMOUS_ID . '[node test view]'] = TRUE; $this->drupalPostForm('admin/people/permissions/' . RoleInterface::ANONYMOUS_ID, $edit, t('Save permissions')); $this->assertText(t('The changes have been saved.'), "Permission 'node test view' successfully assigned to anonymous users."); @@ -530,13 +530,13 @@ function testBookDelete() { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $nodes = $this->createBook(); $this->drupalLogin($this->adminUser); - $edit = array(); + $edit = []; // Test access to delete top-level and child book nodes. $this->drupalGet('node/' . $this->book->id() . '/outline/remove'); $this->assertResponse('403', 'Deleting top-level book node properly forbidden.'); $this->drupalPostForm('node/' . $nodes[4]->id() . '/outline/remove', $edit, t('Remove')); - $node_storage->resetCache(array($nodes[4]->id())); + $node_storage->resetCache([$nodes[4]->id()]); $node4 = $node_storage->load($nodes[4]->id()); $this->assertTrue(empty($node4->book), 'Deleting child book node properly allowed.'); @@ -546,7 +546,7 @@ function testBookDelete() { } entity_delete_multiple('node', $nids); $this->drupalPostForm('node/' . $this->book->id() . '/outline/remove', $edit, t('Remove')); - $node_storage->resetCache(array($this->book->id())); + $node_storage->resetCache([$this->book->id()]); $node = $node_storage->load($this->book->id()); $this->assertTrue(empty($node->book), 'Deleting childless top-level book node properly allowed.'); @@ -577,7 +577,7 @@ public function testBookOutline() { $this->drupalLogin($this->bookAuthor); // Create new node not yet a book. - $empty_book = $this->drupalCreateNode(array('type' => 'book')); + $empty_book = $this->drupalCreateNode(['type' => 'book']); $this->drupalGet('node/' . $empty_book->id() . '/outline'); $this->assertNoLink(t('Book outline'), 'Book Author is not allowed to outline'); @@ -587,7 +587,7 @@ public function testBookOutline() { $this->assertOptionSelected('edit-book-bid', 0, 'Node does not belong to a book'); $this->assertNoLink(t('Remove from book outline')); - $edit = array(); + $edit = []; $edit['book[bid]'] = '1'; $this->drupalPostForm('node/' . $empty_book->id() . '/outline', $edit, t('Add to book outline')); $node = \Drupal::entityManager()->getStorage('node')->load($empty_book->id()); @@ -606,11 +606,11 @@ public function testBookOutline() { $this->drupalGet('node/' . $book->id() . '/outline'); $this->assertRaw(t('Book outline')); $this->clickLink(t('Remove from book outline')); - $this->assertRaw(t('Are you sure you want to remove %title from the book hierarchy?', array('%title' => $book->label()))); + $this->assertRaw(t('Are you sure you want to remove %title from the book hierarchy?', ['%title' => $book->label()])); // Create a new node and set the book after the node was created. - $node = $this->drupalCreateNode(array('type' => 'book')); - $edit = array(); + $node = $this->drupalCreateNode(['type' => 'book']); + $edit = []; $edit['book[bid]'] = $node->id(); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $node = \Drupal::entityManager()->getStorage('node')->load($node->id()); @@ -634,7 +634,7 @@ public function testSaveBookLink() { $book_manager = \Drupal::service('book.manager'); // Mock a link for a new book. - $link = array('nid' => 1, 'has_children' => 0, 'original_bid' => 0, 'parent_depth_limit' => 8, 'pid' => 0, 'weight' => 0, 'bid' => 1); + $link = ['nid' => 1, 'has_children' => 0, 'original_bid' => 0, 'parent_depth_limit' => 8, 'pid' => 0, 'weight' => 0, 'bid' => 1]; $new = TRUE; // Save the link. diff --git a/core/modules/book/src/Tests/Views/BookRelationshipTest.php b/core/modules/book/src/Tests/Views/BookRelationshipTest.php index 2302e8b04e..c1f872803a 100644 --- a/core/modules/book/src/Tests/Views/BookRelationshipTest.php +++ b/core/modules/book/src/Tests/Views/BookRelationshipTest.php @@ -19,14 +19,14 @@ class BookRelationshipTest extends ViewTestBase { * * @var array */ - public static $testViews = array('test_book_view'); + public static $testViews = ['test_book_view']; /** * Modules to install. * * @var array */ - public static $modules = array('book_test_views', 'book', 'views'); + public static $modules = ['book_test_views', 'book', 'views']; /** * A book node. @@ -50,14 +50,14 @@ protected function setUp() { // Create users. $this->bookAuthor = $this->drupalCreateUser( - array( + [ 'create new books', 'create book content', 'edit own book content', 'add content to books', - ) + ] ); - ViewTestData::createTestViews(get_class($this), array('book_test_views')); + ViewTestData::createTestViews(get_class($this), ['book_test_views']); } /** @@ -70,7 +70,7 @@ protected function createBook() { $this->book = $this->createBookNode('new'); $book = $this->book; - $nodes = array(); + $nodes = []; // Node 0. $nodes[] = $this->createBookNode($book->id()); // Node 1. @@ -110,7 +110,7 @@ protected function createBookNode($book_nid, $parent = NULL) { // Used to ensure that when sorted nodes stay in same order. static $number = 0; - $edit = array(); + $edit = []; $edit['title[0][value]'] = $number . ' - SimpleTest test node ' . $this->randomMachineName(10); $edit['body[0][value]'] = 'SimpleTest test body ' . $this->randomMachineName(32) . ' ' . $this->randomMachineName(32); $edit['book[bid]'] = $book_nid; diff --git a/core/modules/book/tests/src/Kernel/BookUninstallTest.php b/core/modules/book/tests/src/Kernel/BookUninstallTest.php index bcd0812484..9430991ffe 100644 --- a/core/modules/book/tests/src/Kernel/BookUninstallTest.php +++ b/core/modules/book/tests/src/Kernel/BookUninstallTest.php @@ -27,11 +27,11 @@ protected function setUp() { parent::setUp(); $this->installEntitySchema('user'); $this->installEntitySchema('node'); - $this->installSchema('book', array('book')); - $this->installSchema('node', array('node_access')); - $this->installConfig(array('node', 'book', 'field')); + $this->installSchema('book', ['book']); + $this->installSchema('node', ['node_access']); + $this->installConfig(['node', 'book', 'field']); // For uninstall to work. - $this->installSchema('user', array('users_data')); + $this->installSchema('user', ['users_data']); } /** @@ -42,17 +42,17 @@ public function testBookUninstall() { $validation_reasons = \Drupal::service('module_installer')->validateUninstall(['book']); $this->assertEqual([], $validation_reasons, 'The book module is not required.'); - $content_type = NodeType::create(array( + $content_type = NodeType::create([ 'type' => $this->randomMachineName(), 'name' => $this->randomString(), - )); + ]); $content_type->save(); $book_config = $this->config('book.settings'); $allowed_types = $book_config->get('allowed_types'); $allowed_types[] = $content_type->id(); $book_config->set('allowed_types', $allowed_types)->save(); - $node = Node::create(array('title' => $this->randomString(), 'type' => $content_type->id())); + $node = Node::create(['title' => $this->randomString(), 'type' => $content_type->id()]); $node->book['bid'] = 'new'; $node->save(); @@ -60,7 +60,7 @@ public function testBookUninstall() { $validation_reasons = \Drupal::service('module_installer')->validateUninstall(['book']); $this->assertEqual(['To uninstall Book, delete all content that is part of a book'], $validation_reasons['book']); - $book_node = Node::create(array('title' => $this->randomString(), 'type' => 'book')); + $book_node = Node::create(['title' => $this->randomString(), 'type' => 'book']); $book_node->book['bid'] = FALSE; $book_node->save(); @@ -79,7 +79,7 @@ public function testBookUninstall() { $module_data = _system_rebuild_module_data(); $this->assertFalse(isset($module_data['book']->info['required']), 'The book module is not required.'); - $node = Node::create(array('title' => $this->randomString(), 'type' => $content_type->id())); + $node = Node::create(['title' => $this->randomString(), 'type' => $content_type->id()]); $node->save(); // One node exists but is not part of a book therefore the book module is // not required. @@ -87,7 +87,7 @@ public function testBookUninstall() { $this->assertEqual([], $validation_reasons, 'The book module is not required.'); // Uninstall the Book module and check the node type is deleted. - \Drupal::service('module_installer')->uninstall(array('book')); + \Drupal::service('module_installer')->uninstall(['book']); $this->assertNull(NodeType::load('book'), "The book node type does not exist."); } diff --git a/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookConfigsTest.php b/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookConfigsTest.php index ee3c0b2177..17a3bfff10 100644 --- a/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookConfigsTest.php +++ b/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookConfigsTest.php @@ -34,7 +34,7 @@ public function testBookSettings() { $config = $this->config('book.settings'); $this->assertIdentical('book', $config->get('child_type')); $this->assertIdentical('all pages', $config->get('block.navigation.mode')); - $this->assertIdentical(array('book'), $config->get('allowed_types')); + $this->assertIdentical(['book'], $config->get('allowed_types')); $this->assertConfigSchema(\Drupal::service('config.typed'), 'book.settings', $config->get()); } diff --git a/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookTest.php b/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookTest.php index ffcc3fec29..f6f1730e35 100644 --- a/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookTest.php +++ b/core/modules/book/tests/src/Kernel/Migrate/d6/MigrateBookTest.php @@ -32,7 +32,7 @@ protected function setUp() { * Tests the Drupal 6 book structure to Drupal 8 migration. */ public function testBook() { - $nodes = Node::loadMultiple(array(4, 5, 6, 7, 8)); + $nodes = Node::loadMultiple([4, 5, 6, 7, 8]); $this->assertIdentical('4', $nodes[4]->book['bid']); $this->assertIdentical('0', $nodes[4]->book['pid']); @@ -53,8 +53,8 @@ public function testBook() { $this->assertIdentical('5', $tree['49990 Node 4 4']['below']['50000 Node 5 5']['link']['nid']); $this->assertIdentical('6', $tree['49990 Node 4 4']['below']['50000 Node 5 5']['below']['50000 Node 6 6']['link']['nid']); $this->assertIdentical('7', $tree['49990 Node 4 4']['below']['50000 Node 5 5']['below']['50000 Node 7 7']['link']['nid']); - $this->assertIdentical(array(), $tree['49990 Node 4 4']['below']['50000 Node 5 5']['below']['50000 Node 6 6']['below']); - $this->assertIdentical(array(), $tree['49990 Node 4 4']['below']['50000 Node 5 5']['below']['50000 Node 7 7']['below']); + $this->assertIdentical([], $tree['49990 Node 4 4']['below']['50000 Node 5 5']['below']['50000 Node 6 6']['below']); + $this->assertIdentical([], $tree['49990 Node 4 4']['below']['50000 Node 5 5']['below']['50000 Node 7 7']['below']); } } diff --git a/core/modules/book/tests/src/Unit/BookManagerTest.php b/core/modules/book/tests/src/Unit/BookManagerTest.php index fdecbbe581..d7835539b5 100644 --- a/core/modules/book/tests/src/Unit/BookManagerTest.php +++ b/core/modules/book/tests/src/Unit/BookManagerTest.php @@ -59,7 +59,7 @@ class BookManagerTest extends UnitTestCase { protected function setUp() { $this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface'); $this->translation = $this->getStringTranslationStub(); - $this->configFactory = $this->getConfigFactoryStub(array()); + $this->configFactory = $this->getConfigFactoryStub([]); $this->bookOutlineStorage = $this->getMock('Drupal\book\BookOutlineStorageInterface'); $this->renderer = $this->getMock('\Drupal\Core\Render\RendererInterface'); $this->bookManager = new BookManager($this->entityManager, $this->translation, $this->configFactory, $this->bookOutlineStorage, $this->renderer); @@ -81,7 +81,7 @@ public function testGetBookParents($book, $parent, $expected) { * The test data. */ public function providerTestGetBookParents() { - $empty = array( + $empty = [ 'p1' => 0, 'p2' => 0, 'p3' => 0, @@ -91,27 +91,27 @@ public function providerTestGetBookParents() { 'p7' => 0, 'p8' => 0, 'p9' => 0, - ); - return array( + ]; + return [ // Provides a book without an existing parent. - array( - array('pid' => 0, 'nid' => 12), - array(), - array('depth' => 1, 'p1' => 12) + $empty, - ), + [ + ['pid' => 0, 'nid' => 12], + [], + ['depth' => 1, 'p1' => 12] + $empty, + ], // Provides a book with an existing parent. - array( - array('pid' => 11, 'nid' => 12), - array('nid' => 11, 'depth' => 1, 'p1' => 11,), - array('depth' => 2, 'p1' => 11, 'p2' => 12) + $empty, - ), + [ + ['pid' => 11, 'nid' => 12], + ['nid' => 11, 'depth' => 1, 'p1' => 11,], + ['depth' => 2, 'p1' => 11, 'p2' => 12] + $empty, + ], // Provides a book with two existing parents. - array( - array('pid' => 11, 'nid' => 12), - array('nid' => 11, 'depth' => 2, 'p1' => 10, 'p2' => 11), - array('depth' => 3, 'p1' => 10, 'p2' => 11, 'p3' => 12) + $empty, - ), - ); + [ + ['pid' => 11, 'nid' => 12], + ['nid' => 11, 'depth' => 2, 'p1' => 10, 'p2' => 11], + ['depth' => 3, 'p1' => 10, 'p2' => 11, 'p3' => 12] + $empty, + ], + ]; } } diff --git a/core/modules/book/tests/src/Unit/Menu/BookLocalTasksTest.php b/core/modules/book/tests/src/Unit/Menu/BookLocalTasksTest.php index 927241f0b2..5b7662c50a 100644 --- a/core/modules/book/tests/src/Unit/Menu/BookLocalTasksTest.php +++ b/core/modules/book/tests/src/Unit/Menu/BookLocalTasksTest.php @@ -12,10 +12,10 @@ class BookLocalTasksTest extends LocalTaskIntegrationTestBase { protected function setUp() { - $this->directoryList = array( + $this->directoryList = [ 'book' => 'core/modules/book', 'node' => 'core/modules/node', - ); + ]; parent::setUp(); } @@ -26,19 +26,19 @@ protected function setUp() { */ public function testBookAdminLocalTasks($route) { - $this->assertLocalTasks($route, array( - 0 => array('book.admin', 'book.settings'), - )); + $this->assertLocalTasks($route, [ + 0 => ['book.admin', 'book.settings'], + ]); } /** * Provides a list of routes to test. */ public function getBookAdminRoutes() { - return array( - array('book.admin'), - array('book.settings'), - ); + return [ + ['book.admin'], + ['book.settings'], + ]; } /** @@ -47,19 +47,19 @@ public function getBookAdminRoutes() { * @dataProvider getBookNodeRoutes */ public function testBookNodeLocalTasks($route) { - $this->assertLocalTasks($route, array( - 0 => array('entity.node.book_outline_form', 'entity.node.canonical', 'entity.node.edit_form', 'entity.node.delete_form', 'entity.node.version_history',), - )); + $this->assertLocalTasks($route, [ + 0 => ['entity.node.book_outline_form', 'entity.node.canonical', 'entity.node.edit_form', 'entity.node.delete_form', 'entity.node.version_history',], + ]); } /** * Provides a list of routes to test. */ public function getBookNodeRoutes() { - return array( - array('entity.node.canonical'), - array('entity.node.book_outline_form'), - ); + return [ + ['entity.node.canonical'], + ['entity.node.book_outline_form'], + ]; } } diff --git a/core/modules/breakpoint/breakpoint.module b/core/modules/breakpoint/breakpoint.module index 103edd9b0d..a0fd468df0 100644 --- a/core/modules/breakpoint/breakpoint.module +++ b/core/modules/breakpoint/breakpoint.module @@ -15,13 +15,13 @@ function breakpoint_help($route_name, RouteMatchInterface $route_match) { case 'help.page.breakpoint': $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Breakpoint module keeps track of the height, width, and resolution breakpoints where a responsive design needs to change in order to respond to different devices being used to view the site. This module does not have a user interface. For more information, see the online documentation for the Breakpoint module.', array(':docs' => 'https://www.drupal.org/documentation/modules/breakpoint')) . '

        '; + $output .= '

        ' . t('The Breakpoint module keeps track of the height, width, and resolution breakpoints where a responsive design needs to change in order to respond to different devices being used to view the site. This module does not have a user interface. For more information, see the online documentation for the Breakpoint module.', [':docs' => 'https://www.drupal.org/documentation/modules/breakpoint']) . '

        '; $output .= '

        ' . t('Terminology') . '

        '; $output .= '
        '; $output .= '
        ' . t('Breakpoint') . '
        '; $output .= '
        ' . t('A breakpoint separates the height or width of viewports (screens, printers, and other media output types) into steps. For instance, a width breakpoint of 40em creates two steps: one for widths up to 40em and one for widths above 40em. Breakpoints can be used to define when layouts should shift from one form to another, when images should be resized, and other changes that need to respond to changes in viewport height or width.') . '
        '; $output .= '
        ' . t('Media query') . '
        '; - $output .= '
        ' . t('Media queries are a formal way to encode breakpoints. For instance, a width breakpoint at 40em would be written as the media query "(min-width: 40em)". Breakpoints are really just media queries with some additional meta-data, such as a name and multiplier information.', array(':w3' => 'http://www.w3.org/TR/css3-mediaqueries/')) . '
        '; + $output .= '
        ' . t('Media queries are a formal way to encode breakpoints. For instance, a width breakpoint at 40em would be written as the media query "(min-width: 40em)". Breakpoints are really just media queries with some additional meta-data, such as a name and multiplier information.', [':w3' => 'http://www.w3.org/TR/css3-mediaqueries/']) . '
        '; $output .= '
        ' . t('Resolution multiplier') . '
        '; $output .= '
        ' . t('Resolution multipliers are a measure of the viewport\'s device resolution, defined to be the ratio between the physical pixel size of the active device and the device-independent pixel size. The Breakpoint module defines multipliers of 1, 1.5, and 2; when defining breakpoints, modules and themes can define which multipliers apply to each breakpoint.') . '
        '; $output .= '
        ' . t('Breakpoint group') . '
        '; diff --git a/core/modules/breakpoint/src/Breakpoint.php b/core/modules/breakpoint/src/Breakpoint.php index 0c51e6353f..0928d55961 100644 --- a/core/modules/breakpoint/src/Breakpoint.php +++ b/core/modules/breakpoint/src/Breakpoint.php @@ -16,7 +16,7 @@ class Breakpoint extends PluginBase implements BreakpointInterface { * {@inheritdoc} */ public function getLabel() { - return $this->t($this->pluginDefinition['label'], array(), array('context' => 'breakpoint')); + return $this->t($this->pluginDefinition['label'], [], ['context' => 'breakpoint']); } /** diff --git a/core/modules/breakpoint/src/BreakpointManager.php b/core/modules/breakpoint/src/BreakpointManager.php index 693ffa9b1e..30caf27ebe 100644 --- a/core/modules/breakpoint/src/BreakpointManager.php +++ b/core/modules/breakpoint/src/BreakpointManager.php @@ -50,7 +50,7 @@ class BreakpointManager extends DefaultPluginManager implements BreakpointManage /** * {@inheritdoc} */ - protected $defaults = array( + protected $defaults = [ // Human readable label for breakpoint. 'label' => '', // The media query for the breakpoint. @@ -58,14 +58,14 @@ class BreakpointManager extends DefaultPluginManager implements BreakpointManage // Weight used for ordering breakpoints. 'weight' => 0, // Breakpoint multipliers. - 'multipliers' => array(), + 'multipliers' => [], // The breakpoint group. 'group' => '', // Default class for breakpoint implementations. 'class' => 'Drupal\breakpoint\Breakpoint', // The plugin id. Set by the plugin system based on the top-level YAML key. 'id' => '', - ); + ]; /** * The theme handler. @@ -86,7 +86,7 @@ class BreakpointManager extends DefaultPluginManager implements BreakpointManage * * @var array */ - protected $instances = array(); + protected $instances = []; /** * Constructs a new BreakpointManager instance. @@ -106,7 +106,7 @@ public function __construct(ModuleHandlerInterface $module_handler, ThemeHandler $this->themeHandler = $theme_handler; $this->setStringTranslation($string_translation); $this->alterInfo('breakpoints'); - $this->setCacheBackend($cache_backend, 'breakpoints', array('breakpoints')); + $this->setCacheBackend($cache_backend, 'breakpoints', ['breakpoints']); } /** @@ -153,19 +153,19 @@ public function getBreakpointsByGroup($group) { $this->breakpointsByGroup[$group] = $cache->data; } else { - $breakpoints = array(); + $breakpoints = []; foreach ($this->getDefinitions() as $plugin_id => $plugin_definition) { if ($plugin_definition['group'] == $group) { $breakpoints[$plugin_id] = $plugin_definition; } } - uasort($breakpoints, array('Drupal\Component\Utility\SortArray', 'sortByWeightElement')); - $this->cacheBackend->set($this->cacheKey . ':' . $group, $breakpoints, Cache::PERMANENT, array('breakpoints')); + uasort($breakpoints, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']); + $this->cacheBackend->set($this->cacheKey . ':' . $group, $breakpoints, Cache::PERMANENT, ['breakpoints']); $this->breakpointsByGroup[$group] = $breakpoints; } } - $instances = array(); + $instances = []; foreach ($this->breakpointsByGroup[$group] as $plugin_id => $definition) { if (!isset($this->instances[$plugin_id])) { $this->instances[$plugin_id] = $this->createInstance($plugin_id); @@ -184,16 +184,16 @@ public function getGroups() { $groups = $cache->data; } else { - $groups = array(); + $groups = []; foreach ($this->getDefinitions() as $plugin_definition) { if (!isset($groups[$plugin_definition['group']])) { $groups[$plugin_definition['group']] = $plugin_definition['group']; } } - $this->cacheBackend->set($this->cacheKey . '::groups', $groups, Cache::PERMANENT, array('breakpoints')); + $this->cacheBackend->set($this->cacheKey . '::groups', $groups, Cache::PERMANENT, ['breakpoints']); } // Get the labels. This is not cacheable due to translation. - $group_labels = array(); + $group_labels = []; foreach ($groups as $group) { $group_labels[$group] = $this->getGroupLabel($group); } @@ -205,7 +205,7 @@ public function getGroups() { * {@inheritdoc} */ public function getGroupProviders($group) { - $providers = array(); + $providers = []; $breakpoints = $this->getBreakpointsByGroup($group); foreach ($breakpoints as $breakpoint) { $provider = $breakpoint->getProvider(); @@ -229,7 +229,7 @@ public function getGroupProviders($group) { public function clearCachedDefinitions() { parent::clearCachedDefinitions(); $this->breakpointsByGroup = NULL; - $this->instances = array(); + $this->instances = []; } /** @@ -251,7 +251,7 @@ protected function getGroupLabel($group) { } else { // Custom group label that should be translatable. - $label = $this->t($group, array(), array('context' => 'breakpoint')); + $label = $this->t($group, [], ['context' => 'breakpoint']); } return $label; } diff --git a/core/modules/breakpoint/tests/src/Kernel/BreakpointDiscoveryTest.php b/core/modules/breakpoint/tests/src/Kernel/BreakpointDiscoveryTest.php index 7683ea1f66..dc8175787b 100644 --- a/core/modules/breakpoint/tests/src/Kernel/BreakpointDiscoveryTest.php +++ b/core/modules/breakpoint/tests/src/Kernel/BreakpointDiscoveryTest.php @@ -16,11 +16,11 @@ class BreakpointDiscoveryTest extends KernelTestBase { * * @var array */ - public static $modules = array('system', 'breakpoint', 'breakpoint_module_test'); + public static $modules = ['system', 'breakpoint', 'breakpoint_module_test']; protected function setUp() { parent::setUp(); - \Drupal::service('theme_handler')->install(array('breakpoint_theme_test')); + \Drupal::service('theme_handler')->install(['breakpoint_theme_test']); } /** @@ -28,56 +28,56 @@ protected function setUp() { */ public function testThemeBreakpoints() { // Verify the breakpoint group for breakpoint_theme_test was created. - $expected_breakpoints = array( - 'breakpoint_theme_test.mobile' => array( + $expected_breakpoints = [ + 'breakpoint_theme_test.mobile' => [ 'label' => 'mobile', 'mediaQuery' => '(min-width: 0px)', 'weight' => 0, - 'multipliers' => array( + 'multipliers' => [ '1x', - ), + ], 'provider' => 'breakpoint_theme_test', 'id' => 'breakpoint_theme_test.mobile', 'group' => 'breakpoint_theme_test', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - 'breakpoint_theme_test.narrow' => array( + ], + 'breakpoint_theme_test.narrow' => [ 'label' => 'narrow', 'mediaQuery' => '(min-width: 560px)', 'weight' => 1, - 'multipliers' => array( + 'multipliers' => [ '1x', - ), + ], 'provider' => 'breakpoint_theme_test', 'id' => 'breakpoint_theme_test.narrow', 'group' => 'breakpoint_theme_test', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - 'breakpoint_theme_test.wide' => array( + ], + 'breakpoint_theme_test.wide' => [ 'label' => 'wide', 'mediaQuery' => '(min-width: 851px)', 'weight' => 2, - 'multipliers' => array( + 'multipliers' => [ '1x', - ), + ], 'provider' => 'breakpoint_theme_test', 'id' => 'breakpoint_theme_test.wide', 'group' => 'breakpoint_theme_test', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - 'breakpoint_theme_test.tv' => array( + ], + 'breakpoint_theme_test.tv' => [ 'label' => 'tv', 'mediaQuery' => 'only screen and (min-width: 1220px)', 'weight' => 3, - 'multipliers' => array( + 'multipliers' => [ '1x', - ), + ], 'provider' => 'breakpoint_theme_test', 'id' => 'breakpoint_theme_test.tv', 'group' => 'breakpoint_theme_test', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - ); + ], + ]; $breakpoints = \Drupal::service('breakpoint.manager')->getBreakpointsByGroup('breakpoint_theme_test'); foreach ($expected_breakpoints as $id => $expected_breakpoint) { @@ -93,46 +93,46 @@ public function testThemeBreakpoints() { */ public function testCustomBreakpointGroups() { // Verify the breakpoint group for breakpoint_theme_test.group2 was created. - $expected_breakpoints = array( - 'breakpoint_theme_test.group2.narrow' => array( + $expected_breakpoints = [ + 'breakpoint_theme_test.group2.narrow' => [ 'label' => 'narrow', 'mediaQuery' => '(min-width: 560px)', 'weight' => 0, - 'multipliers' => array( + 'multipliers' => [ '1x', '2x', - ), + ], 'provider' => 'breakpoint_theme_test', 'id' => 'breakpoint_theme_test.group2.narrow', 'group' => 'breakpoint_theme_test.group2', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - 'breakpoint_theme_test.group2.wide' => array( + ], + 'breakpoint_theme_test.group2.wide' => [ 'label' => 'wide', 'mediaQuery' => '(min-width: 851px)', 'weight' => 1, - 'multipliers' => array( + 'multipliers' => [ '1x', '2x', - ), + ], 'provider' => 'breakpoint_theme_test', 'id' => 'breakpoint_theme_test.group2.wide', 'group' => 'breakpoint_theme_test.group2', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - 'breakpoint_module_test.breakpoint_theme_test.group2.tv' => array( + ], + 'breakpoint_module_test.breakpoint_theme_test.group2.tv' => [ 'label' => 'tv', 'mediaQuery' => '(min-width: 6000px)', 'weight' => 2, - 'multipliers' => array( + 'multipliers' => [ '1x', - ), + ], 'provider' => 'breakpoint_module_test', 'id' => 'breakpoint_module_test.breakpoint_theme_test.group2.tv', 'group' => 'breakpoint_theme_test.group2', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - ); + ], + ]; $breakpoints = \Drupal::service('breakpoint.manager')->getBreakpointsByGroup('breakpoint_theme_test.group2'); foreach ($expected_breakpoints as $id => $expected_breakpoint) { @@ -144,33 +144,33 @@ public function testCustomBreakpointGroups() { * Test the breakpoint group created for a module. */ public function testModuleBreakpoints() { - $expected_breakpoints = array( - 'breakpoint_module_test.mobile' => array( + $expected_breakpoints = [ + 'breakpoint_module_test.mobile' => [ 'label' => 'mobile', 'mediaQuery' => '(min-width: 0px)', 'weight' => 0, - 'multipliers' => array( + 'multipliers' => [ '1x', - ), + ], 'provider' => 'breakpoint_module_test', 'id' => 'breakpoint_module_test.mobile', 'group' => 'breakpoint_module_test', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - 'breakpoint_module_test.standard' => array( + ], + 'breakpoint_module_test.standard' => [ 'label' => 'standard', 'mediaQuery' => '(min-width: 560px)', 'weight' => 1, - 'multipliers' => array( + 'multipliers' => [ '1x', '2x', - ), + ], 'provider' => 'breakpoint_module_test', 'id' => 'breakpoint_module_test.standard', 'group' => 'breakpoint_module_test', 'class' => 'Drupal\\breakpoint\\Breakpoint', - ), - ); + ], + ]; $breakpoints = \Drupal::service('breakpoint.manager')->getBreakpointsByGroup('breakpoint_module_test'); $this->assertEqual(array_keys($expected_breakpoints), array_keys($breakpoints)); @@ -180,20 +180,20 @@ public function testModuleBreakpoints() { * Test the collection of breakpoint groups. */ public function testBreakpointGroups() { - $expected = array( + $expected = [ 'bartik' => 'Bartik', 'breakpoint_module_test' => 'Breakpoint test module', 'breakpoint_theme_test' => 'Breakpoint test theme', 'breakpoint_theme_test.group2' => 'breakpoint_theme_test.group2', - ); + ]; $breakpoint_groups = \Drupal::service('breakpoint.manager')->getGroups(); // Ensure the order is as expected. Should be sorted by label. $this->assertIdentical($expected, $this->castSafeStrings($breakpoint_groups)); - $expected = array( + $expected = [ 'breakpoint_theme_test' => 'theme', 'breakpoint_module_test' => 'module', - ); + ]; $breakpoint_group_providers = \Drupal::service('breakpoint.manager')->getGroupProviders('breakpoint_theme_test.group2'); $this->assertEqual($expected, $breakpoint_group_providers); } diff --git a/core/modules/breakpoint/tests/src/Unit/BreakpointTest.php b/core/modules/breakpoint/tests/src/Unit/BreakpointTest.php index bdd5cd9341..4b8fd88465 100644 --- a/core/modules/breakpoint/tests/src/Unit/BreakpointTest.php +++ b/core/modules/breakpoint/tests/src/Unit/BreakpointTest.php @@ -24,9 +24,9 @@ class BreakpointTest extends UnitTestCase { * * @var array */ - protected $pluginDefinition = array( + protected $pluginDefinition = [ 'id' => 'breakpoint', - ); + ]; /** * The breakpoint under test. @@ -52,7 +52,7 @@ protected function setUp() { * Sets up the breakpoint defaults. */ protected function setupBreakpoint() { - $this->breakpoint = new Breakpoint(array(), $this->pluginId, $this->pluginDefinition); + $this->breakpoint = new Breakpoint([], $this->pluginId, $this->pluginDefinition); $this->breakpoint->setStringTranslation($this->stringTranslation); } @@ -62,7 +62,7 @@ protected function setupBreakpoint() { public function testGetLabel() { $this->pluginDefinition['label'] = 'Test label'; $this->setupBreakpoint(); - $this->assertEquals(new TranslatableMarkup('Test label', array(), array('context' => 'breakpoint'), $this->stringTranslation), $this->breakpoint->getLabel()); + $this->assertEquals(new TranslatableMarkup('Test label', [], ['context' => 'breakpoint'], $this->stringTranslation), $this->breakpoint->getLabel()); } /** @@ -88,9 +88,9 @@ public function testGetMediaQuery() { * @covers ::getMultipliers */ public function testGetMultipliers() { - $this->pluginDefinition['multipliers'] = array('1x', '2x'); + $this->pluginDefinition['multipliers'] = ['1x', '2x']; $this->setupBreakpoint(); - $this->assertSame(array('1x', '2x'), $this->breakpoint->getMultipliers()); + $this->assertSame(['1x', '2x'], $this->breakpoint->getMultipliers()); } /** diff --git a/core/modules/ckeditor/ckeditor.admin.inc b/core/modules/ckeditor/ckeditor.admin.inc index 14b2fd7c91..8a8f68c69b 100644 --- a/core/modules/ckeditor/ckeditor.admin.inc +++ b/core/modules/ckeditor/ckeditor.admin.inc @@ -29,8 +29,8 @@ function template_preprocess_ckeditor_settings_toolbar(&$variables) { // Create lists of active and disabled buttons. $editor = $variables['editor']; $plugins = $variables['plugins']; - $buttons = array(); - $multiple_buttons = array(); + $buttons = []; + $multiple_buttons = []; foreach ($plugins as $plugin_buttons) { foreach ($plugin_buttons as $button_name => $button) { $button['name'] = $button_name; @@ -40,11 +40,11 @@ function template_preprocess_ckeditor_settings_toolbar(&$variables) { $buttons[$button_name] = $button; } } - $button_groups = array(); - $active_buttons = array(); + $button_groups = []; + $active_buttons = []; $settings = $editor->getSettings(); foreach ($settings['toolbar']['rows'] as $row_number => $row) { - $button_groups[$row_number] = array(); + $button_groups[$row_number] = []; foreach ($row as $group) { foreach ($group['items'] as $button_name) { if (isset($buttons[$button_name])) { @@ -75,31 +75,31 @@ function template_preprocess_ckeditor_settings_toolbar(&$variables) { $value = $button['image_alternative']; } elseif (isset($button['image']) || isset($button['image' . $rtl])) { - $value = array( + $value = [ '#theme' => 'image', '#uri' => isset($button['image' . $rtl]) ? $button['image' . $rtl] : $button['image'], '#title' => $button['label'], '#prefix' => '', '#suffix' => '', - ); + ]; } else { $value = '?'; } // Build the button attributes. - $attributes = array( + $attributes = [ 'data-drupal-ckeditor-button-name' => $button['name'], - ); + ]; if (!empty($button['attributes'])) { $attributes = array_merge($attributes, $button['attributes']); } // Build the button item. - $button_item = array( + $button_item = [ 'value' => $value, 'attributes' => new Attribute($attributes), - ); + ]; // If this button has group information, add it to the attributes. if (!empty($button['group'])) { $button_item['group'] = $button['group']; @@ -114,14 +114,14 @@ function template_preprocess_ckeditor_settings_toolbar(&$variables) { }; // Assemble list of disabled buttons (which are always a single row). - $variables['active_buttons'] = array(); + $variables['active_buttons'] = []; foreach ($active_buttons as $row_number => $button_row) { foreach ($button_groups[$row_number] as $group_name) { $group_name = (string) $group_name; - $variables['active_buttons'][$row_number][$group_name] = array( + $variables['active_buttons'][$row_number][$group_name] = [ 'group_name_class' => Html::getClass($group_name), - 'buttons' => array(), - ); + 'buttons' => [], + ]; $buttons = array_filter($button_row, function ($button) use ($group_name) { return (string) $button['group'] === $group_name; }); @@ -131,12 +131,12 @@ function template_preprocess_ckeditor_settings_toolbar(&$variables) { } } // Assemble list of disabled buttons (which are always a single row). - $variables['disabled_buttons'] = array(); + $variables['disabled_buttons'] = []; foreach ($disabled_buttons as $button) { $variables['disabled_buttons'][] = $build_button_item($button, $rtl); } // Assemble list of multiple buttons that may be added multiple times. - $variables['multiple_buttons'] = array(); + $variables['multiple_buttons'] = []; foreach ($multiple_buttons as $button) { $variables['multiple_buttons'][] = $build_button_item($button, $rtl); } diff --git a/core/modules/ckeditor/ckeditor.module b/core/modules/ckeditor/ckeditor.module index 115afe24cf..7905253440 100644 --- a/core/modules/ckeditor/ckeditor.module +++ b/core/modules/ckeditor/ckeditor.module @@ -17,21 +17,21 @@ function ckeditor_help($route_name, RouteMatchInterface $route_match) { case 'help.page.ckeditor': $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The CKEditor module provides a highly-accessible, highly-usable visual text editor and adds a toolbar to text fields. Users can use buttons to format content and to create semantically correct and valid HTML. The CKEditor module uses the framework provided by the Text Editor module. It requires JavaScript to be enabled in the browser. For more information, see the online documentation for the CKEditor module and the CKEditor website.', array( ':doc_url' => 'https://www.drupal.org/documentation/modules/ckeditor', ':cke_url' => 'http://ckeditor.com', ':text_editor' => \Drupal::url('help.page', array('name' => 'editor')))) . '

        '; + $output .= '

        ' . t('The CKEditor module provides a highly-accessible, highly-usable visual text editor and adds a toolbar to text fields. Users can use buttons to format content and to create semantically correct and valid HTML. The CKEditor module uses the framework provided by the Text Editor module. It requires JavaScript to be enabled in the browser. For more information, see the online documentation for the CKEditor module and the CKEditor website.', [ ':doc_url' => 'https://www.drupal.org/documentation/modules/ckeditor', ':cke_url' => 'http://ckeditor.com', ':text_editor' => \Drupal::url('help.page', ['name' => 'editor'])]) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Enabling CKEditor for individual text formats') . '
        '; - $output .= '
        ' . t('CKEditor has to be enabled and configured separately for individual text formats from the Text formats and editors page because the filter settings for each text format can be different. For more information, see the Text Editor help page and Filter help page.', array(':formats' => \Drupal::url('filter.admin_overview'), ':text_editor' => \Drupal::url('help.page', array('name' => 'editor')), ':filter' => \Drupal::url('help.page', array('name' => 'filter')))) . '
        '; + $output .= '
        ' . t('CKEditor has to be enabled and configured separately for individual text formats from the Text formats and editors page because the filter settings for each text format can be different. For more information, see the Text Editor help page and Filter help page.', [':formats' => \Drupal::url('filter.admin_overview'), ':text_editor' => \Drupal::url('help.page', ['name' => 'editor']), ':filter' => \Drupal::url('help.page', ['name' => 'filter'])]) . '
        '; $output .= '
        ' . t('Configuring the toolbar') . '
        '; $output .= '
        ' . t('When CKEditor is chosen from the Text editor drop-down menu, its toolbar configuration is displayed. You can add and remove buttons from the Active toolbar by dragging and dropping them, and additional rows can be added to organize the buttons.') . '
        '; $output .= '
        ' . t('Formatting content') . '
        '; - $output .= '
        ' . t('CKEditor only allow users to format content in accordance with the filter configuration of the specific text format. If a text format excludes certain HTML tags, the corresponding toolbar buttons are not displayed to users when they edit a text field in this format. For more information see the Filter help page.', array(':filter' => \Drupal::url('help.page', array('name' => 'filter')))) . '
        '; + $output .= '
        ' . t('CKEditor only allow users to format content in accordance with the filter configuration of the specific text format. If a text format excludes certain HTML tags, the corresponding toolbar buttons are not displayed to users when they edit a text field in this format. For more information see the Filter help page.', [':filter' => \Drupal::url('help.page', ['name' => 'filter'])]) . '
        '; $output .= '
        ' . t('Toggling between formatted text and HTML source') . '
        '; $output .= '
        ' . t('If the Source button is available in the toolbar, users can click this button to disable the visual editor and edit the HTML source directly. After toggling back, the visual editor uses the allowed HTML tags to format the text — independent of whether buttons for these tags are available in the toolbar. If the text format is set to limit the use of HTML tags, then all excluded tags will be stripped out of the HTML source when the user toggles back to the text editor.') . '
        '; $output .= '
        ' . t('Check my spelling as I type') . '
        '; $output .= '
        ' . t('By default, CKEditor is configured to leverage your browser\'s spell check capability. Make sure your browser\'s spell checker is enabled in your browser\'s settings. To access suggested corrections for misspelled words, it may be necessary to hold the Control or command (Mac) key while right-clicking the misspelling.') . '
        '; $output .= '
        ' . t('Accessibility features') . '
        '; - $output .= '
        ' . t('The built in WYSIWYG editor (CKEditor) comes with a number of accessibility features. CKEditor comes with built in keyboard shortcuts, which can be beneficial for both power users and keyboard only users.', array(':features' => 'http://docs.ckeditor.com/#!/guide/dev_a11y', ':shortcuts' => 'http://docs.ckeditor.com/#!/guide/dev_shortcuts')) . '
        '; + $output .= '
        ' . t('The built in WYSIWYG editor (CKEditor) comes with a number of accessibility features. CKEditor comes with built in keyboard shortcuts, which can be beneficial for both power users and keyboard only users.', [':features' => 'http://docs.ckeditor.com/#!/guide/dev_a11y', ':shortcuts' => 'http://docs.ckeditor.com/#!/guide/dev_shortcuts']) . '
        '; $output .= '
        ' . t('Generating accessible content') . '
        '; $output .= '
        ' . t('HTML tables can be created with both table headers as well as caption/summary elements. Alt text is required by default on images added through CKEditor (note that this can be overridden). Semantic HTML5 figure/figcaption are available to add captions to images.') . '
        '; $output .= '
        '; @@ -43,12 +43,12 @@ function ckeditor_help($route_name, RouteMatchInterface $route_match) { * Implements hook_theme(). */ function ckeditor_theme() { - return array( - 'ckeditor_settings_toolbar' => array( + return [ + 'ckeditor_settings_toolbar' => [ 'file' => 'ckeditor.admin.inc', - 'variables' => array('editor' => NULL, 'plugins' => NULL), - ), - ); + 'variables' => ['editor' => NULL, 'plugins' => NULL], + ], + ]; } /** @@ -79,7 +79,7 @@ function ckeditor_ckeditor_css_alter(array &$css, Editor $editor) { * @endcode */ function _ckeditor_theme_css($theme = NULL) { - $css = array(); + $css = []; if (!isset($theme)) { $theme = \Drupal::config('system.theme')->get('default'); } diff --git a/core/modules/ckeditor/src/CKEditorPluginBase.php b/core/modules/ckeditor/src/CKEditorPluginBase.php index 2fb479834b..99f26630f2 100644 --- a/core/modules/ckeditor/src/CKEditorPluginBase.php +++ b/core/modules/ckeditor/src/CKEditorPluginBase.php @@ -41,14 +41,14 @@ function isInternal() { * {@inheritdoc} */ function getDependencies(Editor $editor) { - return array(); + return []; } /** * {@inheritdoc} */ function getLibraries(Editor $editor) { - return array(); + return []; } } diff --git a/core/modules/ckeditor/src/CKEditorPluginManager.php b/core/modules/ckeditor/src/CKEditorPluginManager.php index dd3315a35a..735cfa6678 100644 --- a/core/modules/ckeditor/src/CKEditorPluginManager.php +++ b/core/modules/ckeditor/src/CKEditorPluginManager.php @@ -68,8 +68,8 @@ public function __construct(\Traversable $namespaces, CacheBackendInterface $cac public function getEnabledPluginFiles(Editor $editor, $include_internal_plugins = FALSE) { $plugins = array_keys($this->getDefinitions()); $toolbar_buttons = $this->getEnabledButtons($editor); - $enabled_plugins = array(); - $additional_plugins = array(); + $enabled_plugins = []; + $additional_plugins = []; foreach ($plugins as $plugin_id) { $plugin = $this->createInstance($plugin_id); @@ -139,7 +139,7 @@ public static function getEnabledButtons(Editor $editor) { */ public function getButtons() { $plugins = array_keys($this->getDefinitions()); - $buttons_plugins = array(); + $buttons_plugins = []; foreach ($plugins as $plugin_id) { $plugin = $this->createInstance($plugin_id); @@ -167,16 +167,16 @@ public function injectPluginSettingsForm(array &$form, FormStateInterface $form_ foreach (array_keys($definitions) as $plugin_id) { $plugin = $this->createInstance($plugin_id); if ($plugin instanceof CKEditorPluginConfigurableInterface) { - $plugin_settings_form = array(); - $form['plugins'][$plugin_id] = array( + $plugin_settings_form = []; + $form['plugins'][$plugin_id] = [ '#type' => 'details', '#title' => $definitions[$plugin_id]['label'], '#open' => TRUE, '#group' => 'editor][settings][plugin_settings', - '#attributes' => array( + '#attributes' => [ 'data-ckeditor-plugin-id' => $plugin_id, - ), - ); + ], + ]; // Provide enough metadata for the drupal.ckeditor.admin library to // allow it to automatically show/hide the vertical tab containing the // settings for this plugin. Only do this if it's a CKEditor plugin that @@ -206,7 +206,7 @@ public function injectPluginSettingsForm(array &$form, FormStateInterface $form_ */ public function getCssFiles(Editor $editor) { $enabled_plugins = array_keys($this->getEnabledPluginFiles($editor, TRUE)); - $css_files = array(); + $css_files = []; foreach ($enabled_plugins as $plugin_id) { $plugin = $this->createInstance($plugin_id); diff --git a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImage.php b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImage.php index 8529adb5ad..90d4eae8f4 100644 --- a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImage.php +++ b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImage.php @@ -29,31 +29,31 @@ public function getFile() { * {@inheritdoc} */ public function getLibraries(Editor $editor) { - return array( + return [ 'core/drupal.ajax', - ); + ]; } /** * {@inheritdoc} */ public function getConfig(Editor $editor) { - return array( + return [ 'drupalImage_dialogTitleAdd' => $this->t('Insert Image'), 'drupalImage_dialogTitleEdit' => $this->t('Edit Image'), - ); + ]; } /** * {@inheritdoc} */ public function getButtons() { - return array( - 'DrupalImage' => array( + return [ + 'DrupalImage' => [ 'label' => $this->t('Image'), 'image' => drupal_get_path('module', 'ckeditor') . '/js/plugins/drupalimage/icons/drupalimage.png', - ), - ); + ], + ]; } /** @@ -66,7 +66,7 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor $form_state->loadInclude('editor', 'admin.inc'); $form['image_upload'] = editor_image_upload_settings_form($editor); $form['image_upload']['#attached']['library'][] = 'ckeditor/drupal.ckeditor.drupalimage.admin'; - $form['image_upload']['#element_validate'][] = array($this, 'validateImageUploadSettings'); + $form['image_upload']['#element_validate'][] = [$this, 'validateImageUploadSettings']; return $form; } @@ -80,9 +80,9 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor * @see editor_image_upload_settings_form() */ function validateImageUploadSettings(array $element, FormStateInterface $form_state) { - $settings = &$form_state->getValue(array('editor', 'settings', 'plugins', 'drupalimage', 'image_upload')); + $settings = &$form_state->getValue(['editor', 'settings', 'plugins', 'drupalimage', 'image_upload']); $form_state->get('editor')->setImageUploadSettings($settings); - $form_state->unsetValue(array('editor', 'settings', 'plugins', 'drupalimage')); + $form_state->unsetValue(['editor', 'settings', 'plugins', 'drupalimage']); } } diff --git a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImageCaption.php b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImageCaption.php index 16c3759d93..4241c3ca02 100644 --- a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImageCaption.php +++ b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalImageCaption.php @@ -30,16 +30,16 @@ public function isInternal() { * {@inheritdoc} */ public function getDependencies(Editor $editor) { - return array(); + return []; } /** * {@inheritdoc} */ public function getLibraries(Editor $editor) { - return array( + return [ 'ckeditor/drupal.ckeditor.plugins.drupalimagecaption', - ); + ]; } /** @@ -54,24 +54,24 @@ public function getFile() { */ public function getConfig(Editor $editor) { $format = $editor->getFilterFormat(); - return array( + return [ 'image2_captionedClass' => 'caption caption-img', - 'image2_alignClasses' => array('align-left', 'align-center', 'align-right'), + 'image2_alignClasses' => ['align-left', 'align-center', 'align-right'], 'drupalImageCaption_captionPlaceholderText' => $this->t('Enter caption here'), // Only enable those parts of DrupalImageCaption for which the // corresponding Drupal text filters are enabled. 'drupalImageCaption_captionFilterEnabled' => $format->filters('filter_caption')->status, 'drupalImageCaption_alignFilterEnabled' => $format->filters('filter_align')->status, - ); + ]; } /** * {@inheritdoc} */ public function getCssFiles(Editor $editor) { - return array( + return [ drupal_get_path('module', 'ckeditor') . '/css/plugins/drupalimagecaption/ckeditor.drupalimagecaption.css' - ); + ]; } /** diff --git a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalLink.php b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalLink.php index f347ebf230..a6363f6b73 100644 --- a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalLink.php +++ b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/DrupalLink.php @@ -27,19 +27,19 @@ public function getFile() { * {@inheritdoc} */ public function getLibraries(Editor $editor) { - return array( + return [ 'core/drupal.ajax', - ); + ]; } /** * {@inheritdoc} */ public function getConfig(Editor $editor) { - return array( + return [ 'drupalLink_dialogTitleAdd' => $this->t('Add Link'), 'drupalLink_dialogTitleEdit' => $this->t('Edit Link'), - ); + ]; } /** @@ -47,16 +47,16 @@ public function getConfig(Editor $editor) { */ public function getButtons() { $path = drupal_get_path('module', 'ckeditor') . '/js/plugins/drupallink'; - return array( - 'DrupalLink' => array( + return [ + 'DrupalLink' => [ 'label' => $this->t('Link'), 'image' => $path . '/icons/drupallink.png', - ), - 'DrupalUnlink' => array( + ], + 'DrupalUnlink' => [ 'label' => $this->t('Unlink'), 'image' => $path . '/icons/drupalunlink.png', - ), - ); + ], + ]; } } diff --git a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Internal.php b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Internal.php index 5011282c39..9a04ce72a2 100644 --- a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Internal.php +++ b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Internal.php @@ -100,14 +100,14 @@ public function getFile() { */ public function getConfig(Editor $editor) { // Reasonable defaults that provide expected basic behavior. - $config = array( + $config = [ 'customConfig' => '', // Don't load CKEditor's config.js file. 'pasteFromWordPromptCleanup' => TRUE, 'resize_dir' => 'vertical', - 'justifyClasses' => array('text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'), + 'justifyClasses' => ['text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'], 'entities' => FALSE, 'disableNativeSpellChecker' => FALSE, - ); + ]; // Add the allowedContent setting, which ensures CKEditor only allows tags // and attributes that are allowed by the text format for this text editor. @@ -144,145 +144,145 @@ public function getButtons() { ]; }; - return array( + return [ // "basicstyles" plugin. - 'Bold' => array( + 'Bold' => [ 'label' => $this->t('Bold'), 'image_alternative' => $button('bold'), 'image_alternative_rtl' => $button('bold', 'rtl'), - ), - 'Italic' => array( + ], + 'Italic' => [ 'label' => $this->t('Italic'), 'image_alternative' => $button('italic'), 'image_alternative_rtl' => $button('italic', 'rtl'), - ), - 'Underline' => array( + ], + 'Underline' => [ 'label' => $this->t('Underline'), 'image_alternative' => $button('underline'), 'image_alternative_rtl' => $button('underline', 'rtl'), - ), - 'Strike' => array( + ], + 'Strike' => [ 'label' => $this->t('Strike-through'), 'image_alternative' => $button('strike'), 'image_alternative_rtl' => $button('strike', 'rtl'), - ), - 'Superscript' => array( + ], + 'Superscript' => [ 'label' => $this->t('Superscript'), 'image_alternative' => $button('super script'), 'image_alternative_rtl' => $button('super script', 'rtl'), - ), - 'Subscript' => array( + ], + 'Subscript' => [ 'label' => $this->t('Subscript'), 'image_alternative' => $button('sub script'), 'image_alternative_rtl' => $button('sub script', 'rtl'), - ), + ], // "removeformat" plugin. - 'RemoveFormat' => array( + 'RemoveFormat' => [ 'label' => $this->t('Remove format'), 'image_alternative' => $button('remove format'), 'image_alternative_rtl' => $button('remove format', 'rtl'), - ), + ], // "justify" plugin. - 'JustifyLeft' => array( + 'JustifyLeft' => [ 'label' => $this->t('Align left'), 'image_alternative' => $button('justify left'), 'image_alternative_rtl' => $button('justify left', 'rtl'), - ), - 'JustifyCenter' => array( + ], + 'JustifyCenter' => [ 'label' => $this->t('Align center'), 'image_alternative' => $button('justify center'), 'image_alternative_rtl' => $button('justify center', 'rtl'), - ), - 'JustifyRight' => array( + ], + 'JustifyRight' => [ 'label' => $this->t('Align right'), 'image_alternative' => $button('justify right'), 'image_alternative_rtl' => $button('justify right', 'rtl'), - ), - 'JustifyBlock' => array( + ], + 'JustifyBlock' => [ 'label' => $this->t('Justify'), 'image_alternative' => $button('justify block'), 'image_alternative_rtl' => $button('justify block', 'rtl'), - ), + ], // "list" plugin. - 'BulletedList' => array( + 'BulletedList' => [ 'label' => $this->t('Bullet list'), 'image_alternative' => $button('bulleted list'), 'image_alternative_rtl' => $button('bulleted list', 'rtl'), - ), - 'NumberedList' => array( + ], + 'NumberedList' => [ 'label' => $this->t('Numbered list'), 'image_alternative' => $button('numbered list'), 'image_alternative_rtl' => $button('numbered list', 'rtl'), - ), + ], // "indent" plugin. - 'Outdent' => array( + 'Outdent' => [ 'label' => $this->t('Outdent'), 'image_alternative' => $button('outdent'), 'image_alternative_rtl' => $button('outdent', 'rtl'), - ), - 'Indent' => array( + ], + 'Indent' => [ 'label' => $this->t('Indent'), 'image_alternative' => $button('indent'), 'image_alternative_rtl' => $button('indent', 'rtl'), - ), + ], // "undo" plugin. - 'Undo' => array( + 'Undo' => [ 'label' => $this->t('Undo'), 'image_alternative' => $button('undo'), 'image_alternative_rtl' => $button('undo', 'rtl'), - ), - 'Redo' => array( + ], + 'Redo' => [ 'label' => $this->t('Redo'), 'image_alternative' => $button('redo'), 'image_alternative_rtl' => $button('redo', 'rtl'), - ), + ], // "blockquote" plugin. - 'Blockquote' => array( + 'Blockquote' => [ 'label' => $this->t('Blockquote'), 'image_alternative' => $button('blockquote'), 'image_alternative_rtl' => $button('blockquote', 'rtl'), - ), + ], // "horizontalrule" plugin - 'HorizontalRule' => array( + 'HorizontalRule' => [ 'label' => $this->t('Horizontal rule'), 'image_alternative' => $button('horizontal rule'), 'image_alternative_rtl' => $button('horizontal rule', 'rtl'), - ), + ], // "clipboard" plugin. - 'Cut' => array( + 'Cut' => [ 'label' => $this->t('Cut'), 'image_alternative' => $button('cut'), 'image_alternative_rtl' => $button('cut', 'rtl'), - ), - 'Copy' => array( + ], + 'Copy' => [ 'label' => $this->t('Copy'), 'image_alternative' => $button('copy'), 'image_alternative_rtl' => $button('copy', 'rtl'), - ), - 'Paste' => array( + ], + 'Paste' => [ 'label' => $this->t('Paste'), 'image_alternative' => $button('paste'), 'image_alternative_rtl' => $button('paste', 'rtl'), - ), + ], // "pastetext" plugin. - 'PasteText' => array( + 'PasteText' => [ 'label' => $this->t('Paste Text'), 'image_alternative' => $button('paste text'), 'image_alternative_rtl' => $button('paste text', 'rtl'), - ), + ], // "pastefromword" plugin. - 'PasteFromWord' => array( + 'PasteFromWord' => [ 'label' => $this->t('Paste from Word'), 'image_alternative' => $button('paste from word'), 'image_alternative_rtl' => $button('paste from word', 'rtl'), - ), + ], // "specialchar" plugin. - 'SpecialChar' => array( + 'SpecialChar' => [ 'label' => $this->t('Character map'), 'image_alternative' => $button('special char'), 'image_alternative_rtl' => $button('special char', 'rtl'), - ), - 'Format' => array( + ], + 'Format' => [ 'label' => $this->t('HTML block format'), 'image_alternative' => [ '#type' => 'inline_template', @@ -291,33 +291,33 @@ public function getButtons() { 'format_text' => $this->t('Format'), ], ], - ), + ], // "table" plugin. - 'Table' => array( + 'Table' => [ 'label' => $this->t('Table'), 'image_alternative' => $button('table'), 'image_alternative_rtl' => $button('table', 'rtl'), - ), + ], // "showblocks" plugin. - 'ShowBlocks' => array( + 'ShowBlocks' => [ 'label' => $this->t('Show blocks'), 'image_alternative' => $button('show blocks'), 'image_alternative_rtl' => $button('show blocks', 'rtl'), - ), + ], // "sourcearea" plugin. - 'Source' => array( + 'Source' => [ 'label' => $this->t('Source code'), 'image_alternative' => $button('source'), 'image_alternative_rtl' => $button('source', 'rtl'), - ), + ], // "maximize" plugin. - 'Maximize' => array( + 'Maximize' => [ 'label' => $this->t('Maximize'), 'image_alternative' => $button('maximize'), 'image_alternative_rtl' => $button('maximize', 'rtl'), - ), + ], // No plugin, separator "button" for toolbar builder UI use only. - '-' => array( + '-' => [ 'label' => $this->t('Separator'), 'image_alternative' => [ '#type' => 'inline_template', @@ -326,13 +326,13 @@ public function getButtons() { 'button_separator_text' => $this->t('Button separator'), ], ], - 'attributes' => array( - 'class' => array('ckeditor-button-separator'), + 'attributes' => [ + 'class' => ['ckeditor-button-separator'], 'data-drupal-ckeditor-type' => 'separator', - ), + ], 'multiple' => TRUE, - ), - ); + ], + ]; } /** @@ -350,7 +350,7 @@ protected function generateFormatTagsSetting(Editor $editor) { // When no text format is associated yet, assume no tag is allowed. // @see \Drupal\Editor\EditorInterface::hasAssociatedFilterFormat() if (!$editor->hasAssociatedFilterFormat()) { - return array(); + return []; } $format = $editor->getFilterFormat(); @@ -416,7 +416,7 @@ protected function generateACFSettings(Editor $editor) { // When nothing is disallowed, set allowedContent to true. if (!in_array(FilterInterface::TYPE_HTML_RESTRICTOR, $filter_types)) { - return array(TRUE, FALSE); + return [TRUE, FALSE]; } // Generate setting that accurately reflects allowed tags and attributes. else { @@ -441,10 +441,10 @@ protected function generateACFSettings(Editor $editor) { // When all HTML is allowed, also set allowedContent to true and // disallowedContent to false. if ($html_restrictions === FALSE) { - return array(TRUE, FALSE); + return [TRUE, FALSE]; } - $allowed = array(); - $disallowed = array(); + $allowed = []; + $disallowed = []; if (isset($html_restrictions['forbidden_tags'])) { foreach ($html_restrictions['forbidden_tags'] as $tag) { $disallowed[$tag] = TRUE; @@ -453,11 +453,11 @@ protected function generateACFSettings(Editor $editor) { foreach ($html_restrictions['allowed'] as $tag => $attributes) { // Tell CKEditor the tag is allowed, but no attributes. if ($attributes === FALSE) { - $allowed[$tag] = array( + $allowed[$tag] = [ 'attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE, - ); + ]; } // Tell CKEditor the tag is allowed, as well as any attribute on it. The // "style" and "class" attributes are handled separately by CKEditor: @@ -465,11 +465,11 @@ protected function generateACFSettings(Editor $editor) { // attributes, unless you state specific values for them that are // allowed. Or, in this case: any value for them is allowed. elseif ($attributes === TRUE) { - $allowed[$tag] = array( + $allowed[$tag] = [ 'attributes' => TRUE, 'styles' => TRUE, 'classes' => TRUE, - ); + ]; // We've just marked that any value for the "style" and "class" // attributes is allowed. However, that may not be the case: the "*" // tag may still apply restrictions. @@ -518,11 +518,11 @@ protected function generateACFSettings(Editor $editor) { elseif (is_array($attributes)) { // Set defaults (these will be overridden below if more specific // values are present). - $allowed[$tag] = array( + $allowed[$tag] = [ 'attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE, - ); + ]; // Configure allowed attributes, allowed "style" attribute values and // allowed "class" attribute values. // CKEditor only allows specific values for the "class" and "style" @@ -600,7 +600,7 @@ protected function generateACFSettings(Editor $editor) { ksort($allowed); ksort($disallowed); - return array($allowed, $disallowed); + return [$allowed, $disallowed]; } } diff --git a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Language.php b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Language.php index 980d5e909a..31ce08fc07 100644 --- a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Language.php +++ b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/Language.php @@ -104,7 +104,7 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor } $predefined_languages = LanguageManager::getStandardLanguageList(); - $form['language_list'] = array( + $form['language_list'] = [ '#title' => $this->t('Language list'), '#title_display' => 'invisible', '#type' => 'select', @@ -118,7 +118,7 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor '@count' => count($predefined_languages), ]), '#attached' => ['library' => ['ckeditor/drupal.ckeditor.language.admin']], - ); + ]; return $form; } @@ -127,9 +127,9 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor * {@inheritdoc} */ function getCssFiles(Editor $editor) { - return array( + return [ drupal_get_path('module', 'ckeditor') . '/css/plugins/language/ckeditor.language.css' - ); + ]; } } diff --git a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php index 9c4f224752..7b3386efe0 100644 --- a/core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php +++ b/core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php @@ -36,7 +36,7 @@ public function getFile() { * {@inheritdoc} */ public function getConfig(Editor $editor) { - $config = array(); + $config = []; $settings = $editor->getSettings(); if (!isset($settings['plugins']['stylescombo']['styles'])) { return $config; @@ -50,8 +50,8 @@ public function getConfig(Editor $editor) { * {@inheritdoc} */ public function getButtons() { - return array( - 'Styles' => array( + return [ + 'Styles' => [ 'label' => $this->t('Font style'), 'image_alternative' => [ '#type' => 'inline_template', @@ -60,8 +60,8 @@ public function getButtons() { 'styles_text' => $this->t('Styles'), ], ], - ), - ); + ], + ]; } /** @@ -69,25 +69,25 @@ public function getButtons() { */ public function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) { // Defaults. - $config = array('styles' => ''); + $config = ['styles' => '']; $settings = $editor->getSettings(); if (isset($settings['plugins']['stylescombo'])) { $config = $settings['plugins']['stylescombo']; } - $form['styles'] = array( + $form['styles'] = [ '#title' => $this->t('Styles'), '#title_display' => 'invisible', '#type' => 'textarea', '#default_value' => $config['styles'], '#description' => $this->t('A list of classes that will be provided in the "Styles" dropdown. Enter one or more classes on each line in the format: element.classA.classB|Label. Example: h1.title|Title. Advanced example: h1.fancy.title|Fancy title.
        These styles should be available in your theme\'s CSS file.'), - '#attached' => array( - 'library' => array('ckeditor/drupal.ckeditor.stylescombo.admin'), - ), - '#element_validate' => array( - array($this, 'validateStylesValue'), - ), - ); + '#attached' => [ + 'library' => ['ckeditor/drupal.ckeditor.stylescombo.admin'], + ], + '#element_validate' => [ + [$this, 'validateStylesValue'], + ], + ]; return $form; } @@ -120,7 +120,7 @@ public function validateStylesValue(array $element, FormStateInterface $form_sta * syntax is invalid. */ protected function generateStylesSetSetting($styles) { - $styles_set = array(); + $styles_set = []; // Early-return when empty. $styles = trim($styles); @@ -128,7 +128,7 @@ protected function generateStylesSetSetting($styles) { return $styles_set; } - $styles = str_replace(array("\r\n", "\r"), "\n", $styles); + $styles = str_replace(["\r\n", "\r"], "\n", $styles); foreach (explode("\n", $styles) as $style) { $style = trim($style); @@ -149,14 +149,14 @@ protected function generateStylesSetSetting($styles) { // Build the data structure CKEditor's stylescombo plugin expects. // @see http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Styles - $configured_style = array( + $configured_style = [ 'name' => trim($label), 'element' => trim($element), - ); + ]; if (!empty($classes)) { - $configured_style['attributes'] = array( + $configured_style['attributes'] = [ 'class' => implode(' ', array_map('trim', $classes)) - ); + ]; } $styles_set[] = $configured_style; } diff --git a/core/modules/ckeditor/src/Plugin/Editor/CKEditor.php b/core/modules/ckeditor/src/Plugin/Editor/CKEditor.php index ba054a61ce..d3a7f6b737 100644 --- a/core/modules/ckeditor/src/Plugin/Editor/CKEditor.php +++ b/core/modules/ckeditor/src/Plugin/Editor/CKEditor.php @@ -102,36 +102,36 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function getDefaultSettings() { - return array( - 'toolbar' => array( - 'rows' => array( + return [ + 'toolbar' => [ + 'rows' => [ // Button groups. - array( - array( + [ + [ 'name' => $this->t('Formatting'), - 'items' => array('Bold', 'Italic',), - ), - array( + 'items' => ['Bold', 'Italic',], + ], + [ 'name' => $this->t('Links'), - 'items' => array('DrupalLink', 'DrupalUnlink',), - ), - array( + 'items' => ['DrupalLink', 'DrupalUnlink',], + ], + [ 'name' => $this->t('Lists'), - 'items' => array('BulletedList', 'NumberedList',), - ), - array( + 'items' => ['BulletedList', 'NumberedList',], + ], + [ 'name' => $this->t('Media'), - 'items' => array('Blockquote', 'DrupalImage',), - ), - array( + 'items' => ['Blockquote', 'DrupalImage',], + ], + [ 'name' => $this->t('Tools'), - 'items' => array('Source',), - ), - ), - ), - ), + 'items' => ['Source',], + ], + ], + ], + ], 'plugins' => ['language' => ['language_list' => 'un']], - ); + ]; } /** @@ -140,39 +140,39 @@ public function getDefaultSettings() { public function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) { $settings = $editor->getSettings(); - $ckeditor_settings_toolbar = array( + $ckeditor_settings_toolbar = [ '#theme' => 'ckeditor_settings_toolbar', '#editor' => $editor, '#plugins' => $this->ckeditorPluginManager->getButtons(), - ); - $form['toolbar'] = array( + ]; + $form['toolbar'] = [ '#type' => 'container', - '#attached' => array( - 'library' => array('ckeditor/drupal.ckeditor.admin'), + '#attached' => [ + 'library' => ['ckeditor/drupal.ckeditor.admin'], 'drupalSettings' => [ 'ckeditor' => [ 'toolbarAdmin' => (string) $this->renderer->renderPlain($ckeditor_settings_toolbar), ], ], - ), - '#attributes' => array('class' => array('ckeditor-toolbar-configuration')), - ); + ], + '#attributes' => ['class' => ['ckeditor-toolbar-configuration']], + ]; - $form['toolbar']['button_groups'] = array( + $form['toolbar']['button_groups'] = [ '#type' => 'textarea', '#title' => $this->t('Toolbar buttons'), '#default_value' => json_encode($settings['toolbar']['rows']), - '#attributes' => array('class' => array('ckeditor-toolbar-textarea')), - ); + '#attributes' => ['class' => ['ckeditor-toolbar-textarea']], + ]; // CKEditor plugin settings, if any. - $form['plugin_settings'] = array( + $form['plugin_settings'] = [ '#type' => 'vertical_tabs', '#title' => $this->t('CKEditor plugin settings'), - '#attributes' => array( + '#attributes' => [ 'id' => 'ckeditor-plugin-settings', - ), - ); + ], + ]; $this->ckeditorPluginManager->injectPluginSettingsForm($form, $form_state, $editor); if (count(Element::children($form['plugins'])) === 0) { unset($form['plugins']); @@ -186,7 +186,7 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor // settings to be updated accordingly. // Get a list of all external plugins and their corresponding files. $plugins = array_keys($this->ckeditorPluginManager->getDefinitions()); - $all_external_plugins = array(); + $all_external_plugins = []; foreach ($plugins as $plugin_id) { $plugin = $this->ckeditorPluginManager->createInstance($plugin_id); if (!$plugin->isInternal()) { @@ -196,37 +196,37 @@ public function settingsForm(array $form, FormStateInterface $form_state, Editor // Get a list of all buttons that are provided by all plugins. $all_buttons = array_reduce($this->ckeditorPluginManager->getButtons(), function($result, $item) { return array_merge($result, array_keys($item)); - }, array()); + }, []); // Build a fake Editor object, which we'll use to generate JavaScript // settings for this fake Editor instance. - $fake_editor = Editor::create(array( + $fake_editor = Editor::create([ 'format' => $editor->id(), 'editor' => 'ckeditor', - 'settings' => array( + 'settings' => [ // Single toolbar row, single button group, all existing buttons. - 'toolbar' => array( - 'rows' => array( - 0 => array( - 0 => array( + 'toolbar' => [ + 'rows' => [ + 0 => [ + 0 => [ 'name' => 'All existing buttons', 'items' => $all_buttons, - ) - ) - ), - ), + ] + ] + ], + ], 'plugins' => $settings['plugins'], - ), - )); + ], + ]); $config = $this->getJSSettings($fake_editor); // Remove the ACF configuration that is generated based on filter settings, // because otherwise we cannot retrieve per-feature metadata. unset($config['allowedContent']); - $form['hidden_ckeditor'] = array( + $form['hidden_ckeditor'] = [ '#markup' => '', - '#attached' => array( + '#attached' => [ 'drupalSettings' => ['ckeditor' => ['hiddenCKEditorConfig' => $config]], - ), - ); + ], + ]; return $form; } @@ -238,7 +238,7 @@ public function settingsFormSubmit(array $form, FormStateInterface $form_state) // Modify the toolbar settings by reference. The values in // $form_state->getValue(array('editor', 'settings')) will be saved directly // by editor_form_filter_admin_format_submit(). - $toolbar_settings = &$form_state->getValue(array('editor', 'settings', 'toolbar')); + $toolbar_settings = &$form_state->getValue(['editor', 'settings', 'toolbar']); // The rows key is not built into the form structure, so decode the button // groups data into this new key and remove the button_groups key. @@ -246,8 +246,8 @@ public function settingsFormSubmit(array $form, FormStateInterface $form_state) unset($toolbar_settings['button_groups']); // Remove the plugin settings' vertical tabs state; no need to save that. - if ($form_state->hasValue(array('editor', 'settings', 'plugins'))) { - $form_state->unsetValue(array('editor', 'settings', 'plugin_settings')); + if ($form_state->hasValue(['editor', 'settings', 'plugins'])) { + $form_state->unsetValue(['editor', 'settings', 'plugin_settings']); } } @@ -255,7 +255,7 @@ public function settingsFormSubmit(array $form, FormStateInterface $form_state) * {@inheritdoc} */ public function getJSSettings(Editor $editor) { - $settings = array(); + $settings = []; // Get the settings for all enabled plugins, even the internal ones. $enabled_plugins = array_keys($this->ckeditorPluginManager->getEnabledPluginFiles($editor, TRUE)); @@ -279,7 +279,7 @@ public function getJSSettings(Editor $editor) { // Next, set the most fundamental CKEditor settings. $external_plugin_files = $this->ckeditorPluginManager->getEnabledPluginFiles($editor); - $settings += array( + $settings += [ 'toolbar' => $this->buildToolbarJSSetting($editor), 'contentsCss' => $this->buildContentsCssJSSetting($editor), 'extraPlugins' => implode(',', array_keys($external_plugin_files)), @@ -290,15 +290,15 @@ public function getJSSettings(Editor $editor) { // styles.js by default. // See http://dev.ckeditor.com/ticket/9992#comment:9. 'stylesSet' => FALSE, - ); + ]; // Finally, set Drupal-specific CKEditor settings. $root_relative_file_url = function ($uri) { return file_url_transform_relative(file_create_url($uri)); }; - $settings += array( + $settings += [ 'drupalExternalPlugins' => array_map($root_relative_file_url, $external_plugin_files), - ); + ]; // Parse all CKEditor plugin JavaScript files for translations. if ($this->moduleHandler->moduleExists('locale')) { @@ -326,7 +326,7 @@ public function getLangcodes() { $langcodes = $langcode_cache->data; } if (empty($langcodes)) { - $langcodes = array(); + $langcodes = []; // Collect languages included with CKEditor based on file listing. $files = scandir('core/assets/vendor/ckeditor/lang'); foreach ($files as $file) { @@ -341,7 +341,7 @@ public function getLangcodes() { // Get language mapping if available to map to Drupal language codes. // This is configurable in the user interface and not expensive to get, so // we don't include it in the cached language list. - $language_mappings = $this->moduleHandler->moduleExists('language') ? language_get_browser_drupal_langcode_mappings() : array(); + $language_mappings = $this->moduleHandler->moduleExists('language') ? language_get_browser_drupal_langcode_mappings() : []; foreach ($langcodes as $langcode) { // If this language code is available in a Drupal mapping, use that to // compute a possibility for matching from the Drupal langcode to the @@ -363,9 +363,9 @@ public function getLangcodes() { * {@inheritdoc} */ public function getLibraries(Editor $editor) { - $libraries = array( + $libraries = [ 'ckeditor/drupal.ckeditor', - ); + ]; // Get the required libraries for any enabled plugins. $enabled_plugins = array_keys($this->ckeditorPluginManager->getEnabledPluginFiles($editor)); @@ -389,7 +389,7 @@ public function getLibraries(Editor $editor) { * An array containing the "toolbar" configuration. */ public function buildToolbarJSSetting(Editor $editor) { - $toolbar = array(); + $toolbar = []; $settings = $editor->getSettings(); foreach ($settings['toolbar']['rows'] as $row) { @@ -412,15 +412,15 @@ public function buildToolbarJSSetting(Editor $editor) { * An array containing the "contentsCss" configuration. */ public function buildContentsCssJSSetting(Editor $editor) { - $css = array( + $css = [ drupal_get_path('module', 'ckeditor') . '/css/ckeditor-iframe.css', drupal_get_path('module', 'system') . '/css/components/align.module.css', - ); + ]; $this->moduleHandler->alter('ckeditor_css', $css, $editor); // Get a list of all enabled plugins' iframe instance CSS files. $plugins_css = array_reduce($this->ckeditorPluginManager->getCssFiles($editor), function($result, $item) { return array_merge($result, array_values($item)); - }, array()); + }, []); $css = array_merge($css, $plugins_css); $css = array_merge($css, _ckeditor_theme_css()); $css = array_map('file_create_url', $css); diff --git a/core/modules/ckeditor/src/Tests/CKEditorAdminTest.php b/core/modules/ckeditor/src/Tests/CKEditorAdminTest.php index d10180db3b..ed08c26d0c 100644 --- a/core/modules/ckeditor/src/Tests/CKEditorAdminTest.php +++ b/core/modules/ckeditor/src/Tests/CKEditorAdminTest.php @@ -20,7 +20,7 @@ class CKEditorAdminTest extends WebTestBase { * * @var array */ - public static $modules = array('filter', 'editor', 'ckeditor'); + public static $modules = ['filter', 'editor', 'ckeditor']; /** * A user with the 'administer filters' permission. @@ -33,16 +33,16 @@ protected function setUp() { parent::setUp(); // Create text format. - $filtered_html_format = FilterFormat::create(array( + $filtered_html_format = FilterFormat::create([ 'format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, - 'filters' => array(), - )); + 'filters' => [], + ]); $filtered_html_format->save(); // Create admin user. - $this->adminUser = $this->drupalCreateUser(array('administer filters')); + $this->adminUser = $this->drupalCreateUser(['administer filters']); } /** @@ -70,43 +70,43 @@ function testExistingFormat() { $this->assertTrue(((string) $options[0]['selected']) === 'selected', 'Option 1 ("None") is selected.'); // Select the "CKEditor" editor and click the "Save configuration" button. - $edit = array( + $edit = [ 'editor[editor]' => 'ckeditor', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save configuration')); $this->assertRaw(t('You must configure the selected text editor.')); // Ensure the CKEditor editor returns the expected default settings. - $expected_default_settings = array( - 'toolbar' => array( - 'rows' => array( + $expected_default_settings = [ + 'toolbar' => [ + 'rows' => [ // Button groups - array( - array( + [ + [ 'name' => 'Formatting', - 'items' => array('Bold', 'Italic',), - ), - array( + 'items' => ['Bold', 'Italic',], + ], + [ 'name' => 'Links', - 'items' => array('DrupalLink', 'DrupalUnlink',), - ), - array( + 'items' => ['DrupalLink', 'DrupalUnlink',], + ], + [ 'name' => 'Lists', - 'items' => array('BulletedList', 'NumberedList',), - ), - array( + 'items' => ['BulletedList', 'NumberedList',], + ], + [ 'name' => 'Media', - 'items' => array('Blockquote', 'DrupalImage',), - ), - array( + 'items' => ['Blockquote', 'DrupalImage',], + ], + [ 'name' => 'Tools', - 'items' => array('Source',), - ), - ), - ), - ), + 'items' => ['Source',], + ], + ], + ], + ], 'plugins' => ['language' => ['language_list' => 'un']], - ); + ]; $this->assertIdentical($this->castSafeStrings($ckeditor->getDefaultSettings()), $expected_default_settings); // Keep the "CKEditor" editor selected and click the "Configure" button. @@ -115,11 +115,11 @@ function testExistingFormat() { $this->assertFalse($editor, 'No Editor config entity exists yet.'); // Ensure that drupalSettings is correct. - $ckeditor_settings_toolbar = array( + $ckeditor_settings_toolbar = [ '#theme' => 'ckeditor_settings_toolbar', '#editor' => Editor::create(['editor' => 'ckeditor']), '#plugins' => $this->container->get('plugin.manager.ckeditor.plugin')->getButtons(), - ); + ]; $this->assertEqual( $this->drupalSettings['ckeditor']['toolbarAdmin'], $this->container->get('renderer')->renderPlain($ckeditor_settings_toolbar), @@ -148,9 +148,9 @@ function testExistingFormat() { // Configure the Styles plugin, and ensure the updated settings are saved. $this->drupalGet('admin/config/content/formats/manage/filtered_html'); - $edit = array( + $edit = [ 'editor[settings][plugins][stylescombo][styles]' => "h1.title|Title\np.callout|Callout\n\n", - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save configuration')); $expected_settings['plugins']['stylescombo']['styles'] = "h1.title|Title\np.callout|Callout\n\n"; $editor = Editor::load('filtered_html'); @@ -161,13 +161,13 @@ function testExistingFormat() { // done via drag and drop, but here we can only emulate the end result of // that interaction). Test multiple toolbar rows and a divider within a row. $this->drupalGet('admin/config/content/formats/manage/filtered_html'); - $expected_settings['toolbar']['rows'][0][] = array( + $expected_settings['toolbar']['rows'][0][] = [ 'name' => 'Action history', - 'items' => array('Undo', '|', 'Redo', 'JustifyCenter'), - ); - $edit = array( + 'items' => ['Undo', '|', 'Redo', 'JustifyCenter'], + ]; + $edit = [ 'editor[settings][toolbar][button_groups]' => json_encode($expected_settings['toolbar']['rows']), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save configuration')); $editor = Editor::load('filtered_html'); $this->assertTrue($editor instanceof Editor, 'An Editor config entity exists.'); @@ -191,7 +191,7 @@ function testExistingFormat() { // Now enable the ckeditor_test module, which provides one configurable // CKEditor plugin — this should not affect the Editor config entity. - \Drupal::service('module_installer')->install(array('ckeditor_test')); + \Drupal::service('module_installer')->install(['ckeditor_test']); $this->resetAll(); $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions(); $this->drupalGet('admin/config/content/formats/manage/filtered_html'); @@ -203,9 +203,9 @@ function testExistingFormat() { // Finally, check the "Ultra llama mode" checkbox. $this->drupalGet('admin/config/content/formats/manage/filtered_html'); - $edit = array( + $edit = [ 'editor[settings][plugins][llama_contextual_and_button][ultra_llama_mode]' => '1', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save configuration')); $this->drupalGet('admin/config/content/formats/manage/filtered_html'); $ultra_llama_mode_checkbox = $this->xpath('//input[@type="checkbox" and @name="editor[settings][plugins][llama_contextual_and_button][ultra_llama_mode]" and @checked="checked"]'); @@ -239,11 +239,11 @@ function testNewFormat() { // Name our fancy new text format, select the "CKEditor" editor and click // the "Configure" button. - $edit = array( + $edit = [ 'name' => 'My amazing text format', 'format' => 'amazing_format', 'editor[editor]' => 'ckeditor', - ); + ]; $this->drupalPostAjaxForm(NULL, $edit, 'editor_configure'); $filter_format = FilterFormat::load('amazing_format'); $this->assertFalse($filter_format, 'No FilterFormat config entity exists yet.'); diff --git a/core/modules/ckeditor/src/Tests/CKEditorLoadingTest.php b/core/modules/ckeditor/src/Tests/CKEditorLoadingTest.php index 6efe647b54..6de5467533 100644 --- a/core/modules/ckeditor/src/Tests/CKEditorLoadingTest.php +++ b/core/modules/ckeditor/src/Tests/CKEditorLoadingTest.php @@ -18,7 +18,7 @@ class CKEditorLoadingTest extends WebTestBase { * * @var array */ - public static $modules = array('filter', 'editor', 'ckeditor', 'node'); + public static $modules = ['filter', 'editor', 'ckeditor', 'node']; /** * An untrusted user with access to only the 'plain_text' format. @@ -38,12 +38,12 @@ protected function setUp() { parent::setUp(); // Create text format, associate CKEditor. - $filtered_html_format = FilterFormat::create(array( + $filtered_html_format = FilterFormat::create([ 'format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, - 'filters' => array(), - )); + 'filters' => [], + ]); $filtered_html_format->save(); $editor = Editor::create([ 'format' => 'filtered_html', @@ -53,22 +53,22 @@ protected function setUp() { // Create a second format without an associated editor so a drop down select // list is created when selecting formats. - $full_html_format = FilterFormat::create(array( + $full_html_format = FilterFormat::create([ 'format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, - 'filters' => array(), - )); + 'filters' => [], + ]); $full_html_format->save(); // Create node type. - $this->drupalCreateContentType(array( + $this->drupalCreateContentType([ 'type' => 'article', 'name' => 'Article', - )); + ]); - $this->untrustedUser = $this->drupalCreateUser(array('create article content', 'edit any article content')); - $this->normalUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'use text format filtered_html', 'use text format full_html')); + $this->untrustedUser = $this->drupalCreateUser(['create article content', 'edit any article content']); + $this->normalUser = $this->drupalCreateUser(['create article content', 'edit any article content', 'use text format filtered_html', 'use text format full_html']); } /** @@ -101,13 +101,13 @@ function testLoading() { list($settings, $editor_settings_present, $editor_js_present, $body, $format_selector) = $this->getThingsToCheck(); $ckeditor_plugin = $this->container->get('plugin.manager.editor')->createInstance('ckeditor'); $editor = Editor::load('filtered_html'); - $expected = array('formats' => array('filtered_html' => array( + $expected = ['formats' => ['filtered_html' => [ 'format' => 'filtered_html', 'editor' => 'ckeditor', 'editorSettings' => $this->castSafeStrings($ckeditor_plugin->getJSSettings($editor)), 'editorSupportsContentFiltering' => TRUE, 'isXssSafe' => FALSE, - ))); + ]]]; $this->assertTrue($editor_settings_present, "Text Editor module's JavaScript settings are on the page."); $this->assertIdentical($expected, $this->castSafeStrings($settings['editor']), "Text Editor module's JavaScript settings on the page are correct."); $this->assertTrue($editor_js_present, 'Text Editor JavaScript is present.'); @@ -122,7 +122,7 @@ function testLoading() { // NOTE: the tests in CKEditorTest already ensure that changing the // configuration also results in modified CKEditor configuration, so we // don't test that here. - \Drupal::service('module_installer')->install(array('ckeditor_test')); + \Drupal::service('module_installer')->install(['ckeditor_test']); $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions(); $editor_settings = $editor->getSettings(); $editor_settings['toolbar']['rows'][0][0]['items'][] = 'Llama'; @@ -130,15 +130,15 @@ function testLoading() { $editor->save(); $this->drupalGet('node/add/article'); list($settings, $editor_settings_present, $editor_js_present, $body, $format_selector) = $this->getThingsToCheck(); - $expected = array( - 'formats' => array( - 'filtered_html' => array( + $expected = [ + 'formats' => [ + 'filtered_html' => [ 'format' => 'filtered_html', 'editor' => 'ckeditor', 'editorSettings' => $this->castSafeStrings($ckeditor_plugin->getJSSettings($editor)), 'editorSupportsContentFiltering' => TRUE, 'isXssSafe' => FALSE, - ))); + ]]]; $this->assertTrue($editor_settings_present, "Text Editor module's JavaScript settings are on the page."); $this->assertIdentical($expected, $this->castSafeStrings($settings['editor']), "Text Editor module's JavaScript settings on the page are correct."); $this->assertTrue($editor_js_present, 'Text Editor JavaScript is present.'); @@ -226,7 +226,7 @@ function testExternalStylesheets() { protected function getThingsToCheck() { $settings = $this->getDrupalSettings(); - return array( + return [ // JavaScript settings. $settings, // Editor.module's JS settings present. @@ -239,7 +239,7 @@ protected function getThingsToCheck() { $this->xpath('//textarea[@id="edit-body-0-value"]'), // Format selector. $this->xpath('//select[contains(@class, "filter-list")]'), - ); + ]; } } diff --git a/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorPluginManagerTest.php b/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorPluginManagerTest.php index 92c448b691..fc79273487 100644 --- a/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorPluginManagerTest.php +++ b/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorPluginManagerTest.php @@ -18,7 +18,7 @@ class CKEditorPluginManagerTest extends KernelTestBase { * * @var array */ - public static $modules = array('system', 'user', 'filter', 'editor', 'ckeditor'); + public static $modules = ['system', 'user', 'filter', 'editor', 'ckeditor']; /** * The manager for "CKEditor plugin" plugins. @@ -33,12 +33,12 @@ protected function setUp() { // Install the Filter module. // Create text format, associate CKEditor. - $filtered_html_format = FilterFormat::create(array( + $filtered_html_format = FilterFormat::create([ 'format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, - 'filters' => array(), - )); + 'filters' => [], + ]); $filtered_html_format->save(); $editor = Editor::create([ 'format' => 'filtered_html', @@ -57,27 +57,27 @@ function testEnabledPlugins() { // Case 1: no CKEditor plugins. $definitions = array_keys($this->manager->getDefinitions()); sort($definitions); - $this->assertIdentical(array('drupalimage', 'drupalimagecaption', 'drupallink', 'internal', 'language', 'stylescombo'), $definitions, 'No CKEditor plugins found besides the built-in ones.'); - $enabled_plugins = array( + $this->assertIdentical(['drupalimage', 'drupalimagecaption', 'drupallink', 'internal', 'language', 'stylescombo'], $definitions, 'No CKEditor plugins found besides the built-in ones.'); + $enabled_plugins = [ 'drupalimage' => drupal_get_path('module', 'ckeditor') . '/js/plugins/drupalimage/plugin.js', 'drupallink' => drupal_get_path('module', 'ckeditor') . '/js/plugins/drupallink/plugin.js', - ); + ]; $this->assertIdentical($enabled_plugins, $this->manager->getEnabledPluginFiles($editor), 'Only built-in plugins are enabled.'); - $this->assertIdentical(array('internal' => NULL) + $enabled_plugins, $this->manager->getEnabledPluginFiles($editor, TRUE), 'Only the "internal" plugin is enabled.'); + $this->assertIdentical(['internal' => NULL] + $enabled_plugins, $this->manager->getEnabledPluginFiles($editor, TRUE), 'Only the "internal" plugin is enabled.'); // Enable the CKEditor Test module, which has the Llama plugin (plus four // variations of it, to cover all possible ways a plugin can be enabled) and // clear the editor manager's cache so it is picked up. - $this->enableModules(array('ckeditor_test')); + $this->enableModules(['ckeditor_test']); $this->manager = $this->container->get('plugin.manager.ckeditor.plugin'); $this->manager->clearCachedDefinitions(); // Case 2: CKEditor plugins are available. $plugin_ids = array_keys($this->manager->getDefinitions()); sort($plugin_ids); - $this->assertIdentical(array('drupalimage', 'drupalimagecaption', 'drupallink', 'internal', 'language', 'llama', 'llama_button', 'llama_contextual', 'llama_contextual_and_button', 'llama_css', 'stylescombo'), $plugin_ids, 'Additional CKEditor plugins found.'); + $this->assertIdentical(['drupalimage', 'drupalimagecaption', 'drupallink', 'internal', 'language', 'llama', 'llama_button', 'llama_contextual', 'llama_contextual_and_button', 'llama_css', 'stylescombo'], $plugin_ids, 'Additional CKEditor plugins found.'); $this->assertIdentical($enabled_plugins, $this->manager->getEnabledPluginFiles($editor), 'Only the internal plugins are enabled.'); - $this->assertIdentical(array('internal' => NULL) + $enabled_plugins, $this->manager->getEnabledPluginFiles($editor, TRUE), 'Only the "internal" plugin is enabled.'); + $this->assertIdentical(['internal' => NULL] + $enabled_plugins, $this->manager->getEnabledPluginFiles($editor, TRUE), 'Only the "internal" plugin is enabled.'); // Case 3: enable each of the newly available plugins, if possible: // a. Llama: cannot be enabled, since it does not implement @@ -100,33 +100,33 @@ function testEnabledPlugins() { $settings['toolbar']['rows'][0][0]['items'][] = 'Llama'; $editor->setSettings($settings); $editor->save(); - $file = array(); + $file = []; $file['b'] = drupal_get_path('module', 'ckeditor_test') . '/js/llama_button.js'; $file['c'] = drupal_get_path('module', 'ckeditor_test') . '/js/llama_contextual.js'; $file['cb'] = drupal_get_path('module', 'ckeditor_test') . '/js/llama_contextual_and_button.js'; $file['css'] = drupal_get_path('module', 'ckeditor_test') . '/js/llama_css.js'; - $expected = $enabled_plugins + array('llama_button' => $file['b'], 'llama_contextual_and_button' => $file['cb']); + $expected = $enabled_plugins + ['llama_button' => $file['b'], 'llama_contextual_and_button' => $file['cb']]; $this->assertIdentical($expected, $this->manager->getEnabledPluginFiles($editor), 'The LlamaButton and LlamaContextualAndButton plugins are enabled.'); - $this->assertIdentical(array('internal' => NULL) + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LlamaButton and LlamaContextualAndButton plugins are enabled.'); + $this->assertIdentical(['internal' => NULL] + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LlamaButton and LlamaContextualAndButton plugins are enabled.'); $settings['toolbar'] = $original_toolbar; $settings['toolbar']['rows'][0][0]['items'][] = 'Strike'; $editor->setSettings($settings); $editor->save(); - $expected = $enabled_plugins + array('llama_contextual' => $file['c'], 'llama_contextual_and_button' => $file['cb']); + $expected = $enabled_plugins + ['llama_contextual' => $file['c'], 'llama_contextual_and_button' => $file['cb']]; $this->assertIdentical($expected, $this->manager->getEnabledPluginFiles($editor), 'The LLamaContextual and LlamaContextualAndButton plugins are enabled.'); - $this->assertIdentical(array('internal' => NULL) + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LlamaContextual and LlamaContextualAndButton plugins are enabled.'); + $this->assertIdentical(['internal' => NULL] + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LlamaContextual and LlamaContextualAndButton plugins are enabled.'); $settings['toolbar']['rows'][0][0]['items'][] = 'Llama'; $editor->setSettings($settings); $editor->save(); - $expected = $enabled_plugins + array('llama_button' => $file['b'], 'llama_contextual' => $file['c'], 'llama_contextual_and_button' => $file['cb']); + $expected = $enabled_plugins + ['llama_button' => $file['b'], 'llama_contextual' => $file['c'], 'llama_contextual_and_button' => $file['cb']]; $this->assertIdentical($expected, $this->manager->getEnabledPluginFiles($editor), 'The LlamaButton, LlamaContextual and LlamaContextualAndButton plugins are enabled.'); - $this->assertIdentical(array('internal' => NULL) + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LLamaButton, LlamaContextual and LlamaContextualAndButton plugins are enabled.'); + $this->assertIdentical(['internal' => NULL] + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LLamaButton, LlamaContextual and LlamaContextualAndButton plugins are enabled.'); $settings['toolbar']['rows'][0][0]['items'][] = 'LlamaCSS'; $editor->setSettings($settings); $editor->save(); - $expected = $enabled_plugins + array('llama_button' => $file['b'], 'llama_contextual' => $file['c'], 'llama_contextual_and_button' => $file['cb'], 'llama_css' => $file['css']); + $expected = $enabled_plugins + ['llama_button' => $file['b'], 'llama_contextual' => $file['c'], 'llama_contextual_and_button' => $file['cb'], 'llama_css' => $file['css']]; $this->assertIdentical($expected, $this->manager->getEnabledPluginFiles($editor), 'The LlamaButton, LlamaContextual, LlamaContextualAndButton and LlamaCSS plugins are enabled.'); - $this->assertIdentical(array('internal' => NULL) + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LLamaButton, LlamaContextual, LlamaContextualAndButton and LlamaCSS plugins are enabled.'); + $this->assertIdentical(['internal' => NULL] + $expected, $this->manager->getEnabledPluginFiles($editor, TRUE), 'The LLamaButton, LlamaContextual, LlamaContextualAndButton and LlamaCSS plugins are enabled.'); } /** @@ -137,11 +137,11 @@ function testCssFiles() { $editor = Editor::load('filtered_html'); // Case 1: no CKEditor iframe instance CSS file. - $this->assertIdentical(array(), $this->manager->getCssFiles($editor), 'No iframe instance CSS file found.'); + $this->assertIdentical([], $this->manager->getCssFiles($editor), 'No iframe instance CSS file found.'); // Enable the CKEditor Test module, which has the LlamaCss plugin and // clear the editor manager's cache so it is picked up. - $this->enableModules(array('ckeditor_test')); + $this->enableModules(['ckeditor_test']); $this->manager = $this->container->get('plugin.manager.ckeditor.plugin'); $settings = $editor->getSettings(); // LlamaCss: automatically enabled by adding its 'LlamaCSS' button. @@ -150,9 +150,9 @@ function testCssFiles() { $editor->save(); // Case 2: CKEditor iframe instance CSS file. - $expected = array( - 'llama_css' => array(drupal_get_path('module', 'ckeditor_test') . '/css/llama.css') - ); + $expected = [ + 'llama_css' => [drupal_get_path('module', 'ckeditor_test') . '/css/llama.css'] + ]; $this->assertIdentical($expected, $this->manager->getCssFiles($editor), 'Iframe instance CSS file found.'); } diff --git a/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorTest.php b/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorTest.php index 3711a54e38..9e159c3d51 100644 --- a/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorTest.php +++ b/core/modules/ckeditor/tests/modules/src/Kernel/CKEditorTest.php @@ -19,7 +19,7 @@ class CKEditorTest extends KernelTestBase { * * @var array */ - public static $modules = array('system', 'user', 'filter', 'editor', 'ckeditor', 'filter_test'); + public static $modules = ['system', 'user', 'filter', 'editor', 'ckeditor', 'filter_test']; /** * An instance of the "CKEditor" text editor plugin. @@ -41,19 +41,19 @@ protected function setUp() { // Install the Filter module. // Create text format, associate CKEditor. - $filtered_html_format = FilterFormat::create(array( + $filtered_html_format = FilterFormat::create([ 'format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, - 'filters' => array( - 'filter_html' => array( + 'filters' => [ + 'filter_html' => [ 'status' => 1, - 'settings' => array( + 'settings' => [ 'allowed_html' => '


        ', - ) - ), - ), - )); + ] + ], + ], + ]); $filtered_html_format->save(); $editor = Editor::create([ 'format' => 'filtered_html', @@ -72,7 +72,7 @@ function testGetJSSettings() { $editor = Editor::load('filtered_html'); // Default toolbar. - $expected_config = $this->getDefaultInternalConfig() + array( + $expected_config = $this->getDefaultInternalConfig() + [ 'drupalImage_dialogTitleAdd' => 'Insert Image', 'drupalImage_dialogTitleEdit' => 'Edit Image', 'drupalLink_dialogTitleAdd' => 'Add Link', @@ -84,11 +84,11 @@ function testGetJSSettings() { 'extraPlugins' => 'drupalimage,drupallink', 'language' => 'en', 'stylesSet' => FALSE, - 'drupalExternalPlugins' => array( + 'drupalExternalPlugins' => [ 'drupalimage' => file_url_transform_relative(file_create_url('core/modules/ckeditor/js/plugins/drupalimage/plugin.js')), 'drupallink' => file_url_transform_relative(file_create_url('core/modules/ckeditor/js/plugins/drupallink/plugin.js')), - ), - ); + ], + ]; $expected_config = $this->castSafeStrings($expected_config); ksort($expected_config); ksort($expected_config['allowedContent']); @@ -96,7 +96,7 @@ function testGetJSSettings() { // Customize the configuration: add button, have two contextually enabled // buttons, and configure a CKEditor plugin setting. - $this->enableModules(array('ckeditor_test')); + $this->enableModules(['ckeditor_test']); $this->container->get('plugin.manager.editor')->clearCachedDefinitions(); $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor'); $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions(); @@ -121,16 +121,16 @@ function testGetJSSettings() { $format->filters('filter_html')->settings['allowed_html'] .= '

         

        '; $format->save(); - $expected_config['allowedContent']['pre'] = array('attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE); - $expected_config['allowedContent']['h1'] = array('attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE); - $expected_config['allowedContent']['blockquote'] = array('attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE); - $expected_config['allowedContent']['address'] = array('attributes' => 'class', 'styles' => FALSE, 'classes' => 'foo,bar-*'); + $expected_config['allowedContent']['pre'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE]; + $expected_config['allowedContent']['h1'] = ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE]; + $expected_config['allowedContent']['blockquote'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE]; + $expected_config['allowedContent']['address'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => 'foo,bar-*']; $expected_config['format_tags'] = 'p;h1;h2;h3;h4;h5;h6;pre'; ksort($expected_config['allowedContent']); $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.'); // Disable the filter_html filter: allow *all *tags. - $format->setFilterConfig('filter_html', array('status' => 0)); + $format->setFilterConfig('filter_html', ['status' => 0]); $format->save(); $expected_config['allowedContent'] = TRUE; @@ -139,73 +139,73 @@ function testGetJSSettings() { $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.'); // Enable the filter_test_restrict_tags_and_attributes filter. - $format->setFilterConfig('filter_test_restrict_tags_and_attributes', array( + $format->setFilterConfig('filter_test_restrict_tags_and_attributes', [ 'status' => 1, - 'settings' => array( - 'restrictions' => array( - 'allowed' => array( + 'settings' => [ + 'restrictions' => [ + 'allowed' => [ 'p' => TRUE, - 'a' => array( + 'a' => [ 'href' => TRUE, - 'rel' => array('nofollow' => TRUE), - 'class' => array('external' => TRUE), - 'target' => array('_blank' => FALSE), - ), - 'span' => array( - 'class' => array('dodo' => FALSE), - 'property' => array('dc:*' => TRUE), - 'rel' => array('foaf:*' => FALSE), - 'style' => array('underline' => FALSE, 'color' => FALSE, 'font-size' => TRUE), - ), - '*' => array( + 'rel' => ['nofollow' => TRUE], + 'class' => ['external' => TRUE], + 'target' => ['_blank' => FALSE], + ], + 'span' => [ + 'class' => ['dodo' => FALSE], + 'property' => ['dc:*' => TRUE], + 'rel' => ['foaf:*' => FALSE], + 'style' => ['underline' => FALSE, 'color' => FALSE, 'font-size' => TRUE], + ], + '*' => [ 'style' => FALSE, 'on*' => FALSE, - 'class' => array('is-a-hipster-llama' => TRUE, 'and-more' => TRUE), + 'class' => ['is-a-hipster-llama' => TRUE, 'and-more' => TRUE], 'data-*' => TRUE, - ), + ], 'del' => FALSE, - ), - ), - ), - )); + ], + ], + ], + ]); $format->save(); - $expected_config['allowedContent'] = array( - 'p' => array( + $expected_config['allowedContent'] = [ + 'p' => [ 'attributes' => TRUE, 'styles' => FALSE, 'classes' => 'is-a-hipster-llama,and-more', - ), - 'a' => array( + ], + 'a' => [ 'attributes' => 'href,rel,class,target', 'styles' => FALSE, 'classes' => 'external', - ), - 'span' => array( + ], + 'span' => [ 'attributes' => 'class,property,rel,style', 'styles' => 'font-size', 'classes' => FALSE, - ), - '*' => array( + ], + '*' => [ 'attributes' => 'class,data-*', 'styles' => FALSE, 'classes' => 'is-a-hipster-llama,and-more', - ), - 'del' => array( + ], + 'del' => [ 'attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE, - ), - ); - $expected_config['disallowedContent'] = array( - 'span' => array( + ], + ]; + $expected_config['disallowedContent'] = [ + 'span' => [ 'styles' => 'underline,color', 'classes' => 'dodo', - ), - '*' => array( + ], + '*' => [ 'attributes' => 'on*', - ), - ); + ], + ]; $expected_config['format_tags'] = 'p'; ksort($expected_config); ksort($expected_config['allowedContent']); @@ -232,7 +232,7 @@ function testBuildToolbarJSSetting() { $this->assertIdentical($expected, $this->castSafeStrings($this->ckeditor->buildToolbarJSSetting($editor)), '"toolbar" configuration part of JS settings built correctly for customized toolbar.'); // Enable the editor_test module, customize further. - $this->enableModules(array('ckeditor_test')); + $this->enableModules(['ckeditor_test']); $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions(); // Override the label of a toolbar component. $settings['toolbar']['rows'][0][0]['name'] = 'JunkScience'; @@ -255,7 +255,7 @@ function testBuildContentsCssJSSetting() { $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly for default toolbar.'); // Enable the editor_test module, which implements hook_ckeditor_css_alter(). - $this->enableModules(array('ckeditor_test')); + $this->enableModules(['ckeditor_test']); $expected[] = file_url_transform_relative(file_create_url(drupal_get_path('module', 'ckeditor_test') . '/ckeditor_test.css')); $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a hook_ckeditor_css_alter() implementation exists.'); @@ -315,7 +315,7 @@ function testStylesComboGetConfig() { $settings['plugins']['stylescombo']['styles'] = ''; $editor->setSettings($settings); $editor->save(); - $expected['stylesSet'] = array(); + $expected['stylesSet'] = []; $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.'); // Configure the optional "styles" setting in odd ways that shouldn't affect @@ -333,10 +333,10 @@ function testStylesComboGetConfig() { $settings['plugins']['stylescombo']['styles'] = "h1.title|Title\np.mAgical.Callout|Callout"; $editor->setSettings($settings); $editor->save(); - $expected['stylesSet'] = array( - array('name' => 'Title', 'element' => 'h1', 'attributes' => array('class' => 'title')), - array('name' => 'Callout', 'element' => 'p', 'attributes' => array('class' => 'mAgical Callout')), - ); + $expected['stylesSet'] = [ + ['name' => 'Title', 'element' => 'h1', 'attributes' => ['class' => 'title']], + ['name' => 'Callout', 'element' => 'p', 'attributes' => ['class' => 'mAgical Callout']], + ]; $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.'); // Same configuration, but now interspersed with nonsense. Should yield the @@ -350,7 +350,7 @@ function testStylesComboGetConfig() { $settings['plugins']['stylescombo']['styles'] = " h1 | Title "; $editor->setSettings($settings); $editor->save(); - $expected['stylesSet'] = array(array('name' => 'Title', 'element' => 'h1')); + $expected['stylesSet'] = [['name' => 'Title', 'element' => 'h1']]; $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.'); // Invalid syntax should cause stylesSet to be set to FALSE. @@ -366,8 +366,8 @@ function testStylesComboGetConfig() { */ function testLanguages() { // Get CKEditor supported language codes and spot-check. - $this->enableModules(array('language')); - $this->installConfig(array('language')); + $this->enableModules(['language']); + $this->installConfig(['language']); $langcodes = $this->ckeditor->getLangcodes(); // Language codes transformed with browser mappings. @@ -390,14 +390,14 @@ function testLanguages() { * Tests that CKEditor plugins participate in JS translation. */ function testJSTranslation() { - $this->enableModules(array('language', 'locale')); + $this->enableModules(['language', 'locale']); $this->installSchema('locale', 'locales_source'); $this->installSchema('locale', 'locales_location'); $this->installSchema('locale', 'locales_target'); $editor = Editor::load('filtered_html'); $this->ckeditor->getJSSettings($editor); $localeStorage = $this->container->get('locale.storage'); - $string = $localeStorage->findString(array('source' => 'Edit Link', 'context' => '')); + $string = $localeStorage->findString(['source' => 'Edit Link', 'context' => '']); $this->assertTrue(!empty($string), 'String from JavaScript file saved.'); // With locale module, CKEditor should not adhere to the language selected. @@ -428,14 +428,14 @@ protected function assertCKEditorLanguage($langcode = 'fr') { } protected function getDefaultInternalConfig() { - return array( + return [ 'customConfig' => '', 'pasteFromWordPromptCleanup' => TRUE, 'resize_dir' => 'vertical', - 'justifyClasses' => array('text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'), + 'justifyClasses' => ['text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'], 'entities' => FALSE, 'disableNativeSpellChecker' => FALSE, - ); + ]; } protected function getDefaultAllowedContentConfig() { @@ -454,42 +454,42 @@ protected function getDefaultAllowedContentConfig() { } protected function getDefaultDisallowedContentConfig() { - return array( - '*' => array('attributes' => 'on*'), - ); + return [ + '*' => ['attributes' => 'on*'], + ]; } protected function getDefaultToolbarConfig() { - return array( - array( + return [ + [ 'name' => 'Formatting', - 'items' => array('Bold', 'Italic',), - ), - array( + 'items' => ['Bold', 'Italic',], + ], + [ 'name' => 'Links', - 'items' => array('DrupalLink', 'DrupalUnlink',), - ), - array( + 'items' => ['DrupalLink', 'DrupalUnlink',], + ], + [ 'name' => 'Lists', - 'items' => array('BulletedList', 'NumberedList',), - ), - array( + 'items' => ['BulletedList', 'NumberedList',], + ], + [ 'name' => 'Media', - 'items' => array('Blockquote', 'DrupalImage',), - ), - array( + 'items' => ['Blockquote', 'DrupalImage',], + ], + [ 'name' => 'Tools', - 'items' => array('Source',), - ), + 'items' => ['Source',], + ], '/', - ); + ]; } protected function getDefaultContentsCssConfig() { - return array( + return [ file_url_transform_relative(file_create_url('core/modules/ckeditor/css/ckeditor-iframe.css')), file_url_transform_relative(file_create_url('core/modules/system/css/components/align.module.css')), - ); + ]; } } diff --git a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/Llama.php b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/Llama.php index 932b05ca4d..012579de89 100644 --- a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/Llama.php +++ b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/Llama.php @@ -30,14 +30,14 @@ class Llama extends PluginBase implements CKEditorPluginInterface { * {@inheritdoc} */ function getDependencies(Editor $editor) { - return array(); + return []; } /** * {@inheritdoc} */ function getLibraries(Editor $editor) { - return array(); + return []; } /** @@ -58,7 +58,7 @@ function getFile() { * {@inheritdoc} */ public function getConfig(Editor $editor) { - return array(); + return []; } } diff --git a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaButton.php b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaButton.php index 7520dfd117..4568192e03 100644 --- a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaButton.php +++ b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaButton.php @@ -18,11 +18,11 @@ class LlamaButton extends Llama implements CKEditorPluginButtonsInterface { * {@inheritdoc} */ function getButtons() { - return array( - 'Llama' => array( + return [ + 'Llama' => [ 'label' => t('Insert Llama'), - ), - ); + ], + ]; } /** diff --git a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaContextualAndButton.php b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaContextualAndButton.php index 43060d9046..5e1955fbd3 100644 --- a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaContextualAndButton.php +++ b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaContextualAndButton.php @@ -39,11 +39,11 @@ function isEnabled(Editor $editor) { * {@inheritdoc} */ function getButtons() { - return array( - 'Llama' => array( + return [ + 'Llama' => [ 'label' => t('Insert Llama'), - ), - ); + ], + ]; } /** @@ -58,17 +58,17 @@ function getFile() { */ function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) { // Defaults. - $config = array('ultra_llama_mode' => FALSE); + $config = ['ultra_llama_mode' => FALSE]; $settings = $editor->getSettings(); if (isset($settings['plugins']['llama_contextual_and_button'])) { $config = $settings['plugins']['llama_contextual_and_button']; } - $form['ultra_llama_mode'] = array( + $form['ultra_llama_mode'] = [ '#title' => t('Ultra llama mode'), '#type' => 'checkbox', '#default_value' => $config['ultra_llama_mode'], - ); + ]; return $form; } diff --git a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaCss.php b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaCss.php index 294b39c92a..d3b9a7f623 100644 --- a/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaCss.php +++ b/core/modules/ckeditor/tests/modules/src/Plugin/CKEditorPlugin/LlamaCss.php @@ -20,20 +20,20 @@ class LlamaCss extends Llama implements CKEditorPluginButtonsInterface, CKEditor * {@inheritdoc} */ function getButtons() { - return array( - 'LlamaCSS' => array( + return [ + 'LlamaCSS' => [ 'label' => t('Insert Llama CSS'), - ), - ); + ], + ]; } /** * {@inheritdoc} */ function getCssFiles(Editor $editor) { - return array( + return [ drupal_get_path('module', 'ckeditor_test') . '/css/llama.css' - ); + ]; } /** diff --git a/core/modules/color/color.install b/core/modules/color/color.install index 7f6133819d..3cc098caa0 100644 --- a/core/modules/color/color.install +++ b/core/modules/color/color.install @@ -9,15 +9,15 @@ * Implements hook_requirements(). */ function color_requirements($phase) { - $requirements = array(); + $requirements = []; if ($phase == 'runtime') { // Check for the PHP GD library. if (function_exists('imagegd2')) { $info = gd_info(); - $requirements['color_gd'] = array( + $requirements['color_gd'] = [ 'value' => $info['GD Version'], - ); + ]; // Check for PNG support. if (!function_exists('imagecreatefrompng')) { @@ -26,11 +26,11 @@ function color_requirements($phase) { } } else { - $requirements['color_gd'] = array( + $requirements['color_gd'] = [ 'value' => t('Not installed'), 'severity' => REQUIREMENT_ERROR, 'description' => t('The GD library for PHP is missing or outdated. Check the PHP image documentation for information on how to correct this.'), - ); + ]; } $requirements['color_gd']['title'] = t('GD library PNG support'); } diff --git a/core/modules/color/color.module b/core/modules/color/color.module index 3cae04532e..20d099abcf 100644 --- a/core/modules/color/color.module +++ b/core/modules/color/color.module @@ -23,11 +23,11 @@ function color_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.color': $output = '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Color module allows users with the Administer site configuration permission to change the color scheme (color of links, backgrounds, text, and other theme elements) of compatible themes. For more information, see the online documentation for the Color module.', array(':color_do' => 'https://www.drupal.org/documentation/modules/color')) . '

        '; + $output .= '

        ' . t('The Color module allows users with the Administer site configuration permission to change the color scheme (color of links, backgrounds, text, and other theme elements) of compatible themes. For more information, see the online documentation for the Color module.', [':color_do' => 'https://www.drupal.org/documentation/modules/color']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Changing colors') . '
        '; - $output .= '

        ' . t('To change the color settings, select the Settings link for your theme on the Appearance page. If the color picker does not appear then the theme is not compatible with the Color module.', array(':appearance' => \Drupal::url('system.themes_page'))) . '

        '; + $output .= '

        ' . t('To change the color settings, select the Settings link for your theme on the Appearance page. If the color picker does not appear then the theme is not compatible with the Color module.', [':appearance' => \Drupal::url('system.themes_page')]) . '

        '; $output .= '

        ' . t('The Color module saves a modified copy of the theme\'s specified stylesheets in the files directory. If you make any manual changes to your theme\'s stylesheet, you must save your color settings again, even if you haven\'t changed the colors. This step is required because the module stylesheets in the files directory need to be recreated to reflect your changes.') . '

        '; $output .= '
        '; return $output; @@ -38,11 +38,11 @@ function color_help($route_name, RouteMatchInterface $route_match) { * Implements hook_theme(). */ function color_theme() { - return array( - 'color_scheme_form' => array( + return [ + 'color_scheme_form' => [ 'render element' => 'form', - ), - ); + ], + ]; } /** @@ -51,14 +51,14 @@ function color_theme() { function color_form_system_theme_settings_alter(&$form, FormStateInterface $form_state) { $build_info = $form_state->getBuildInfo(); if (isset($build_info['args'][0]) && ($theme = $build_info['args'][0]) && color_get_info($theme) && function_exists('gd_info')) { - $form['color'] = array( + $form['color'] = [ '#type' => 'details', '#title' => t('Color scheme'), '#open' => TRUE, '#weight' => -1, - '#attributes' => array('id' => 'color_scheme_form'), + '#attributes' => ['id' => 'color_scheme_form'], '#theme' => 'color_scheme_form', - ); + ]; $form['color'] += color_scheme_form($form, $form_state, $theme); $form['#validate'][] = 'color_scheme_form_validate'; // Ensure color submission happens first so we can unset extra values. @@ -137,7 +137,7 @@ function color_block_view_pre_render(array $build) { * Retrieves the Color module information for a particular theme. */ function color_get_info($theme) { - static $theme_info = array(); + static $theme_info = []; if (isset($theme_info[$theme])) { return $theme_info[$theme]; @@ -148,21 +148,21 @@ function color_get_info($theme) { if ($path && file_exists($file)) { include $file; // Add in default values. - $info += array( + $info += [ // CSS files (excluding @import) to rewrite with new color scheme. - 'css' => array(), + 'css' => [], // Files to copy. - 'copy' => array(), + 'copy' => [], // Gradient definitions. - 'gradients' => array(), + 'gradients' => [], // Color areas to fill (x, y, width, height). - 'fill' => array(), + 'fill' => [], // Coordinates of all the theme slices (x, y, width, height) with their // filename as used in the stylesheet. - 'slices' => array(), + 'slices' => [], // Reference color used for blending. 'blend_target' => '#ffffff', - ); + ]; $theme_info[$theme] = $info; return $info; } @@ -200,9 +200,9 @@ function color_get_palette($theme, $default = FALSE) { function color_scheme_form($complete_form, FormStateInterface $form_state, $theme) { $info = color_get_info($theme); - $info['schemes'][''] = array('title' => t('Custom'), 'colors' => array()); - $color_sets = array(); - $schemes = array(); + $info['schemes'][''] = ['title' => t('Custom'), 'colors' => []]; + $color_sets = []; + $schemes = []; foreach ($info['schemes'] as $key => $scheme) { $color_sets[$key] = $scheme['title']; $schemes[$key] = $scheme['colors']; @@ -233,16 +233,16 @@ function color_scheme_form($complete_form, FormStateInterface $form_state, $them // Add scheme selector. $default_palette = color_get_palette($theme, TRUE); - $form['scheme'] = array( + $form['scheme'] = [ '#type' => 'select', '#title' => t('Color set'), '#options' => $color_sets, '#default_value' => $scheme_name, - '#attached' => array( - 'library' => array( + '#attached' => [ + 'library' => [ 'color/drupal.color', 'color/admin', - ), + ], // Add custom JavaScript. 'drupalSettings' => [ 'color' => [ @@ -251,8 +251,8 @@ function color_scheme_form($complete_form, FormStateInterface $form_state, $them ], 'gradients' => $info['gradients'], ], - ), - ); + ], + ]; // Add palette fields. Use the configuration if available. $palette = $current_scheme ?: $default_palette; @@ -260,22 +260,22 @@ function color_scheme_form($complete_form, FormStateInterface $form_state, $them $form['palette']['#tree'] = TRUE; foreach ($palette as $name => $value) { if (isset($names[$name])) { - $form['palette'][$name] = array( + $form['palette'][$name] = [ '#type' => 'textfield', '#title' => $names[$name], '#value_callback' => 'color_palette_color_value', '#default_value' => $value, '#size' => 8, - '#attributes' => array('dir' => LanguageInterface::DIRECTION_LTR), - ); + '#attributes' => ['dir' => LanguageInterface::DIRECTION_LTR], + ]; } } - $form['theme'] = array('#type' => 'value', '#value' => $theme); + $form['theme'] = ['#type' => 'value', '#value' => $theme]; if (isset($info['#attached'])) { $form['#attached'] = $info['#attached']; unset($info['#attached']); } - $form['info'] = array('#type' => 'value', '#value' => $info); + $form['info'] = ['#type' => 'value', '#value' => $info]; return $form; } @@ -360,7 +360,7 @@ function color_scheme_form_validate($form, FormStateInterface $form_state) { // Only accept hexadecimal CSS color strings to avoid XSS upon use. foreach ($form_state->getValue('palette') as $key => $color) { if (!color_valid_hexadecimal_string($color)) { - $form_state->setErrorByName('palette][' . $key, t('You must enter a valid hexadecimal color value for %name.', array('%name' => $form['color']['palette'][$key]['#title']))); + $form_state->setErrorByName('palette][' . $key, t('You must enter a valid hexadecimal color value for %name.', ['%name' => $form['color']['palette'][$key]['#title']])); } } } @@ -373,7 +373,7 @@ function color_scheme_form_validate($form, FormStateInterface $form_state) { function color_scheme_form_submit($form, FormStateInterface $form_state) { // Avoid color settings spilling over to theme settings. - $color_settings = array('theme', 'palette', 'scheme'); + $color_settings = ['theme', 'palette', 'scheme']; if ($form_state->hasValue('info')) { $color_settings[] = 'info'; } @@ -414,7 +414,7 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) { $memory_limit = ini_get('memory_limit'); $size = Bytes::toInt($memory_limit); if (!Environment::checkMemoryLimit($usage + $required, $memory_limit)) { - drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the PHP documentation for more information.', array('%size' => format_size($usage + $required - $size))), 'error'); + drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the PHP documentation for more information.', ['%size' => format_size($usage + $required - $size)]), 'error'); return; } } @@ -446,7 +446,7 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) { $paths['target'] = $paths['target'] . '/'; $paths['id'] = $id; $paths['source'] = drupal_get_path('theme', $theme) . '/'; - $paths['files'] = $paths['map'] = array(); + $paths['files'] = $paths['map'] = []; // Save palette and logo location. $config @@ -469,10 +469,10 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) { } // Rewrite theme stylesheets. - $css = array(); + $css = []; foreach ($info['css'] as $stylesheet) { // Build a temporary array with CSS files. - $files = array(); + $files = []; if (file_exists($paths['source'] . $stylesheet)) { $files[] = $stylesheet; } @@ -489,7 +489,7 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) { $css_optimizer->rewriteFileURIBasePath = base_path() . dirname($paths['source'] . $file) . '/'; // Prefix all paths within this CSS file, ignoring absolute paths. - $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', array($css_optimizer, 'rewriteFileURI'), $style); + $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', [$css_optimizer, 'rewriteFileURI'], $style); // Rewrite stylesheet with new colors. $style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style); @@ -729,7 +729,7 @@ function _color_shift($given, $ref1, $ref2, $target) { * Converts a hex triplet into a GD color. */ function _color_gd($img, $hex) { - $c = array_merge(array($img), _color_unpack($hex)); + $c = array_merge([$img], _color_unpack($hex)); return call_user_func_array('imagecolorallocate', $c); } @@ -739,7 +739,7 @@ function _color_gd($img, $hex) { function _color_blend($img, $hex1, $hex2, $alpha) { $in1 = _color_unpack($hex1); $in2 = _color_unpack($hex2); - $out = array($img); + $out = [$img]; for ($i = 0; $i < 3; ++$i) { $out[] = $in1[$i] + ($in2[$i] - $in1[$i]) * $alpha; } @@ -784,11 +784,11 @@ function _color_hsl2rgb($hsl) { $m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l * $s; $m1 = $l * 2 - $m2; - return array( + return [ _color_hue2rgb($m1, $m2, $h + 0.33333), _color_hue2rgb($m1, $m2, $h), _color_hue2rgb($m1, $m2, $h - 0.33333), - ); + ]; } /** @@ -828,5 +828,5 @@ function _color_rgb2hsl($rgb) { $h /= 6; } - return array($h, $s, $l); + return [$h, $s, $l]; } diff --git a/core/modules/color/tests/modules/color_test/themes/color_test_theme/color/color.inc b/core/modules/color/tests/modules/color_test/themes/color_test_theme/color/color.inc index b88e8eae72..ee77a5a173 100644 --- a/core/modules/color/tests/modules/color_test/themes/color_test_theme/color/color.inc +++ b/core/modules/color/tests/modules/color_test/themes/color_test_theme/color/color.inc @@ -5,29 +5,29 @@ * Lists available colors and color schemes for the Color test theme. */ -$info = array( - 'fields' => array( +$info = [ + 'fields' => [ 'bg' => t('Main background'), 'text' => t('Text color'), - ), - 'schemes' => array( - 'default' => array( + ], + 'schemes' => [ + 'default' => [ 'title' => t('Default'), - 'colors' => array( + 'colors' => [ 'bg' => '#ff0000', 'text' => '#0000ff', - ), - ), - 'custom' => array( + ], + ], + 'custom' => [ 'title' => t('Custom'), - 'colors' => array( + 'colors' => [ 'bg' => '#ff0000', 'text' => '#3b3b3b', - ), - ), - ), - 'css' => array( + ], + ], + ], + 'css' => [ 'css/colors.css', - ), + ], 'preview_html' => 'color/preview.html', -); +]; diff --git a/core/modules/color/tests/src/Functional/ColorConfigSchemaTest.php b/core/modules/color/tests/src/Functional/ColorConfigSchemaTest.php index 157deb8dc0..e55275deb7 100644 --- a/core/modules/color/tests/src/Functional/ColorConfigSchemaTest.php +++ b/core/modules/color/tests/src/Functional/ColorConfigSchemaTest.php @@ -16,7 +16,7 @@ class ColorConfigSchemaTest extends BrowserTestBase { * * @var array */ - public static $modules = array('color'); + public static $modules = ['color']; /** * A user with administrative permissions. @@ -30,10 +30,10 @@ class ColorConfigSchemaTest extends BrowserTestBase { */ protected function setUp() { parent::setUp(); - \Drupal::service('theme_handler')->install(array('bartik')); + \Drupal::service('theme_handler')->install(['bartik']); // Create user. - $this->adminUser = $this->drupalCreateUser(array('administer themes')); + $this->adminUser = $this->drupalCreateUser(['administer themes']); $this->drupalLogin($this->adminUser); } diff --git a/core/modules/color/tests/src/Functional/ColorTest.php b/core/modules/color/tests/src/Functional/ColorTest.php index dc4456608e..8416913396 100644 --- a/core/modules/color/tests/src/Functional/ColorTest.php +++ b/core/modules/color/tests/src/Functional/ColorTest.php @@ -17,7 +17,7 @@ class ColorTest extends BrowserTestBase { * * @var array */ - public static $modules = array('color', 'color_test', 'block', 'file'); + public static $modules = ['color', 'color_test', 'block', 'file']; /** * A user with administrative permissions. @@ -50,25 +50,25 @@ protected function setUp() { parent::setUp(); // Create user. - $this->bigUser = $this->drupalCreateUser(array('administer themes')); + $this->bigUser = $this->drupalCreateUser(['administer themes']); // This tests the color module in Bartik. - $this->themes = array( - 'bartik' => array( + $this->themes = [ + 'bartik' => [ 'palette_input' => 'palette[bg]', 'scheme' => 'slate', 'scheme_color' => '#3b3b3b', - ), - 'color_test_theme' => array( + ], + 'color_test_theme' => [ 'palette_input' => 'palette[bg]', 'scheme' => 'custom', 'scheme_color' => '#3b3b3b', - ), - ); + ], + ]; \Drupal::service('theme_handler')->install(array_keys($this->themes)); // Array filled with valid and not valid color values. - $this->colorTests = array( + $this->colorTests = [ '#000' => TRUE, '#123456' => TRUE, '#abcdef' => TRUE, @@ -78,7 +78,7 @@ protected function setUp() { '#00000' => FALSE, '123456' => FALSE, '#00000g' => FALSE, - ); + ]; } /** @@ -138,7 +138,7 @@ function _testColor($theme, $test_values) { $config->set('css.preprocess', 1); $config->save(); $this->drupalGet(''); - $stylesheets = \Drupal::state()->get('drupal_css_cache_files') ?: array(); + $stylesheets = \Drupal::state()->get('drupal_css_cache_files') ?: []; $stylesheet_content = ''; foreach ($stylesheets as $uri) { $stylesheet_content .= join("\n", file(drupal_realpath($uri))); @@ -178,10 +178,10 @@ function testValidColor() { */ function testLogoSettingOverride() { $this->drupalLogin($this->bigUser); - $edit = array( + $edit = [ 'default_logo' => FALSE, 'logo_path' => 'core/misc/druplicon.png', - ); + ]; $this->drupalPostForm('admin/appearance/settings', $edit, t('Save configuration')); // Ensure that the overridden logo is present in Bartik, which is colorable. diff --git a/core/modules/comment/comment.api.php b/core/modules/comment/comment.api.php index 7b922cbcc0..ec6b4ce8ef 100644 --- a/core/modules/comment/comment.api.php +++ b/core/modules/comment/comment.api.php @@ -31,16 +31,16 @@ * @see \Drupal\comment\CommentViewBuilder::buildLinks() */ function hook_comment_links_alter(array &$links, CommentInterface $entity, array &$context) { - $links['mymodule'] = array( + $links['mymodule'] = [ '#theme' => 'links__comment__mymodule', - '#attributes' => array('class' => array('links', 'inline')), - '#links' => array( - 'comment-report' => array( + '#attributes' => ['class' => ['links', 'inline']], + '#links' => [ + 'comment-report' => [ 'title' => t('Report'), 'url' => Url::fromRoute('comment_test.report', ['comment' => $entity->id()], ['query' => ['token' => \Drupal::getContainer()->get('csrf_token')->get("comment/{$entity->id()}/report")]]), - ), - ), - ); + ], + ], + ]; } /** diff --git a/core/modules/comment/comment.install b/core/modules/comment/comment.install index ca356eb031..a0d819ee23 100644 --- a/core/modules/comment/comment.install +++ b/core/modules/comment/comment.install @@ -15,7 +15,7 @@ */ function comment_uninstall() { // Remove the comment fields. - $fields = entity_load_multiple_by_properties('field_storage_config', array('type' => 'comment')); + $fields = entity_load_multiple_by_properties('field_storage_config', ['type' => 'comment']); foreach ($fields as $field) { $field->delete(); } @@ -37,78 +37,78 @@ function comment_install() { * Implements hook_schema(). */ function comment_schema() { - $schema['comment_entity_statistics'] = array( + $schema['comment_entity_statistics'] = [ 'description' => 'Maintains statistics of entity and comments posts to show "new" and "updated" flags.', - 'fields' => array( - 'entity_id' => array( + 'fields' => [ + 'entity_id' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The entity_id of the entity for which the statistics are compiled.', - ), - 'entity_type' => array( + ], + 'entity_type' => [ 'type' => 'varchar_ascii', 'not null' => TRUE, 'default' => 'node', 'length' => EntityTypeInterface::ID_MAX_LENGTH, 'description' => 'The entity_type of the entity to which this comment is a reply.', - ), - 'field_name' => array( + ], + 'field_name' => [ 'type' => 'varchar_ascii', 'not null' => TRUE, 'default' => '', 'length' => FieldStorageConfig::NAME_MAX_LENGTH, 'description' => 'The field_name of the field that was used to add this comment.', - ), - 'cid' => array( + ], + 'cid' => [ 'type' => 'int', 'not null' => TRUE, 'default' => 0, 'description' => 'The {comment}.cid of the last comment.', - ), - 'last_comment_timestamp' => array( + ], + 'last_comment_timestamp' => [ 'type' => 'int', 'not null' => TRUE, 'default' => 0, 'description' => 'The Unix timestamp of the last comment that was posted within this node, from {comment}.changed.', - ), - 'last_comment_name' => array( + ], + 'last_comment_name' => [ 'type' => 'varchar', 'length' => 60, 'not null' => FALSE, 'description' => 'The name of the latest author to post a comment on this node, from {comment}.name.', - ), - 'last_comment_uid' => array( + ], + 'last_comment_uid' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The user ID of the latest author to post a comment on this node, from {comment}.uid.', - ), - 'comment_count' => array( + ], + 'comment_count' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The total number of comments on this entity.', - ), - ), - 'primary key' => array('entity_id', 'entity_type', 'field_name'), - 'indexes' => array( - 'last_comment_timestamp' => array('last_comment_timestamp'), - 'comment_count' => array('comment_count'), - 'last_comment_uid' => array('last_comment_uid'), - ), - 'foreign keys' => array( - 'last_comment_author' => array( + ], + ], + 'primary key' => ['entity_id', 'entity_type', 'field_name'], + 'indexes' => [ + 'last_comment_timestamp' => ['last_comment_timestamp'], + 'comment_count' => ['comment_count'], + 'last_comment_uid' => ['last_comment_uid'], + ], + 'foreign keys' => [ + 'last_comment_author' => [ 'table' => 'users', - 'columns' => array( + 'columns' => [ 'last_comment_uid' => 'uid', - ), - ), - ), - ); + ], + ], + ], + ]; return $schema; } diff --git a/core/modules/comment/comment.module b/core/modules/comment/comment.module index ae8131559d..ee26510729 100644 --- a/core/modules/comment/comment.module +++ b/core/modules/comment/comment.module @@ -68,19 +68,19 @@ function comment_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.comment': $output = '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the online documentation for the Comment module.', array(':comment' => 'https://www.drupal.org/documentation/modules/comment')) . '

        '; + $output .= '

        ' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the online documentation for the Comment module.', [':comment' => 'https://www.drupal.org/documentation/modules/comment']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Enabling commenting') . '
        '; - $output .= '
        ' . t('Comment functionality can be enabled for any entity sub-type (for example, a content type) by adding a Comments field on its Manage fields page. Adding or removing commenting for an entity through the user interface requires the Field UI module to be enabled, even though the commenting functionality works without it. For more information on fields and entities, see the Field module help page.', array(':content-type' => (\Drupal::moduleHandler()->moduleExists('node')) ? \Drupal::url('entity.node_type.collection') : '#', ':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '
        '; + $output .= '
        ' . t('Comment functionality can be enabled for any entity sub-type (for example, a content type) by adding a Comments field on its Manage fields page. Adding or removing commenting for an entity through the user interface requires the Field UI module to be enabled, even though the commenting functionality works without it. For more information on fields and entities, see the Field module help page.', [':content-type' => (\Drupal::moduleHandler()->moduleExists('node')) ? \Drupal::url('entity.node_type.collection') : '#', ':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '
        '; $output .= '
        ' . t('Configuring commenting settings') . '
        '; $output .= '
        ' . t('Commenting settings can be configured by editing the Comments field on the Manage fields page of an entity type if the Field UI module is enabled. Configuration includes the label of the comments field, the number of comments to be displayed, and whether they are shown in threaded list. Commenting can be be configured as: Open to allow new comments, Closed to view existing comments, but prevent new comments, or Hidden to hide existing comments and prevent new comments. Changing this configuration for an entity type will not change existing entity items.') . '
        '; $output .= '
        ' . t('Overriding default settings') . '
        '; $output .= '
        ' . t('Users with the appropriate permissions can override the default commenting settings of an entity type when they create an item of that type.') . '
        '; $output .= '
        ' . t('Adding comment types') . '
        '; - $output .= '
        ' . t('Additional comment types can be created per entity sub-type and added on the Comment types page. If there are multiple comment types available you can select the appropriate one after adding a Comments field.', array(':field' => \Drupal::url('entity.comment_type.collection'))) . '
        '; + $output .= '
        ' . t('Additional comment types can be created per entity sub-type and added on the Comment types page. If there are multiple comment types available you can select the appropriate one after adding a Comments field.', [':field' => \Drupal::url('entity.comment_type.collection')]) . '
        '; $output .= '
        ' . t('Approving and managing comments') . '
        '; - $output .= '
        ' . t('Comments from users who have the Skip comment approval permission are published immediately. All other comments are placed in the Unapproved comments queue, until a user who has permission to Administer comments and comment settings publishes or deletes them. Published comments can be bulk managed on the Published comments administration page. When a comment has no replies, it remains editable by its author, as long as the author has Edit own comments permission.', array(':comment-approval' => \Drupal::url('comment.admin_approval'), ':admin-comment' => \Drupal::url('comment.admin'))) . '
        '; + $output .= '
        ' . t('Comments from users who have the Skip comment approval permission are published immediately. All other comments are placed in the Unapproved comments queue, until a user who has permission to Administer comments and comment settings publishes or deletes them. Published comments can be bulk managed on the Published comments administration page. When a comment has no replies, it remains editable by its author, as long as the author has Edit own comments permission.', [':comment-approval' => \Drupal::url('comment.admin_approval'), ':admin-comment' => \Drupal::url('comment.admin')]) . '
        '; $output .= '
        '; return $output; @@ -96,10 +96,10 @@ function comment_help($route_name, RouteMatchInterface $route_match) { function comment_uri(CommentInterface $comment) { return new Url( 'entity.comment.canonical', - array( + [ 'comment' => $comment->id(), - ), - array('fragment' => 'comment-' . $comment->id()) + ], + ['fragment' => 'comment-' . $comment->id()] ); } @@ -107,23 +107,23 @@ function comment_uri(CommentInterface $comment) { * Implements hook_entity_extra_field_info(). */ function comment_entity_extra_field_info() { - $return = array(); + $return = []; foreach (CommentType::loadMultiple() as $comment_type) { - $return['comment'][$comment_type->id()] = array( - 'form' => array( - 'author' => array( + $return['comment'][$comment_type->id()] = [ + 'form' => [ + 'author' => [ 'label' => t('Author'), 'description' => t('Author textfield'), 'weight' => -2, - ), - ), - ); - $return['comment'][$comment_type->id()]['display']['links'] = array( + ], + ], + ]; + $return['comment'][$comment_type->id()]['display']['links'] = [ 'label' => t('Links'), 'description' => t('Comment operation links'), 'weight' => 100, 'visible' => TRUE, - ); + ]; } return $return; @@ -133,14 +133,14 @@ function comment_entity_extra_field_info() { * Implements hook_theme(). */ function comment_theme() { - return array( - 'comment' => array( + return [ + 'comment' => [ 'render element' => 'elements', - ), - 'field__comment' => array( + ], + 'field__comment' => [ 'base hook' => 'field', - ), - ); + ], + ]; } /** @@ -150,15 +150,15 @@ function comment_field_config_create(FieldConfigInterface $field) { if ($field->getType() == 'comment' && !$field->isSyncing()) { // Assign default values for the field. $default_value = $field->getDefaultValueLiteral(); - $default_value += array(array()); - $default_value[0] += array( + $default_value += [[]]; + $default_value[0] += [ 'status' => CommentItemInterface::OPEN, 'cid' => 0, 'last_comment_timestamp' => 0, 'last_comment_name' => '', 'last_comment_uid' => 0, 'comment_count' => 0, - ); + ]; $field->setDefaultValue($default_value); } } @@ -227,14 +227,14 @@ function comment_entity_view(array &$build, EntityInterface $entity, EntityViewD if ($entity->hasField($field_name) && $entity->get($field_name)->status != CommentItemInterface::HIDDEN) { // Add a comments RSS element which is a URL to the comments of this // entity. - $options = array( + $options = [ 'fragment' => 'comments', 'absolute' => TRUE, - ); - $entity->rss_elements[] = array( + ]; + $entity->rss_elements[] = [ 'key' => 'comments', 'value' => $entity->url('canonical', $options), - ); + ]; } } } @@ -457,7 +457,7 @@ function comment_node_update_index(EntityInterface $node) { } } - $build = array(); + $build = []; if ($index_comments) { foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) { @@ -517,7 +517,7 @@ function comment_node_search_result(EntityInterface $node) { // Do not make a string if there are no comment fields, or no comments exist // or all comment fields are hidden. if ($comments > 0 || $open) { - return array('comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')); + return ['comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')]; } } @@ -527,7 +527,7 @@ function comment_node_search_result(EntityInterface $node) { function comment_user_cancel($edit, $account, $method) { switch ($method) { case 'user_cancel_block_unpublish': - $comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id())); + $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]); foreach ($comments as $comment) { $comment->setPublished(CommentInterface::NOT_PUBLISHED); $comment->save(); @@ -536,7 +536,7 @@ function comment_user_cancel($edit, $account, $method) { case 'user_cancel_reassign': /** @var \Drupal\comment\CommentInterface[] $comments */ - $comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id())); + $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]); foreach ($comments as $comment) { $comment->setOwnerId(0); $comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous')); @@ -568,7 +568,7 @@ function comment_user_predelete($account) { * An array as expected by drupal_render(). */ function comment_preview(CommentInterface $comment, FormStateInterface $form_state) { - $preview_build = array(); + $preview_build = []; $entity = $comment->getCommentedEntity(); if (!$form_state->getErrors()) { @@ -580,7 +580,7 @@ function comment_preview(CommentInterface $comment, FormStateInterface $form_sta } if ($comment->hasParentComment()) { - $build = array(); + $build = []; $parent = $comment->getParentComment(); if ($parent && $parent->isPublished()) { $build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($parent); @@ -636,10 +636,10 @@ function template_preprocess_comment(&$variables) { $variables['threaded'] = $variables['elements']['#comment_threaded']; $account = $comment->getOwner(); - $username = array( + $username = [ '#theme' => 'username', '#account' => $account, - ); + ]; $variables['author'] = drupal_render($username); $variables['author_id'] = $comment->getOwnerId(); $variables['new_indicator_timestamp'] = $comment->getChangedTime(); @@ -658,7 +658,7 @@ function template_preprocess_comment(&$variables) { $variables['user_picture'] = user_view($account, 'compact'); } else { - $variables['user_picture'] = array(); + $variables['user_picture'] = []; } if (isset($comment->in_preview)) { @@ -667,25 +667,25 @@ function template_preprocess_comment(&$variables) { } else { $uri = $comment->permalink(); - $attributes = $uri->getOption('attributes') ?: array(); - $attributes += array('class' => array('permalink'), 'rel' => 'bookmark'); + $attributes = $uri->getOption('attributes') ?: []; + $attributes += ['class' => ['permalink'], 'rel' => 'bookmark']; $uri->setOption('attributes', $attributes); $variables['title'] = \Drupal::l($comment->getSubject(), $uri); $variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink()); } - $variables['submitted'] = t('Submitted by @username on @datetime', array('@username' => $variables['author'], '@datetime' => $variables['created'])); + $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]); if ($comment->hasParentComment()) { // Fetch and store the parent comment information for use in templates. $comment_parent = $comment->getParentComment(); $account_parent = $comment_parent->getOwner(); $variables['parent_comment'] = $comment_parent; - $username = array( + $username = [ '#theme' => 'username', '#account' => $account_parent, - ); + ]; $variables['parent_author'] = drupal_render($username); $variables['parent_created'] = format_date($comment_parent->getCreatedTime()); // Avoid calling format_date() twice on the same timestamp. @@ -696,13 +696,13 @@ function template_preprocess_comment(&$variables) { $variables['parent_changed'] = format_date($comment_parent->getChangedTime()); } $permalink_uri_parent = $comment_parent->permalink(); - $attributes = $permalink_uri_parent->getOption('attributes') ?: array(); - $attributes += array('class' => array('permalink'), 'rel' => 'bookmark'); + $attributes = $permalink_uri_parent->getOption('attributes') ?: []; + $attributes += ['class' => ['permalink'], 'rel' => 'bookmark']; $permalink_uri_parent->setOption('attributes', $attributes); $variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent); $variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent); $variables['parent'] = t('In reply to @parent_title by @parent_username', - array('@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title'])); + ['@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']]); } else { $variables['parent_comment'] = ''; diff --git a/core/modules/comment/comment.tokens.inc b/core/modules/comment/comment.tokens.inc index 5af2e6a174..884144196a 100644 --- a/core/modules/comment/comment.tokens.inc +++ b/core/modules/comment/comment.tokens.inc @@ -15,11 +15,11 @@ * Implements hook_token_info(). */ function comment_token_info() { - $type = array( + $type = [ 'name' => t('Comments'), 'description' => t('Tokens for comments posted on the site.'), 'needs-data' => 'comment', - ); + ]; $tokens = []; // Provide a integration for each entity type except comment. @@ -45,76 +45,76 @@ function comment_token_info() { } // Core comment tokens - $comment['cid'] = array( + $comment['cid'] = [ 'name' => t("Comment ID"), 'description' => t("The unique ID of the comment."), - ); - $comment['hostname'] = array( + ]; + $comment['hostname'] = [ 'name' => t("IP Address"), 'description' => t("The IP address of the computer the comment was posted from."), - ); - $comment['mail'] = array( + ]; + $comment['mail'] = [ 'name' => t("Email address"), 'description' => t("The email address left by the comment author."), - ); - $comment['homepage'] = array( + ]; + $comment['homepage'] = [ 'name' => t("Home page"), 'description' => t("The home page URL left by the comment author."), - ); - $comment['title'] = array( + ]; + $comment['title'] = [ 'name' => t("Title"), 'description' => t("The title of the comment."), - ); - $comment['body'] = array( + ]; + $comment['body'] = [ 'name' => t("Content"), 'description' => t("The formatted content of the comment itself."), - ); - $comment['langcode'] = array( + ]; + $comment['langcode'] = [ 'name' => t('Language code'), 'description' => t('The language code of the language the comment is written in.'), - ); - $comment['url'] = array( + ]; + $comment['url'] = [ 'name' => t("URL"), 'description' => t("The URL of the comment."), - ); - $comment['edit-url'] = array( + ]; + $comment['edit-url'] = [ 'name' => t("Edit URL"), 'description' => t("The URL of the comment's edit page."), - ); + ]; // Chained tokens for comments - $comment['created'] = array( + $comment['created'] = [ 'name' => t("Date created"), 'description' => t("The date the comment was posted."), 'type' => 'date', - ); - $comment['changed'] = array( + ]; + $comment['changed'] = [ 'name' => t("Date changed"), 'description' => t("The date the comment was most recently updated."), 'type' => 'date', - ); - $comment['parent'] = array( + ]; + $comment['parent'] = [ 'name' => t("Parent"), 'description' => t("The comment's parent, if comment threading is active."), 'type' => 'comment', - ); - $comment['entity'] = array( + ]; + $comment['entity'] = [ 'name' => t("Entity"), 'description' => t("The entity the comment was posted to."), 'type' => 'entity', - ); - $comment['author'] = array( + ]; + $comment['author'] = [ 'name' => t("Author"), 'description' => t("The author name of the comment."), 'type' => 'user', - ); + ]; - return array( - 'types' => array('comment' => $type), - 'tokens' => array( + return [ + 'types' => ['comment' => $type], + 'tokens' => [ 'comment' => $comment, - ) + $tokens, - ); + ] + $tokens, + ]; } /** @@ -123,7 +123,7 @@ function comment_token_info() { function comment_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { $token_service = \Drupal::token(); - $url_options = array('absolute' => TRUE); + $url_options = ['absolute' => TRUE]; if (isset($options['langcode'])) { $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']); $langcode = $options['langcode']; @@ -131,7 +131,7 @@ function comment_tokens($type, $tokens, array $data, array $options, BubbleableM else { $langcode = NULL; } - $replacements = array(); + $replacements = []; if ($type == 'comment' && !empty($data['comment'])) { /** @var \Drupal\comment\CommentInterface $comment */ @@ -230,23 +230,23 @@ function comment_tokens($type, $tokens, array $data, array $options, BubbleableM // Chained token relationships. if ($entity_tokens = $token_service->findwithPrefix($tokens, 'entity')) { $entity = $comment->getCommentedEntity(); - $replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, array($comment->getCommentedEntityTypeId() => $entity), $options, $bubbleable_metadata); + $replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, [$comment->getCommentedEntityTypeId() => $entity], $options, $bubbleable_metadata); } if ($date_tokens = $token_service->findwithPrefix($tokens, 'created')) { - $replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getCreatedTime()), $options, $bubbleable_metadata); + $replacements += $token_service->generate('date', $date_tokens, ['date' => $comment->getCreatedTime()], $options, $bubbleable_metadata); } if ($date_tokens = $token_service->findwithPrefix($tokens, 'changed')) { - $replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getChangedTime()), $options, $bubbleable_metadata); + $replacements += $token_service->generate('date', $date_tokens, ['date' => $comment->getChangedTime()], $options, $bubbleable_metadata); } if (($parent_tokens = $token_service->findwithPrefix($tokens, 'parent')) && $parent = $comment->getParentComment()) { - $replacements += $token_service->generate('comment', $parent_tokens, array('comment' => $parent), $options, $bubbleable_metadata); + $replacements += $token_service->generate('comment', $parent_tokens, ['comment' => $parent], $options, $bubbleable_metadata); } if (($author_tokens = $token_service->findwithPrefix($tokens, 'author')) && $account = $comment->getOwner()) { - $replacements += $token_service->generate('user', $author_tokens, array('user' => $account), $options, $bubbleable_metadata); + $replacements += $token_service->generate('user', $author_tokens, ['user' => $account], $options, $bubbleable_metadata); } } // Replacement tokens for any content entities that have comment field. diff --git a/core/modules/comment/comment.views.inc b/core/modules/comment/comment.views.inc index fb11a4f7a5..11abede944 100644 --- a/core/modules/comment/comment.views.inc +++ b/core/modules/comment/comment.views.inc @@ -13,14 +13,14 @@ function comment_views_data_alter(&$data) { // New comments are only supported for node table because it requires the // history table. - $data['node']['new_comments'] = array( + $data['node']['new_comments'] = [ 'title' => t('New comments'), 'help' => t('The number of new comments on the node.'), - 'field' => array( + 'field' => [ 'id' => 'node_new_comments', 'no group by' => TRUE, - ), - ); + ], + ]; // Provide a integration for each entity type except comment. foreach (\Drupal::entityManager()->getDefinitions() as $entity_type_id => $entity_type) { @@ -29,25 +29,25 @@ function comment_views_data_alter(&$data) { } $fields = \Drupal::service('comment.manager')->getFields($entity_type_id); $base_table = $entity_type->getDataTable() ?: $entity_type->getBaseTable(); - $args = array('@entity_type' => $entity_type_id); + $args = ['@entity_type' => $entity_type_id]; if ($fields) { - $data[$base_table]['comments_link'] = array( - 'field' => array( + $data[$base_table]['comments_link'] = [ + 'field' => [ 'title' => t('Add comment link'), 'help' => t('Display the standard add comment link used on regular @entity_type, which will only display if the viewing user has access to add a comment.', $args), 'id' => 'comment_entity_link', - ), - ); + ], + ]; // Multilingual properties are stored in data table. if (!($table = $entity_type->getDataTable())) { $table = $entity_type->getBaseTable(); } - $data[$table]['uid_touch'] = array( + $data[$table]['uid_touch'] = [ 'title' => t('User posted or commented'), 'help' => t('Display nodes only if a user posted the @entity_type or commented on the @entity_type.', $args), - 'argument' => array( + 'argument' => [ 'field' => 'uid', 'name table' => 'users_field_data', 'name field' => 'name', @@ -55,40 +55,40 @@ function comment_views_data_alter(&$data) { 'no group by' => TRUE, 'entity_type' => $entity_type_id, 'entity_id' => $entity_type->getKey('id'), - ), - 'filter' => array( + ], + 'filter' => [ 'field' => 'uid', 'name table' => 'users_field_data', 'name field' => 'name', 'id' => 'comment_user_uid', 'entity_type' => $entity_type_id, 'entity_id' => $entity_type->getKey('id'), - ), - ); + ], + ]; foreach ($fields as $field_name => $field) { - $data[$base_table][$field_name . '_cid'] = array( - 'title' => t('Comments of the @entity_type using field: @field_name', $args + array('@field_name' => $field_name)), + $data[$base_table][$field_name . '_cid'] = [ + 'title' => t('Comments of the @entity_type using field: @field_name', $args + ['@field_name' => $field_name]), 'help' => t('Relate all comments on the @entity_type. This will create 1 duplicate record for every comment. Usually if you need this it is better to create a comment view.', $args), - 'relationship' => array( + 'relationship' => [ 'group' => t('Comment'), 'label' => t('Comments'), 'base' => 'comment_field_data', 'base field' => 'entity_id', 'relationship field' => $entity_type->getKey('id'), 'id' => 'standard', - 'extra' => array( - array( + 'extra' => [ + [ 'field' => 'entity_type', 'value' => $entity_type_id, - ), - array( + ], + [ 'field' => 'field_name', 'value' => $field_name, - ), - ), - ), - ); + ], + ], + ], + ]; } } } diff --git a/core/modules/comment/src/CommentAccessControlHandler.php b/core/modules/comment/src/CommentAccessControlHandler.php index 639575a423..bcb0fd7a08 100644 --- a/core/modules/comment/src/CommentAccessControlHandler.php +++ b/core/modules/comment/src/CommentAccessControlHandler.php @@ -67,23 +67,23 @@ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_ if ($operation == 'edit') { // Only users with the "administer comments" permission can edit // administrative fields. - $administrative_fields = array( + $administrative_fields = [ 'uid', 'status', 'created', 'date', - ); + ]; if (in_array($field_definition->getName(), $administrative_fields, TRUE)) { return AccessResult::allowedIfHasPermission($account, 'administer comments'); } // No user can change read-only fields. - $read_only_fields = array( + $read_only_fields = [ 'hostname', 'changed', 'cid', 'thread', - ); + ]; // These fields can be edited during comment creation. $create_only_fields = [ 'comment_type', diff --git a/core/modules/comment/src/CommentForm.php b/core/modules/comment/src/CommentForm.php index 3a2e704100..28231b8cb7 100644 --- a/core/modules/comment/src/CommentForm.php +++ b/core/modules/comment/src/CommentForm.php @@ -91,7 +91,7 @@ public function form(array $form, FormStateInterface $form_state) { // Use #comment-form as unique jump target, regardless of entity type. $form['#id'] = Html::getUniqueId('comment_form'); - $form['#theme'] = array('comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form'); + $form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form']; $anonymous_contact = $field_definition->getSetting('anonymous'); $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments'); @@ -104,7 +104,7 @@ public function form(array $form, FormStateInterface $form_state) { // If not replying to a comment, use our dedicated page callback for new // Comments on entities. if (!$comment->id() && !$comment->hasParentComment()) { - $form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name)); + $form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]); } $comment_preview = $form_state->get('comment_preview'); @@ -112,13 +112,13 @@ public function form(array $form, FormStateInterface $form_state) { $form += $comment_preview; } - $form['author'] = array(); + $form['author'] = []; // Display author information in a details element for comment moderators. if ($is_admin) { - $form['author'] += array( + $form['author'] += [ '#type' => 'details', '#title' => $this->t('Administration'), - ); + ]; } // Prepare default values for form elements. @@ -129,9 +129,9 @@ public function form(array $form, FormStateInterface $form_state) { } $status = $comment->getStatus(); if (empty($comment_preview)) { - $form['#title'] = $this->t('Edit comment %title', array( + $form['#title'] = $this->t('Edit comment %title', [ '%title' => $comment->getSubject(), - )); + ]); } } else { @@ -162,7 +162,7 @@ public function form(array $form, FormStateInterface $form_state) { // The name field is displayed when an anonymous user is adding a comment or // when a user with the permission 'administer comments' is editing an // existing comment from an anonymous user. - $form['author']['name'] = array( + $form['author']['name'] = [ '#type' => 'textfield', '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'), '#default_value' => $author, @@ -173,20 +173,20 @@ public function form(array $form, FormStateInterface $form_state) { '#attributes' => [ 'data-drupal-default-value' => $config->get('anonymous'), ], - ); + ]; if ($is_admin) { // When editing a comment only display the name textfield if the uid field // is empty. $form['author']['name']['#states'] = [ 'visible' => [ - ':input[name="uid"]' => array('empty' => TRUE), + ':input[name="uid"]' => ['empty' => TRUE], ], ]; } // Add author email and homepage fields depending on the current user. - $form['author']['mail'] = array( + $form['author']['mail'] = [ '#type' => 'email', '#title' => $this->t('Email'), '#default_value' => $comment->getAuthorEmail(), @@ -195,36 +195,36 @@ public function form(array $form, FormStateInterface $form_state) { '#size' => 30, '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'), '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT), - ); + ]; - $form['author']['homepage'] = array( + $form['author']['homepage'] = [ '#type' => 'url', '#title' => $this->t('Homepage'), '#default_value' => $comment->getHomepage(), '#maxlength' => 255, '#size' => 30, '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT), - ); + ]; // Add administrative comment publishing options. - $form['author']['date'] = array( + $form['author']['date'] = [ '#type' => 'datetime', '#title' => $this->t('Authored on'), '#default_value' => $date, '#size' => 20, '#access' => $is_admin, - ); + ]; - $form['author']['status'] = array( + $form['author']['status'] = [ '#type' => 'radios', '#title' => $this->t('Status'), '#default_value' => $status, - '#options' => array( + '#options' => [ CommentInterface::PUBLISHED => $this->t('Published'), CommentInterface::NOT_PUBLISHED => $this->t('Not published'), - ), + ], '#access' => $is_admin, - ); + ]; return parent::form($form, $form_state, $comment); } @@ -250,12 +250,12 @@ protected function actions(array $form, FormStateInterface $form_state) { // already previewing the submission. $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview'); - $element['preview'] = array( + $element['preview'] = [ '#type' => 'submit', '#value' => $this->t('Preview'), '#access' => $preview_mode != DRUPAL_DISABLED, - '#submit' => array('::submitForm', '::preview'), - ); + '#submit' => ['::submitForm', '::preview'], + ]; return $element; } @@ -365,10 +365,10 @@ public function save(array $form, FormStateInterface $form_state) { $form_state->setValue('cid', $comment->id()); // Add a log entry. - $logger->notice('Comment posted: %subject.', array( + $logger->notice('Comment posted: %subject.', [ '%subject' => $comment->getSubject(), 'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id())) - )); + ]); // Explain the approval queue if necessary. if (!$comment->isPublished()) { @@ -379,7 +379,7 @@ public function save(array $form, FormStateInterface $form_state) { else { drupal_set_message($this->t('Your comment has been posted.')); } - $query = array(); + $query = []; // Find the current display page for this comment. $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name]; $page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page')); @@ -391,8 +391,8 @@ public function save(array $form, FormStateInterface $form_state) { $uri->setOption('fragment', 'comment-' . $comment->id()); } else { - $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject())); - drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject())), 'error'); + $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]); + drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]), 'error'); // Redirect the user to the entity they are commenting on. } $form_state->setRedirectUrl($uri); diff --git a/core/modules/comment/src/CommentLazyBuilders.php b/core/modules/comment/src/CommentLazyBuilders.php index 4eeeb59d0c..730c840897 100644 --- a/core/modules/comment/src/CommentLazyBuilders.php +++ b/core/modules/comment/src/CommentLazyBuilders.php @@ -99,13 +99,13 @@ public function __construct(EntityManagerInterface $entity_manager, EntityFormBu * A renderable array containing the comment form. */ public function renderForm($commented_entity_type_id, $commented_entity_id, $field_name, $comment_type_id) { - $values = array( + $values = [ 'entity_type' => $commented_entity_type_id, 'entity_id' => $commented_entity_id, 'field_name' => $field_name, 'comment_type' => $comment_type_id, 'pid' => NULL, - ); + ]; $comment = $this->entityManager->getStorage('comment')->create($values); return $this->entityFormBuilder->getForm($comment); } @@ -126,11 +126,11 @@ public function renderForm($commented_entity_type_id, $commented_entity_id, $fie * A renderable array representing the comment links. */ public function renderLinks($comment_entity_id, $view_mode, $langcode, $is_in_preview) { - $links = array( + $links = [ '#theme' => 'links__comment', - '#pre_render' => array('drupal_pre_render_links'), - '#attributes' => array('class' => array('links', 'inline')), - ); + '#pre_render' => ['drupal_pre_render_links'], + '#attributes' => ['class' => ['links', 'inline']], + ]; if (!$is_in_preview) { /** @var \Drupal\comment\CommentInterface $entity */ @@ -140,11 +140,11 @@ public function renderLinks($comment_entity_id, $view_mode, $langcode, $is_in_pr $links['comment'] = $this->buildLinks($entity, $commented_entity); // Allow other modules to alter the comment links. - $hook_context = array( + $hook_context = [ 'view_mode' => $view_mode, 'langcode' => $langcode, 'commented_entity' => $commented_entity, - ); + ]; $this->moduleHandler->alter('comment_links', $links, $entity, $hook_context); } return $links; @@ -162,25 +162,25 @@ public function renderLinks($comment_entity_id, $view_mode, $langcode, $is_in_pr * An array that can be processed by drupal_pre_render_links(). */ protected function buildLinks(CommentInterface $entity, EntityInterface $commented_entity) { - $links = array(); + $links = []; $status = $commented_entity->get($entity->getFieldName())->status; if ($status == CommentItemInterface::OPEN) { if ($entity->access('delete')) { - $links['comment-delete'] = array( + $links['comment-delete'] = [ 'title' => t('Delete'), 'url' => $entity->urlInfo('delete-form'), - ); + ]; } if ($entity->access('update')) { - $links['comment-edit'] = array( + $links['comment-edit'] = [ 'title' => t('Edit'), 'url' => $entity->urlInfo('edit-form'), - ); + ]; } if ($entity->access('create')) { - $links['comment-reply'] = array( + $links['comment-reply'] = [ 'title' => t('Reply'), 'url' => Url::fromRoute('comment.reply', [ 'entity_type' => $entity->getCommentedEntityTypeId(), @@ -188,13 +188,13 @@ protected function buildLinks(CommentInterface $entity, EntityInterface $comment 'field_name' => $entity->getFieldName(), 'pid' => $entity->id(), ]), - ); + ]; } if (!$entity->isPublished() && $entity->access('approve')) { - $links['comment-approve'] = array( + $links['comment-approve'] = [ 'title' => t('Approve'), 'url' => Url::fromRoute('comment.approve', ['comment' => $entity->id()]), - ); + ]; } if (empty($links) && $this->currentUser->isAnonymous()) { $links['comment-forbidden']['title'] = $this->commentManager->forbiddenMessage($commented_entity, $entity->getFieldName()); @@ -203,18 +203,18 @@ protected function buildLinks(CommentInterface $entity, EntityInterface $comment // Add translations link for translation-enabled comment bundles. if ($this->moduleHandler->moduleExists('content_translation') && $this->access($entity)->isAllowed()) { - $links['comment-translations'] = array( + $links['comment-translations'] = [ 'title' => t('Translate'), 'url' => $entity->urlInfo('drupal:content-translation-overview'), - ); + ]; } - return array( + return [ '#theme' => 'links__comment__comment', // The "entity" property is specified to be present, so no need to check. '#links' => $links, - '#attributes' => array('class' => array('links', 'inline')), - ); + '#attributes' => ['class' => ['links', 'inline']], + ]; } /** diff --git a/core/modules/comment/src/CommentLinkBuilder.php b/core/modules/comment/src/CommentLinkBuilder.php index 9998e3f3d6..c7cbc18d37 100644 --- a/core/modules/comment/src/CommentLinkBuilder.php +++ b/core/modules/comment/src/CommentLinkBuilder.php @@ -75,7 +75,7 @@ public function __construct(AccountInterface $current_user, CommentManagerInterf * {@inheritdoc} */ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, array &$context) { - $entity_links = array(); + $entity_links = []; $view_mode = $context['view_mode']; if ($view_mode == 'search_index' || $view_mode == 'search_result' || $view_mode == 'print' || $view_mode == 'rss') { // Do not add any links if the entity is displayed for: @@ -83,7 +83,7 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra // - constructing a search result excerpt. // - print. // - rss. - return array(); + return []; } $fields = $this->commentManager->getFields($entity->getEntityTypeId()); @@ -92,7 +92,7 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra if (!$entity->hasField($field_name)) { continue; } - $links = array(); + $links = []; $commenting_status = $entity->get($field_name)->status; if ($commenting_status != CommentItemInterface::HIDDEN) { // Entity has commenting status open or closed. @@ -103,23 +103,23 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra // entity is open to new comments, and there currently are none. if ($this->currentUser->hasPermission('access comments')) { if (!empty($entity->get($field_name)->comment_count)) { - $links['comment-comments'] = array( + $links['comment-comments'] = [ 'title' => $this->formatPlural($entity->get($field_name)->comment_count, '1 comment', '@count comments'), - 'attributes' => array('title' => $this->t('Jump to the first comment.')), + 'attributes' => ['title' => $this->t('Jump to the first comment.')], 'fragment' => 'comments', 'url' => $entity->urlInfo(), - ); + ]; if ($this->moduleHandler->moduleExists('history')) { - $links['comment-new-comments'] = array( + $links['comment-new-comments'] = [ 'title' => '', 'url' => Url::fromRoute(''), - 'attributes' => array( + 'attributes' => [ 'class' => 'hidden', 'title' => $this->t('Jump to the first new comment.'), 'data-history-node-last-comment-timestamp' => $entity->get($field_name)->last_comment_timestamp, 'data-history-node-field-name' => $field_name, - ), - ); + ], + ]; } } } @@ -127,12 +127,12 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra if ($commenting_status == CommentItemInterface::OPEN) { $comment_form_location = $field_definition->getSetting('form_location'); if ($this->currentUser->hasPermission('post comments')) { - $links['comment-add'] = array( + $links['comment-add'] = [ 'title' => $this->t('Add new comment'), 'language' => $entity->language(), - 'attributes' => array('title' => $this->t('Share your thoughts and opinions.')), + 'attributes' => ['title' => $this->t('Share your thoughts and opinions.')], 'fragment' => 'comment-form', - ); + ]; if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) { $links['comment-add']['url'] = Url::fromRoute('comment.reply', [ 'entity_type' => $entity->getEntityTypeId(), @@ -145,9 +145,9 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra } } elseif ($this->currentUser->isAnonymous()) { - $links['comment-forbidden'] = array( + $links['comment-forbidden'] = [ 'title' => $this->commentManager->forbiddenMessage($entity, $field_name), - ); + ]; } } } @@ -161,11 +161,11 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra // Show the "post comment" link if the form is on another page, or // if there are existing comments that the link will skip past. if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE || (!empty($entity->get($field_name)->comment_count) && $this->currentUser->hasPermission('access comments'))) { - $links['comment-add'] = array( + $links['comment-add'] = [ 'title' => $this->t('Add new comment'), - 'attributes' => array('title' => $this->t('Share your thoughts and opinions.')), + 'attributes' => ['title' => $this->t('Share your thoughts and opinions.')], 'fragment' => 'comment-form', - ); + ]; if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) { $links['comment-add']['url'] = Url::fromRoute('comment.reply', [ 'entity_type' => $entity->getEntityTypeId(), @@ -179,20 +179,20 @@ public function buildCommentedEntityLinks(FieldableEntityInterface $entity, arra } } elseif ($this->currentUser->isAnonymous()) { - $links['comment-forbidden'] = array( + $links['comment-forbidden'] = [ 'title' => $this->commentManager->forbiddenMessage($entity, $field_name), - ); + ]; } } } } if (!empty($links)) { - $entity_links['comment__' . $field_name] = array( + $entity_links['comment__' . $field_name] = [ '#theme' => 'links__entity__comment__' . $field_name, '#links' => $links, - '#attributes' => array('class' => array('links', 'inline')), - ); + '#attributes' => ['class' => ['links', 'inline']], + ]; if ($view_mode == 'teaser' && $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) { $entity_links['comment__' . $field_name]['#cache']['contexts'][] = 'user'; $entity_links['comment__' . $field_name]['#attached']['library'][] = 'comment/drupal.node-new-comments-link'; diff --git a/core/modules/comment/src/CommentManager.php b/core/modules/comment/src/CommentManager.php index fb1c61e4da..80cc427e34 100644 --- a/core/modules/comment/src/CommentManager.php +++ b/core/modules/comment/src/CommentManager.php @@ -90,11 +90,11 @@ public function __construct(EntityManagerInterface $entity_manager, ConfigFactor public function getFields($entity_type_id) { $entity_type = $this->entityManager->getDefinition($entity_type_id); if (!$entity_type->entityClassImplements(FieldableEntityInterface::class)) { - return array(); + return []; } $map = $this->entityManager->getFieldMapByFieldType('comment'); - return isset($map[$entity_type_id]) ? $map[$entity_type_id] : array(); + return isset($map[$entity_type_id]) ? $map[$entity_type_id] : []; } /** @@ -103,28 +103,28 @@ public function getFields($entity_type_id) { public function addBodyField($comment_type_id) { if (!FieldConfig::loadByName('comment', $comment_type_id, 'comment_body')) { // Attaches the body field by default. - $field = $this->entityManager->getStorage('field_config')->create(array( + $field = $this->entityManager->getStorage('field_config')->create([ 'label' => 'Comment', 'bundle' => $comment_type_id, 'required' => TRUE, 'field_storage' => FieldStorageConfig::loadByName('comment', 'comment_body'), - )); + ]); $field->save(); // Assign widget settings for the 'default' form mode. entity_get_form_display('comment', $comment_type_id, 'default') - ->setComponent('comment_body', array( + ->setComponent('comment_body', [ 'type' => 'text_textarea', - )) + ]) ->save(); // Assign display settings for the 'default' view mode. entity_get_display('comment', $comment_type_id, 'default') - ->setComponent('comment_body', array( + ->setComponent('comment_body', [ 'label' => 'hidden', 'type' => 'text_default', 'weight' => 0, - )) + ]) ->save(); } } @@ -151,24 +151,24 @@ public function forbiddenMessage(EntityInterface $entity, $field_name) { 'entity' => $entity->id(), 'field_name' => $field_name, ]; - $destination = array('destination' => $this->url('comment.reply', $comment_reply_parameters, array('fragment' => 'comment-form'))); + $destination = ['destination' => $this->url('comment.reply', $comment_reply_parameters, ['fragment' => 'comment-form'])]; } else { - $destination = array('destination' => $entity->url('canonical', array('fragment' => 'comment-form'))); + $destination = ['destination' => $entity->url('canonical', ['fragment' => 'comment-form'])]; } if ($this->userConfig->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) { // Users can register themselves. - return $this->t('Log in or register to post comments', array( - ':login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)), - ':register' => $this->urlGenerator->generateFromRoute('user.register', array(), array('query' => $destination)), - )); + return $this->t('Log in or register to post comments', [ + ':login' => $this->urlGenerator->generateFromRoute('user.login', [], ['query' => $destination]), + ':register' => $this->urlGenerator->generateFromRoute('user.register', [], ['query' => $destination]), + ]); } else { // Only admins can add new users, no public registration. - return $this->t('Log in to post comments', array( - ':login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)), - )); + return $this->t('Log in to post comments', [ + ':login' => $this->urlGenerator->generateFromRoute('user.login', [], ['query' => $destination]), + ]); } } return ''; diff --git a/core/modules/comment/src/CommentStatistics.php b/core/modules/comment/src/CommentStatistics.php index 74061ee615..3c6b571c26 100644 --- a/core/modules/comment/src/CommentStatistics.php +++ b/core/modules/comment/src/CommentStatistics.php @@ -65,14 +65,14 @@ public function __construct(Connection $database, AccountInterface $current_user * {@inheritdoc} */ public function read($entities, $entity_type, $accurate = TRUE) { - $options = $accurate ? array() : array('target' => 'replica'); + $options = $accurate ? [] : ['target' => 'replica']; $stats = $this->database->select('comment_entity_statistics', 'ces', $options) ->fields('ces') ->condition('ces.entity_id', array_keys($entities), 'IN') ->condition('ces.entity_type', $entity_type) ->execute(); - $statistics_records = array(); + $statistics_records = []; while ($entry = $stats->fetchObject()) { $statistics_records[] = $entry; } @@ -94,7 +94,7 @@ public function delete(EntityInterface $entity) { */ public function create(FieldableEntityInterface $entity, $fields) { $query = $this->database->insert('comment_entity_statistics') - ->fields(array( + ->fields([ 'entity_id', 'entity_type', 'field_name', @@ -103,7 +103,7 @@ public function create(FieldableEntityInterface $entity, $fields) { 'last_comment_name', 'last_comment_uid', 'comment_count', - )); + ]); foreach ($fields as $field_name => $detail) { // Skip fields that entity does not have. if (!$entity->hasField($field_name)) { @@ -127,7 +127,7 @@ public function create(FieldableEntityInterface $entity, $fields) { if ($entity instanceof EntityChangedInterface) { $last_comment_timestamp = $entity->getChangedTimeAcrossTranslations(); } - $query->values(array( + $query->values([ 'entity_id' => $entity->id(), 'entity_type' => $entity->getEntityTypeId(), 'field_name' => $field_name, @@ -136,7 +136,7 @@ public function create(FieldableEntityInterface $entity, $fields) { 'last_comment_name' => NULL, 'last_comment_uid' => $last_comment_uid, 'comment_count' => 0, - )); + ]); } $query->execute(); } @@ -145,24 +145,24 @@ public function create(FieldableEntityInterface $entity, $fields) { * {@inheritdoc} */ public function getMaximumCount($entity_type) { - return $this->database->query('SELECT MAX(comment_count) FROM {comment_entity_statistics} WHERE entity_type = :entity_type', array(':entity_type' => $entity_type))->fetchField(); + return $this->database->query('SELECT MAX(comment_count) FROM {comment_entity_statistics} WHERE entity_type = :entity_type', [':entity_type' => $entity_type])->fetchField(); } /** * {@inheritdoc} */ public function getRankingInfo() { - return array( - 'comments' => array( + return [ + 'comments' => [ 'title' => t('Number of comments'), - 'join' => array( + 'join' => [ 'type' => 'LEFT', 'table' => 'comment_entity_statistics', 'alias' => 'ces', // Default to comment field as this is the most common use case for // nodes. 'on' => "ces.entity_id = i.sid AND ces.entity_type = 'node' AND ces.field_name = 'comment'", - ), + ], // Inverse law that maps the highest view count on the site to 1 and 0 // to 0. Note that the ROUND here is necessary for PostgreSQL and SQLite // in order to ensure that the :comment_scale argument is treated as @@ -170,9 +170,9 @@ public function getRankingInfo() { // values in as strings instead of numbers in complex expressions like // this. 'score' => '2.0 - 2.0 / (1.0 + ces.comment_count * (ROUND(:comment_scale, 4)))', - 'arguments' => array(':comment_scale' => \Drupal::state()->get('comment.node_comment_statistics_scale') ?: 0), - ), - ); + 'arguments' => [':comment_scale' => \Drupal::state()->get('comment.node_comment_statistics_scale') ?: 0], + ], + ]; } /** @@ -198,7 +198,7 @@ public function update(CommentInterface $comment) { if ($count > 0) { // Comments exist. $last_reply = $this->database->select('comment_field_data', 'c') - ->fields('c', array('cid', 'name', 'changed', 'uid')) + ->fields('c', ['cid', 'name', 'changed', 'uid']) ->condition('c.entity_id', $comment->getCommentedEntityId()) ->condition('c.entity_type', $comment->getCommentedEntityTypeId()) ->condition('c.field_name', $comment->getFieldName()) @@ -210,18 +210,18 @@ public function update(CommentInterface $comment) { ->fetchObject(); // Use merge here because entity could be created before comment field. $this->database->merge('comment_entity_statistics') - ->fields(array( + ->fields([ 'cid' => $last_reply->cid, 'comment_count' => $count, 'last_comment_timestamp' => $last_reply->changed, 'last_comment_name' => $last_reply->uid ? '' : $last_reply->name, 'last_comment_uid' => $last_reply->uid, - )) - ->keys(array( + ]) + ->keys([ 'entity_id' => $comment->getCommentedEntityId(), 'entity_type' => $comment->getCommentedEntityTypeId(), 'field_name' => $comment->getFieldName(), - )) + ]) ->execute(); } else { @@ -238,7 +238,7 @@ public function update(CommentInterface $comment) { $last_comment_uid = $this->currentUser->id(); } $this->database->update('comment_entity_statistics') - ->fields(array( + ->fields([ 'cid' => 0, 'comment_count' => 0, // Use the changed date of the entity if it's set, or default to @@ -246,7 +246,7 @@ public function update(CommentInterface $comment) { 'last_comment_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : REQUEST_TIME, 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid, - )) + ]) ->condition('entity_id', $comment->getCommentedEntityId()) ->condition('entity_type', $comment->getCommentedEntityTypeId()) ->condition('field_name', $comment->getFieldName()) @@ -255,7 +255,7 @@ public function update(CommentInterface $comment) { // Reset the cache of the commented entity so that when the entity is loaded // the next time, the statistics will be loaded again. - $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache(array($comment->getCommentedEntityId())); + $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache([$comment->getCommentedEntityId()]); } } diff --git a/core/modules/comment/src/CommentStorage.php b/core/modules/comment/src/CommentStorage.php index cc4fdcfc46..d164d8ad9e 100644 --- a/core/modules/comment/src/CommentStorage.php +++ b/core/modules/comment/src/CommentStorage.php @@ -147,7 +147,7 @@ public function getNewCommentPageNumber($total_comments, $new_comments, Fieldabl // 1. Find all the threads with a new comment. $unread_threads_query = $this->database->select('comment_field_data', 'comment') - ->fields('comment', array('thread')) + ->fields('comment', ['thread']) ->condition('entity_id', $entity->id()) ->condition('entity_type', $entity->getEntityTypeId()) ->condition('field_name', $field_name) @@ -161,7 +161,7 @@ public function getNewCommentPageNumber($total_comments, $new_comments, Fieldabl $first_thread_query = $this->database->select($unread_threads_query, 'thread'); $first_thread_query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'torder'); $first_thread = $first_thread_query - ->fields('thread', array('thread')) + ->fields('thread', ['thread']) ->orderBy('torder') ->range(0, 1) ->execute() @@ -176,13 +176,13 @@ public function getNewCommentPageNumber($total_comments, $new_comments, Fieldabl AND field_name = :field_name AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread - AND default_langcode = 1', array( + AND default_langcode = 1', [ ':status' => CommentInterface::PUBLISHED, ':entity_id' => $entity->id(), ':field_name' => $field_name, ':entity_type' => $entity->getEntityTypeId(), ':thread' => $first_thread, - ))->fetchField(); + ])->fetchField(); } return $comments_per_page > 0 ? (int) ($count / $comments_per_page) : 0; @@ -193,7 +193,7 @@ public function getNewCommentPageNumber($total_comments, $new_comments, Fieldabl */ public function getChildCids(array $comments) { return $this->database->select('comment_field_data', 'c') - ->fields('c', array('cid')) + ->fields('c', ['cid']) ->condition('pid', array_keys($comments), 'IN') ->condition('default_langcode', 1) ->execute() @@ -312,7 +312,7 @@ public function loadThread(EntityInterface $entity, $field_name, $mode, $comment $cids = $query->execute()->fetchCol(); - $comments = array(); + $comments = []; if ($cids) { $comments = $this->loadMultiple($cids); } diff --git a/core/modules/comment/src/CommentStorageSchema.php b/core/modules/comment/src/CommentStorageSchema.php index ee663c0d0c..2106a8ec2b 100644 --- a/core/modules/comment/src/CommentStorageSchema.php +++ b/core/modules/comment/src/CommentStorageSchema.php @@ -17,9 +17,9 @@ class CommentStorageSchema extends SqlContentEntityStorageSchema { protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) { $schema = parent::getEntitySchema($entity_type, $reset); - $schema['comment_field_data']['indexes'] += array( - 'comment__status_pid' => array('pid', 'status'), - 'comment__num_new' => array( + $schema['comment_field_data']['indexes'] += [ + 'comment__status_pid' => ['pid', 'status'], + 'comment__num_new' => [ 'entity_id', 'entity_type', 'comment_type', @@ -27,14 +27,14 @@ protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $res 'created', 'cid', 'thread', - ), - 'comment__entity_langcode' => array( + ], + 'comment__entity_langcode' => [ 'entity_id', 'entity_type', 'comment_type', 'default_langcode', - ), - ); + ], + ]; return $schema; } diff --git a/core/modules/comment/src/CommentTranslationHandler.php b/core/modules/comment/src/CommentTranslationHandler.php index 98afe3bdbc..a0abe4b710 100644 --- a/core/modules/comment/src/CommentTranslationHandler.php +++ b/core/modules/comment/src/CommentTranslationHandler.php @@ -30,7 +30,7 @@ public function entityFormAlter(array &$form, FormStateInterface $form_state, En * {@inheritdoc} */ protected function entityFormTitle(EntityInterface $entity) { - return t('Edit comment @subject', array('@subject' => $entity->label())); + return t('Edit comment @subject', ['@subject' => $entity->label()]); } /** diff --git a/core/modules/comment/src/CommentTypeForm.php b/core/modules/comment/src/CommentTypeForm.php index 594726ae62..9cb147f7f0 100644 --- a/core/modules/comment/src/CommentTypeForm.php +++ b/core/modules/comment/src/CommentTypeForm.php @@ -71,32 +71,32 @@ public function form(array $form, FormStateInterface $form_state) { $comment_type = $this->entity; - $form['label'] = array( + $form['label'] = [ '#type' => 'textfield', '#title' => t('Label'), '#maxlength' => 255, '#default_value' => $comment_type->label(), '#required' => TRUE, - ); - $form['id'] = array( + ]; + $form['id'] = [ '#type' => 'machine_name', '#default_value' => $comment_type->id(), - '#machine_name' => array( + '#machine_name' => [ 'exists' => '\Drupal\comment\Entity\CommentType::load', - ), + ], '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, '#disabled' => !$comment_type->isNew(), - ); + ]; - $form['description'] = array( + $form['description'] = [ '#type' => 'textarea', '#default_value' => $comment_type->getDescription(), '#description' => t('Describe this comment type. The text will be displayed on the Comment types administration overview page.'), '#title' => t('Description'), - ); + ]; if ($comment_type->isNew()) { - $options = array(); + $options = []; foreach ($this->entityManager->getDefinitions() as $entity_type) { // Only expose entities that have field UI enabled, only those can // get comment fields added in the UI. @@ -104,47 +104,47 @@ public function form(array $form, FormStateInterface $form_state) { $options[$entity_type->id()] = $entity_type->getLabel(); } } - $form['target_entity_type_id'] = array( + $form['target_entity_type_id'] = [ '#type' => 'select', '#default_value' => $comment_type->getTargetEntityTypeId(), '#title' => t('Target entity type'), '#options' => $options, '#description' => t('The target entity type can not be changed after the comment type has been created.') - ); + ]; } else { - $form['target_entity_type_id_display'] = array( + $form['target_entity_type_id_display'] = [ '#type' => 'item', '#markup' => $this->entityManager->getDefinition($comment_type->getTargetEntityTypeId())->getLabel(), '#title' => t('Target entity type'), - ); + ]; } if ($this->moduleHandler->moduleExists('content_translation')) { - $form['language'] = array( + $form['language'] = [ '#type' => 'details', '#title' => t('Language settings'), '#group' => 'additional_settings', - ); + ]; $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('comment', $comment_type->id()); - $form['language']['language_configuration'] = array( + $form['language']['language_configuration'] = [ '#type' => 'language_configuration', - '#entity_information' => array( + '#entity_information' => [ 'entity_type' => 'comment', 'bundle' => $comment_type->id(), - ), + ], '#default_value' => $language_configuration, - ); + ]; $form['#submit'][] = 'language_configuration_element_submit'; } - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => t('Save'), - ); + ]; return $form; } @@ -158,13 +158,13 @@ public function save(array $form, FormStateInterface $form_state) { $edit_link = $this->entity->link($this->t('Edit')); if ($status == SAVED_UPDATED) { - drupal_set_message(t('Comment type %label has been updated.', array('%label' => $comment_type->label()))); - $this->logger->notice('Comment type %label has been updated.', array('%label' => $comment_type->label(), 'link' => $edit_link)); + drupal_set_message(t('Comment type %label has been updated.', ['%label' => $comment_type->label()])); + $this->logger->notice('Comment type %label has been updated.', ['%label' => $comment_type->label(), 'link' => $edit_link]); } else { $this->commentManager->addBodyField($comment_type->id()); - drupal_set_message(t('Comment type %label has been added.', array('%label' => $comment_type->label()))); - $this->logger->notice('Comment type %label has been added.', array('%label' => $comment_type->label(), 'link' => $edit_link)); + drupal_set_message(t('Comment type %label has been added.', ['%label' => $comment_type->label()])); + $this->logger->notice('Comment type %label has been added.', ['%label' => $comment_type->label(), 'link' => $edit_link]); } $form_state->setRedirectUrl($comment_type->urlInfo('collection')); diff --git a/core/modules/comment/src/CommentViewBuilder.php b/core/modules/comment/src/CommentViewBuilder.php index 5771ed5064..ec6d49a5b0 100644 --- a/core/modules/comment/src/CommentViewBuilder.php +++ b/core/modules/comment/src/CommentViewBuilder.php @@ -88,7 +88,7 @@ public function buildComponents(array &$build, array $entities, array $displays, } // Pre-load associated users into cache to leverage multiple loading. - $uids = array(); + $uids = []; foreach ($entities as $entity) { $uids[] = $entity->getOwnerId(); } @@ -125,7 +125,7 @@ public function buildComponents(array &$build, array $entities, array $displays, $display = $displays[$entity->bundle()]; if ($display->getComponent('links')) { - $build[$id]['links'] = array( + $build[$id]['links'] = [ '#lazy_builder' => ['comment.lazy_builders:renderLinks', [ $entity->id(), $view_mode, @@ -133,11 +133,11 @@ public function buildComponents(array &$build, array $entities, array $displays, !empty($entity->in_preview), ]], '#create_placeholder' => TRUE, - ); + ]; } if (!isset($build[$id]['#attached'])) { - $build[$id]['#attached'] = array(); + $build[$id]['#attached'] = []; } $build[$id]['#attached']['library'][] = 'comment/drupal.comment-by-viewer'; if ($this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) { diff --git a/core/modules/comment/src/CommentViewsData.php b/core/modules/comment/src/CommentViewsData.php index e4ca5b0259..52af015d59 100644 --- a/core/modules/comment/src/CommentViewsData.php +++ b/core/modules/comment/src/CommentViewsData.php @@ -36,148 +36,148 @@ public function getViewsData() { $data['comment_field_data']['created']['title'] = $this->t('Post date'); $data['comment_field_data']['created']['help'] = $this->t('Date and time of when the comment was created.'); - $data['comment_field_data']['created_fulldata'] = array( + $data['comment_field_data']['created_fulldata'] = [ 'title' => $this->t('Created date'), 'help' => $this->t('Date in the form of CCYYMMDD.'), - 'argument' => array( + 'argument' => [ 'field' => 'created', 'id' => 'date_fulldate', - ), - ); + ], + ]; - $data['comment_field_data']['created_year_month'] = array( + $data['comment_field_data']['created_year_month'] = [ 'title' => $this->t('Created year + month'), 'help' => $this->t('Date in the form of YYYYMM.'), - 'argument' => array( + 'argument' => [ 'field' => 'created', 'id' => 'date_year_month', - ), - ); + ], + ]; - $data['comment_field_data']['created_year'] = array( + $data['comment_field_data']['created_year'] = [ 'title' => $this->t('Created year'), 'help' => $this->t('Date in the form of YYYY.'), - 'argument' => array( + 'argument' => [ 'field' => 'created', 'id' => 'date_year', - ), - ); + ], + ]; - $data['comment_field_data']['created_month'] = array( + $data['comment_field_data']['created_month'] = [ 'title' => $this->t('Created month'), 'help' => $this->t('Date in the form of MM (01 - 12).'), - 'argument' => array( + 'argument' => [ 'field' => 'created', 'id' => 'date_month', - ), - ); + ], + ]; - $data['comment_field_data']['created_day'] = array( + $data['comment_field_data']['created_day'] = [ 'title' => $this->t('Created day'), 'help' => $this->t('Date in the form of DD (01 - 31).'), - 'argument' => array( + 'argument' => [ 'field' => 'created', 'id' => 'date_day', - ), - ); + ], + ]; - $data['comment_field_data']['created_week'] = array( + $data['comment_field_data']['created_week'] = [ 'title' => $this->t('Created week'), 'help' => $this->t('Date in the form of WW (01 - 53).'), - 'argument' => array( + 'argument' => [ 'field' => 'created', 'id' => 'date_week', - ), - ); + ], + ]; $data['comment_field_data']['changed']['title'] = $this->t('Updated date'); $data['comment_field_data']['changed']['help'] = $this->t('Date and time of when the comment was last updated.'); - $data['comment_field_data']['changed_fulldata'] = array( + $data['comment_field_data']['changed_fulldata'] = [ 'title' => $this->t('Changed date'), 'help' => $this->t('Date in the form of CCYYMMDD.'), - 'argument' => array( + 'argument' => [ 'field' => 'changed', 'id' => 'date_fulldate', - ), - ); + ], + ]; - $data['comment_field_data']['changed_year_month'] = array( + $data['comment_field_data']['changed_year_month'] = [ 'title' => $this->t('Changed year + month'), 'help' => $this->t('Date in the form of YYYYMM.'), - 'argument' => array( + 'argument' => [ 'field' => 'changed', 'id' => 'date_year_month', - ), - ); + ], + ]; - $data['comment_field_data']['changed_year'] = array( + $data['comment_field_data']['changed_year'] = [ 'title' => $this->t('Changed year'), 'help' => $this->t('Date in the form of YYYY.'), - 'argument' => array( + 'argument' => [ 'field' => 'changed', 'id' => 'date_year', - ), - ); + ], + ]; - $data['comment_field_data']['changed_month'] = array( + $data['comment_field_data']['changed_month'] = [ 'title' => $this->t('Changed month'), 'help' => $this->t('Date in the form of MM (01 - 12).'), - 'argument' => array( + 'argument' => [ 'field' => 'changed', 'id' => 'date_month', - ), - ); + ], + ]; - $data['comment_field_data']['changed_day'] = array( + $data['comment_field_data']['changed_day'] = [ 'title' => $this->t('Changed day'), 'help' => $this->t('Date in the form of DD (01 - 31).'), - 'argument' => array( + 'argument' => [ 'field' => 'changed', 'id' => 'date_day', - ), - ); + ], + ]; - $data['comment_field_data']['changed_week'] = array( + $data['comment_field_data']['changed_week'] = [ 'title' => $this->t('Changed week'), 'help' => $this->t('Date in the form of WW (01 - 53).'), - 'argument' => array( + 'argument' => [ 'field' => 'changed', 'id' => 'date_week', - ), - ); + ], + ]; $data['comment_field_data']['status']['title'] = $this->t('Approved status'); $data['comment_field_data']['status']['help'] = $this->t('Whether the comment is approved (or still in the moderation queue).'); $data['comment_field_data']['status']['filter']['label'] = $this->t('Approved comment status'); $data['comment_field_data']['status']['filter']['type'] = 'yes-no'; - $data['comment']['approve_comment'] = array( - 'field' => array( + $data['comment']['approve_comment'] = [ + 'field' => [ 'title' => $this->t('Link to approve comment'), 'help' => $this->t('Provide a simple link to approve the comment.'), 'id' => 'comment_link_approve', - ), - ); + ], + ]; - $data['comment']['replyto_comment'] = array( - 'field' => array( + $data['comment']['replyto_comment'] = [ + 'field' => [ 'title' => $this->t('Link to reply-to comment'), 'help' => $this->t('Provide a simple link to reply to the comment.'), 'id' => 'comment_link_reply', - ), - ); + ], + ]; - $data['comment_field_data']['thread']['field'] = array( + $data['comment_field_data']['thread']['field'] = [ 'title' => $this->t('Depth'), 'help' => $this->t('Display the depth of the comment if it is threaded.'), 'id' => 'comment_depth', - ); - $data['comment_field_data']['thread']['sort'] = array( + ]; + $data['comment_field_data']['thread']['sort'] = [ 'title' => $this->t('Thread'), 'help' => $this->t('Sort by the threaded order. This will keep child comments together with their parents.'), 'id' => 'comment_thread', - ); + ]; unset($data['comment_field_data']['thread']['filter']); unset($data['comment_field_data']['thread']['argument']); @@ -189,24 +189,24 @@ public function getViewsData() { continue; } if ($fields = \Drupal::service('comment.manager')->getFields($type)) { - $data['comment_field_data'][$type] = array( - 'relationship' => array( + $data['comment_field_data'][$type] = [ + 'relationship' => [ 'title' => $entity_type->getLabel(), - 'help' => $this->t('The @entity_type to which the comment is a reply to.', array('@entity_type' => $entity_type->getLabel())), + 'help' => $this->t('The @entity_type to which the comment is a reply to.', ['@entity_type' => $entity_type->getLabel()]), 'base' => $entity_type->getDataTable() ?: $entity_type->getBaseTable(), 'base field' => $entity_type->getKey('id'), 'relationship field' => 'entity_id', 'id' => 'standard', 'label' => $entity_type->getLabel(), - 'extra' => array( - array( + 'extra' => [ + [ 'field' => 'entity_type', 'value' => $type, 'table' => 'comment_field_data' - ), - ), - ), - ); + ], + ], + ], + ]; } } @@ -237,84 +237,84 @@ public function getViewsData() { // {comment_entity_statistics} for each field as multiple joins between // the same two tables is not supported. if (\Drupal::service('comment.manager')->getFields($type)) { - $data['comment_entity_statistics']['table']['join'][$entity_type->getDataTable() ?: $entity_type->getBaseTable()] = array( + $data['comment_entity_statistics']['table']['join'][$entity_type->getDataTable() ?: $entity_type->getBaseTable()] = [ 'type' => 'INNER', 'left_field' => $entity_type->getKey('id'), 'field' => 'entity_id', - 'extra' => array( - array( + 'extra' => [ + [ 'field' => 'entity_type', 'value' => $type, - ), - ), - ); + ], + ], + ]; } } - $data['comment_entity_statistics']['last_comment_timestamp'] = array( + $data['comment_entity_statistics']['last_comment_timestamp'] = [ 'title' => $this->t('Last comment time'), 'help' => $this->t('Date and time of when the last comment was posted.'), - 'field' => array( + 'field' => [ 'id' => 'comment_last_timestamp', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'date', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'date', - ), - ); + ], + ]; - $data['comment_entity_statistics']['last_comment_name'] = array( + $data['comment_entity_statistics']['last_comment_name'] = [ 'title' => $this->t("Last comment author"), 'help' => $this->t('The name of the author of the last posted comment.'), - 'field' => array( + 'field' => [ 'id' => 'comment_ces_last_comment_name', 'no group by' => TRUE, - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'comment_ces_last_comment_name', 'no group by' => TRUE, - ), - ); + ], + ]; - $data['comment_entity_statistics']['comment_count'] = array( + $data['comment_entity_statistics']['comment_count'] = [ 'title' => $this->t('Comment count'), 'help' => $this->t('The number of comments an entity has.'), - 'field' => array( + 'field' => [ 'id' => 'numeric', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'numeric', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['comment_entity_statistics']['last_updated'] = array( + $data['comment_entity_statistics']['last_updated'] = [ 'title' => $this->t('Updated/commented date'), 'help' => $this->t('The most recent of last comment posted or entity updated time.'), - 'field' => array( + 'field' => [ 'id' => 'comment_ces_last_updated', 'no group by' => TRUE, - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'comment_ces_last_updated', 'no group by' => TRUE, - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'comment_ces_last_updated', - ), - ); + ], + ]; - $data['comment_entity_statistics']['cid'] = array( + $data['comment_entity_statistics']['cid'] = [ 'title' => $this->t('Last comment CID'), 'help' => $this->t('Display the last comment of an entity'), - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('Last comment'), 'help' => $this->t('The last comment of an entity.'), 'group' => $this->t('Comment'), @@ -322,62 +322,62 @@ public function getViewsData() { 'base field' => 'cid', 'id' => 'standard', 'label' => $this->t('Last Comment'), - ), - ); + ], + ]; - $data['comment_entity_statistics']['last_comment_uid'] = array( + $data['comment_entity_statistics']['last_comment_uid'] = [ 'title' => $this->t('Last comment uid'), 'help' => $this->t('The User ID of the author of the last comment of an entity.'), - 'relationship' => array( + 'relationship' => [ 'title' => $this->t('Last comment author'), 'base' => 'users', 'base field' => 'uid', 'id' => 'standard', 'label' => $this->t('Last comment author'), - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'numeric', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'numeric', - ), - 'field' => array( + ], + 'field' => [ 'id' => 'numeric', - ), - ); + ], + ]; - $data['comment_entity_statistics']['entity_type'] = array( + $data['comment_entity_statistics']['entity_type'] = [ 'title' => $this->t('Entity type'), 'help' => $this->t('The entity type to which the comment is a reply to.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); - $data['comment_entity_statistics']['field_name'] = array( + ], + ]; + $data['comment_entity_statistics']['field_name'] = [ 'title' => $this->t('Comment field name'), 'help' => $this->t('The field name from which the comment originated.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; return $data; } diff --git a/core/modules/comment/src/Controller/CommentController.php b/core/modules/comment/src/Controller/CommentController.php index 5f1b504b63..c834fa67a1 100644 --- a/core/modules/comment/src/Controller/CommentController.php +++ b/core/modules/comment/src/Controller/CommentController.php @@ -125,7 +125,7 @@ public function commentPermalink(Request $request, CommentInterface $comment) { $page = $this->entityManager()->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page')); // @todo: Cleaner sub request handling. $subrequest_url = $entity->urlInfo()->setOption('query', ['page' => $page])->toString(TRUE); - $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all(), $request->cookies->all(), array(), $request->server->all()); + $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all(), $request->cookies->all(), [], $request->server->all()); // Carry over the session to the subrequest. if ($session = $request->getSession()) { $redirect_request->setSession($session); @@ -174,11 +174,11 @@ public function redirectNode(EntityInterface $node) { // Legacy nodes only had a single comment field, so use the first comment // field on the entity. if (!empty($fields) && ($field_names = array_keys($fields)) && ($field_name = reset($field_names))) { - return $this->redirect('comment.reply', array( + return $this->redirect('comment.reply', [ 'entity_type' => 'node', 'entity' => $node->id(), 'field_name' => $field_name, - )); + ]); } throw new NotFoundHttpException(); } @@ -211,7 +211,7 @@ public function redirectNode(EntityInterface $node) { */ public function getReplyForm(Request $request, EntityInterface $entity, $field_name, $pid = NULL) { $account = $this->currentUser(); - $build = array(); + $build = []; // The user is not just previewing a comment. if ($request->request->get('op') != $this->t('Preview')) { @@ -240,12 +240,12 @@ public function getReplyForm(Request $request, EntityInterface $entity, $field_n } // Show the actual reply box. - $comment = $this->entityManager()->getStorage('comment')->create(array( + $comment = $this->entityManager()->getStorage('comment')->create([ 'entity_id' => $entity->id(), 'pid' => $pid, 'entity_type' => $entity->getEntityTypeId(), 'field_name' => $field_name, - )); + ]); $build['comment_form'] = $this->entityFormBuilder()->getForm($comment); return $build; @@ -324,17 +324,17 @@ public function renderNewCommentsNodeLinks(Request $request) { // Only handle up to 100 nodes. $nids = array_slice($nids, 0, 100); - $links = array(); + $links = []; foreach ($nids as $nid) { $node = $this->entityManager->getStorage('node')->load($nid); $new = $this->commentManager->getCountNewComments($node); $page_number = $this->entityManager()->getStorage('comment') ->getNewCommentPageNumber($node->{$field_name}->comment_count, $new, $node, $field_name); - $query = $page_number ? array('page' => $page_number) : NULL; - $links[$nid] = array( + $query = $page_number ? ['page' => $page_number] : NULL; + $links[$nid] = [ 'new_comment_count' => (int) $new, - 'first_new_comment_link' => $this->getUrlGenerator()->generateFromRoute('entity.node.canonical', array('node' => $node->id()), array('query' => $query, 'fragment' => 'new')), - ); + 'first_new_comment_link' => $this->getUrlGenerator()->generateFromRoute('entity.node.canonical', ['node' => $node->id()], ['query' => $query, 'fragment' => 'new']), + ]; } return new JsonResponse($links); diff --git a/core/modules/comment/src/Entity/Comment.php b/core/modules/comment/src/Entity/Comment.php index d52f04dcbb..83dffaa9e5 100644 --- a/core/modules/comment/src/Entity/Comment.php +++ b/core/modules/comment/src/Entity/Comment.php @@ -249,11 +249,11 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setLabel(t('Subject')) ->setTranslatable(TRUE) ->setSetting('max_length', 64) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'string_textfield', // Default comment body field has weight 20. 'weight' => 10, - )) + ]) ->setDisplayConfigurable('form', TRUE); $fields['uid'] = BaseFieldDefinition::create('entity_reference') @@ -328,7 +328,7 @@ public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $fields['entity_id']->setSetting('target_type', $comment_type->getTargetEntityTypeId()); return $fields; } - return array(); + return []; } /** diff --git a/core/modules/comment/src/Form/CommentAdminOverview.php b/core/modules/comment/src/Form/CommentAdminOverview.php index 3966fca1bf..24f8b0aa2e 100644 --- a/core/modules/comment/src/Form/CommentAdminOverview.php +++ b/core/modules/comment/src/Form/CommentAdminOverview.php @@ -99,12 +99,12 @@ public function getFormId() { public function buildForm(array $form, FormStateInterface $form_state, $type = 'new') { // Build an 'Update options' form. - $form['options'] = array( + $form['options'] = [ '#type' => 'details', '#title' => $this->t('Update options'), '#open' => TRUE, - '#attributes' => array('class' => array('container-inline')), - ); + '#attributes' => ['class' => ['container-inline']], + ]; if ($type == 'approval') { $options['publish'] = $this->t('Publish the selected comments'); @@ -114,42 +114,42 @@ public function buildForm(array $form, FormStateInterface $form_state, $type = ' } $options['delete'] = $this->t('Delete the selected comments'); - $form['options']['operation'] = array( + $form['options']['operation'] = [ '#type' => 'select', '#title' => $this->t('Action'), '#title_display' => 'invisible', '#options' => $options, '#default_value' => 'publish', - ); - $form['options']['submit'] = array( + ]; + $form['options']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Update'), - ); + ]; // Load the comments that need to be displayed. $status = ($type == 'approval') ? CommentInterface::NOT_PUBLISHED : CommentInterface::PUBLISHED; - $header = array( - 'subject' => array( + $header = [ + 'subject' => [ 'data' => $this->t('Subject'), 'specifier' => 'subject', - ), - 'author' => array( + ], + 'author' => [ 'data' => $this->t('Author'), 'specifier' => 'name', - 'class' => array(RESPONSIVE_PRIORITY_MEDIUM), - ), - 'posted_in' => array( + 'class' => [RESPONSIVE_PRIORITY_MEDIUM], + ], + 'posted_in' => [ 'data' => $this->t('Posted in'), - 'class' => array(RESPONSIVE_PRIORITY_LOW), - ), - 'changed' => array( + 'class' => [RESPONSIVE_PRIORITY_LOW], + ], + 'changed' => [ 'data' => $this->t('Updated'), 'specifier' => 'changed', 'sort' => 'desc', - 'class' => array(RESPONSIVE_PRIORITY_LOW), - ), + 'class' => [RESPONSIVE_PRIORITY_LOW], + ], 'operations' => $this->t('Operations'), - ); + ]; $cids = $this->commentStorage->getQuery() ->condition('status', $status) ->tableSort($header) @@ -160,11 +160,11 @@ public function buildForm(array $form, FormStateInterface $form_state, $type = ' $comments = $this->commentStorage->loadMultiple($cids); // Build a table listing the appropriate comments. - $options = array(); + $options = []; $destination = $this->getDestinationArray(); - $commented_entity_ids = array(); - $commented_entities = array(); + $commented_entity_ids = []; + $commented_entities = []; foreach ($comments as $comment) { $commented_entity_ids[$comment->getCommentedEntityTypeId()][] = $comment->getCommentedEntityId(); @@ -179,61 +179,61 @@ public function buildForm(array $form, FormStateInterface $form_state, $type = ' $commented_entity = $commented_entities[$comment->getCommentedEntityTypeId()][$comment->getCommentedEntityId()]; $comment_permalink = $comment->permalink(); if ($comment->hasField('comment_body') && ($body = $comment->get('comment_body')->value)) { - $attributes = $comment_permalink->getOption('attributes') ?: array(); - $attributes += array('title' => Unicode::truncate($body, 128)); + $attributes = $comment_permalink->getOption('attributes') ?: []; + $attributes += ['title' => Unicode::truncate($body, 128)]; $comment_permalink->setOption('attributes', $attributes); } - $options[$comment->id()] = array( - 'title' => array('data' => array('#title' => $comment->getSubject() ?: $comment->id())), - 'subject' => array( - 'data' => array( + $options[$comment->id()] = [ + 'title' => ['data' => ['#title' => $comment->getSubject() ?: $comment->id()]], + 'subject' => [ + 'data' => [ '#type' => 'link', '#title' => $comment->getSubject(), '#url' => $comment_permalink, - ), - ), - 'author' => array( - 'data' => array( + ], + ], + 'author' => [ + 'data' => [ '#theme' => 'username', '#account' => $comment->getOwner(), - ), - ), - 'posted_in' => array( - 'data' => array( + ], + ], + 'posted_in' => [ + 'data' => [ '#type' => 'link', '#title' => $commented_entity->label(), '#access' => $commented_entity->access('view'), '#url' => $commented_entity->urlInfo(), - ), - ), + ], + ], 'changed' => $this->dateFormatter->format($comment->getChangedTimeAcrossTranslations(), 'short'), - ); + ]; $comment_uri_options = $comment->urlInfo()->getOptions() + ['query' => $destination]; - $links = array(); - $links['edit'] = array( + $links = []; + $links['edit'] = [ 'title' => $this->t('Edit'), 'url' => $comment->urlInfo('edit-form', $comment_uri_options), - ); - if ($this->moduleHandler->moduleExists('content_translation') && $this->moduleHandler->invoke('content_translation', 'translate_access', array($comment))->isAllowed()) { - $links['translate'] = array( + ]; + if ($this->moduleHandler->moduleExists('content_translation') && $this->moduleHandler->invoke('content_translation', 'translate_access', [$comment])->isAllowed()) { + $links['translate'] = [ 'title' => $this->t('Translate'), 'url' => $comment->urlInfo('drupal:content-translation-overview', $comment_uri_options), - ); + ]; } - $options[$comment->id()]['operations']['data'] = array( + $options[$comment->id()]['operations']['data'] = [ '#type' => 'operations', '#links' => $links, - ); + ]; } - $form['comments'] = array( + $form['comments'] = [ '#type' => 'tableselect', '#header' => $header, '#options' => $options, '#empty' => $this->t('No comments available.'), - ); + ]; - $form['pager'] = array('#type' => 'pager'); + $form['pager'] = ['#type' => 'pager']; return $form; } @@ -242,7 +242,7 @@ public function buildForm(array $form, FormStateInterface $form_state, $type = ' * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { - $form_state->setValue('comments', array_diff($form_state->getValue('comments'), array(0))); + $form_state->setValue('comments', array_diff($form_state->getValue('comments'), [0])); // We can't execute any 'Update options' if no comments were selected. if (count($form_state->getValue('comments')) == 0) { $form_state->setErrorByName('', $this->t('Select one or more comments to perform the update on.')); diff --git a/core/modules/comment/src/Form/CommentTypeDeleteForm.php b/core/modules/comment/src/Form/CommentTypeDeleteForm.php index 8c3da7a20e..30181c1d9b 100644 --- a/core/modules/comment/src/Form/CommentTypeDeleteForm.php +++ b/core/modules/comment/src/Form/CommentTypeDeleteForm.php @@ -82,18 +82,18 @@ public function buildForm(array $form, FormStateInterface $form_state) { foreach (array_keys($this->commentManager->getFields($entity_type)) as $field_name) { /** @var \Drupal\field\FieldStorageConfigInterface $field_storage */ if (($field_storage = FieldStorageConfig::loadByName($entity_type, $field_name)) && $field_storage->getSetting('comment_type') == $this->entity->id() && !$field_storage->isDeleted()) { - $caption .= '

        ' . $this->t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', array( + $caption .= '

        ' . $this->t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', [ '%label' => $this->entity->label(), '%field' => $field_storage->label(), - )) . '

        '; + ]) . '

        '; } } if (!empty($comments)) { - $caption .= '

        ' . $this->formatPlural(count($comments), '%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', '%label is used by @count comments on your site. You may not remove %label until you have removed all of the %label comments.', array('%label' => $this->entity->label())) . '

        '; + $caption .= '

        ' . $this->formatPlural(count($comments), '%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', '%label is used by @count comments on your site. You may not remove %label until you have removed all of the %label comments.', ['%label' => $this->entity->label()]) . '

        '; } if ($caption) { - $form['description'] = array('#markup' => $caption); + $form['description'] = ['#markup' => $caption]; return $form; } else { diff --git a/core/modules/comment/src/Form/ConfirmDeleteMultiple.php b/core/modules/comment/src/Form/ConfirmDeleteMultiple.php index c66e428e92..5906248316 100644 --- a/core/modules/comment/src/Form/ConfirmDeleteMultiple.php +++ b/core/modules/comment/src/Form/ConfirmDeleteMultiple.php @@ -81,25 +81,25 @@ public function getConfirmText() { public function buildForm(array $form, FormStateInterface $form_state) { $edit = $form_state->getUserInput(); - $form['comments'] = array( + $form['comments'] = [ '#prefix' => '
          ', '#suffix' => '
        ', '#tree' => TRUE, - ); + ]; // array_filter() returns only elements with actual values. $comment_counter = 0; $this->comments = $this->commentStorage->loadMultiple(array_keys(array_filter($edit['comments']))); foreach ($this->comments as $comment) { $cid = $comment->id(); - $form['comments'][$cid] = array( + $form['comments'][$cid] = [ '#type' => 'hidden', '#value' => $cid, '#prefix' => '
      • ', '#suffix' => Html::escape($comment->label()) . '
      • ' - ); + ]; $comment_counter++; } - $form['operation'] = array('#type' => 'hidden', '#value' => 'delete'); + $form['operation'] = ['#type' => 'hidden', '#value' => 'delete']; if (!$comment_counter) { drupal_set_message($this->t('There do not appear to be any comments to delete, or your selected comment was deleted by another administrator.')); @@ -116,7 +116,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getValue('confirm')) { $this->commentStorage->delete($this->comments); $count = count($form_state->getValue('comments')); - $this->logger('comment')->notice('Deleted @count comments.', array('@count' => $count)); + $this->logger('comment')->notice('Deleted @count comments.', ['@count' => $count]); drupal_set_message($this->formatPlural($count, 'Deleted 1 comment.', 'Deleted @count comments.')); } $form_state->setRedirectUrl($this->getCancelUrl()); diff --git a/core/modules/comment/src/Form/DeleteForm.php b/core/modules/comment/src/Form/DeleteForm.php index 285abe58ef..fa7ab9d207 100644 --- a/core/modules/comment/src/Form/DeleteForm.php +++ b/core/modules/comment/src/Form/DeleteForm.php @@ -42,7 +42,7 @@ protected function getDeletionMessage() { * {@inheritdoc} */ public function logDeletionMessage() { - $this->logger('comment')->notice('Deleted comment @cid and its replies.', array('@cid' => $this->entity->id())); + $this->logger('comment')->notice('Deleted comment @cid and its replies.', ['@cid' => $this->entity->id()]); } } diff --git a/core/modules/comment/src/Plugin/Action/UnpublishByKeywordComment.php b/core/modules/comment/src/Plugin/Action/UnpublishByKeywordComment.php index cacac89f66..ec1b268d7b 100644 --- a/core/modules/comment/src/Plugin/Action/UnpublishByKeywordComment.php +++ b/core/modules/comment/src/Plugin/Action/UnpublishByKeywordComment.php @@ -89,21 +89,21 @@ public function execute($comment = NULL) { * {@inheritdoc} */ public function defaultConfiguration() { - return array( - 'keywords' => array(), - ); + return [ + 'keywords' => [], + ]; } /** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { - $form['keywords'] = array( + $form['keywords'] = [ '#title' => $this->t('Keywords'), '#type' => 'textarea', '#description' => $this->t('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'), '#default_value' => Tags::implode($this->configuration['keywords']), - ); + ]; return $form; } diff --git a/core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php b/core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php index 43542a0eb5..3e22ede6e3 100644 --- a/core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php +++ b/core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php @@ -24,19 +24,19 @@ class AuthorNameFormatter extends FormatterBase { * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($items as $delta => $item) { /** @var $comment \Drupal\comment\CommentInterface */ $comment = $item->getEntity(); $account = $comment->getOwner(); - $elements[$delta] = array( + $elements[$delta] = [ '#theme' => 'username', '#account' => $account, - '#cache' => array( + '#cache' => [ 'tags' => $account->getCacheTags() + $comment->getCacheTags(), - ), - ); + ], + ]; } return $elements; diff --git a/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php b/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php index c7d9bba85f..b03accc489 100644 --- a/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php +++ b/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php @@ -36,10 +36,10 @@ class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryP * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'view_mode' => 'default', 'pager_id' => 0, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -141,8 +141,8 @@ public function __construct($plugin_id, $plugin_definition, FieldDefinitionInter * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); - $output = array(); + $elements = []; + $output = []; $field_name = $this->fieldDefinition->getName(); $entity = $items->getEntity(); @@ -153,7 +153,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) { // Comments are added to the search results and search index by // comment_node_update_index() instead of by this formatter, so don't // return anything if the view mode is search_index or search_result. - !in_array($this->viewMode, array('search_result', 'search_index'))) { + !in_array($this->viewMode, ['search_result', 'search_index'])) { $comment_settings = $this->getFieldSettings(); // Only attempt to render comments if the entity has visible comments. @@ -203,12 +203,12 @@ public function viewElements(FieldItemListInterface $items, $langcode) { } } - $elements[] = $output + array( + $elements[] = $output + [ '#comment_type' => $this->getFieldSetting('comment_type'), '#comment_display_mode' => $this->getFieldSetting('default_mode'), - 'comments' => array(), - 'comment_form' => array(), - ); + 'comments' => [], + 'comment_form' => [], + ]; } return $elements; @@ -218,7 +218,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) { * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { - $element = array(); + $element = []; $view_modes = $this->getViewModes(); $element['view_mode'] = [ '#type' => 'select', @@ -229,13 +229,13 @@ public function settingsForm(array $form, FormStateInterface $form_state) { // Only show the select element when there are more than one options. '#access' => count($view_modes) > 1, ]; - $element['pager_id'] = array( + $element['pager_id'] = [ '#type' => 'select', '#title' => $this->t('Pager ID'), '#options' => range(0, 10), '#default_value' => $this->getSetting('pager_id'), '#description' => $this->t("Unless you're experiencing problems with pagers related to this field, you should leave this at 0. If using multiple pagers on one page you may need to set this number to a higher value so as not to conflict within the ?page= array. Large values will add a lot of commas to your URLs, so avoid if possible."), - ); + ]; return $element; } diff --git a/core/modules/comment/src/Plugin/Field/FieldType/CommentItem.php b/core/modules/comment/src/Plugin/Field/FieldType/CommentItem.php index 888b64b255..e3fd2b060e 100644 --- a/core/modules/comment/src/Plugin/Field/FieldType/CommentItem.php +++ b/core/modules/comment/src/Plugin/Field/FieldType/CommentItem.php @@ -31,22 +31,22 @@ class CommentItem extends FieldItemBase implements CommentItemInterface { * {@inheritdoc} */ public static function defaultStorageSettings() { - return array( + return [ 'comment_type' => '', - ) + parent::defaultStorageSettings(); + ] + parent::defaultStorageSettings(); } /** * {@inheritdoc} */ public static function defaultFieldSettings() { - return array( + return [ 'default_mode' => CommentManagerInterface::COMMENT_MODE_THREADED, 'per_page' => 50, 'form_location' => CommentItemInterface::FORM_BELOW, 'anonymous' => COMMENT_ANONYMOUS_MAYNOT_CONTACT, 'preview' => DRUPAL_OPTIONAL, - ) + parent::defaultFieldSettings(); + ] + parent::defaultFieldSettings(); } /** @@ -82,36 +82,36 @@ public static function propertyDefinitions(FieldStorageDefinitionInterface $fiel * {@inheritdoc} */ public static function schema(FieldStorageDefinitionInterface $field_definition) { - return array( - 'columns' => array( - 'status' => array( + return [ + 'columns' => [ + 'status' => [ 'description' => 'Whether comments are allowed on this entity: 0 = no, 1 = closed (read only), 2 = open (read/write).', 'type' => 'int', 'default' => 0, - ), - ), - 'indexes' => array(), - 'foreign keys' => array(), - ); + ], + ], + 'indexes' => [], + 'foreign keys' => [], + ]; } /** * {@inheritdoc} */ public function fieldSettingsForm(array $form, FormStateInterface $form_state) { - $element = array(); + $element = []; $settings = $this->getSettings(); $anonymous_user = new AnonymousUserSession(); - $element['default_mode'] = array( + $element['default_mode'] = [ '#type' => 'checkbox', '#title' => t('Threading'), '#default_value' => $settings['default_mode'], '#description' => t('Show comment replies in a threaded list.'), - ); - $element['per_page'] = array( + ]; + $element['per_page'] = [ '#type' => 'number', '#title' => t('Comments per page'), '#default_value' => $settings['per_page'], @@ -119,33 +119,33 @@ public function fieldSettingsForm(array $form, FormStateInterface $form_state) { '#min' => 10, '#max' => 1000, '#step' => 10, - ); - $element['anonymous'] = array( + ]; + $element['anonymous'] = [ '#type' => 'select', '#title' => t('Anonymous commenting'), '#default_value' => $settings['anonymous'], - '#options' => array( + '#options' => [ COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'), COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'), COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'), - ), + ], '#access' => $anonymous_user->hasPermission('post comments'), - ); - $element['form_location'] = array( + ]; + $element['form_location'] = [ '#type' => 'checkbox', '#title' => t('Show reply form on the same page as comments'), '#default_value' => $settings['form_location'], - ); - $element['preview'] = array( + ]; + $element['preview'] = [ '#type' => 'radios', '#title' => t('Preview comment'), '#default_value' => $settings['preview'], - '#options' => array( + '#options' => [ DRUPAL_DISABLED => t('Disabled'), DRUPAL_OPTIONAL => t('Optional'), DRUPAL_REQUIRED => t('Required'), - ), - ); + ], + ]; return $element; } @@ -171,27 +171,27 @@ public function isEmpty() { * {@inheritdoc} */ public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) { - $element = array(); + $element = []; // @todo Inject entity storage once typed-data supports container injection. // See https://www.drupal.org/node/2053415 for more details. $comment_types = CommentType::loadMultiple(); - $options = array(); + $options = []; $entity_type = $this->getEntity()->getEntityTypeId(); foreach ($comment_types as $comment_type) { if ($comment_type->getTargetEntityTypeId() == $entity_type) { $options[$comment_type->id()] = $comment_type->label(); } } - $element['comment_type'] = array( + $element['comment_type'] = [ '#type' => 'select', '#title' => t('Comment type'), '#options' => $options, '#required' => TRUE, - '#description' => $this->t('Select the Comment type to use for this comment field. Manage the comment types from the administration overview page.', array(':url' => $this->url('entity.comment_type.collection'))), + '#description' => $this->t('Select the Comment type to use for this comment field. Manage the comment types from the administration overview page.', [':url' => $this->url('entity.comment_type.collection')]), '#default_value' => $this->getSetting('comment_type'), '#disabled' => $has_data, - ); + ]; return $element; } diff --git a/core/modules/comment/src/Plugin/Field/FieldWidget/CommentWidget.php b/core/modules/comment/src/Plugin/Field/FieldWidget/CommentWidget.php index 818226d053..c9478f622c 100644 --- a/core/modules/comment/src/Plugin/Field/FieldWidget/CommentWidget.php +++ b/core/modules/comment/src/Plugin/Field/FieldWidget/CommentWidget.php @@ -27,26 +27,26 @@ class CommentWidget extends WidgetBase { public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $entity = $items->getEntity(); - $element['status'] = array( + $element['status'] = [ '#type' => 'radios', '#title' => t('Comments'), '#title_display' => 'invisible', '#default_value' => $items->status, - '#options' => array( + '#options' => [ CommentItemInterface::OPEN => t('Open'), CommentItemInterface::CLOSED => t('Closed'), CommentItemInterface::HIDDEN => t('Hidden'), - ), - CommentItemInterface::OPEN => array( + ], + CommentItemInterface::OPEN => [ '#description' => t('Users with the "Post comments" permission can post comments.'), - ), - CommentItemInterface::CLOSED => array( + ], + CommentItemInterface::CLOSED => [ '#description' => t('Users cannot post comments, but existing comments will be displayed.'), - ), - CommentItemInterface::HIDDEN => array( + ], + CommentItemInterface::HIDDEN => [ '#description' => t('Comments are hidden from view.'), - ), - ); + ], + ]; // If the entity doesn't have any comments, the "hidden" option makes no // sense, so don't even bother presenting it to the user unless this is the // default value widget on the field settings form. @@ -65,19 +65,19 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen // Override widget title to be helpful for end users. $element['#title'] = $this->t('Comment settings'); - $element += array( + $element += [ '#type' => 'details', // Open the details when the selected value is different to the stored // default values for the field. '#open' => ($items->status != $field_default_values[0]['status']), '#group' => 'advanced', - '#attributes' => array( - 'class' => array('comment-' . Html::getClass($entity->getEntityTypeId()) . '-settings-form'), - ), - '#attached' => array( - 'library' => array('comment/drupal.comment'), - ), - ); + '#attributes' => [ + 'class' => ['comment-' . Html::getClass($entity->getEntityTypeId()) . '-settings-form'], + ], + '#attached' => [ + 'library' => ['comment/drupal.comment'], + ], + ]; } return $element; @@ -90,13 +90,13 @@ public function massageFormValues(array $values, array $form, FormStateInterface // Add default values for statistics properties because we don't want to // have them in form. foreach ($values as &$value) { - $value += array( + $value += [ 'cid' => 0, 'last_comment_timestamp' => 0, 'last_comment_name' => '', 'last_comment_uid' => 0, 'comment_count' => 0, - ); + ]; } return $values; } diff --git a/core/modules/comment/src/Plugin/Menu/LocalTask/UnapprovedComments.php b/core/modules/comment/src/Plugin/Menu/LocalTask/UnapprovedComments.php index 5fa0193651..89542d34ff 100644 --- a/core/modules/comment/src/Plugin/Menu/LocalTask/UnapprovedComments.php +++ b/core/modules/comment/src/Plugin/Menu/LocalTask/UnapprovedComments.php @@ -54,7 +54,7 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function getTitle() { - return $this->t('Unapproved comments (@count)', array('@count' => $this->commentStorage->getUnapprovedCount())); + return $this->t('Unapproved comments (@count)', ['@count' => $this->commentStorage->getUnapprovedCount()]); } } diff --git a/core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php b/core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php index f06dfd8383..87cdaf91de 100644 --- a/core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php +++ b/core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php @@ -55,9 +55,9 @@ public function validate($entity, Constraint $constraint) { // Do not allow unauthenticated comment authors to use a name that is // taken by a registered user. if (isset($author_name) && $author_name !== '' && $owner_id === 0) { - $users = $this->userStorage->loadByProperties(array('name' => $author_name)); + $users = $this->userStorage->loadByProperties(['name' => $author_name]); if (!empty($users)) { - $this->context->buildViolation($constraint->messageNameTaken, array('%name' => $author_name)) + $this->context->buildViolation($constraint->messageNameTaken, ['%name' => $author_name]) ->atPath('name') ->addViolation(); } diff --git a/core/modules/comment/src/Plugin/migrate/destination/EntityComment.php b/core/modules/comment/src/Plugin/migrate/destination/EntityComment.php index a3e82af61b..efce666a77 100644 --- a/core/modules/comment/src/Plugin/migrate/destination/EntityComment.php +++ b/core/modules/comment/src/Plugin/migrate/destination/EntityComment.php @@ -80,7 +80,7 @@ public static function create(ContainerInterface $container, array $configuratio /** * {@inheritdoc} */ - public function import(Row $row, array $old_destination_id_values = array()) { + public function import(Row $row, array $old_destination_id_values = []) { if ($row->isStub() && ($state = $this->state->get('comment.maintain_entity_statistics', 0))) { $this->state->set('comment.maintain_entity_statistics', 0); } diff --git a/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php b/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php index b014af3fad..9bee87a3a1 100644 --- a/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php +++ b/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php @@ -15,7 +15,7 @@ class EntityCommentType extends EntityConfigBase { /** * {@inheritdoc} */ - public function import(Row $row, array $old_destination_id_values = array()) { + public function import(Row $row, array $old_destination_id_values = []) { $entity_ids = parent::import($row, $old_destination_id_values); \Drupal::service('comment.manager')->addBodyField(reset($entity_ids)); return $entity_ids; diff --git a/core/modules/comment/src/Plugin/migrate/source/d6/Comment.php b/core/modules/comment/src/Plugin/migrate/source/d6/Comment.php index 6081f39f91..93f77a0e3f 100644 --- a/core/modules/comment/src/Plugin/migrate/source/d6/Comment.php +++ b/core/modules/comment/src/Plugin/migrate/source/d6/Comment.php @@ -20,11 +20,11 @@ class Comment extends DrupalSqlBase { */ public function query() { $query = $this->select('comments', 'c') - ->fields('c', array('cid', 'pid', 'nid', 'uid', 'subject', + ->fields('c', ['cid', 'pid', 'nid', 'uid', 'subject', 'comment', 'hostname', 'timestamp', 'status', 'thread', 'name', - 'mail', 'homepage', 'format')); + 'mail', 'homepage', 'format']); $query->innerJoin('node', 'n', 'c.nid = n.nid'); - $query->fields('n', array('type')); + $query->fields('n', ['type']); $query->orderBy('c.timestamp'); return $query; } @@ -52,7 +52,7 @@ public function prepareRow(Row $row) { * {@inheritdoc} */ public function fields() { - return array( + return [ 'cid' => $this->t('Comment ID.'), 'pid' => $this->t('Parent comment ID. If set to 0, this comment is not a reply to an existing comment.'), 'nid' => $this->t('The {node}.nid to which this comment is a reply.'), @@ -68,7 +68,7 @@ public function fields() { 'mail' => $this->t("The comment author's email address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."), 'homepage' => $this->t("The comment author's home page address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."), 'type' => $this->t("The {node}.type to which this comment is a reply."), - ); + ]; } /** diff --git a/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariable.php b/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariable.php index 3294721381..a56fb4dc21 100644 --- a/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariable.php +++ b/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariable.php @@ -35,7 +35,7 @@ public function count() { */ protected function getCommentVariables() { $comment_prefixes = array_keys($this->commentPrefixes()); - $variables = array(); + $variables = []; $node_types = $this->select('node_type', 'nt') ->fields('nt', ['type']) ->execute() @@ -45,7 +45,7 @@ protected function getCommentVariables() { $variables[] = $prefix . '_' . $node_type; } } - $return = array(); + $return = []; $values = $this->select('variable', 'v') ->fields('v', ['name', 'value']) ->condition('name', $variables, 'IN') @@ -74,17 +74,17 @@ protected function getCommentVariables() { * {@inheritdoc} */ public function fields() { - return $this->commentPrefixes() + array( + return $this->commentPrefixes() + [ 'node_type' => $this->t('The node type'), 'comment_type' => $this->t('The comment type'), - ); + ]; } /** * Comment related data for fields. */ protected function commentPrefixes() { - return array( + return [ 'comment' => $this->t('Default comment setting'), 'comment_default_mode' => $this->t('Default display mode'), 'comment_default_order' => $this->t('Default display order'), @@ -94,7 +94,7 @@ protected function commentPrefixes() { 'comment_subject_field' => $this->t('Comment subject field'), 'comment_preview' => $this->t('Preview comment'), 'comment_form_location' => $this->t('Location of comment submission form'), - ); + ]; } /** diff --git a/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariablePerCommentType.php b/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariablePerCommentType.php index 5d16ed0297..0eea68608c 100644 --- a/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariablePerCommentType.php +++ b/core/modules/comment/src/Plugin/migrate/source/d6/CommentVariablePerCommentType.php @@ -17,24 +17,24 @@ class CommentVariablePerCommentType extends CommentVariable { protected function getCommentVariables() { $node_types = parent::getCommentVariables(); // The return key used to separate comment types with hidden subject field. - $return = array(); + $return = []; foreach ($node_types as $node_type => $data) { // Only 2 comment types depending on subject field visibility. if (!empty($data['comment_subject_field'])) { // Default label and description should be set in migration. - $return['comment'] = array( + $return['comment'] = [ 'comment_type' => 'comment', 'label' => $this->t('Default comments'), 'description' => $this->t('Allows commenting on content') - ); + ]; } else { // Provide a special comment type with hidden subject field. - $return['comment_no_subject'] = array( + $return['comment_no_subject'] = [ 'comment_type' => 'comment_no_subject', 'label' => $this->t('Comments without subject field'), 'description' => $this->t('Allows commenting on content, comments without subject field') - ); + ]; } } return $return; @@ -44,11 +44,11 @@ protected function getCommentVariables() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'comment_type' => $this->t('The comment type'), 'label' => $this->t('The comment type label'), 'description' => $this->t('The comment type description'), - ); + ]; } /** diff --git a/core/modules/comment/src/Plugin/migrate/source/d7/Comment.php b/core/modules/comment/src/Plugin/migrate/source/d7/Comment.php index 5531f1d395..e643eb178c 100644 --- a/core/modules/comment/src/Plugin/migrate/source/d7/Comment.php +++ b/core/modules/comment/src/Plugin/migrate/source/d7/Comment.php @@ -47,7 +47,7 @@ public function prepareRow(Row $row) { * {@inheritdoc} */ public function fields() { - return array( + return [ 'cid' => $this->t('Comment ID.'), 'pid' => $this->t('Parent comment ID. If set to 0, this comment is not a reply to an existing comment.'), 'nid' => $this->t('The {node}.nid to which this comment is a reply.'), @@ -64,7 +64,7 @@ public function fields() { 'mail' => $this->t("The comment author's email address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."), 'homepage' => $this->t("The comment author's home page address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on."), 'type' => $this->t("The {node}.type to which this comment is a reply."), - ); + ]; } /** diff --git a/core/modules/comment/src/Plugin/migrate/source/d7/CommentType.php b/core/modules/comment/src/Plugin/migrate/source/d7/CommentType.php index fc194b2a6d..2ac7c97a05 100644 --- a/core/modules/comment/src/Plugin/migrate/source/d7/CommentType.php +++ b/core/modules/comment/src/Plugin/migrate/source/d7/CommentType.php @@ -21,7 +21,7 @@ class CommentType extends DrupalSqlBase { * * @var string[] */ - protected $nodeTypes = array(); + protected $nodeTypes = []; /** * {@inheritdoc} @@ -29,7 +29,7 @@ class CommentType extends DrupalSqlBase { public function query() { return $this->select('field_config_instance', 'fci') ->distinct() - ->fields('fci', array('bundle')) + ->fields('fci', ['bundle']) ->condition('fci.entity_type', 'comment'); } @@ -38,7 +38,7 @@ public function query() { */ protected function initializeIterator() { $this->nodeTypes = $this->select('node_type', 'nt') - ->fields('nt', array('type', 'name')) + ->fields('nt', ['type', 'name']) ->execute() ->fetchAllKeyed(); @@ -71,7 +71,7 @@ public function prepareRow(Row $row) { * {@inheritdoc} */ public function fields() { - return array( + return [ 'label' => $this->t('The label of the comment type.'), 'bundle' => $this->t('Bundle ID of the comment type.'), 'node_type' => $this->t('The node type to which this comment type is attached.'), @@ -81,18 +81,18 @@ public function fields() { 'form_location' => $this->t('Location of the comment form.'), 'preview' => $this->t('Whether previews are enabled for the comment type.'), 'subject' => $this->t('Whether a subject field is enabled for the comment type.'), - ); + ]; } /** * {@inheritdoc} */ public function getIds() { - return array( - 'bundle' => array( + return [ + 'bundle' => [ 'type' => 'string', - ), - ); + ], + ]; } } diff --git a/core/modules/comment/src/Plugin/views/argument/UserUid.php b/core/modules/comment/src/Plugin/views/argument/UserUid.php index cd384d560d..c670d19e8d 100644 --- a/core/modules/comment/src/Plugin/views/argument/UserUid.php +++ b/core/modules/comment/src/Plugin/views/argument/UserUid.php @@ -53,7 +53,7 @@ function title() { $title = \Drupal::config('user.settings')->get('anonymous'); } else { - $title = $this->database->query('SELECT name FROM {users_field_data} WHERE uid = :uid AND default_langcode = 1', array(':uid' => $this->argument))->fetchField(); + $title = $this->database->query('SELECT name FROM {users_field_data} WHERE uid = :uid AND default_langcode = 1', [':uid' => $this->argument])->fetchField(); } if (empty($title)) { return $this->t('No user'); @@ -102,7 +102,7 @@ public function query($group_by = FALSE) { * {@inheritdoc} */ public function getSortName() { - return $this->t('Numerical', array(), array('context' => 'Sort order')); + return $this->t('Numerical', [], ['context' => 'Sort order']); } } diff --git a/core/modules/comment/src/Plugin/views/field/EntityLink.php b/core/modules/comment/src/Plugin/views/field/EntityLink.php index dc4f8cf181..03e6f6c843 100644 --- a/core/modules/comment/src/Plugin/views/field/EntityLink.php +++ b/core/modules/comment/src/Plugin/views/field/EntityLink.php @@ -27,7 +27,7 @@ class EntityLink extends FieldPluginBase { */ protected function defineOptions() { $options = parent::defineOptions(); - $options['teaser'] = array('default' => FALSE); + $options['teaser'] = ['default' => FALSE]; return $options; } @@ -35,12 +35,12 @@ protected function defineOptions() { * {@inheritdoc} */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { - $form['teaser'] = array( + $form['teaser'] = [ '#type' => 'checkbox', '#title' => $this->t('Show teaser-style link'), '#default_value' => $this->options['teaser'], '#description' => $this->t('Show the comment link in the form used on standard entity teasers, rather than the full entity form.'), - ); + ]; parent::buildOptionsForm($form, $form_state); } @@ -55,7 +55,7 @@ public function query() {} */ public function preRender(&$values) { // Render all nodes, so you can grep the comment links. - $entities = array(); + $entities = []; foreach ($values as $row) { $entity = $row->_entity; $entities[$entity->id()] = $entity; diff --git a/core/modules/comment/src/Plugin/views/field/NodeNewComments.php b/core/modules/comment/src/Plugin/views/field/NodeNewComments.php index 5a9f5b3a12..c53b52ed15 100644 --- a/core/modules/comment/src/Plugin/views/field/NodeNewComments.php +++ b/core/modules/comment/src/Plugin/views/field/NodeNewComments.php @@ -68,7 +68,7 @@ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$o $this->additional_fields['entity_id'] = 'nid'; $this->additional_fields['type'] = 'type'; - $this->additional_fields['comment_count'] = array('table' => 'comment_entity_statistics', 'field' => 'comment_count'); + $this->additional_fields['comment_count'] = ['table' => 'comment_entity_statistics', 'field' => 'comment_count']; } /** @@ -77,7 +77,7 @@ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$o protected function defineOptions() { $options = parent::defineOptions(); - $options['link_to_comment'] = array('default' => TRUE); + $options['link_to_comment'] = ['default' => TRUE]; return $options; } @@ -86,12 +86,12 @@ protected function defineOptions() { * {@inheritdoc} */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { - $form['link_to_comment'] = array( + $form['link_to_comment'] = [ '#title' => $this->t('Link this field to new comments'), '#description' => $this->t("Enable to override this field's links."), '#type' => 'checkbox', '#default_value' => $this->options['link_to_comment'], - ); + ]; parent::buildOptionsForm($form, $form_state); } @@ -114,14 +114,14 @@ public function preRender(&$values) { return; } - $nids = array(); - $ids = array(); + $nids = []; + $ids = []; foreach ($values as $id => $result) { $nids[] = $result->{$this->aliases['nid']}; $values[$id]->{$this->field_alias} = 0; // Create a reference so we can find this record in the values again. if (empty($ids[$result->{$this->aliases['nid']}])) { - $ids[$result->{$this->aliases['nid']}] = array(); + $ids[$result->{$this->aliases['nid']}] = []; } $ids[$result->{$this->aliases['nid']}][] = $id; } @@ -129,13 +129,13 @@ public function preRender(&$values) { if ($nids) { $result = $this->database->query("SELECT n.nid, COUNT(c.cid) as num_comments FROM {node} n INNER JOIN {comment_field_data} c ON n.nid = c.entity_id AND c.entity_type = 'node' AND c.default_langcode = 1 LEFT JOIN {history} h ON h.nid = n.nid AND h.uid = :h_uid WHERE n.nid IN ( :nids[] ) - AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp1), :timestamp2) AND c.status = :status GROUP BY n.nid", array( + AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp1), :timestamp2) AND c.status = :status GROUP BY n.nid", [ ':status' => CommentInterface::PUBLISHED, ':h_uid' => $user->id(), ':nids[]' => $nids, ':timestamp1' => HISTORY_READ_LIMIT, ':timestamp2' => HISTORY_READ_LIMIT, - )); + ]); foreach ($result as $node) { foreach ($ids[$node->nid] as $id) { $values[$id]->{$this->field_alias} = $node->num_comments; @@ -181,7 +181,7 @@ protected function renderLink($data, ResultRow $values) { ->getNewCommentPageNumber($this->getValue($values, 'comment_count'), $this->getValue($values), $node, $comment_field_name); $this->options['alter']['make_link'] = TRUE; $this->options['alter']['url'] = $node->urlInfo(); - $this->options['alter']['query'] = $page_number ? array('page' => $page_number) : NULL; + $this->options['alter']['query'] = $page_number ? ['page' => $page_number] : NULL; $this->options['alter']['fragment'] = 'new'; } diff --git a/core/modules/comment/src/Plugin/views/field/StatisticsLastCommentName.php b/core/modules/comment/src/Plugin/views/field/StatisticsLastCommentName.php index 61a5d17ef4..fa24c3ffe8 100644 --- a/core/modules/comment/src/Plugin/views/field/StatisticsLastCommentName.php +++ b/core/modules/comment/src/Plugin/views/field/StatisticsLastCommentName.php @@ -23,19 +23,19 @@ public function query() { // have to join in a specially related user table. $this->ensureMyTable(); // join 'users' to this table via vid - $definition = array( + $definition = [ 'table' => 'users_field_data', 'field' => 'uid', 'left_table' => 'comment_entity_statistics', 'left_field' => 'last_comment_uid', - 'extra' => array( - array( + 'extra' => [ + [ 'field' => 'uid', 'operator' => '!=', 'value' => '0' - ) - ) - ); + ] + ] + ]; $join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition); // nes_user alias so this can work with the sort handler, below. @@ -53,7 +53,7 @@ public function query() { protected function defineOptions() { $options = parent::defineOptions(); - $options['link_to_user'] = array('default' => TRUE); + $options['link_to_user'] = ['default' => TRUE]; return $options; } @@ -66,10 +66,10 @@ public function render(ResultRow $values) { $account = User::create(); $account->name = $this->getValue($values); $account->uid = $values->{$this->uid}; - $username = array( + $username = [ '#theme' => 'username', '#account' => $account, - ); + ]; return drupal_render($username); } else { diff --git a/core/modules/comment/src/Plugin/views/filter/NodeComment.php b/core/modules/comment/src/Plugin/views/filter/NodeComment.php index e34584f4b3..238c05e867 100644 --- a/core/modules/comment/src/Plugin/views/filter/NodeComment.php +++ b/core/modules/comment/src/Plugin/views/filter/NodeComment.php @@ -15,11 +15,11 @@ class NodeComment extends InOperator { public function getValueOptions() { - $this->valueOptions = array( + $this->valueOptions = [ CommentItemInterface::HIDDEN => $this->t('Hidden'), CommentItemInterface::CLOSED => $this->t('Closed'), CommentItemInterface::OPEN => $this->t('Open'), - ); + ]; return $this->valueOptions; } diff --git a/core/modules/comment/src/Plugin/views/row/Rss.php b/core/modules/comment/src/Plugin/views/row/Rss.php index d528040002..cb9c1046d1 100644 --- a/core/modules/comment/src/Plugin/views/row/Rss.php +++ b/core/modules/comment/src/Plugin/views/row/Rss.php @@ -40,7 +40,7 @@ class Rss extends RssPluginBase { protected $entityTypeId = 'comment'; public function preRender($result) { - $cids = array(); + $cids = []; foreach ($result as $row) { $cids[] = $row->cid; @@ -79,23 +79,23 @@ public function render($row) { return; } - $comment->link = $comment->url('canonical', array('absolute' => TRUE)); - $comment->rss_namespaces = array(); - $comment->rss_elements = array( - array( + $comment->link = $comment->url('canonical', ['absolute' => TRUE]); + $comment->rss_namespaces = []; + $comment->rss_elements = [ + [ 'key' => 'pubDate', 'value' => gmdate('r', $comment->getCreatedTime()), - ), - array( + ], + [ 'key' => 'dc:creator', 'value' => $comment->getAuthorName(), - ), - array( + ], + [ 'key' => 'guid', 'value' => 'comment ' . $comment->id() . ' at ' . $base_url, - 'attributes' => array('isPermaLink' => 'false'), - ), - ); + 'attributes' => ['isPermaLink' => 'false'], + ], + ]; // The comment gets built and modules add to or modify // $comment->rss_elements and $comment->rss_namespaces. @@ -118,12 +118,12 @@ public function render($row) { $item->elements = &$comment->rss_elements; $item->cid = $comment->id(); - $build = array( + $build = [ '#theme' => $this->themeFunctions(), '#view' => $this->view, '#options' => $this->options, '#row' => $item, - ); + ]; return $build; } diff --git a/core/modules/comment/src/Plugin/views/sort/StatisticsLastCommentName.php b/core/modules/comment/src/Plugin/views/sort/StatisticsLastCommentName.php index 863b3a43ba..48f556e68a 100644 --- a/core/modules/comment/src/Plugin/views/sort/StatisticsLastCommentName.php +++ b/core/modules/comment/src/Plugin/views/sort/StatisticsLastCommentName.php @@ -16,12 +16,12 @@ class StatisticsLastCommentName extends SortPluginBase { public function query() { $this->ensureMyTable(); - $definition = array( + $definition = [ 'table' => 'users_field_data', 'field' => 'uid', 'left_table' => 'comment_entity_statistics', 'left_field' => 'last_comment_uid', - ); + ]; $join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition); // @todo this might be safer if we had an ensure_relationship rather than guessing diff --git a/core/modules/comment/src/Plugin/views/wizard/Comment.php b/core/modules/comment/src/Plugin/views/wizard/Comment.php index 1f0d4aa45e..61d92c591a 100644 --- a/core/modules/comment/src/Plugin/views/wizard/Comment.php +++ b/core/modules/comment/src/Plugin/views/wizard/Comment.php @@ -27,16 +27,16 @@ class Comment extends WizardPluginBase { /** * Set default values for the filters. */ - protected $filters = array( - 'status' => array( + protected $filters = [ + 'status' => [ 'value' => TRUE, 'table' => 'comment_field_data', 'field' => 'status', 'plugin_id' => 'boolean', 'entity_type' => 'comment', 'entity_field' => 'status', - ), - 'status_node' => array( + ], + 'status_node' => [ 'value' => TRUE, 'table' => 'node_field_data', 'field' => 'status', @@ -44,14 +44,14 @@ class Comment extends WizardPluginBase { 'relationship' => 'node', 'entity_type' => 'node', 'entity_field' => 'status', - ), - ); + ], + ]; /** * {@inheritdoc} */ protected function rowStyleOptions() { - $options = array(); + $options = []; $options['entity:comment'] = $this->t('comments'); $options['fields'] = $this->t('fields'); return $options; diff --git a/core/modules/comment/src/Tests/CommentActionsTest.php b/core/modules/comment/src/Tests/CommentActionsTest.php index 220be20be7..8b741e7927 100644 --- a/core/modules/comment/src/Tests/CommentActionsTest.php +++ b/core/modules/comment/src/Tests/CommentActionsTest.php @@ -17,7 +17,7 @@ class CommentActionsTest extends CommentTestBase { * * @var array */ - public static $modules = array('dblog', 'action'); + public static $modules = ['dblog', 'action']; /** * Tests comment publish and unpublish actions. @@ -30,12 +30,12 @@ function testCommentPublishUnpublishActions() { // Unpublish a comment. $action = Action::load('comment_unpublish_action'); - $action->execute(array($comment)); + $action->execute([$comment]); $this->assertTrue($comment->isPublished() === FALSE, 'Comment was unpublished'); // Publish a comment. $action = Action::load('comment_publish_action'); - $action->execute(array($comment)); + $action->execute([$comment]); $this->assertTrue($comment->isPublished() === TRUE, 'Comment was published'); } @@ -46,15 +46,15 @@ function testCommentUnpublishByKeyword() { $this->drupalLogin($this->adminUser); $keyword_1 = $this->randomMachineName(); $keyword_2 = $this->randomMachineName(); - $action = Action::create(array( + $action = Action::create([ 'id' => 'comment_unpublish_by_keyword_action', 'label' => $this->randomMachineName(), 'type' => 'comment', - 'configuration' => array( - 'keywords' => array($keyword_1, $keyword_2), - ), + 'configuration' => [ + 'keywords' => [$keyword_1, $keyword_2], + ], 'plugin' => 'comment_unpublish_by_keyword_action', - )); + ]); $action->save(); $comment = $this->postComment($this->node, $keyword_2, $this->randomMachineName()); @@ -64,7 +64,7 @@ function testCommentUnpublishByKeyword() { $this->assertTrue($comment->isPublished() === TRUE, 'The comment status was set to published.'); - $action->execute(array($comment)); + $action->execute([$comment]); $this->assertTrue($comment->isPublished() === FALSE, 'The comment status was set to not published.'); } diff --git a/core/modules/comment/src/Tests/CommentAdminTest.php b/core/modules/comment/src/Tests/CommentAdminTest.php index 5ae57cb819..74e6e45969 100644 --- a/core/modules/comment/src/Tests/CommentAdminTest.php +++ b/core/modules/comment/src/Tests/CommentAdminTest.php @@ -23,11 +23,11 @@ protected function setUp() { */ function testApprovalAdminInterface() { // Set anonymous comments to require approval. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => FALSE, - )); + ]); $this->drupalLogin($this->adminUser); $this->setCommentAnonymous('0'); // Ensure that doesn't require contact info. @@ -46,14 +46,14 @@ function testApprovalAdminInterface() { // Get unapproved comment id. $this->drupalLogin($this->adminUser); $anonymous_comment4 = $this->getUnapprovedComment($subject); - $anonymous_comment4 = Comment::create(array( + $anonymous_comment4 = Comment::create([ 'cid' => $anonymous_comment4, 'subject' => $subject, 'comment_body' => $body, 'entity_id' => $this->node->id(), 'entity_type' => 'node', 'field_name' => 'comment' - )); + ]); $this->drupalLogout(); $this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.'); @@ -73,29 +73,29 @@ function testApprovalAdminInterface() { // Publish multiple comments in one operation. $this->drupalLogin($this->adminUser); $this->drupalGet('admin/content/comment/approval'); - $this->assertText(t('Unapproved comments (@count)', array('@count' => 2)), 'Two unapproved comments waiting for approval.'); - $edit = array( + $this->assertText(t('Unapproved comments (@count)', ['@count' => 2]), 'Two unapproved comments waiting for approval.'); + $edit = [ "comments[{$comments[0]->id()}]" => 1, "comments[{$comments[1]->id()}]" => 1, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Update')); - $this->assertText(t('Unapproved comments (@count)', array('@count' => 0)), 'All comments were approved.'); + $this->assertText(t('Unapproved comments (@count)', ['@count' => 0]), 'All comments were approved.'); // Delete multiple comments in one operation. - $edit = array( + $edit = [ 'operation' => 'delete', "comments[{$comments[0]->id()}]" => 1, "comments[{$comments[1]->id()}]" => 1, "comments[{$anonymous_comment4->id()}]" => 1, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Update')); $this->assertText(t('Are you sure you want to delete these comments and all their children?'), 'Confirmation required.'); $this->drupalPostForm(NULL, $edit, t('Delete comments')); $this->assertText(t('No comments available.'), 'All comments were deleted.'); // Test message when no comments selected. - $edit = array( + $edit = [ 'operation' => 'delete', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Update')); $this->assertText(t('Select one or more comments to perform the update on.')); } @@ -105,11 +105,11 @@ function testApprovalAdminInterface() { */ function testApprovalNodeInterface() { // Set anonymous comments to require approval. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => FALSE, - )); + ]); $this->drupalLogin($this->adminUser); $this->setCommentAnonymous('0'); // Ensure that doesn't require contact info. $this->drupalLogout(); @@ -123,14 +123,14 @@ function testApprovalNodeInterface() { // Get unapproved comment id. $this->drupalLogin($this->adminUser); $anonymous_comment4 = $this->getUnapprovedComment($subject); - $anonymous_comment4 = Comment::create(array( + $anonymous_comment4 = Comment::create([ 'cid' => $anonymous_comment4, 'subject' => $subject, 'comment_body' => $body, 'entity_id' => $this->node->id(), 'entity_type' => 'node', 'field_name' => 'comment' - )); + ]); $this->drupalLogout(); $this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.'); @@ -139,7 +139,7 @@ function testApprovalNodeInterface() { $this->drupalLogin($this->adminUser); $this->drupalGet('comment/1/approve'); $this->assertResponse(403, 'Forged comment approval was denied.'); - $this->drupalGet('comment/1/approve', array('query' => array('token' => 'forged'))); + $this->drupalGet('comment/1/approve', ['query' => ['token' => 'forged']]); $this->assertResponse(403, 'Forged comment approval was denied.'); $this->drupalGet('comment/1/edit'); $this->assertFieldChecked('edit-status-0'); @@ -178,11 +178,11 @@ public function testCommentAdmin() { */ public function testEditComment() { // Enable anonymous user comments. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments', 'post comments', 'skip comment approval', - )); + ]); // Log in as a web user. $this->drupalLogin($this->webUser); @@ -199,7 +199,7 @@ public function testEditComment() { // Post comment with contact info (required). $author_name = $this->randomMachineName(); $author_mail = $this->randomMachineName() . '@example.com'; - $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), array('name' => $author_name, 'mail' => $author_mail)); + $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), ['name' => $author_name, 'mail' => $author_mail]); // Log in as an admin user. $this->drupalLogin($this->adminUser); diff --git a/core/modules/comment/src/Tests/CommentAnonymousTest.php b/core/modules/comment/src/Tests/CommentAnonymousTest.php index 2a5feb2f1f..7c94e5af87 100644 --- a/core/modules/comment/src/Tests/CommentAnonymousTest.php +++ b/core/modules/comment/src/Tests/CommentAnonymousTest.php @@ -15,16 +15,16 @@ protected function setUp() { parent::setUp(); // Enable anonymous and authenticated user comments. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments', 'post comments', 'skip comment approval', - )); - user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array( + ]); + user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [ 'access comments', 'post comments', 'skip comment approval', - )); + ]); } /** @@ -66,10 +66,10 @@ function testAnonymous() { $this->assertTrue($this->commentExists($anonymous_comment1), 'Anonymous comment without contact info found.'); // Ensure anonymous users cannot post in the name of registered users. - $edit = array( + $edit = [ 'name' => $this->adminUser->getUsername(), 'comment_body[0][value]' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save')); $this->assertRaw(t('The name you used (%name) belongs to a registered user.', [ '%name' => $this->adminUser->getUsername(), @@ -97,12 +97,12 @@ function testAnonymous() { $this->assertTrue($this->commentExists($anonymous_comment2), 'Anonymous comment with contact info (optional) found.'); // Ensure anonymous users cannot post in the name of registered users. - $edit = array( + $edit = [ 'name' => $this->adminUser->getUsername(), 'mail' => $this->randomMachineName() . '@example.com', 'subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save')); $this->assertRaw(t('The name you used (%name) belongs to a registered user.', [ '%name' => $this->adminUser->getUsername(), @@ -125,7 +125,7 @@ function testAnonymous() { // Post comment with contact info (required). $author_name = $this->randomMachineName(); $author_mail = $this->randomMachineName() . '@example.com'; - $anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), array('name' => $author_name, 'mail' => $author_mail)); + $anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), ['name' => $author_name, 'mail' => $author_mail]); $this->assertTrue($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) found.'); // Make sure the user data appears correctly when editing the comment. @@ -159,11 +159,11 @@ function testAnonymous() { $this->assertResponse(403); // Reset. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => FALSE, 'post comments' => FALSE, 'skip comment approval' => FALSE, - )); + ]); // Attempt to view comments while disallowed. // NOTE: if authenticated user has permission to post comments, then a @@ -176,21 +176,21 @@ function testAnonymous() { $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); $this->assertResponse(403); - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => TRUE, 'post comments' => FALSE, 'skip comment approval' => FALSE, - )); + ]); $this->drupalGet('node/' . $this->node->id()); $this->assertPattern('@]*>Comments

        @', 'Comments were displayed.'); $this->assertLink('Log in', 1, 'Link to login was found.'); $this->assertLink('register', 1, 'Link to register was found.'); - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => FALSE, 'post comments' => TRUE, 'skip comment approval' => TRUE, - )); + ]); $this->drupalGet('node/' . $this->node->id()); $this->assertNoPattern('@]*>Comments
        @', 'Comments were not displayed.'); $this->assertFieldByName('subject[0][value]', '', 'Subject field found.'); diff --git a/core/modules/comment/src/Tests/CommentBlockTest.php b/core/modules/comment/src/Tests/CommentBlockTest.php index de92238ddf..fca7223a41 100644 --- a/core/modules/comment/src/Tests/CommentBlockTest.php +++ b/core/modules/comment/src/Tests/CommentBlockTest.php @@ -17,12 +17,12 @@ class CommentBlockTest extends CommentTestBase { * * @var array */ - public static $modules = array('block', 'views'); + public static $modules = ['block', 'views']; protected function setUp() { parent::setUp(); // Update admin user to have the 'administer blocks' permission. - $this->adminUser = $this->drupalCreateUser(array( + $this->adminUser = $this->drupalCreateUser([ 'administer content types', 'administer comments', 'skip comment approval', @@ -30,7 +30,7 @@ protected function setUp() { 'access comments', 'access content', 'administer blocks', - )); + ]); } /** @@ -54,10 +54,10 @@ function testRecentCommentBlock() { // Test that a user without the 'access comments' permission cannot see the // block. $this->drupalLogout(); - user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access comments')); + user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']); $this->drupalGet(''); $this->assertNoText(t('Recent comments')); - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access comments')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']); // Test that a user with the 'access comments' permission can see the // block. @@ -68,11 +68,11 @@ function testRecentCommentBlock() { // Test the only the 10 latest comments are shown and in the proper order. $this->assertNoText($comments[10]->getSubject(), 'Comment 11 not found in block.'); for ($i = 0; $i < 10; $i++) { - $this->assertText($comments[$i]->getSubject(), SafeMarkup::format('Comment @number found in block.', array('@number' => 10 - $i))); + $this->assertText($comments[$i]->getSubject(), SafeMarkup::format('Comment @number found in block.', ['@number' => 10 - $i])); if ($i > 1) { $previous_position = $position; $position = strpos($this->getRawContent(), $comments[$i]->getSubject()); - $this->assertTrue($position > $previous_position, SafeMarkup::format('Comment @a appears after comment @b', array('@a' => 10 - $i, '@b' => 11 - $i))); + $this->assertTrue($position > $previous_position, SafeMarkup::format('Comment @a appears after comment @b', ['@a' => 10 - $i, '@b' => 11 - $i])); } $position = strpos($this->getRawContent(), $comments[$i]->getSubject()); } diff --git a/core/modules/comment/src/Tests/CommentBookTest.php b/core/modules/comment/src/Tests/CommentBookTest.php index b23028b42e..4afd07ed83 100644 --- a/core/modules/comment/src/Tests/CommentBookTest.php +++ b/core/modules/comment/src/Tests/CommentBookTest.php @@ -21,7 +21,7 @@ class CommentBookTest extends WebTestBase { * * @var array */ - public static $modules = array('book', 'comment'); + public static $modules = ['book', 'comment']; protected function setUp() { parent::setUp(); @@ -44,17 +44,17 @@ public function testBookCommentPrint() { $comment_subject = $this->randomMachineName(8); $comment_body = $this->randomMachineName(8); - $comment = Comment::create(array( + $comment = Comment::create([ 'subject' => $comment_subject, 'comment_body' => $comment_body, 'entity_id' => $book_node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'status' => CommentInterface::PUBLISHED, - )); + ]); $comment->save(); - $commenting_user = $this->drupalCreateUser(array('access printer-friendly version', 'access comments', 'post comments')); + $commenting_user = $this->drupalCreateUser(['access printer-friendly version', 'access comments', 'post comments']); $this->drupalLogin($commenting_user); $this->drupalGet('node/' . $book_node->id()); diff --git a/core/modules/comment/src/Tests/CommentCSSTest.php b/core/modules/comment/src/Tests/CommentCSSTest.php index f015f3fb39..3c48f698cd 100644 --- a/core/modules/comment/src/Tests/CommentCSSTest.php +++ b/core/modules/comment/src/Tests/CommentCSSTest.php @@ -18,10 +18,10 @@ protected function setUp() { parent::setUp(); // Allow anonymous users to see comments. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments', 'access content' - )); + ]); } /** @@ -29,21 +29,21 @@ protected function setUp() { */ function testCommentClasses() { // Create all permutations for comments, users, and nodes. - $parameters = array( - 'node_uid' => array(0, $this->webUser->id()), - 'comment_uid' => array(0, $this->webUser->id(), $this->adminUser->id()), - 'comment_status' => array(CommentInterface::PUBLISHED, CommentInterface::NOT_PUBLISHED), - 'user' => array('anonymous', 'authenticated', 'admin'), - ); + $parameters = [ + 'node_uid' => [0, $this->webUser->id()], + 'comment_uid' => [0, $this->webUser->id(), $this->adminUser->id()], + 'comment_status' => [CommentInterface::PUBLISHED, CommentInterface::NOT_PUBLISHED], + 'user' => ['anonymous', 'authenticated', 'admin'], + ]; $permutations = $this->generatePermutations($parameters); foreach ($permutations as $case) { // Create a new node. - $node = $this->drupalCreateNode(array('type' => 'article', 'uid' => $case['node_uid'])); + $node = $this->drupalCreateNode(['type' => 'article', 'uid' => $case['node_uid']]); // Add a comment. /** @var \Drupal\comment\CommentInterface $comment */ - $comment = Comment::create(array( + $comment = Comment::create([ 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment', @@ -51,8 +51,8 @@ function testCommentClasses() { 'status' => $case['comment_status'], 'subject' => $this->randomMachineName(), 'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED, - 'comment_body' => array(LanguageInterface::LANGCODE_NOT_SPECIFIED => array($this->randomMachineName())), - )); + 'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]], + ]); $comment->save(); // Adjust the current/viewing user. diff --git a/core/modules/comment/src/Tests/CommentCacheTagsTest.php b/core/modules/comment/src/Tests/CommentCacheTagsTest.php index 3c7ab00963..12e0ef8451 100644 --- a/core/modules/comment/src/Tests/CommentCacheTagsTest.php +++ b/core/modules/comment/src/Tests/CommentCacheTagsTest.php @@ -24,7 +24,7 @@ class CommentCacheTagsTest extends EntityWithUriCacheTagsTestBase { /** * {@inheritdoc} */ - public static $modules = array('comment'); + public static $modules = ['comment']; /** * @var \Drupal\entity_test\Entity\EntityTest @@ -66,24 +66,24 @@ protected function createEntity() { $field->save(); // Create a "Camelids" test entity that the comment will be assigned to. - $this->entityTestCamelid = EntityTest::create(array( + $this->entityTestCamelid = EntityTest::create([ 'name' => 'Camelids', 'type' => 'bar', - )); + ]); $this->entityTestCamelid->save(); // Create a "Llama" comment. - $comment = Comment::create(array( + $comment = Comment::create([ 'subject' => 'Llama', - 'comment_body' => array( + 'comment_body' => [ 'value' => 'The name "llama" was adopted by European settlers from native Peruvians.', 'format' => 'plain_text', - ), + ], 'entity_id' => $this->entityTestCamelid->id(), 'entity_type' => 'entity_test', 'field_name' => 'comment', 'status' => CommentInterface::PUBLISHED, - )); + ]); $comment->save(); return $comment; @@ -97,26 +97,26 @@ public function testCommentEntity() { $this->verifyPageCache($this->entityTestCamelid->urlInfo(), 'HIT'); // Create a "Hippopotamus" comment. - $this->entityTestHippopotamidae = EntityTest::create(array( + $this->entityTestHippopotamidae = EntityTest::create([ 'name' => 'Hippopotamus', 'type' => 'bar', - )); + ]); $this->entityTestHippopotamidae->save(); $this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'MISS'); $this->verifyPageCache($this->entityTestHippopotamidae->urlInfo(), 'HIT'); - $hippo_comment = Comment::create(array( + $hippo_comment = Comment::create([ 'subject' => 'Hippopotamus', - 'comment_body' => array( + 'comment_body' => [ 'value' => 'The common hippopotamus (Hippopotamus amphibius), or hippo, is a large, mostly herbivorous mammal in sub-Saharan Africa', 'format' => 'plain_text', - ), + ], 'entity_id' => $this->entityTestHippopotamidae->id(), 'entity_type' => 'entity_test', 'field_name' => 'comment', 'status' => CommentInterface::PUBLISHED, - )); + ]); $hippo_comment->save(); // Ensure that a new comment only invalidates the commented entity. @@ -145,11 +145,11 @@ protected function getAdditionalCacheContextsForEntity(EntityInterface $entity) */ protected function getAdditionalCacheTagsForEntity(EntityInterface $entity) { /** @var \Drupal\comment\CommentInterface $entity */ - return array( + return [ 'config:filter.format.plain_text', 'user:' . $entity->getOwnerId(), 'user_view', - ); + ]; } } diff --git a/core/modules/comment/src/Tests/CommentFieldsTest.php b/core/modules/comment/src/Tests/CommentFieldsTest.php index 4da6e756ee..fa8a72a6a8 100644 --- a/core/modules/comment/src/Tests/CommentFieldsTest.php +++ b/core/modules/comment/src/Tests/CommentFieldsTest.php @@ -19,7 +19,7 @@ class CommentFieldsTest extends CommentTestBase { * * @var array */ - public static $modules = array('field_ui'); + public static $modules = ['field_ui']; /** * Tests that the default 'comment_body' field is correctly added. @@ -27,7 +27,7 @@ class CommentFieldsTest extends CommentTestBase { function testCommentDefaultFields() { // Do not make assumptions on default node types created by the test // installation profile, and create our own. - $this->drupalCreateContentType(array('type' => 'test_node_type')); + $this->drupalCreateContentType(['type' => 'test_node_type']); $this->addDefaultCommentField('node', 'test_node_type'); // Check that the 'comment_body' field is present on the comment bundle. @@ -43,7 +43,7 @@ function testCommentDefaultFields() { // Create a new content type. $type_name = 'test_node_type_2'; - $this->drupalCreateContentType(array('type' => $type_name)); + $this->drupalCreateContentType(['type' => $type_name]); $this->addDefaultCommentField('node', $type_name); // Check that the 'comment_body' field exists and has an instance on the @@ -51,7 +51,7 @@ function testCommentDefaultFields() { $field_storage = FieldStorageConfig::loadByName('comment', 'comment_body'); $this->assertTrue($field_storage, 'The comment_body field exists'); $field = FieldConfig::loadByName('comment', 'comment', 'comment_body'); - $this->assertTrue(isset($field), format_string('The comment_body field is present for comments on type @type', array('@type' => $type_name))); + $this->assertTrue(isset($field), format_string('The comment_body field is present for comments on type @type', ['@type' => $type_name])); // Test adding a field that defaults to CommentItemInterface::CLOSED. $this->addDefaultCommentField('node', 'test_node_type', 'who_likes_ponies', CommentItemInterface::CLOSED, 'who_likes_ponies'); @@ -63,7 +63,7 @@ function testCommentDefaultFields() { * Tests that you can remove a comment field. */ public function testCommentFieldDelete() { - $this->drupalCreateContentType(array('type' => 'test_node_type')); + $this->drupalCreateContentType(['type' => 'test_node_type']); $this->addDefaultCommentField('node', 'test_node_type'); // We want to test the handling of removing the primary comment field, so we // ensure there is at least one other comment field attached to a node type @@ -71,10 +71,10 @@ public function testCommentFieldDelete() { $this->addDefaultCommentField('node', 'test_node_type', 'comment2'); // Create a sample node. - $node = $this->drupalCreateNode(array( + $node = $this->drupalCreateNode([ 'title' => 'Baloney', 'type' => 'test_node_type', - )); + ]); $this->drupalLogin($this->webUser); @@ -143,38 +143,38 @@ public function testCommentFieldLinksNonDefaultName() { */ public function testCommentFieldCreate() { // Create user who can administer user fields. - $user = $this->drupalCreateUser(array( + $user = $this->drupalCreateUser([ 'administer user fields', - )); + ]); $this->drupalLogin($user); // Create comment field in account settings. - $edit = array( + $edit = [ 'new_storage_type' => 'comment', 'label' => 'User comment', 'field_name' => 'user_comment', - ); + ]; $this->drupalPostForm('admin/config/people/accounts/fields/add-field', $edit, 'Save and continue'); // Try to save the comment field without selecting a comment type. - $edit = array(); + $edit = []; $this->drupalPostForm('admin/config/people/accounts/fields/user.user.field_user_comment/storage', $edit, t('Save field settings')); // We should get an error message. $this->assertText(t('An illegal choice has been detected. Please contact the site administrator.')); // Create a comment type for users. - $bundle = CommentType::create(array( + $bundle = CommentType::create([ 'id' => 'user_comment_type', 'label' => 'user_comment_type', 'description' => '', 'target_entity_type_id' => 'user', - )); + ]); $bundle->save(); // Select a comment type and try to save again. - $edit = array( + $edit = [ 'settings[comment_type]' => 'user_comment_type', - ); + ]; $this->drupalPostForm('admin/config/people/accounts/fields/user.user.field_user_comment/storage', $edit, t('Save field settings')); // We shouldn't get an error message. $this->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.')); @@ -185,7 +185,7 @@ public function testCommentFieldCreate() { */ function testCommentInstallAfterContentModule() { // Create a user to do module administration. - $this->adminUser = $this->drupalCreateUser(array('access administration pages', 'administer modules')); + $this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer modules']); $this->drupalLogin($this->adminUser); // Drop default comment field added in CommentTestBase::setup(). @@ -199,20 +199,20 @@ function testCommentInstallAfterContentModule() { field_purge_batch(10); // Uninstall the comment module. - $edit = array(); + $edit = []; $edit['uninstall[comment]'] = TRUE; $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall')); - $this->drupalPostForm(NULL, array(), t('Uninstall')); + $this->drupalPostForm(NULL, [], t('Uninstall')); $this->rebuildContainer(); $this->assertFalse($this->container->get('module_handler')->moduleExists('comment'), 'Comment module uninstalled.'); // Install core content type module (book). - $edit = array(); + $edit = []; $edit['modules[book][enable]'] = 'book'; $this->drupalPostForm('admin/modules', $edit, t('Install')); // Now install the comment module. - $edit = array(); + $edit = []; $edit['modules[comment][enable]'] = 'comment'; $this->drupalPostForm('admin/modules', $edit, t('Install')); $this->rebuildContainer(); @@ -220,14 +220,14 @@ function testCommentInstallAfterContentModule() { // Create nodes of each type. $this->addDefaultCommentField('node', 'book'); - $book_node = $this->drupalCreateNode(array('type' => 'book')); + $book_node = $this->drupalCreateNode(['type' => 'book']); $this->drupalLogout(); // Try to post a comment on each node. A failure will be triggered if the // comment body is missing on one of these forms, due to postComment() // asserting that the body is actually posted correctly. - $this->webUser = $this->drupalCreateUser(array('access content', 'access comments', 'post comments', 'skip comment approval')); + $this->webUser = $this->drupalCreateUser(['access content', 'access comments', 'post comments', 'skip comment approval']); $this->drupalLogin($this->webUser); $this->postComment($book_node, $this->randomMachineName(), $this->randomMachineName()); } diff --git a/core/modules/comment/src/Tests/CommentInterfaceTest.php b/core/modules/comment/src/Tests/CommentInterfaceTest.php index ba43224c73..6f67ca84db 100644 --- a/core/modules/comment/src/Tests/CommentInterfaceTest.php +++ b/core/modules/comment/src/Tests/CommentInterfaceTest.php @@ -68,7 +68,7 @@ public function testCommentInterface() { // Comment as anonymous with preview required. $this->drupalLogout(); - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access content', 'access comments', 'post comments', 'skip comment approval')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access content', 'access comments', 'post comments', 'skip comment approval']); $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $this->assertTrue($this->commentExists($anonymous_comment), 'Comment found.'); $anonymous_comment->delete(); @@ -92,24 +92,24 @@ public function testCommentInterface() { $this->setCommentPreview(DRUPAL_OPTIONAL); $this->drupalGet('comment/' . $comment->id() . '/edit'); - $this->assertTitle(t('Edit comment @title | Drupal', array( + $this->assertTitle(t('Edit comment @title | Drupal', [ '@title' => $comment->getSubject(), - ))); + ])); // Test changing the comment author to "Anonymous". - $comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), array('uid' => '')); + $comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['uid' => '']); $this->assertTrue($comment->getAuthorName() == t('Anonymous') && $comment->getOwnerId() == 0, 'Comment author successfully changed to anonymous.'); // Test changing the comment author to an unverified user. $random_name = $this->randomMachineName(); $this->drupalGet('comment/' . $comment->id() . '/edit'); - $comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), array('name' => $random_name)); + $comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['name' => $random_name]); $this->drupalGet('node/' . $this->node->id()); $this->assertText($random_name . ' (' . t('not verified') . ')', 'Comment author successfully changed to an unverified user.'); // Test changing the comment author to a verified user. $this->drupalGet('comment/' . $comment->id() . '/edit'); - $comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), array('uid' => $this->webUser->getUsername() . ' (' . $this->webUser->id() . ')')); + $comment = $this->postComment(NULL, $comment->comment_body->value, $comment->getSubject(), ['uid' => $this->webUser->getUsername() . ' (' . $this->webUser->id() . ')']); $this->assertTrue($comment->getAuthorName() == $this->webUser->getUsername() && $comment->getOwnerId() == $this->webUser->id(), 'Comment author successfully changed to a registered user.'); $this->drupalLogout(); @@ -121,7 +121,7 @@ public function testCommentInterface() { // \Drupal\comment\Controller\CommentController::redirectNode(). $this->drupalGet('comment/' . $this->node->id() . '/reply'); // Verify we were correctly redirected. - $this->assertUrl(\Drupal::url('comment.reply', array('entity_type' => 'node', 'entity' => $this->node->id(), 'field_name' => 'comment'), array('absolute' => TRUE))); + $this->assertUrl(\Drupal::url('comment.reply', ['entity_type' => 'node', 'entity' => $this->node->id(), 'field_name' => 'comment'], ['absolute' => TRUE])); $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $comment->id()); $this->assertText($subject_text, 'Individual comment-reply subject found.'); $this->assertText($comment_text, 'Individual comment-reply body found.'); @@ -161,7 +161,7 @@ public function testCommentInterface() { $this->setCommentsPerPage(2); $comment_new_page = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $this->assertTrue($this->commentExists($comment_new_page), 'Page one exists. %s'); - $this->drupalGet('node/' . $this->node->id(), array('query' => array('page' => 2))); + $this->drupalGet('node/' . $this->node->id(), ['query' => ['page' => 2]]); $this->assertTrue($this->commentExists($reply, TRUE), 'Page two exists. %s'); $this->setCommentsPerPage(50); @@ -172,21 +172,21 @@ public function testCommentInterface() { $this->assertResponse(403); // Attempt to post to node with comments disabled. - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => array(array('status' => CommentItemInterface::HIDDEN)))); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::HIDDEN]]]); $this->assertTrue($this->node, 'Article node created.'); $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); $this->assertResponse(403); $this->assertNoField('edit-comment', 'Comment body field found.'); // Attempt to post to node with read-only comments. - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => array(array('status' => CommentItemInterface::CLOSED)))); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::CLOSED]]]); $this->assertTrue($this->node, 'Article node created.'); $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); $this->assertResponse(403); $this->assertNoField('edit-comment', 'Comment body field found.'); // Attempt to post to node with comments enabled (check field names etc). - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => array(array('status' => CommentItemInterface::OPEN)))); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'comment' => [['status' => CommentItemInterface::OPEN]]]); $this->assertTrue($this->node, 'Article node created.'); $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); $this->assertNoText('This discussion is closed', 'Posting to node with comments enabled'); @@ -254,17 +254,17 @@ public function testAutoFilledHtmlSubject() { // can select one of them. Then create a user that can use these formats, // log the user in, and then GET the node page on which to test the // comments. - $filtered_html_format = FilterFormat::create(array( + $filtered_html_format = FilterFormat::create([ 'format' => 'filtered_html', 'name' => 'Filtered HTML', - )); + ]); $filtered_html_format->save(); - $full_html_format = FilterFormat::create(array( + $full_html_format = FilterFormat::create([ 'format' => 'full_html', 'name' => 'Full HTML', - )); + ]); $full_html_format->save(); - $html_user = $this->drupalCreateUser(array( + $html_user = $this->drupalCreateUser([ 'access comments', 'post comments', 'edit own comments', @@ -272,25 +272,25 @@ public function testAutoFilledHtmlSubject() { 'access content', $filtered_html_format->getPermissionName(), $full_html_format->getPermissionName(), - )); + ]); $this->drupalLogin($html_user); $this->drupalGet('node/' . $this->node->id()); // HTML should not be included in the character count. $body_text1 = ' Hello World
        '; - $edit1 = array( + $edit1 = [ 'comment_body[0][value]' => $body_text1, 'comment_body[0][format]' => 'filtered_html', - ); + ]; $this->drupalPostForm(NULL, $edit1, t('Save')); $this->assertEqual('Hello World', Comment::load(1)->getSubject()); // If there's nothing other than HTML, the subject should be '(No subject)'. $body_text2 = '
        '; - $edit2 = array( + $edit2 = [ 'comment_body[0][value]' => $body_text2, 'comment_body[0][format]' => 'filtered_html', - ); + ]; $this->drupalPostForm(NULL, $edit2, t('Save')); $this->assertEqual('(No subject)', Comment::load(2)->getSubject()); } diff --git a/core/modules/comment/src/Tests/CommentLanguageTest.php b/core/modules/comment/src/Tests/CommentLanguageTest.php index c60f82783f..b047b40341 100644 --- a/core/modules/comment/src/Tests/CommentLanguageTest.php +++ b/core/modules/comment/src/Tests/CommentLanguageTest.php @@ -25,23 +25,23 @@ class CommentLanguageTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'language', 'language_test', 'comment_test'); + public static $modules = ['node', 'language', 'language_test', 'comment_test']; protected function setUp() { parent::setUp(); - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); // Create and log in user. - $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval')); + $admin_user = $this->drupalCreateUser(['administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval']); $this->drupalLogin($admin_user); // Add language. - $edit = array('predefined_langcode' => 'fr'); + $edit = ['predefined_langcode' => 'fr']; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); // Set "Article" content type to use multilingual support. - $edit = array('language_configuration[language_alterable]' => TRUE); + $edit = ['language_configuration[language_alterable]' => TRUE]; $this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type')); // Enable content language negotiation UI. @@ -51,16 +51,16 @@ protected function setUp() { // to URL. Disable inheritance from interface language to ensure content // language will fall back to the default language if no URL language can be // detected. - $edit = array( + $edit = [ 'language_interface[enabled][language-user]' => TRUE, 'language_content[enabled][language-url]' => TRUE, 'language_content[enabled][language-interface]' => FALSE, - ); + ]; $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings')); // Change user language preference, this way interface language is always // French no matter what path prefix the URLs have. - $edit = array('preferred_langcode' => 'fr'); + $edit = ['preferred_langcode' => 'fr']; $this->drupalPostForm("user/" . $admin_user->id() . "/edit", $edit, t('Save')); // Create comment field on article. @@ -87,12 +87,12 @@ function testCommentLanguage() { foreach ($this->container->get('language_manager')->getLanguages() as $node_langcode => $node_language) { // Create "Article" content. $title = $this->randomMachineName(); - $edit = array( + $edit = [ 'title[0][value]' => $title, 'body[0][value]' => $this->randomMachineName(), 'langcode[0][value]' => $node_langcode, 'comment[0][status]' => CommentItemInterface::OPEN, - ); + ]; $this->drupalPostForm("node/add/article", $edit, t('Save')); $node = $this->drupalGetNodeByTitle($title); @@ -101,10 +101,10 @@ function testCommentLanguage() { // Post a comment with content language $langcode. $prefix = empty($prefixes[$langcode]) ? '' : $prefixes[$langcode] . '/'; $comment_values[$node_langcode][$langcode] = $this->randomMachineName(); - $edit = array( + $edit = [ 'subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $comment_values[$node_langcode][$langcode], - ); + ]; $this->drupalPostForm($prefix . 'node/' . $node->id(), $edit, t('Preview')); $this->drupalPostForm(NULL, $edit, t('Save')); @@ -117,7 +117,7 @@ function testCommentLanguage() { ->range(0, 1) ->execute(); $comment = Comment::load(reset($cids)); - $args = array('%node_language' => $node_langcode, '%comment_language' => $comment->langcode->value, '%langcode' => $langcode); + $args = ['%node_language' => $node_langcode, '%comment_language' => $comment->langcode->value, '%langcode' => $langcode]; $this->assertEqual($comment->langcode->value, $langcode, format_string('The comment posted with content language %langcode and belonging to the node with language %node_language has language %comment_language', $args)); $this->assertEqual($comment->comment_body->value, $comment_values[$node_langcode][$langcode], 'Comment body correctly stored.'); } diff --git a/core/modules/comment/src/Tests/CommentLinksAlterTest.php b/core/modules/comment/src/Tests/CommentLinksAlterTest.php index 22ff587c3d..88e092f08d 100644 --- a/core/modules/comment/src/Tests/CommentLinksAlterTest.php +++ b/core/modules/comment/src/Tests/CommentLinksAlterTest.php @@ -9,7 +9,7 @@ */ class CommentLinksAlterTest extends CommentTestBase { - public static $modules = array('comment_test'); + public static $modules = ['comment_test']; protected function setUp() { parent::setUp(); diff --git a/core/modules/comment/src/Tests/CommentLinksTest.php b/core/modules/comment/src/Tests/CommentLinksTest.php index 1115f57936..589a355663 100644 --- a/core/modules/comment/src/Tests/CommentLinksTest.php +++ b/core/modules/comment/src/Tests/CommentLinksTest.php @@ -27,7 +27,7 @@ class CommentLinksTest extends CommentTestBase { * * @var array */ - protected $seen = array(); + protected $seen = []; /** * Use the main node listing to test rendering on teasers. @@ -36,14 +36,14 @@ class CommentLinksTest extends CommentTestBase { * * @todo Remove this dependency. */ - public static $modules = array('views'); + public static $modules = ['views']; /** * Tests that comment links are output and can be hidden. */ public function testCommentLinks() { // Bartik theme alters comment links, so use a different theme. - \Drupal::service('theme_handler')->install(array('stark')); + \Drupal::service('theme_handler')->install(['stark']); $this->config('system.theme') ->set('default', 'stark') ->save(); @@ -51,11 +51,11 @@ public function testCommentLinks() { // Remove additional user permissions from $this->webUser added by setUp(), // since this test is limited to anonymous and authenticated roles only. $roles = $this->webUser->getRoles(); - entity_delete_multiple('user_role', array(reset($roles))); + entity_delete_multiple('user_role', [reset($roles)]); // Create a comment via CRUD API functionality, since // $this->postComment() relies on actual user permissions. - $comment = Comment::create(array( + $comment = Comment::create([ 'cid' => NULL, 'entity_id' => $this->node->id(), 'entity_type' => 'node', @@ -66,8 +66,8 @@ public function testCommentLinks() { 'subject' => $this->randomMachineName(), 'hostname' => '127.0.0.1', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, - 'comment_body' => array(array('value' => $this->randomMachineName())), - )); + 'comment_body' => [['value' => $this->randomMachineName()]], + ]); $comment->save(); $this->comment = $comment; @@ -78,19 +78,19 @@ public function testCommentLinks() { $this->node->save(); // Change user permissions. - $perms = array( + $perms = [ 'access comments' => 1, 'post comments' => 1, 'skip comment approval' => 1, 'edit own comments' => 1, - ); + ]; user_role_change_permissions(RoleInterface::ANONYMOUS_ID, $perms); $nid = $this->node->id(); // Assert basic link is output, actual functionality is unit-tested in // \Drupal\comment\Tests\CommentLinkBuilderTest. - foreach (array('node', "node/$nid") as $path) { + foreach (['node', "node/$nid"] as $path) { $this->drupalGet($path); // In teaser view, a link containing the comment count is always @@ -103,7 +103,7 @@ public function testCommentLinks() { // Change weight to make links go before comment body. entity_get_display('comment', 'comment', 'default') - ->setComponent('links', array('weight' => -100)) + ->setComponent('links', ['weight' => -100]) ->save(); $this->drupalGet($this->node->urlInfo()); $element = $this->cssSelect('article.js-comment > div'); @@ -113,7 +113,7 @@ public function testCommentLinks() { // Change weight to make links go after comment body. entity_get_display('comment', 'comment', 'default') - ->setComponent('links', array('weight' => 100)) + ->setComponent('links', ['weight' => 100]) ->save(); $this->drupalGet($this->node->urlInfo()); $element = $this->cssSelect('article.js-comment > div'); diff --git a/core/modules/comment/src/Tests/CommentNewIndicatorTest.php b/core/modules/comment/src/Tests/CommentNewIndicatorTest.php index 6d89d4a646..55609e3778 100644 --- a/core/modules/comment/src/Tests/CommentNewIndicatorTest.php +++ b/core/modules/comment/src/Tests/CommentNewIndicatorTest.php @@ -22,7 +22,7 @@ class CommentNewIndicatorTest extends CommentTestBase { * * @todo Remove this dependency. */ - public static $modules = array('views'); + public static $modules = ['views']; /** * Get node "x new comments" metadata from the server for the current user. @@ -35,7 +35,7 @@ class CommentNewIndicatorTest extends CommentTestBase { */ protected function renderNewCommentsNodeLinks(array $node_ids) { // Build POST values. - $post = array(); + $post = []; for ($i = 0; $i < count($node_ids); $i++) { $post['node_ids[' . $i . ']'] = $node_ids[$i]; } @@ -51,15 +51,15 @@ protected function renderNewCommentsNodeLinks(array $node_ids) { $post = implode('&', $post); // Perform HTTP request. - return $this->curlExec(array( - CURLOPT_URL => \Drupal::url('comment.new_comments_node_links', array(), array('absolute' => TRUE)), + return $this->curlExec([ + CURLOPT_URL => \Drupal::url('comment.new_comments_node_links', [], ['absolute' => TRUE]), CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, - CURLOPT_HTTPHEADER => array( + CURLOPT_HTTPHEADER => [ 'Accept: application/json', 'Content-Type: application/x-www-form-urlencoded', - ), - )); + ], + ]); } /** @@ -70,7 +70,7 @@ public function testCommentNewCommentsIndicator() { // node. $this->drupalLogin($this->adminUser); $this->drupalGet('node'); - $this->assertNoLink(t('@count comments', array('@count' => 0))); + $this->assertNoLink(t('@count comments', ['@count' => 0])); $this->assertLink(t('Read more')); // Verify the data-history-node-last-comment-timestamp attribute, which is // used by the drupal.node-new-comments-link library to determine whether @@ -81,7 +81,7 @@ public function testCommentNewCommentsIndicator() { // Create a new comment. This helper function may be run with different // comment settings so use $comment->save() to avoid complex setup. /** @var \Drupal\comment\CommentInterface $comment */ - $comment = Comment::create(array( + $comment = Comment::create([ 'cid' => NULL, 'entity_id' => $this->node->id(), 'entity_type' => 'node', @@ -92,8 +92,8 @@ public function testCommentNewCommentsIndicator() { 'subject' => $this->randomMachineName(), 'hostname' => '127.0.0.1', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, - 'comment_body' => array(LanguageInterface::LANGCODE_NOT_SPECIFIED => array($this->randomMachineName())), - )); + 'comment_body' => [LanguageInterface::LANGCODE_NOT_SPECIFIED => [$this->randomMachineName()]], + ]); $comment->save(); $this->drupalLogout(); @@ -126,24 +126,24 @@ public function testCommentNewCommentsIndicator() { ]); // Pretend the data was not present in drupalSettings, i.e. test the // separate request to the server. - $response = $this->renderNewCommentsNodeLinks(array($this->node->id())); + $response = $this->renderNewCommentsNodeLinks([$this->node->id()]); $this->assertResponse(200); $json = Json::decode($response); - $expected = array($this->node->id() => array( + $expected = [$this->node->id() => [ 'new_comment_count' => 1, - 'first_new_comment_link' => $this->node->url('canonical', array('fragment' => 'new')), - )); + 'first_new_comment_link' => $this->node->url('canonical', ['fragment' => 'new']), + ]]; $this->assertIdentical($expected, $json); // Failing to specify node IDs for the endpoint should return a 404. - $this->renderNewCommentsNodeLinks(array()); + $this->renderNewCommentsNodeLinks([]); $this->assertResponse(404); // Accessing the endpoint as the anonymous user should return a 403. $this->drupalLogout(); - $this->renderNewCommentsNodeLinks(array($this->node->id())); + $this->renderNewCommentsNodeLinks([$this->node->id()]); $this->assertResponse(403); - $this->renderNewCommentsNodeLinks(array()); + $this->renderNewCommentsNodeLinks([]); $this->assertResponse(403); } diff --git a/core/modules/comment/src/Tests/CommentNodeAccessTest.php b/core/modules/comment/src/Tests/CommentNodeAccessTest.php index e69bfdeda5..60f8bbdd5a 100644 --- a/core/modules/comment/src/Tests/CommentNodeAccessTest.php +++ b/core/modules/comment/src/Tests/CommentNodeAccessTest.php @@ -19,7 +19,7 @@ class CommentNodeAccessTest extends CommentTestBase { * * @var array */ - public static $modules = array('node_access_test'); + public static $modules = ['node_access_test']; protected function setUp() { parent::setUp(); @@ -27,14 +27,14 @@ protected function setUp() { node_access_rebuild(); // Re-create user. - $this->webUser = $this->drupalCreateUser(array( + $this->webUser = $this->drupalCreateUser([ 'access comments', 'post comments', 'create article content', 'edit own comments', 'node test view', 'skip comment approval', - )); + ]); // Set the author of the created node to the web_user uid. $this->node->setOwnerId($this->webUser->id())->save(); diff --git a/core/modules/comment/src/Tests/CommentNodeChangesTest.php b/core/modules/comment/src/Tests/CommentNodeChangesTest.php index 9fed4df887..7724f9979a 100644 --- a/core/modules/comment/src/Tests/CommentNodeChangesTest.php +++ b/core/modules/comment/src/Tests/CommentNodeChangesTest.php @@ -27,7 +27,7 @@ function testNodeDeletion() { $this->assertNotNull(FieldStorageConfig::load('node.comment'), 'Comment field storage exists'); $this->assertNotNull(FieldConfig::load('node.article.comment'), 'Comment field exists'); // Delete the node type. - entity_delete_multiple('node_type', array($this->node->bundle())); + entity_delete_multiple('node_type', [$this->node->bundle()]); $this->assertNull(FieldStorageConfig::load('node.comment'), 'Comment field storage deleted'); $this->assertNull(FieldConfig::load('node.article.comment'), 'Comment field deleted'); } diff --git a/core/modules/comment/src/Tests/CommentNonNodeTest.php b/core/modules/comment/src/Tests/CommentNonNodeTest.php index e43e0bc42a..bc40c9d8ad 100644 --- a/core/modules/comment/src/Tests/CommentNonNodeTest.php +++ b/core/modules/comment/src/Tests/CommentNonNodeTest.php @@ -24,7 +24,7 @@ class CommentNonNodeTest extends WebTestBase { use FieldUiTestTrait; use CommentTestTrait; - public static $modules = array('comment', 'user', 'field_ui', 'entity_test', 'block'); + public static $modules = ['comment', 'user', 'field_ui', 'entity_test', 'block']; /** * An administrative user with permission to configure comment settings. @@ -50,12 +50,12 @@ protected function setUp() { // Create a bundle for entity_test. entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test'); - CommentType::create(array( + CommentType::create([ 'id' => 'comment', 'label' => 'Comment settings', 'description' => 'Comment settings', 'target_entity_type_id' => 'entity_test', - ))->save(); + ])->save(); // Create comment field on entity_test bundle. $this->addDefaultCommentField('entity_test', 'entity_test'); @@ -64,30 +64,30 @@ protected function setUp() { $this->assertEqual($bundles['comment']['label'], 'Comment settings'); // Create test user. - $this->adminUser = $this->drupalCreateUser(array( + $this->adminUser = $this->drupalCreateUser([ 'administer comments', 'skip comment approval', 'post comments', 'access comments', 'view test entity', 'administer entity_test content', - )); + ]); // Enable anonymous and authenticated user comments. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments', 'post comments', 'skip comment approval', - )); - user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array( + ]); + user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, [ 'access comments', 'post comments', 'skip comment approval', - )); + ]); // Create a test entity. $random_label = $this->randomMachineName(); - $data = array('type' => 'entity_test', 'name' => $random_label); + $data = ['type' => 'entity_test', 'name' => $random_label]; $this->entity = EntityTest::create($data); $this->entity->save(); } @@ -109,7 +109,7 @@ protected function setUp() { * The new comment entity. */ function postComment(EntityInterface $entity, $comment, $subject = '', $contact = NULL) { - $edit = array(); + $edit = []; $edit['comment_body[0][value]'] = $comment; $field = FieldConfig::loadByName('entity_test', 'entity_test', 'comment'); @@ -151,7 +151,7 @@ function postComment(EntityInterface $entity, $comment, $subject = '', $contact $this->drupalPostForm(NULL, $edit, t('Save')); break; } - $match = array(); + $match = []; // Get comment ID preg_match('/#comment-([0-9]+)/', $this->getURL(), $match); @@ -216,17 +216,17 @@ function commentContactInfoAvailable() { * Operation is found on approval page. */ function performCommentOperation($comment, $operation, $approval = FALSE) { - $edit = array(); + $edit = []; $edit['operation'] = $operation; $edit['comments[' . $comment->id() . ']'] = TRUE; $this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update')); if ($operation == 'delete') { - $this->drupalPostForm(NULL, array(), t('Delete comments')); - $this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation))); + $this->drupalPostForm(NULL, [], t('Delete comments')); + $this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation])); } else { - $this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation))); + $this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation])); } } @@ -250,9 +250,9 @@ function getUnapprovedComment($subject) { * Tests anonymous comment functionality. */ function testCommentFunctionality() { - $limited_user = $this->drupalCreateUser(array( + $limited_user = $this->drupalCreateUser([ 'administer entity_test fields' - )); + ]); $this->drupalLogin($limited_user); // Test that default field exists. $this->drupalGet('entity_test/structure/entity_test/fields'); @@ -320,9 +320,9 @@ function testCommentFunctionality() { // Check that entity access applies to administrative page. $this->assertText($this->entity->label(), 'Name of commented account found.'); - $limited_user = $this->drupalCreateUser(array( + $limited_user = $this->drupalCreateUser([ 'administer comments', - )); + ]); $this->drupalLogin($limited_user); $this->drupalGet('admin/content/comment'); $this->assertNoText($this->entity->label(), 'No commented account name found.'); @@ -330,12 +330,12 @@ function testCommentFunctionality() { $this->drupalLogout(); // Deny anonymous users access to comments. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => FALSE, 'post comments' => FALSE, 'skip comment approval' => FALSE, 'view test entity' => TRUE, - )); + ]); // Attempt to view comments while disallowed. $this->drupalGet('entity-test/' . $this->entity->id()); @@ -348,12 +348,12 @@ function testCommentFunctionality() { $this->assertNoFieldByName('subject[0][value]', '', 'Subject field not found.'); $this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field not found.'); - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => TRUE, 'post comments' => FALSE, 'view test entity' => TRUE, 'skip comment approval' => FALSE, - )); + ]); $this->drupalGet('entity_test/' . $this->entity->id()); $this->assertPattern('@]*>Comments@', 'Comments were displayed.'); $this->assertLink('Log in', 0, 'Link to login was found.'); @@ -364,12 +364,12 @@ function testCommentFunctionality() { // Test the combination of anonymous users being able to post, but not view // comments, to ensure that access to post comments doesn't grant access to // view them. - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => FALSE, 'post comments' => TRUE, 'skip comment approval' => TRUE, 'view test entity' => TRUE, - )); + ]); $this->drupalGet('entity_test/' . $this->entity->id()); $this->assertNoPattern('@]*>Comments@', 'Comments were not displayed.'); $this->assertFieldByName('subject[0][value]', '', 'Subject field found.'); @@ -380,22 +380,22 @@ function testCommentFunctionality() { $this->assertNoText($comment1->getSubject(), 'Comment not displayed.'); // Test comment field widget changes. - $limited_user = $this->drupalCreateUser(array( + $limited_user = $this->drupalCreateUser([ 'administer entity_test fields', 'view test entity', 'administer entity_test content', 'administer comments', - )); + ]); $this->drupalLogin($limited_user); $this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment'); $this->assertNoFieldChecked('edit-default-value-input-comment-0-status-0'); $this->assertNoFieldChecked('edit-default-value-input-comment-0-status-1'); $this->assertFieldChecked('edit-default-value-input-comment-0-status-2'); // Test comment option change in field settings. - $edit = array( + $edit = [ 'default_value_input[comment][0][status]' => CommentItemInterface::CLOSED, 'settings[anonymous]' => COMMENT_ANONYMOUS_MAY_CONTACT, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save settings')); $this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.comment'); $this->assertNoFieldChecked('edit-default-value-input-comment-0-status-0'); @@ -404,18 +404,18 @@ function testCommentFunctionality() { $this->assertFieldByName('settings[anonymous]', COMMENT_ANONYMOUS_MAY_CONTACT); // Add a new comment-type. - $bundle = CommentType::create(array( + $bundle = CommentType::create([ 'id' => 'foobar', 'label' => 'Foobar', 'description' => '', 'target_entity_type_id' => 'entity_test', - )); + ]); $bundle->save(); // Add a new comment field. - $storage_edit = array( + $storage_edit = [ 'settings[comment_type]' => 'foobar', - ); + ]; $this->fieldUIAddNewField('entity_test/structure/entity_test', 'foobar', 'Foobar', 'comment', $storage_edit); // Add a third comment field. @@ -429,7 +429,7 @@ function testCommentFunctionality() { // Test the new entity commenting inherits default. $random_label = $this->randomMachineName(); - $data = array('bundle' => 'entity_test', 'name' => $random_label); + $data = ['bundle' => 'entity_test', 'name' => $random_label]; $new_entity = EntityTest::create($data); $new_entity->save(); $this->drupalGet('entity_test/manage/' . $new_entity->id() . '/edit'); @@ -443,12 +443,12 @@ function testCommentFunctionality() { $this->assertNoFieldByName('comment_body[0][value]', '', 'Comment field found.'); // Test removal of comment_body field. - $limited_user = $this->drupalCreateUser(array( + $limited_user = $this->drupalCreateUser([ 'administer entity_test fields', 'post comments', 'administer comment fields', 'administer comment types', - )); + ]); $this->drupalLogin($limited_user); $this->drupalGet('comment/reply/entity_test/' . $this->entity->id() . '/comment'); @@ -467,9 +467,9 @@ function testCommentFunctionality() { public function testsNonIntegerIdEntities() { // Create a bundle for entity_test_string_id. entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_string_id'); - $limited_user = $this->drupalCreateUser(array( + $limited_user = $this->drupalCreateUser([ 'administer entity_test_string_id fields', - )); + ]); $this->drupalLogin($limited_user); // Visit the Field UI field add page. $this->drupalGet('entity_test_string_id/structure/entity_test/fields/add-field'); @@ -480,9 +480,9 @@ public function testsNonIntegerIdEntities() { // Create a bundle for entity_test_no_id. entity_test_create_bundle('entity_test', 'Entity Test', 'entity_test_no_id'); - $this->drupalLogin($this->drupalCreateUser(array( + $this->drupalLogin($this->drupalCreateUser([ 'administer entity_test_no_id fields', - ))); + ])); // Visit the Field UI field add page. $this->drupalGet('entity_test_no_id/structure/entity_test/fields/add-field'); // Ensure field isn't shown for empty IDs. diff --git a/core/modules/comment/src/Tests/CommentPagerTest.php b/core/modules/comment/src/Tests/CommentPagerTest.php index aa7d09997b..1bfda557f5 100644 --- a/core/modules/comment/src/Tests/CommentPagerTest.php +++ b/core/modules/comment/src/Tests/CommentPagerTest.php @@ -24,8 +24,8 @@ function testCommentPaging() { $this->setCommentPreview(DRUPAL_DISABLED); // Create a node and three comments. - $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); - $comments = array(); + $node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]); + $comments = []; $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); @@ -45,13 +45,13 @@ function testCommentPaging() { $this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 1.'); // Check the second page. - $this->drupalGet('node/' . $node->id(), array('query' => array('page' => 1))); + $this->drupalGet('node/' . $node->id(), ['query' => ['page' => 1]]); $this->assertTrue($this->commentExists($comments[1]), 'Comment 2 appears on page 2.'); $this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 2.'); $this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 2.'); // Check the third page. - $this->drupalGet('node/' . $node->id(), array('query' => array('page' => 2))); + $this->drupalGet('node/' . $node->id(), ['query' => ['page' => 2]]); $this->assertTrue($this->commentExists($comments[2]), 'Comment 3 appears on page 3.'); $this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 3.'); $this->assertFalse($this->commentExists($comments[1]), 'Comment 2 does not appear on page 3.'); @@ -64,27 +64,27 @@ function testCommentPaging() { $this->setCommentsPerPage(2); // We are still in flat view - the replies should not be on the first page, // even though they are replies to the oldest comment. - $this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0))); + $this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]); $this->assertFalse($this->commentExists($reply, TRUE), 'In flat mode, reply does not appear on page 1.'); // If we switch to threaded mode, the replies on the oldest comment // should be bumped to the first page and comment 6 should be bumped // to the second page. $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.'); - $this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0))); + $this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]); $this->assertTrue($this->commentExists($reply, TRUE), 'In threaded mode, reply appears on page 1.'); $this->assertFalse($this->commentExists($comments[1]), 'In threaded mode, comment 2 has been bumped off of page 1.'); // If (# replies > # comments per page) in threaded expanded view, // the overage should be bumped. $reply2 = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName(), TRUE); - $this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0))); + $this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]); $this->assertFalse($this->commentExists($reply2, TRUE), 'In threaded mode where # replies > # comments per page, the newest reply does not appear on page 1.'); // Test that the page build process does not somehow generate errors when // # comments per page is set to 0. $this->setCommentsPerPage(0); - $this->drupalGet('node/' . $node->id(), array('query' => array('page' => 0))); + $this->drupalGet('node/' . $node->id(), ['query' => ['page' => 0]]); $this->assertFalse($this->commentExists($reply2, TRUE), 'Threaded mode works correctly when comments per page is 0.'); $this->drupalLogout(); @@ -102,8 +102,8 @@ function testCommentPermalink() { $this->setCommentPreview(DRUPAL_DISABLED); // Create a node and three comments. - $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); - $comments = array(); + $node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]); + $comments = []; $comments[] = $this->postComment($node, 'comment 1: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, 'comment 2: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, 'comment 3: ' . $this->randomMachineName(), $this->randomMachineName(), TRUE); @@ -137,8 +137,8 @@ function testCommentOrderingThreading() { $this->setCommentsPerPage(1000); // Create a node and three comments. - $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); - $comments = array(); + $node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]); + $comments = []; $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); @@ -170,7 +170,7 @@ function testCommentOrderingThreading() { $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.'); - $expected_order = array( + $expected_order = [ 0, 1, 2, @@ -178,13 +178,13 @@ function testCommentOrderingThreading() { 4, 5, 6, - ); + ]; $this->drupalGet('node/' . $node->id()); $this->assertCommentOrder($comments, $expected_order); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.'); - $expected_order = array( + $expected_order = [ 0, 4, 1, @@ -192,7 +192,7 @@ function testCommentOrderingThreading() { 6, 2, 5, - ); + ]; $this->drupalGet('node/' . $node->id()); $this->assertCommentOrder($comments, $expected_order); } @@ -206,7 +206,7 @@ function testCommentOrderingThreading() { * An array of keys from $comments describing the expected order. */ function assertCommentOrder(array $comments, array $expected_order) { - $expected_cids = array(); + $expected_cids = []; // First, rekey the expected order by cid. foreach ($expected_order as $key) { @@ -214,11 +214,11 @@ function assertCommentOrder(array $comments, array $expected_order) { } $comment_anchors = $this->xpath('//a[starts-with(@id,"comment-")]'); - $result_order = array(); + $result_order = []; foreach ($comment_anchors as $anchor) { $result_order[] = substr($anchor['id'], 8); } - return $this->assertEqual($expected_cids, $result_order, format_string('Comment order: expected @expected, returned @returned.', array('@expected' => implode(',', $expected_cids), '@returned' => implode(',', $result_order)))); + return $this->assertEqual($expected_cids, $result_order, format_string('Comment order: expected @expected, returned @returned.', ['@expected' => implode(',', $expected_cids), '@returned' => implode(',', $result_order)])); } /** @@ -237,8 +237,8 @@ function testCommentNewPageIndicator() { $this->setCommentsPerPage(1); // Create a node and three comments. - $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); - $comments = array(); + $node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]); + $comments = []; $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); $comments[] = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); @@ -265,39 +265,39 @@ function testCommentNewPageIndicator() { $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.'); - $expected_pages = array( + $expected_pages = [ 1 => 5, // Page of comment 5 2 => 4, // Page of comment 4 3 => 3, // Page of comment 3 4 => 2, // Page of comment 2 5 => 1, // Page of comment 1 6 => 0, // Page of comment 0 - ); + ]; $node = Node::load($node->id()); foreach ($expected_pages as $new_replies => $expected_page) { $returned_page = \Drupal::entityManager()->getStorage('comment') ->getNewCommentPageNumber($node->get('comment')->comment_count, $new_replies, $node, 'comment'); - $this->assertIdentical($expected_page, $returned_page, format_string('Flat mode, @new replies: expected page @expected, returned page @returned.', array('@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page))); + $this->assertIdentical($expected_page, $returned_page, format_string('Flat mode, @new replies: expected page @expected, returned page @returned.', ['@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page])); } $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Switched to threaded mode.'); - $expected_pages = array( + $expected_pages = [ 1 => 5, // Page of comment 5 2 => 1, // Page of comment 4 3 => 1, // Page of comment 4 4 => 1, // Page of comment 4 5 => 1, // Page of comment 4 6 => 0, // Page of comment 0 - ); + ]; - \Drupal::entityManager()->getStorage('node')->resetCache(array($node->id())); + \Drupal::entityManager()->getStorage('node')->resetCache([$node->id()]); $node = Node::load($node->id()); foreach ($expected_pages as $new_replies => $expected_page) { $returned_page = \Drupal::entityManager()->getStorage('comment') ->getNewCommentPageNumber($node->get('comment')->comment_count, $new_replies, $node, 'comment'); - $this->assertEqual($expected_page, $returned_page, format_string('Threaded mode, @new replies: expected page @expected, returned page @returned.', array('@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page))); + $this->assertEqual($expected_page, $returned_page, format_string('Threaded mode, @new replies: expected page @expected, returned page @returned.', ['@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page])); } } @@ -309,39 +309,39 @@ function testTwoPagers() { $this->addDefaultCommentField('node', 'article', 'comment_2'); // Set default to display comment list with unique pager id. entity_get_display('node', 'article', 'default') - ->setComponent('comment_2', array( + ->setComponent('comment_2', [ 'label' => 'hidden', 'type' => 'comment_default', 'weight' => 30, - 'settings' => array( + 'settings' => [ 'pager_id' => 1, 'view_mode' => 'default', - ) - )) + ] + ]) ->save(); // Make sure pager appears in formatter summary and settings form. - $account = $this->drupalCreateUser(array('administer node display')); + $account = $this->drupalCreateUser(['administer node display']); $this->drupalLogin($account); $this->drupalGet('admin/structure/types/manage/article/display'); - $this->assertNoText(t('Pager ID: @id', array('@id' => 0)), 'No summary for standard pager'); - $this->assertText(t('Pager ID: @id', array('@id' => 1))); - $this->drupalPostAjaxForm(NULL, array(), 'comment_settings_edit'); + $this->assertNoText(t('Pager ID: @id', ['@id' => 0]), 'No summary for standard pager'); + $this->assertText(t('Pager ID: @id', ['@id' => 1])); + $this->drupalPostAjaxForm(NULL, [], 'comment_settings_edit'); // Change default pager to 2. - $this->drupalPostForm(NULL, array('fields[comment][settings_edit_form][settings][pager_id]' => 2), t('Save')); - $this->assertText(t('Pager ID: @id', array('@id' => 2))); + $this->drupalPostForm(NULL, ['fields[comment][settings_edit_form][settings][pager_id]' => 2], t('Save')); + $this->assertText(t('Pager ID: @id', ['@id' => 2])); // Revert the changes. - $this->drupalPostAjaxForm(NULL, array(), 'comment_settings_edit'); - $this->drupalPostForm(NULL, array('fields[comment][settings_edit_form][settings][pager_id]' => 0), t('Save')); - $this->assertNoText(t('Pager ID: @id', array('@id' => 0)), 'No summary for standard pager'); + $this->drupalPostAjaxForm(NULL, [], 'comment_settings_edit'); + $this->drupalPostForm(NULL, ['fields[comment][settings_edit_form][settings][pager_id]' => 0], t('Save')); + $this->assertNoText(t('Pager ID: @id', ['@id' => 0]), 'No summary for standard pager'); $this->drupalLogin($this->adminUser); // Add a new node with both comment fields open. - $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id())); + $node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]); // Set comment options. - $comments = array(); - foreach (array('comment', 'comment_2') as $field_name) { + $comments = []; + foreach (['comment', 'comment_2'] as $field_name) { $this->setCommentForm(TRUE, $field_name); $this->setCommentPreview(DRUPAL_OPTIONAL, $field_name); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_FLAT, 'Comment paging changed.', $field_name); @@ -350,10 +350,10 @@ function testTwoPagers() { // needing to insert large numbers of comments. $this->setCommentsPerPage(1, $field_name); for ($i = 0; $i < 3; $i++) { - $comment = t('Comment @count on field @field', array( + $comment = t('Comment @count on field @field', [ '@count' => $i + 1, '@field' => $field_name, - )); + ]); $comments[] = $this->postComment($node, $comment, $comment, TRUE, $field_name); } } @@ -365,19 +365,19 @@ function testTwoPagers() { $this->assertRaw('Comment 1 on field comment'); $this->assertRaw('Comment 1 on field comment_2'); // Navigate to next page of field 1. - $this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', array(':label' => 'Comment 1 on field comment')); + $this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment']); // Check only one pager updated. $this->assertRaw('Comment 2 on field comment'); $this->assertRaw('Comment 1 on field comment_2'); // Return to page 1. $this->drupalGet('node/' . $node->id()); // Navigate to next page of field 2. - $this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', array(':label' => 'Comment 1 on field comment_2')); + $this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment_2']); // Check only one pager updated. $this->assertRaw('Comment 1 on field comment'); $this->assertRaw('Comment 2 on field comment_2'); // Navigate to next page of field 1. - $this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', array(':label' => 'Comment 1 on field comment')); + $this->clickLinkWithXPath('//h3/a[normalize-space(text())=:label]/ancestor::section[1]//a[@rel="next"]', [':label' => 'Comment 1 on field comment']); // Check only one pager updated. $this->assertRaw('Comment 2 on field comment'); $this->assertRaw('Comment 2 on field comment_2'); @@ -405,15 +405,15 @@ function testTwoPagers() { * * @see WebTestBase::clickLink() */ - protected function clickLinkWithXPath($xpath, $arguments = array(), $index = 0) { + protected function clickLinkWithXPath($xpath, $arguments = [], $index = 0) { $url_before = $this->getUrl(); $urls = $this->xpath($xpath, $arguments); if (isset($urls[$index])) { $url_target = $this->getAbsoluteUrl($urls[$index]['href']); - $this->pass(SafeMarkup::format('Clicked link %label (@url_target) from @url_before', array('%label' => $xpath, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser'); + $this->pass(SafeMarkup::format('Clicked link %label (@url_target) from @url_before', ['%label' => $xpath, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser'); return $this->drupalGet($url_target); } - $this->fail(SafeMarkup::format('Link %label does not exist on @url_before', array('%label' => $xpath, '@url_before' => $url_before)), 'Browser'); + $this->fail(SafeMarkup::format('Link %label does not exist on @url_before', ['%label' => $xpath, '@url_before' => $url_before]), 'Browser'); return FALSE; } diff --git a/core/modules/comment/src/Tests/CommentPreviewTest.php b/core/modules/comment/src/Tests/CommentPreviewTest.php index 837a78aa94..039c6ab10b 100644 --- a/core/modules/comment/src/Tests/CommentPreviewTest.php +++ b/core/modules/comment/src/Tests/CommentPreviewTest.php @@ -41,7 +41,7 @@ function testCommentPreview() { // Test escaping of the username on the preview form. \Drupal::service('module_installer')->install(['user_hooks_test']); \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE); - $edit = array(); + $edit = []; $edit['subject[0][value]'] = $this->randomMachineName(8); $edit['comment_body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview')); @@ -90,7 +90,7 @@ public function testCommentPreviewDuplicateSubmission() { $this->drupalLogin($this->webUser); // As the web user, fill in the comment form and preview the comment. - $edit = array(); + $edit = []; $edit['subject[0][value]'] = $this->randomMachineName(8); $edit['comment_body[0][value]'] = $this->randomMachineName(16); $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Preview')); @@ -124,14 +124,14 @@ public function testCommentPreviewDuplicateSubmission() { * Tests comment edit, preview, and save. */ function testCommentEditPreviewSave() { - $web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'skip comment approval', 'edit own comments')); + $web_user = $this->drupalCreateUser(['access comments', 'post comments', 'skip comment approval', 'edit own comments']); $this->drupalLogin($this->adminUser); $this->setCommentPreview(DRUPAL_OPTIONAL); $this->setCommentForm(TRUE); $this->setCommentSubject(TRUE); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.'); - $edit = array(); + $edit = []; $date = new DrupalDateTime('2008-03-02 17:23'); $edit['subject[0][value]'] = $this->randomMachineName(8); $edit['comment_body[0][value]'] = $this->randomMachineName(16); @@ -172,7 +172,7 @@ function testCommentEditPreviewSave() { $this->assertFieldByName('date[time]', $expected_form_time, 'Time field displayed.'); // Submit the form using the displayed values. - $displayed = array(); + $displayed = []; $displayed['subject[0][value]'] = (string) current($this->xpath("//input[@id='edit-subject-0-value']/@value")); $displayed['comment_body[0][value]'] = (string) current($this->xpath("//textarea[@id='edit-comment-body-0-value']")); $displayed['uid'] = (string) current($this->xpath("//input[@id='edit-uid']/@value")); @@ -182,7 +182,7 @@ function testCommentEditPreviewSave() { // Check that the saved comment is still correct. $comment_storage = \Drupal::entityManager()->getStorage('comment'); - $comment_storage->resetCache(array($comment->id())); + $comment_storage->resetCache([$comment->id()]); /** @var \Drupal\comment\CommentInterface $comment_loaded */ $comment_loaded = Comment::load($comment->id()); $this->assertEqual($comment_loaded->getSubject(), $edit['subject[0][value]'], 'Subject loaded.'); @@ -193,13 +193,13 @@ function testCommentEditPreviewSave() { // Check that the date and time of the comment are correct when edited by // non-admin users. - $user_edit = array(); + $user_edit = []; $expected_created_time = $comment_loaded->getCreatedTime(); $this->drupalLogin($web_user); // Web user cannot change the comment author. unset($edit['uid']); $this->drupalPostForm('comment/' . $comment->id() . '/edit', $user_edit, t('Save')); - $comment_storage->resetCache(array($comment->id())); + $comment_storage->resetCache([$comment->id()]); $comment_loaded = Comment::load($comment->id()); $this->assertEqual($comment_loaded->getCreatedTime(), $expected_created_time, 'Expected date and time for comment edited.'); $this->drupalLogout(); diff --git a/core/modules/comment/src/Tests/CommentRssTest.php b/core/modules/comment/src/Tests/CommentRssTest.php index ec673dfb46..5c9fe3d667 100644 --- a/core/modules/comment/src/Tests/CommentRssTest.php +++ b/core/modules/comment/src/Tests/CommentRssTest.php @@ -21,7 +21,7 @@ class CommentRssTest extends CommentTestBase { * * @var array */ - public static $modules = array('views'); + public static $modules = ['views']; /** * {@inheritdoc} @@ -66,7 +66,7 @@ function testCommentRss() { 'user:3', ])); - $raw = '' . $this->node->url('canonical', array('fragment' => 'comments', 'absolute' => TRUE)) . ''; + $raw = '' . $this->node->url('canonical', ['fragment' => 'comments', 'absolute' => TRUE]) . ''; $this->assertRaw($raw, 'Comments as part of RSS feed.'); // Hide comments from RSS feed and check presence. diff --git a/core/modules/comment/src/Tests/CommentStatisticsTest.php b/core/modules/comment/src/Tests/CommentStatisticsTest.php index 0c370d1127..bd0838ca5d 100644 --- a/core/modules/comment/src/Tests/CommentStatisticsTest.php +++ b/core/modules/comment/src/Tests/CommentStatisticsTest.php @@ -24,7 +24,7 @@ protected function setUp() { parent::setUp(); // Create a second user to post comments. - $this->webUser2 = $this->drupalCreateUser(array( + $this->webUser2 = $this->drupalCreateUser([ 'post comments', 'create article content', 'edit own comments', @@ -32,7 +32,7 @@ protected function setUp() { 'skip comment approval', 'access comments', 'access content', - )); + ]); } /** @@ -62,7 +62,7 @@ function testCommentNodeCommentStatistics() { // Checks the new values of node comment statistics with comment #1. // The node cache needs to be reset before reload. - $node_storage->resetCache(array($this->node->id())); + $node_storage->resetCache([$this->node->id()]); $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is NULL.'); $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is the comment #1 uid.'); @@ -70,11 +70,11 @@ function testCommentNodeCommentStatistics() { // Prepare for anonymous comment submission (comment approval enabled). $this->drupalLogin($this->adminUser); - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => FALSE, - )); + ]); // Ensure that the poster can leave some contact info. $this->setCommentAnonymous('1'); $this->drupalLogout(); @@ -86,7 +86,7 @@ function testCommentNodeCommentStatistics() { // Checks the new values of node comment statistics with comment #2 and // ensure they haven't changed since the comment has not been moderated. // The node needs to be reloaded with the cache reset. - $node_storage->resetCache(array($this->node->id())); + $node_storage->resetCache([$this->node->id()]); $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is still NULL.'); $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is still the comment #1 uid.'); @@ -94,21 +94,21 @@ function testCommentNodeCommentStatistics() { // Prepare for anonymous comment submission (no approval required). $this->drupalLogin($this->adminUser); - user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array( + user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [ 'access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => TRUE, - )); + ]); $this->drupalLogout(); // Post comment #3 as anonymous. $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); - $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', array('name' => $this->randomMachineName())); + $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', ['name' => $this->randomMachineName()]); $comment_loaded = Comment::load($anonymous_comment->id()); // Checks the new values of node comment statistics with comment #3. // The node needs to be reloaded with the cache reset. - $node_storage->resetCache(array($this->node->id())); + $node_storage->resetCache([$this->node->id()]); $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_name, $comment_loaded->getAuthorName(), 'The value of node last_comment_name is the name of the anonymous user.'); $this->assertEqual($node->get('comment')->last_comment_uid, 0, 'The value of node last_comment_uid is zero.'); diff --git a/core/modules/comment/src/Tests/CommentTestBase.php b/core/modules/comment/src/Tests/CommentTestBase.php index c99dd32fc4..716b3bd96f 100644 --- a/core/modules/comment/src/Tests/CommentTestBase.php +++ b/core/modules/comment/src/Tests/CommentTestBase.php @@ -52,11 +52,11 @@ protected function setUp() { // child classes may specify the standard profile. $types = NodeType::loadMultiple(); if (empty($types['article'])) { - $this->drupalCreateContentType(array('type' => 'article', 'name' => t('Article'))); + $this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]); } // Create two test users. - $this->adminUser = $this->drupalCreateUser(array( + $this->adminUser = $this->drupalCreateUser([ 'administer content types', 'administer comments', 'administer comment types', @@ -69,21 +69,21 @@ protected function setUp() { // permission is granted. 'access user profiles', 'access content', - )); - $this->webUser = $this->drupalCreateUser(array( + ]); + $this->webUser = $this->drupalCreateUser([ 'access comments', 'post comments', 'create article content', 'edit own comments', 'skip comment approval', 'access content', - )); + ]); // Create comment field on article. $this->addDefaultCommentField('node', 'article'); // Create a test node authored by the web user. - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id())); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]); $this->drupalPlaceBlock('local_tasks_block'); } @@ -107,7 +107,7 @@ protected function setUp() { * The posted comment or NULL when posted comment was not found. */ public function postComment($entity, $comment, $subject = '', $contact = NULL, $field_name = 'comment') { - $edit = array(); + $edit = []; $edit['comment_body[0][value]'] = $comment; if ($entity !== NULL) { @@ -154,7 +154,7 @@ public function postComment($entity, $comment, $subject = '', $contact = NULL, $ $this->drupalPostForm(NULL, $edit, t('Save')); break; } - $match = array(); + $match = []; // Get comment ID preg_match('/#comment-([0-9]+)/', $this->getURL(), $match); @@ -168,7 +168,7 @@ public function postComment($entity, $comment, $subject = '', $contact = NULL, $ } if (isset($match[1])) { - \Drupal::entityManager()->getStorage('comment')->resetCache(array($match[1])); + \Drupal::entityManager()->getStorage('comment')->resetCache([$match[1]]); return Comment::load($match[1]); } } @@ -215,7 +215,7 @@ function commentExists(CommentInterface $comment = NULL, $reply = FALSE) { * Comment to delete. */ function deleteComment(CommentInterface $comment) { - $this->drupalPostForm('comment/' . $comment->id() . '/delete', array(), t('Delete')); + $this->drupalPostForm('comment/' . $comment->id() . '/delete', [], t('Delete')); $this->assertText(t('The comment and all its replies have been deleted.'), 'Comment deleted.'); } @@ -228,9 +228,9 @@ function deleteComment(CommentInterface $comment) { public function setCommentSubject($enabled) { $form_display = entity_get_form_display('comment', 'comment', 'default'); if ($enabled) { - $form_display->setComponent('subject', array( + $form_display->setComponent('subject', [ 'type' => 'string_textfield', - )); + ]); } else { $form_display->removeComponent('subject'); @@ -263,7 +263,7 @@ public function setCommentPreview($mode, $field_name = 'comment') { $mode_text = 'required'; break; } - $this->setCommentSettings('preview', $mode, format_string('Comment preview @mode_text.', array('@mode_text' => $mode_text)), $field_name); + $this->setCommentSettings('preview', $mode, format_string('Comment preview @mode_text.', ['@mode_text' => $mode_text]), $field_name); } /** @@ -290,7 +290,7 @@ public function setCommentForm($enabled, $field_name = 'comment') { * - 2: Contact information required. */ function setCommentAnonymous($level) { - $this->setCommentSettings('anonymous', $level, format_string('Anonymous commenting set to level @level.', array('@level' => $level))); + $this->setCommentSettings('anonymous', $level, format_string('Anonymous commenting set to level @level.', ['@level' => $level])); } /** @@ -303,7 +303,7 @@ function setCommentAnonymous($level) { * Defaults to 'comment'. */ public function setCommentsPerPage($number, $field_name = 'comment') { - $this->setCommentSettings('per_page', $number, format_string('Number of comments per page set to @number.', array('@number' => $number)), $field_name); + $this->setCommentSettings('per_page', $number, format_string('Number of comments per page set to @number.', ['@number' => $number]), $field_name); } /** @@ -348,17 +348,17 @@ function commentContactInfoAvailable() { * Operation is found on approval page. */ function performCommentOperation(CommentInterface $comment, $operation, $approval = FALSE) { - $edit = array(); + $edit = []; $edit['operation'] = $operation; $edit['comments[' . $comment->id() . ']'] = TRUE; $this->drupalPostForm('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update')); if ($operation == 'delete') { - $this->drupalPostForm(NULL, array(), t('Delete comments')); - $this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation))); + $this->drupalPostForm(NULL, [], t('Delete comments')); + $this->assertRaw(\Drupal::translation()->formatPlural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation])); } else { - $this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', array('@operation' => $operation))); + $this->assertText(t('The update has been performed.'), format_string('Operation "@operation" was performed on comment.', ['@operation' => $operation])); } } @@ -388,12 +388,12 @@ function getUnapprovedComment($subject) { * Created comment type. */ protected function createCommentType($label) { - $bundle = CommentType::create(array( + $bundle = CommentType::create([ 'id' => $label, 'label' => $label, 'description' => '', 'target_entity_type_id' => 'node', - )); + ]); $bundle->save(); return $bundle; } diff --git a/core/modules/comment/src/Tests/CommentTestTrait.php b/core/modules/comment/src/Tests/CommentTestTrait.php index f22d80f893..038a3df091 100644 --- a/core/modules/comment/src/Tests/CommentTestTrait.php +++ b/core/modules/comment/src/Tests/CommentTestTrait.php @@ -43,12 +43,12 @@ public function addDefaultCommentField($entity_type, $bundle, $field_name = 'com } } else { - $comment_type_storage->create(array( + $comment_type_storage->create([ 'id' => $comment_type_id, 'label' => Unicode::ucfirst($comment_type_id), 'target_entity_type_id' => $entity_type, 'description' => 'Default comment field', - ))->save(); + ])->save(); } // Add a body field to the comment type. \Drupal::service('comment.manager')->addBodyField($comment_type_id); @@ -56,43 +56,43 @@ public function addDefaultCommentField($entity_type, $bundle, $field_name = 'com // Add a comment field to the host entity type. Create the field storage if // needed. if (!array_key_exists($field_name, $entity_manager->getFieldStorageDefinitions($entity_type))) { - $entity_manager->getStorage('field_storage_config')->create(array( + $entity_manager->getStorage('field_storage_config')->create([ 'entity_type' => $entity_type, 'field_name' => $field_name, 'type' => 'comment', 'translatable' => TRUE, - 'settings' => array( + 'settings' => [ 'comment_type' => $comment_type_id, - ), - ))->save(); + ], + ])->save(); } // Create the field if needed, and configure its form and view displays. if (!array_key_exists($field_name, $entity_manager->getFieldDefinitions($entity_type, $bundle))) { - $entity_manager->getStorage('field_config')->create(array( + $entity_manager->getStorage('field_config')->create([ 'label' => 'Comments', 'description' => '', 'field_name' => $field_name, 'entity_type' => $entity_type, 'bundle' => $bundle, 'required' => 1, - 'default_value' => array( - array( + 'default_value' => [ + [ 'status' => $default_value, 'cid' => 0, 'last_comment_name' => '', 'last_comment_timestamp' => 0, 'last_comment_uid' => 0, - ), - ), - ))->save(); + ], + ], + ])->save(); // Entity form displays: assign widget settings for the 'default' form // mode, and hide the field in all other form modes. entity_get_form_display($entity_type, $bundle, 'default') - ->setComponent($field_name, array( + ->setComponent($field_name, [ 'type' => 'comment_default', 'weight' => 20, - )) + ]) ->save(); foreach ($entity_manager->getFormModes($entity_type) as $id => $form_mode) { $display = entity_get_form_display($entity_type, $bundle, $id); @@ -105,12 +105,12 @@ public function addDefaultCommentField($entity_type, $bundle, $field_name = 'com // Entity view displays: assign widget settings for the 'default' view // mode, and hide the field in all other view modes. entity_get_display($entity_type, $bundle, 'default') - ->setComponent($field_name, array( + ->setComponent($field_name, [ 'label' => 'above', 'type' => 'comment_default', 'weight' => 20, - 'settings' => array('view_mode' => $comment_view_mode), - )) + 'settings' => ['view_mode' => $comment_view_mode], + ]) ->save(); foreach ($entity_manager->getViewModes($entity_type) as $id => $view_mode) { $display = entity_get_display($entity_type, $bundle, $id); diff --git a/core/modules/comment/src/Tests/CommentThreadingTest.php b/core/modules/comment/src/Tests/CommentThreadingTest.php index c8ea93e276..2dbf5bdea8 100644 --- a/core/modules/comment/src/Tests/CommentThreadingTest.php +++ b/core/modules/comment/src/Tests/CommentThreadingTest.php @@ -24,7 +24,7 @@ function testCommentThreading() { // Create a node. $this->drupalLogin($this->webUser); - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id())); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]); // Post comment #1. $this->drupalLogin($this->webUser); @@ -139,10 +139,10 @@ protected function assertParentLink($cid, $pid) { $this->assertFieldByXpath($pattern, NULL, format_string( 'Comment %cid has a link to parent %pid.', - array( + [ '%cid' => $cid, '%pid' => $pid, - ) + ] )); } @@ -162,9 +162,9 @@ protected function assertNoParentLink($cid) { $pattern = "//a[@id='comment-$cid']/following-sibling::article//p[contains(@class, 'parent')]"; $this->assertNoFieldByXpath($pattern, NULL, format_string( 'Comment %cid does not have a link to a parent.', - array( + [ '%cid' => $cid, - ) + ] )); } diff --git a/core/modules/comment/src/Tests/CommentTitleTest.php b/core/modules/comment/src/Tests/CommentTitleTest.php index aab1cf5ec8..30d39357ba 100644 --- a/core/modules/comment/src/Tests/CommentTitleTest.php +++ b/core/modules/comment/src/Tests/CommentTitleTest.php @@ -14,7 +14,7 @@ class CommentTitleTest extends CommentTestBase { */ public function testCommentEmptyTitles() { // Installs module that sets comments to an empty string. - \Drupal::service('module_installer')->install(array('comment_empty_title_test')); + \Drupal::service('module_installer')->install(['comment_empty_title_test']); // Set comments to have a subject with preview disabled. $this->setCommentPreview(DRUPAL_DISABLED); @@ -23,7 +23,7 @@ public function testCommentEmptyTitles() { // Create a node. $this->drupalLogin($this->webUser); - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id())); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]); // Post comment #1 and verify that h3's are not rendered. $subject_text = $this->randomMachineName(); @@ -49,7 +49,7 @@ public function testCommentPopulatedTitles() { // Create a node. $this->drupalLogin($this->webUser); - $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id())); + $this->node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1, 'uid' => $this->webUser->id()]); // Post comment #1 and verify that title is rendered in h3. $subject_text = $this->randomMachineName(); diff --git a/core/modules/comment/src/Tests/CommentTokenReplaceTest.php b/core/modules/comment/src/Tests/CommentTokenReplaceTest.php index c7b72276a1..325aecb2da 100644 --- a/core/modules/comment/src/Tests/CommentTokenReplaceTest.php +++ b/core/modules/comment/src/Tests/CommentTokenReplaceTest.php @@ -32,10 +32,10 @@ class CommentTokenReplaceTest extends CommentTestBase { function testCommentTokenReplacement() { $token_service = \Drupal::token(); $language_interface = \Drupal::languageManager()->getCurrentLanguage(); - $url_options = array( + $url_options = [ 'absolute' => TRUE, 'language' => $language_interface, - ); + ]; // Setup vocabulary. Vocabulary::create([ @@ -65,7 +65,7 @@ function testCommentTokenReplacement() { $comment->setSubject('Blinking Comment'); // Generate and test tokens. - $tests = array(); + $tests = []; $tests['[comment:cid]'] = $comment->id(); $tests['[comment:hostname]'] = $comment->getHostname(); $tests['[comment:author]'] = Html::escape($comment->getAuthorName()); @@ -74,11 +74,11 @@ function testCommentTokenReplacement() { $tests['[comment:title]'] = Html::escape($comment->getSubject()); $tests['[comment:body]'] = $comment->comment_body->processed; $tests['[comment:langcode]'] = $comment->language()->getId(); - $tests['[comment:url]'] = $comment->url('canonical', $url_options + array('fragment' => 'comment-' . $comment->id())); + $tests['[comment:url]'] = $comment->url('canonical', $url_options + ['fragment' => 'comment-' . $comment->id()]); $tests['[comment:edit-url]'] = $comment->url('edit-form', $url_options); - $tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', array('langcode' => $language_interface->getId())); - $tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), array('langcode' => $language_interface->getId())); - $tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), array('langcode' => $language_interface->getId())); + $tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', ['langcode' => $language_interface->getId()]); + $tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), ['langcode' => $language_interface->getId()]); + $tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), ['langcode' => $language_interface->getId()]); $tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL; $tests['[comment:parent:title]'] = $parent_comment->getSubject(); $tests['[comment:entity]'] = Html::escape($node->getTitle()); @@ -127,7 +127,7 @@ function testCommentTokenReplacement() { foreach ($tests as $input => $expected) { $bubbleable_metadata = new BubbleableMetadata(); - $output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId()), $bubbleable_metadata); + $output = $token_service->replace($input, ['comment' => $comment], ['langcode' => $language_interface->getId()], $bubbleable_metadata); $this->assertEqual($output, $expected, new FormattableMarkup('Comment token %token replaced.', ['%token' => $input])); $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]); } @@ -136,8 +136,8 @@ function testCommentTokenReplacement() { $author_name = 'This is a random & " > string'; $comment->setOwnerId(0)->setAuthorName($author_name); $input = '[comment:author]'; - $output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId())); - $this->assertEqual($output, Html::escape($author_name), format_string('Comment author token %token replaced.', array('%token' => $input))); + $output = $token_service->replace($input, ['comment' => $comment], ['langcode' => $language_interface->getId()]); + $this->assertEqual($output, Html::escape($author_name), format_string('Comment author token %token replaced.', ['%token' => $input])); // Add comment field to user and term entities. $this->addDefaultCommentField('user', 'user', 'comment', CommentItemInterface::OPEN, 'comment_user'); $this->addDefaultCommentField('taxonomy_term', 'tags', 'comment', CommentItemInterface::OPEN, 'comment_term'); @@ -162,7 +162,7 @@ function testCommentTokenReplacement() { // Generate comment tokens for node (it has 2 comments, both new), // user and term. - $tests = array(); + $tests = []; $tests['[entity:comment-count]'] = 2; $tests['[entity:comment-count-new]'] = 2; $tests['[node:comment-count]'] = 2; diff --git a/core/modules/comment/src/Tests/CommentTranslationUITest.php b/core/modules/comment/src/Tests/CommentTranslationUITest.php index e89bd3f318..3157e23bdd 100644 --- a/core/modules/comment/src/Tests/CommentTranslationUITest.php +++ b/core/modules/comment/src/Tests/CommentTranslationUITest.php @@ -46,7 +46,7 @@ class CommentTranslationUITest extends ContentTranslationUITestBase { * * @var array */ - public static $modules = array('language', 'content_translation', 'node', 'comment'); + public static $modules = ['language', 'content_translation', 'node', 'comment']; protected function setUp() { $this->entityTypeId = 'comment'; @@ -62,11 +62,11 @@ protected function setUp() { */ function setupBundle() { parent::setupBundle(); - $this->drupalCreateContentType(array('type' => $this->nodeBundle, 'name' => $this->nodeBundle)); + $this->drupalCreateContentType(['type' => $this->nodeBundle, 'name' => $this->nodeBundle]); // Add a comment field to the article content type. $this->addDefaultCommentField('node', 'article', 'comment_article', CommentItemInterface::OPEN, 'comment_article'); // Create a page content type. - $this->drupalCreateContentType(array('type' => 'page', 'name' => 'page')); + $this->drupalCreateContentType(['type' => 'page', 'name' => 'page']); // Add a comment field to the page content type - this one won't be // translatable. $this->addDefaultCommentField('node', 'page', 'comment'); @@ -78,7 +78,7 @@ function setupBundle() { * {@inheritdoc} */ protected function getTranslatorPermissions() { - return array_merge(parent::getTranslatorPermissions(), array('post comments', 'administer comments', 'access comments')); + return array_merge(parent::getTranslatorPermissions(), ['post comments', 'administer comments', 'access comments']); } /** @@ -95,12 +95,12 @@ protected function createEntity($values, $langcode, $comment_type = 'comment_art $node_type = 'page'; $field_name = 'comment'; } - $node = $this->drupalCreateNode(array( + $node = $this->drupalCreateNode([ 'type' => $node_type, - $field_name => array( - array('status' => CommentItemInterface::OPEN) - ), - )); + $field_name => [ + ['status' => CommentItemInterface::OPEN] + ], + ]); $values['entity_id'] = $node->id(); $values['entity_type'] = 'node'; $values['field_name'] = $field_name; @@ -113,10 +113,10 @@ protected function createEntity($values, $langcode, $comment_type = 'comment_art */ protected function getNewEntityValues($langcode) { // Comment subject is not translatable hence we use a fixed value. - return array( - 'subject' => array(array('value' => $this->subject)), - 'comment_body' => array(array('value' => $this->randomMachineName(16))), - ) + parent::getNewEntityValues($langcode); + return [ + 'subject' => [['value' => $this->subject]], + 'comment_body' => [['value' => $this->randomMachineName(16)]], + ] + parent::getNewEntityValues($langcode); } /** @@ -132,8 +132,8 @@ protected function doTestPublishedStatus() { // Unpublish translations. foreach ($this->langcodes as $index => $langcode) { if ($index > 0) { - $edit = array('status' => 0); - $url = $entity->urlInfo('edit-form', array('language' => ConfigurableLanguage::load($langcode))); + $edit = ['status' => 0]; + $url = $entity->urlInfo('edit-form', ['language' => ConfigurableLanguage::load($langcode)]); $this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode)); $storage->resetCache(); $entity = $storage->load($this->entityId); @@ -151,21 +151,21 @@ protected function doTestAuthoringInfo() { $storage->resetCache([$this->entityId]); $entity = $storage->load($this->entityId); $languages = $this->container->get('language_manager')->getLanguages(); - $values = array(); + $values = []; // Post different authoring information for each translation. foreach ($this->langcodes as $langcode) { $url = $entity->urlInfo('edit-form', ['language' => $languages[$langcode]]); $user = $this->drupalCreateUser(); - $values[$langcode] = array( + $values[$langcode] = [ 'uid' => $user->id(), 'created' => REQUEST_TIME - mt_rand(0, 1000), - ); - $edit = array( + ]; + $edit = [ 'uid' => $user->getUsername() . ' (' . $user->id() . ')', 'date[date]' => format_date($values[$langcode]['created'], 'custom', 'Y-m-d'), 'date[time]' => format_date($values[$langcode]['created'], 'custom', 'H:i:s'), - ); + ]; $this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode)); } @@ -182,11 +182,11 @@ protected function doTestAuthoringInfo() { * Tests translate link on comment content admin page. */ function testTranslateLinkCommentAdminPage() { - $this->adminUser = $this->drupalCreateUser(array_merge(parent::getTranslatorPermissions(), array('access administration pages', 'administer comments', 'skip comment approval'))); + $this->adminUser = $this->drupalCreateUser(array_merge(parent::getTranslatorPermissions(), ['access administration pages', 'administer comments', 'skip comment approval'])); $this->drupalLogin($this->adminUser); - $cid_translatable = $this->createEntity(array(), $this->langcodes[0]); - $cid_untranslatable = $this->createEntity(array(), $this->langcodes[0], 'comment'); + $cid_translatable = $this->createEntity([], $this->langcodes[0]); + $cid_untranslatable = $this->createEntity([], $this->langcodes[0], 'comment'); // Verify translation links. $this->drupalGet('admin/content/comment'); @@ -208,15 +208,15 @@ protected function doTestTranslationEdit() { foreach ($this->langcodes as $langcode) { // We only want to test the title for non-english translations. if ($langcode != 'en') { - $options = array('language' => $languages[$langcode]); + $options = ['language' => $languages[$langcode]]; $url = $entity->urlInfo('edit-form', $options); $this->drupalGet($url); - $title = t('Edit @type @title [%language translation]', array( + $title = t('Edit @type @title [%language translation]', [ '@type' => $this->entityTypeId, '@title' => $entity->getTranslation($langcode)->label(), '%language' => $languages[$langcode]->getName(), - )); + ]); $this->assertRaw($title); } } diff --git a/core/modules/comment/src/Tests/CommentTypeTest.php b/core/modules/comment/src/Tests/CommentTypeTest.php index fb5028f719..343bb9148c 100644 --- a/core/modules/comment/src/Tests/CommentTypeTest.php +++ b/core/modules/comment/src/Tests/CommentTypeTest.php @@ -27,11 +27,11 @@ class CommentTypeTest extends CommentTestBase { * * @var array */ - protected $permissions = array( + protected $permissions = [ 'administer comments', 'administer comment fields', 'administer comment types', - ); + ]; /** * Sets the test up. @@ -61,12 +61,12 @@ public function testCommentTypeCreation() { $this->assertResponse(200, 'The new comment type can be accessed at the edit form.'); // Create a comment type via the user interface. - $edit = array( + $edit = [ 'id' => 'foo', 'label' => 'title for foo', 'description' => '', 'target_entity_type_id' => 'node', - ); + ]; $this->drupalPostForm('admin/structure/comment/types/add', $edit, t('Save')); $comment_type = CommentType::load('foo'); $this->assertTrue($comment_type, 'The new comment type has been created.'); @@ -81,8 +81,8 @@ public function testCommentTypeCreation() { $this->assertText(t('Target entity type')); // Save the form and ensure the entity-type value is preserved even though // the field isn't present. - $this->drupalPostForm(NULL, array(), t('Save')); - \Drupal::entityManager()->getStorage('comment_type')->resetCache(array('foo')); + $this->drupalPostForm(NULL, [], t('Save')); + \Drupal::entityManager()->getStorage('comment_type')->resetCache(['foo']); $comment_type = CommentType::load('foo'); $this->assertEqual($comment_type->getTargetEntityTypeId(), 'node'); } @@ -98,9 +98,9 @@ public function testCommentTypeEditing() { // Change the comment type name. $this->drupalGet('admin/structure/comment'); - $edit = array( + $edit = [ 'label' => 'Bar', - ); + ]; $this->drupalPostForm('admin/structure/comment/manage/comment', $edit, t('Save')); $this->drupalGet('admin/structure/comment'); @@ -110,9 +110,9 @@ public function testCommentTypeEditing() { $this->assertTrue($this->cssSelect('tr#comment-body'), 'Body field exists.'); // Remove the body field. - $this->drupalPostForm('admin/structure/comment/manage/comment/fields/comment.comment.comment_body/delete', array(), t('Delete')); + $this->drupalPostForm('admin/structure/comment/manage/comment/fields/comment.comment.comment_body/delete', [], t('Delete')); // Resave the settings for this type. - $this->drupalPostForm('admin/structure/comment/manage/comment', array(), t('Save')); + $this->drupalPostForm('admin/structure/comment/manage/comment', [], t('Save')); // Check that the body field doesn't exist. $this->drupalGet('admin/structure/comment/manage/comment/fields'); $this->assertFalse($this->cssSelect('tr#comment-body'), 'Body field does not exist.'); @@ -124,39 +124,39 @@ public function testCommentTypeEditing() { public function testCommentTypeDeletion() { // Create a comment type programmatically. $type = $this->createCommentType('foo'); - $this->drupalCreateContentType(array('type' => 'page')); + $this->drupalCreateContentType(['type' => 'page']); $this->addDefaultCommentField('node', 'page', 'foo', CommentItemInterface::OPEN, 'foo'); $field_storage = FieldStorageConfig::loadByName('node', 'foo'); $this->drupalLogin($this->adminUser); // Create a node. - $node = Node::create(array( + $node = Node::create([ 'type' => 'page', 'title' => 'foo', - )); + ]); $node->save(); // Add a new comment of this type. - $comment = Comment::create(array( + $comment = Comment::create([ 'comment_type' => 'foo', 'entity_type' => 'node', 'field_name' => 'foo', 'entity_id' => $node->id(), - )); + ]); $comment->save(); // Attempt to delete the comment type, which should not be allowed. $this->drupalGet('admin/structure/comment/manage/' . $type->id() . '/delete'); $this->assertRaw( - t('%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', array('%label' => $type->label())), + t('%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', ['%label' => $type->label()]), 'The comment type will not be deleted until all comments of that type are removed.' ); $this->assertRaw( - t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', array( + t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', [ '%label' => 'foo', '%field' => 'node.foo', - )), + ]), 'The comment type will not be deleted until all fields of that type are removed.' ); $this->assertNoText(t('This action cannot be undone.'), 'The comment type deletion confirmation form is not available.'); @@ -167,7 +167,7 @@ public function testCommentTypeDeletion() { // Attempt to delete the comment type, which should now be allowed. $this->drupalGet('admin/structure/comment/manage/' . $type->id() . '/delete'); $this->assertRaw( - t('Are you sure you want to delete the comment type %type?', array('%type' => $type->id())), + t('Are you sure you want to delete the comment type %type?', ['%type' => $type->id()]), 'The comment type is available for deletion.' ); $this->assertText(t('This action cannot be undone.'), 'The comment type deletion confirmation form is available.'); @@ -182,9 +182,9 @@ public function testCommentTypeDeletion() { } // Delete the comment type. - $this->drupalPostForm('admin/structure/comment/manage/' . $type->id() . '/delete', array(), t('Delete')); + $this->drupalPostForm('admin/structure/comment/manage/' . $type->id() . '/delete', [], t('Delete')); $this->assertNull(CommentType::load($type->id()), 'Comment type deleted.'); - $this->assertRaw(t('The comment type %label has been deleted.', array('%label' => $type->label()))); + $this->assertRaw(t('The comment type %label has been deleted.', ['%label' => $type->label()])); } } diff --git a/core/modules/comment/src/Tests/CommentUninstallTest.php b/core/modules/comment/src/Tests/CommentUninstallTest.php index 4d86df9479..9f9d36ad01 100644 --- a/core/modules/comment/src/Tests/CommentUninstallTest.php +++ b/core/modules/comment/src/Tests/CommentUninstallTest.php @@ -20,13 +20,13 @@ class CommentUninstallTest extends WebTestBase { * * @var array */ - public static $modules = array('comment', 'node'); + public static $modules = ['comment', 'node']; protected function setUp() { parent::setup(); // Create an article content type. - $this->drupalCreateContentType(array('type' => 'article', 'name' => t('Article'))); + $this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]); // Create comment field on article so that adds 'comment_body' field. $this->addDefaultCommentField('node', 'article'); } @@ -43,7 +43,7 @@ function testCommentUninstallWithField() { // Uninstall the comment module which should trigger an exception. try { - $this->container->get('module_installer')->uninstall(array('comment')); + $this->container->get('module_installer')->uninstall(['comment']); $this->fail("Expected an exception when uninstall was attempted."); } catch (ModuleUninstallValidatorException $e) { @@ -77,7 +77,7 @@ function testCommentUninstallWithoutField() { field_purge_batch(10); // Ensure that uninstallation succeeds even if the field has already been // deleted manually beforehand. - $this->container->get('module_installer')->uninstall(array('comment')); + $this->container->get('module_installer')->uninstall(['comment']); } } diff --git a/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php b/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php index 63a008277c..3365918ff9 100644 --- a/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php +++ b/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php @@ -18,7 +18,7 @@ class ArgumentUserUIDTest extends CommentTestBase { * * @var array */ - public static $testViews = array('test_comment_user_uid'); + public static $testViews = ['test_comment_user_uid']; function testCommentUserUIDTest() { // Add an additional comment which is not created by the user. @@ -35,16 +35,16 @@ function testCommentUserUIDTest() { $comment->save(); $view = Views::getView('test_comment_user_uid'); - $this->executeView($view, array($this->account->id())); - $result_set = array( - array( + $this->executeView($view, [$this->account->id()]); + $result_set = [ + [ 'nid' => $this->nodeUserPosted->id(), - ), - array( + ], + [ 'nid' => $this->nodeUserCommented->id(), - ), - ); - $column_map = array('nid' => 'nid'); + ], + ]; + $column_map = ['nid' => 'nid']; $this->assertIdenticalResultset($view, $result_set, $column_map); } diff --git a/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php b/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php index c0cf374762..040fc7dadb 100644 --- a/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php +++ b/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php @@ -15,21 +15,21 @@ class CommentFieldFilterTest extends CommentTestBase { /** * {@inheritdoc} */ - public static $modules = array('language'); + public static $modules = ['language']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_field_filters'); + public static $testViews = ['test_field_filters']; /** * List of comment titles by language. * * @var array */ - public $commentTitles = array(); + public $commentTitles = []; function setUp() { parent::setUp(); @@ -40,15 +40,15 @@ function setUp() { ConfigurableLanguage::createFromLangcode('es')->save(); // Set up comment titles. - $this->commentTitles = array( + $this->commentTitles = [ 'en' => 'Food in Paris', 'es' => 'Comida en Paris', 'fr' => 'Nouriture en Paris', - ); + ]; // Create a new comment. Using the one created earlier will not work, // as it predates the language set-up. - $comment = array( + $comment = [ 'uid' => $this->loggedInUser->id(), 'entity_id' => $this->nodeUserCommented->id(), 'entity_type' => 'node', @@ -56,7 +56,7 @@ function setUp() { 'cid' => '', 'pid' => '', 'node_type' => '', - ); + ]; $this->comment = Comment::create($comment); // Add field values and translate the comment. @@ -64,8 +64,8 @@ function setUp() { $this->comment->comment_body->value = $this->commentTitles['en']; $this->comment->langcode = 'en'; $this->comment->save(); - foreach (array('es', 'fr') as $langcode) { - $translation = $this->comment->addTranslation($langcode, array()); + foreach (['es', 'fr'] as $langcode) { + $translation = $this->comment->addTranslation($langcode, []); $translation->comment_body->value = $this->commentTitles[$langcode]; $translation->subject->value = $this->commentTitles[$langcode]; } @@ -78,19 +78,19 @@ function setUp() { public function testFilters() { // Test the title filter page, which filters for title contains 'Comida'. // Should show just the Spanish translation, once. - $this->assertPageCounts('test-title-filter', array('es' => 1, 'fr' => 0, 'en' => 0), 'Comida title filter'); + $this->assertPageCounts('test-title-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida title filter'); // Test the body filter page, which filters for body contains 'Comida'. // Should show just the Spanish translation, once. - $this->assertPageCounts('test-body-filter', array('es' => 1, 'fr' => 0, 'en' => 0), 'Comida body filter'); + $this->assertPageCounts('test-body-filter', ['es' => 1, 'fr' => 0, 'en' => 0], 'Comida body filter'); // Test the title Paris filter page, which filters for title contains // 'Paris'. Should show each translation once. - $this->assertPageCounts('test-title-paris', array('es' => 1, 'fr' => 1, 'en' => 1), 'Paris title filter'); + $this->assertPageCounts('test-title-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris title filter'); // Test the body Paris filter page, which filters for body contains // 'Paris'. Should show each translation once. - $this->assertPageCounts('test-body-paris', array('es' => 1, 'fr' => 1, 'en' => 1), 'Paris body filter'); + $this->assertPageCounts('test-body-paris', ['es' => 1, 'fr' => 1, 'en' => 1], 'Paris body filter'); } /** diff --git a/core/modules/comment/src/Tests/Views/CommentRestExportTest.php b/core/modules/comment/src/Tests/Views/CommentRestExportTest.php index a3d7e2dcc2..ed7ce55e35 100644 --- a/core/modules/comment/src/Tests/Views/CommentRestExportTest.php +++ b/core/modules/comment/src/Tests/Views/CommentRestExportTest.php @@ -27,7 +27,7 @@ class CommentRestExportTest extends CommentTestBase { protected function setUp() { parent::setUp(); // Add another anonymous comment. - $comment = array( + $comment = [ 'uid' => 0, 'entity_id' => $this->nodeUserCommented->id(), 'entity_type' => 'node', @@ -38,7 +38,7 @@ protected function setUp() { 'mail' => 'someone@example.com', 'name' => 'bobby tables', 'hostname' => 'public.example.com', - ); + ]; $this->comment = Comment::create($comment); $this->comment->save(); diff --git a/core/modules/comment/src/Tests/Views/CommentRowTest.php b/core/modules/comment/src/Tests/Views/CommentRowTest.php index e96869c0b2..d73811e51e 100644 --- a/core/modules/comment/src/Tests/Views/CommentRowTest.php +++ b/core/modules/comment/src/Tests/Views/CommentRowTest.php @@ -14,7 +14,7 @@ class CommentRowTest extends CommentTestBase { * * @var array */ - public static $testViews = array('test_comment_row'); + public static $testViews = ['test_comment_row']; /** * Test comment row. diff --git a/core/modules/comment/src/Tests/Views/CommentTestBase.php b/core/modules/comment/src/Tests/Views/CommentTestBase.php index d687488b53..d7bec04812 100644 --- a/core/modules/comment/src/Tests/Views/CommentTestBase.php +++ b/core/modules/comment/src/Tests/Views/CommentTestBase.php @@ -19,7 +19,7 @@ * * @var array */ - public static $modules = array('node', 'comment', 'comment_test_views'); + public static $modules = ['node', 'comment', 'comment_test_views']; /** * A normal user with permission to post comments (without approval). @@ -59,21 +59,21 @@ protected function setUp() { parent::setUp(); - ViewTestData::createTestViews(get_class($this), array('comment_test_views')); + ViewTestData::createTestViews(get_class($this), ['comment_test_views']); // Add two users, create a node with the user1 as author and another node // with user2 as author. For the second node add a comment from user1. - $this->account = $this->drupalCreateUser(array('skip comment approval')); + $this->account = $this->drupalCreateUser(['skip comment approval']); $this->account2 = $this->drupalCreateUser(); $this->drupalLogin($this->account); - $this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page'))); + $this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]); $this->addDefaultCommentField('node', 'page'); $this->nodeUserPosted = $this->drupalCreateNode(); - $this->nodeUserCommented = $this->drupalCreateNode(array('uid' => $this->account2->id())); + $this->nodeUserCommented = $this->drupalCreateNode(['uid' => $this->account2->id()]); - $comment = array( + $comment = [ 'uid' => $this->loggedInUser->id(), 'entity_id' => $this->nodeUserCommented->id(), 'entity_type' => 'node', @@ -82,7 +82,7 @@ protected function setUp() { 'cid' => '', 'pid' => '', 'mail' => 'someone@example.com', - ); + ]; $this->comment = Comment::create($comment); $this->comment->save(); } diff --git a/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php b/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php index ff151c68b6..3e5f26b0e8 100644 --- a/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php +++ b/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php @@ -22,7 +22,7 @@ class DefaultViewRecentCommentsTest extends ViewTestBase { * * @var array */ - public static $modules = array('node', 'comment', 'block'); + public static $modules = ['node', 'comment', 'block']; /** * Number of results for the Master display. @@ -50,7 +50,7 @@ class DefaultViewRecentCommentsTest extends ViewTestBase { * * @var array */ - protected $commentsCreated = array(); + protected $commentsCreated = []; /** * Contains the node object used for comments of this test. @@ -66,9 +66,9 @@ protected function setUp() { $content_type = $this->drupalCreateContentType(); // Add a node of the new content type. - $node_data = array( + $node_data = [ 'type' => $content_type->id(), - ); + ]; $this->addDefaultCommentField('node', $content_type->id()); $this->node = $this->drupalCreateNode($node_data); @@ -79,12 +79,12 @@ protected function setUp() { // Create some comments and attach them to the created node. for ($i = 0; $i < $this->masterDisplayResults; $i++) { /** @var \Drupal\comment\CommentInterface $comment */ - $comment = Comment::create(array( + $comment = Comment::create([ 'status' => CommentInterface::PUBLISHED, 'field_name' => 'comment', 'entity_type' => 'node', 'entity_id' => $this->node->id(), - )); + ]); $comment->setOwnerId(0); $comment->setSubject('Test comment ' . $i); $comment->comment_body->value = 'Test body ' . $i; @@ -116,12 +116,12 @@ public function testBlockDisplay() { $view->setDisplay('block_1'); $this->executeView($view); - $map = array( + $map = [ 'subject' => 'subject', 'cid' => 'cid', 'comment_field_data_created' => 'created' - ); - $expected_result = array(); + ]; + $expected_result = []; foreach (array_values($this->commentsCreated) as $key => $comment) { $expected_result[$key]['subject'] = $comment->getSubject(); $expected_result[$key]['cid'] = $comment->id(); @@ -132,7 +132,7 @@ public function testBlockDisplay() { // Check the number of results given by the display is the expected. $this->assertEqual(sizeof($view->result), $this->blockDisplayResults, format_string('There are exactly @results comments. Expected @expected', - array('@results' => count($view->result), '@expected' => $this->blockDisplayResults) + ['@results' => count($view->result), '@expected' => $this->blockDisplayResults] ) ); } diff --git a/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php b/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php index ee8281b50c..c4570cee32 100644 --- a/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php +++ b/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php @@ -20,7 +20,7 @@ class FilterUserUIDTest extends CommentTestBase { * * @var array */ - public static $testViews = array('test_comment_user_uid'); + public static $testViews = ['test_comment_user_uid']; function testCommentUserUIDTest() { $view = Views::getView('test_comment_user_uid'); @@ -40,23 +40,23 @@ function testCommentUserUIDTest() { ]); $comment->save(); - $options = array( + $options = [ 'id' => 'uid_touch', 'table' => 'node_field_data', 'field' => 'uid_touch', - 'value' => array($this->loggedInUser->id()), - ); + 'value' => [$this->loggedInUser->id()], + ]; $view->addHandler('default', 'filter', 'node_field_data', 'uid_touch', $options); - $this->executeView($view, array($this->account->id())); - $result_set = array( - array( + $this->executeView($view, [$this->account->id()]); + $result_set = [ + [ 'nid' => $this->nodeUserPosted->id(), - ), - array( + ], + [ 'nid' => $this->nodeUserCommented->id(), - ), - ); - $column_map = array('nid' => 'nid'); + ], + ]; + $column_map = ['nid' => 'nid']; $this->assertIdenticalResultset($view, $result_set, $column_map); } diff --git a/core/modules/comment/src/Tests/Views/RowRssTest.php b/core/modules/comment/src/Tests/Views/RowRssTest.php index 85bd34fb68..343b797cf5 100644 --- a/core/modules/comment/src/Tests/Views/RowRssTest.php +++ b/core/modules/comment/src/Tests/Views/RowRssTest.php @@ -15,7 +15,7 @@ class RowRssTest extends CommentTestBase { * * @var array */ - public static $testViews = array('test_comment_rss'); + public static $testViews = ['test_comment_rss']; /** * Test comment rss output. diff --git a/core/modules/comment/src/Tests/Views/WizardTest.php b/core/modules/comment/src/Tests/Views/WizardTest.php index 885ce2cf46..a7f14c82ea 100644 --- a/core/modules/comment/src/Tests/Views/WizardTest.php +++ b/core/modules/comment/src/Tests/Views/WizardTest.php @@ -21,7 +21,7 @@ class WizardTest extends WizardTestBase { * * @var array */ - public static $modules = array('node', 'comment'); + public static $modules = ['node', 'comment']; /** @@ -29,7 +29,7 @@ class WizardTest extends WizardTestBase { */ protected function setUp() { parent::setUp(); - $this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page'))); + $this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]); // Add comment field to page node type. $this->addDefaultCommentField('node', 'page'); } @@ -38,7 +38,7 @@ protected function setUp() { * Tests adding a view of comments. */ public function testCommentWizard() { - $view = array(); + $view = []; $view['label'] = $this->randomMachineName(16); $view['id'] = strtolower($this->randomMachineName(16)); $view['show[wizard_key]'] = 'comment'; @@ -48,7 +48,7 @@ public function testCommentWizard() { // Just triggering the saving should automatically choose a proper row // plugin. $this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit')); - $this->assertUrl('admin/structure/views/view/' . $view['id'], array(), 'Make sure the view saving was successful and the browser got redirected to the edit page.'); + $this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.'); // If we update the type first we should get a selection of comment valid // row plugins as the select field. @@ -59,19 +59,19 @@ public function testCommentWizard() { // Check for available options of the row plugin. $xpath = $this->constructFieldXpath('name', 'page[style][row_plugin]'); $fields = $this->xpath($xpath); - $options = array(); + $options = []; foreach ($fields as $field) { $items = $this->getAllOptions($field); foreach ($items as $item) { $options[] = $item->attributes()->value; } } - $expected_options = array('entity:comment', 'fields'); + $expected_options = ['entity:comment', 'fields']; $this->assertEqual($options, $expected_options); $view['id'] = strtolower($this->randomMachineName(16)); $this->drupalPostForm(NULL, $view, t('Save and edit')); - $this->assertUrl('admin/structure/views/view/' . $view['id'], array(), 'Make sure the view saving was successful and the browser got redirected to the edit page.'); + $this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.'); $user = $this->drupalCreateUser(['access comments']); $this->drupalLogin($user); diff --git a/core/modules/comment/tests/modules/comment_test/comment_test.module b/core/modules/comment/tests/modules/comment_test/comment_test.module index d54814ba1c..b1cca02f25 100644 --- a/core/modules/comment/tests/modules/comment_test/comment_test.module +++ b/core/modules/comment/tests/modules/comment_test/comment_test.module @@ -31,14 +31,14 @@ function comment_test_comment_links_alter(array &$links, CommentInterface &$enti return; } - $links['comment_test'] = array( + $links['comment_test'] = [ '#theme' => 'links__comment__comment_test', - '#attributes' => array('class' => array('links', 'inline')), - '#links' => array( - 'comment-report' => array( + '#attributes' => ['class' => ['links', 'inline']], + '#links' => [ + 'comment-report' => [ 'title' => t('Report'), 'url' => Url::fromRoute('comment_test.report', ['comment' => $entity->id()], ['query' => ['token' => \Drupal::getContainer()->get('csrf_token')->get("comment/{$entity->id()}/report")]]), - ), - ), - ); + ], + ], + ]; } diff --git a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php index a95088e941..bdea71df15 100644 --- a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php @@ -26,7 +26,7 @@ class CommentDefaultFormatterCacheTagsTest extends EntityKernelTestBase { * * @var array */ - public static $modules = array('entity_test', 'comment'); + public static $modules = ['entity_test', 'comment']; /** * {@inheritdoc} @@ -48,11 +48,11 @@ protected function setUp() { // user does not have access to the 'administer comments' permission, to // ensure only published comments are visible to the end user. $current_user = $this->container->get('current_user'); - $current_user->setAccount($this->createUser(array(), array('access comments'))); + $current_user->setAccount($this->createUser([], ['access comments'])); // Install tables and config needed to render comments. - $this->installSchema('comment', array('comment_entity_statistics')); - $this->installConfig(array('system', 'filter', 'comment')); + $this->installSchema('comment', ['comment_entity_statistics']); + $this->installConfig(['system', 'filter', 'comment']); // Comment rendering generates links, so build the router. $this->container->get('router.builder')->rebuild(); @@ -70,7 +70,7 @@ public function testCacheTags() { $renderer = $this->container->get('renderer'); // Create the entity that will be commented upon. - $commented_entity = EntityTest::create(array('name' => $this->randomMachineName())); + $commented_entity = EntityTest::create(['name' => $this->randomMachineName()]); $commented_entity->save(); // Verify cache tags on the rendered entity before it has comments. @@ -94,19 +94,19 @@ public function testCacheTags() { // also exists in the {users} table. $user = $this->createUser(); $user->save(); - $comment = Comment::create(array( + $comment = Comment::create([ 'subject' => 'Llama', - 'comment_body' => array( + 'comment_body' => [ 'value' => 'Llamas are cool!', 'format' => 'plain_text', - ), + ], 'entity_id' => $commented_entity->id(), 'entity_type' => 'entity_test', 'field_name' => 'comment', 'comment_type' => 'comment', 'status' => CommentInterface::PUBLISHED, 'uid' => $user->id(), - )); + ]); $comment->save(); // Load commented entity so comment_count gets computed. diff --git a/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php b/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php index 674c7f3e33..5046353302 100644 --- a/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php @@ -29,30 +29,30 @@ class CommentFieldAccessTest extends EntityKernelTestBase { * * @var array */ - public static $modules = array('comment', 'entity_test', 'user'); + public static $modules = ['comment', 'entity_test', 'user']; /** * Fields that only users with administer comments permissions can change. * * @var array */ - protected $administrativeFields = array( + protected $administrativeFields = [ 'uid', 'status', 'created', - ); + ]; /** * These fields are automatically managed and can not be changed by any user. * * @var array */ - protected $readOnlyFields = array( + protected $readOnlyFields = [ 'changed', 'hostname', 'cid', 'thread', - ); + ]; /** * These fields can be edited on create only. @@ -73,19 +73,19 @@ class CommentFieldAccessTest extends EntityKernelTestBase { * * @var array */ - protected $contactFields = array( + protected $contactFields = [ 'name', 'mail', 'homepage', - ); + ]; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); - $this->installConfig(array('user', 'comment')); - $this->installSchema('comment', array('comment_entity_statistics')); + $this->installConfig(['user', 'comment']); + $this->installSchema('comment', ['comment_entity_statistics']); } /** diff --git a/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php b/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php index ed56cc9aed..adbe1b08d5 100644 --- a/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php @@ -18,21 +18,21 @@ class CommentStringIdEntitiesTest extends KernelTestBase { * * @var array */ - public static $modules = array( + public static $modules = [ 'comment', 'user', 'field', 'field_ui', 'entity_test', 'text', - ); + ]; protected function setUp() { parent::setUp(); $this->installEntitySchema('comment'); - $this->installSchema('comment', array('comment_entity_statistics')); + $this->installSchema('comment', ['comment_entity_statistics']); // Create the comment body field storage. - $this->installConfig(array('field')); + $this->installConfig(['field']); } /** @@ -40,21 +40,21 @@ protected function setUp() { */ public function testCommentFieldNonStringId() { try { - $bundle = CommentType::create(array( + $bundle = CommentType::create([ 'id' => 'foo', 'label' => 'foo', 'description' => '', 'target_entity_type_id' => 'entity_test_string_id', - )); + ]); $bundle->save(); - $field_storage = FieldStorageConfig::create(array( + $field_storage = FieldStorageConfig::create([ 'field_name' => 'foo', 'entity_type' => 'entity_test_string_id', - 'settings' => array( + 'settings' => [ 'comment_type' => 'entity_test_string_id', - ), + ], 'type' => 'comment', - )); + ]); $field_storage->save(); $this->fail('Did not throw an exception as expected.'); } diff --git a/core/modules/comment/tests/src/Kernel/CommentValidationTest.php b/core/modules/comment/tests/src/Kernel/CommentValidationTest.php index eb37006ac4..98b771513b 100644 --- a/core/modules/comment/tests/src/Kernel/CommentValidationTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentValidationTest.php @@ -19,14 +19,14 @@ class CommentValidationTest extends EntityKernelTestBase { * * @var array */ - public static $modules = array('comment', 'node'); + public static $modules = ['comment', 'node']; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); - $this->installSchema('comment', array('comment_entity_statistics')); + $this->installSchema('comment', ['comment_entity_statistics']); } /** @@ -34,54 +34,54 @@ protected function setUp() { */ public function testValidation() { // Add a user. - $user = User::create(array('name' => 'test', 'status' => TRUE)); + $user = User::create(['name' => 'test', 'status' => TRUE]); $user->save(); // Add comment type. - $this->entityManager->getStorage('comment_type')->create(array( + $this->entityManager->getStorage('comment_type')->create([ 'id' => 'comment', 'label' => 'comment', 'target_entity_type_id' => 'node', - ))->save(); + ])->save(); // Add comment field to content. - $this->entityManager->getStorage('field_storage_config')->create(array( + $this->entityManager->getStorage('field_storage_config')->create([ 'entity_type' => 'node', 'field_name' => 'comment', 'type' => 'comment', - 'settings' => array( + 'settings' => [ 'comment_type' => 'comment', - ) - ))->save(); + ] + ])->save(); // Create a page node type. - $this->entityManager->getStorage('node_type')->create(array( + $this->entityManager->getStorage('node_type')->create([ 'type' => 'page', 'name' => 'page', - ))->save(); + ])->save(); // Add comment field to page content. /** @var \Drupal\field\FieldConfigInterface $field */ - $field = $this->entityManager->getStorage('field_config')->create(array( + $field = $this->entityManager->getStorage('field_config')->create([ 'field_name' => 'comment', 'entity_type' => 'node', 'bundle' => 'page', 'label' => 'Comment settings', - )); + ]); $field->save(); - $node = $this->entityManager->getStorage('node')->create(array( + $node = $this->entityManager->getStorage('node')->create([ 'type' => 'page', 'title' => 'test', - )); + ]); $node->save(); - $comment = $this->entityManager->getStorage('comment')->create(array( + $comment = $this->entityManager->getStorage('comment')->create([ 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'comment_body' => $this->randomMachineName(), - )); + ]); $violations = $comment->validate(); $this->assertEqual(count($violations), 0, 'No violations when validating a default comment.'); @@ -101,7 +101,7 @@ public function testValidation() { $violations = $comment->validate(); $this->assertEqual(count($violations), 1, "Violation found on author name collision"); $this->assertEqual($violations[0]->getPropertyPath(), "name"); - $this->assertEqual($violations[0]->getMessage(), t('The name you used (%name) belongs to a registered user.', array('%name' => 'test'))); + $this->assertEqual($violations[0]->getMessage(), t('The name you used (%name) belongs to a registered user.', ['%name' => 'test'])); // Make the name valid. $comment->set('name', 'valid unused name'); @@ -141,39 +141,39 @@ public function testValidation() { \Drupal::entityManager()->getStorage('node')->resetCache([$node->id()]); $node = Node::load($node->id()); // Create a new comment with the new field. - $comment = $this->entityManager->getStorage('comment')->create(array( + $comment = $this->entityManager->getStorage('comment')->create([ 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'comment_body' => $this->randomMachineName(), 'uid' => 0, 'name' => '', - )); + ]); $violations = $comment->validate(); $this->assertEqual(count($violations), 1, 'Violation found when name is required, but empty and UID is anonymous.'); $this->assertEqual($violations[0]->getPropertyPath(), 'name'); $this->assertEqual($violations[0]->getMessage(), t('You have to specify a valid author.')); // Test creating a default comment with a given user id works. - $comment = $this->entityManager->getStorage('comment')->create(array( + $comment = $this->entityManager->getStorage('comment')->create([ 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'comment_body' => $this->randomMachineName(), 'uid' => $user->id(), - )); + ]); $violations = $comment->validate(); $this->assertEqual(count($violations), 0, 'No violations when validating a default comment with an author.'); // Test specifying a wrong author name does not work. - $comment = $this->entityManager->getStorage('comment')->create(array( + $comment = $this->entityManager->getStorage('comment')->create([ 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'comment_body' => $this->randomMachineName(), 'uid' => $user->id(), 'name' => 'not-test', - )); + ]); $violations = $comment->validate(); $this->assertEqual(count($violations), 1, 'Violation found when author name and comment author do not match.'); $this->assertEqual($violations[0]->getPropertyPath(), 'name'); @@ -195,7 +195,7 @@ protected function assertLengthViolation(CommentInterface $comment, $field_name, $this->assertEqual(count($violations), 1, "Violation found when $field_name is too long."); $this->assertEqual($violations[0]->getPropertyPath(), "$field_name.0.value"); $field_label = $comment->get($field_name)->getFieldDefinition()->getLabel(); - $this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', array('%name' => $field_label, '@max' => $length))); + $this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => $field_label, '@max' => $length])); } } diff --git a/core/modules/comment/tests/src/Kernel/Migrate/MigrateCommentStubTest.php b/core/modules/comment/tests/src/Kernel/Migrate/MigrateCommentStubTest.php index b5fc4fe34a..0b256ea51a 100644 --- a/core/modules/comment/tests/src/Kernel/Migrate/MigrateCommentStubTest.php +++ b/core/modules/comment/tests/src/Kernel/Migrate/MigrateCommentStubTest.php @@ -33,11 +33,11 @@ protected function setUp() { $storage = \Drupal::entityManager()->getStorage('user'); // Insert a row for the anonymous user. $storage - ->create(array( + ->create([ 'uid' => 0, 'status' => 0, 'name' => '', - )) + ]) ->save(); // Need at least one node type and comment type present. NodeType::create([ diff --git a/core/modules/comment/tests/src/Kernel/Migrate/d7/MigrateCommentTest.php b/core/modules/comment/tests/src/Kernel/Migrate/d7/MigrateCommentTest.php index 4d4df032e4..f1e094f39b 100644 --- a/core/modules/comment/tests/src/Kernel/Migrate/d7/MigrateCommentTest.php +++ b/core/modules/comment/tests/src/Kernel/Migrate/d7/MigrateCommentTest.php @@ -34,11 +34,11 @@ protected function setUp() { $this->executeMigration('d7_node_type'); // We only need the test_content_type node migration to run for real, so // mock all the others. - $this->prepareMigrations(array( - 'd7_node' => array( - array(array(0), array(0)), - ), - )); + $this->prepareMigrations([ + 'd7_node' => [ + [[0], [0]], + ], + ]); $this->executeMigrations([ 'd7_node', 'd7_comment_type', diff --git a/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php b/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php index dae2c480cf..cad7b2b981 100644 --- a/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php +++ b/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php @@ -43,11 +43,11 @@ protected function setUp($import_test_views = TRUE) { $storage = \Drupal::entityManager()->getStorage('user'); // Insert a row for the anonymous user. $storage - ->create(array( + ->create([ 'uid' => 0, 'name' => '', 'status' => 0, - )) + ]) ->save(); $admin_role = Role::create([ diff --git a/core/modules/comment/tests/src/Unit/CommentLinkBuilderTest.php b/core/modules/comment/tests/src/Unit/CommentLinkBuilderTest.php index 61e93a1127..18da223d9a 100644 --- a/core/modules/comment/tests/src/Unit/CommentLinkBuilderTest.php +++ b/core/modules/comment/tests/src/Unit/CommentLinkBuilderTest.php @@ -75,9 +75,9 @@ protected function setUp() { $this->commentManager->expects($this->any()) ->method('getFields') ->with('node') - ->willReturn(array( - 'comment' => array(), - )); + ->willReturn([ + 'comment' => [], + ]); $this->commentManager->expects($this->any()) ->method('forbiddenMessage') ->willReturn("Can't let you do that Dave."); @@ -116,10 +116,10 @@ public function testCommentLinkBuilder(NodeInterface $node, $context, $has_acces ->willReturn($history_exists); $this->currentUser->expects($this->any()) ->method('hasPermission') - ->willReturnMap(array( - array('access comments', $has_access_comments), - array('post comments', $has_post_comments), - )); + ->willReturnMap([ + ['access comments', $has_access_comments], + ['post comments', $has_post_comments], + ]); $this->currentUser->expects($this->any()) ->method('isAuthenticated') ->willReturn(!$is_anonymous); @@ -155,57 +155,57 @@ public function testCommentLinkBuilder(NodeInterface $node, $context, $has_acces * Data provider for ::testCommentLinkBuilder. */ public function getLinkCombinations() { - $cases = array(); + $cases = []; // No links should be created if the entity doesn't have the field. - $cases[] = array( + $cases[] = [ $this->getMockNode(FALSE, CommentItemInterface::OPEN, CommentItemInterface::FORM_BELOW, 1), - array('view_mode' => 'teaser'), + ['view_mode' => 'teaser'], TRUE, TRUE, TRUE, TRUE, - array(), - ); - foreach (array('search_result', 'search_index', 'print') as $view_mode) { + [], + ]; + foreach (['search_result', 'search_index', 'print'] as $view_mode) { // Nothing should be output in these view modes. - $cases[] = array( + $cases[] = [ $this->getMockNode(TRUE, CommentItemInterface::OPEN, CommentItemInterface::FORM_BELOW, 1), - array('view_mode' => $view_mode), + ['view_mode' => $view_mode], TRUE, TRUE, TRUE, TRUE, - array(), - ); + [], + ]; } // All other combinations. - $combinations = array( - 'is_anonymous' => array(FALSE, TRUE), - 'comment_count' => array(0, 1), - 'has_access_comments' => array(0, 1), - 'history_exists' => array(FALSE, TRUE), - 'has_post_comments' => array(0, 1), - 'form_location' => array(CommentItemInterface::FORM_BELOW, CommentItemInterface::FORM_SEPARATE_PAGE), - 'comments' => array( + $combinations = [ + 'is_anonymous' => [FALSE, TRUE], + 'comment_count' => [0, 1], + 'has_access_comments' => [0, 1], + 'history_exists' => [FALSE, TRUE], + 'has_post_comments' => [0, 1], + 'form_location' => [CommentItemInterface::FORM_BELOW, CommentItemInterface::FORM_SEPARATE_PAGE], + 'comments' => [ CommentItemInterface::OPEN, CommentItemInterface::CLOSED, CommentItemInterface::HIDDEN, - ), - 'view_mode' => array( + ], + 'view_mode' => [ 'teaser', 'rss', 'full', - ), - ); + ], + ]; $permutations = TestBase::generatePermutations($combinations); foreach ($permutations as $combination) { - $case = array( + $case = [ $this->getMockNode(TRUE, $combination['comments'], $combination['form_location'], $combination['comment_count']), - array('view_mode' => $combination['view_mode']), + ['view_mode' => $combination['view_mode']], $combination['has_access_comments'], $combination['history_exists'], $combination['has_post_comments'], $combination['is_anonymous'], - ); - $expected = array(); + ]; + $expected = []; // When comments are enabled in teaser mode, and comments exist, and the // user has access - we can output the comment count. if ($combination['comments'] && $combination['view_mode'] == 'teaser' && $combination['comment_count'] && $combination['has_access_comments']) { @@ -225,7 +225,7 @@ public function getLinkCombinations() { // comments exist or the form is on a separate page. if ($combination['view_mode'] == 'teaser' || ($combination['has_access_comments'] && $combination['comment_count']) || $combination['form_location'] == CommentItemInterface::FORM_SEPARATE_PAGE) { // There should be a add comment link. - $expected['comment-add'] = array('title' => 'Add new comment'); + $expected['comment-add'] = ['title' => 'Add new comment']; if ($combination['form_location'] == CommentItemInterface::FORM_BELOW) { // On the same page. $expected['comment-add']['url'] = Url::fromRoute('node.view'); @@ -274,11 +274,11 @@ protected function getMockNode($has_field, $comment_status, $form_location, $com if (empty($this->timestamp)) { $this->timestamp = time(); } - $field_item = (object) array( + $field_item = (object) [ 'status' => $comment_status, 'comment_count' => $comment_count, 'last_comment_timestamp' => $this->timestamp, - ); + ]; $node->expects($this->any()) ->method('get') ->with('comment') @@ -312,7 +312,7 @@ protected function getMockNode($has_field, $comment_status, $form_location, $com ->willReturn($url); $node->expects($this->any()) ->method('url') - ->willReturn(array('route_name' => 'node.view')); + ->willReturn(['route_name' => 'node.view']); return $node; } diff --git a/core/modules/comment/tests/src/Unit/CommentManagerTest.php b/core/modules/comment/tests/src/Unit/CommentManagerTest.php index 78f14bbb1b..3a6e20124b 100644 --- a/core/modules/comment/tests/src/Unit/CommentManagerTest.php +++ b/core/modules/comment/tests/src/Unit/CommentManagerTest.php @@ -32,13 +32,13 @@ public function testGetFields() { $entity_manager->expects($this->once()) ->method('getFieldMapByFieldType') - ->will($this->returnValue(array( - 'node' => array( - 'field_foobar' => array( + ->will($this->returnValue([ + 'node' => [ + 'field_foobar' => [ 'type' => 'comment', - ), - ), - ))); + ], + ], + ])); $entity_manager->expects($this->any()) ->method('getDefinition') diff --git a/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php b/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php index 39b4cf0a07..2a6d379308 100644 --- a/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php +++ b/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php @@ -56,7 +56,7 @@ protected function setUp() { $this->statement->expects($this->any()) ->method('fetchObject') - ->will($this->returnCallback(array($this, 'fetchObjectCallback'))); + ->will($this->returnCallback([$this, 'fetchObjectCallback'])); $this->select = $this->getMockBuilder('Drupal\Core\Database\Query\Select') ->disableOriginalConstructor() @@ -95,8 +95,8 @@ protected function setUp() { */ public function testRead() { $this->calls_to_fetch = 0; - $results = $this->commentStatistics->read(array('1' => 'boo', '2' => 'foo'), 'snafoos'); - $this->assertEquals($results, array('something', 'something-else')); + $results = $this->commentStatistics->read(['1' => 'boo', '2' => 'foo'], 'snafoos'); + $this->assertEquals($results, ['something', 'something-else']); } /** diff --git a/core/modules/comment/tests/src/Unit/Entity/CommentLockTest.php b/core/modules/comment/tests/src/Unit/Entity/CommentLockTest.php index 97c109f0ed..e724dc6b89 100644 --- a/core/modules/comment/tests/src/Unit/Entity/CommentLockTest.php +++ b/core/modules/comment/tests/src/Unit/Entity/CommentLockTest.php @@ -26,7 +26,7 @@ public function testLocks() { $request_stack = new RequestStack(); $request_stack->push(Request::create('/')); $container->set('request_stack', $request_stack); - $container->setParameter('cache_bins', array('cache.test' => 'test')); + $container->setParameter('cache_bins', ['cache.test' => 'test']); $lock = $this->getMock('Drupal\Core\Lock\LockBackendInterface'); $cid = 2; $lock_name = "comment:$cid:.00/"; @@ -84,7 +84,7 @@ public function testLocks() { $comment->expects($this->at(1)) ->method('get') ->with('status') - ->will($this->returnValue((object) array('value' => NULL))); + ->will($this->returnValue((object) ['value' => NULL])); $storage = $this->getMock('Drupal\comment\CommentStorageInterface'); // preSave() should acquire the lock. (This is what's really being tested.) diff --git a/core/modules/comment/tests/src/Unit/Migrate/d6/CommentTestBase.php b/core/modules/comment/tests/src/Unit/Migrate/d6/CommentTestBase.php index 79bae3e3a1..220328be00 100644 --- a/core/modules/comment/tests/src/Unit/Migrate/d6/CommentTestBase.php +++ b/core/modules/comment/tests/src/Unit/Migrate/d6/CommentTestBase.php @@ -14,20 +14,20 @@ const PLUGIN_CLASS = 'Drupal\comment\Plugin\migrate\source\d6\Comment'; // The fake Migration configuration entity. - protected $migrationConfiguration = array( + protected $migrationConfiguration = [ // The ID of the entity, can be any string. 'id' => 'test', // This needs to be the identifier of the actual key: cid for comment, nid // for node and so on. - 'source' => array( + 'source' => [ 'plugin' => 'd6_comment', - ), - ); + ], + ]; // We need to set up the database contents; it's easier to do that below. - protected $expectedResults = array( - array( + protected $expectedResults = [ + [ 'cid' => 1, 'pid' => 0, 'nid' => 2, @@ -43,8 +43,8 @@ 'homepage' => '', 'format' => 'testformat1', 'type' => 'story', - ), - array( + ], + [ 'cid' => 2, 'pid' => 1, 'nid' => 3, @@ -60,8 +60,8 @@ 'homepage' => '', 'format' => 'testformat2', 'type' => 'page', - ), - ); + ], + ]; /** * {@inheritdoc} @@ -72,8 +72,8 @@ protected function setUp() { $this->databaseContents['comments'][$k]['status'] = 1 - $this->databaseContents['comments'][$k]['status']; } // Add node table data. - $this->databaseContents['node'][] = array('nid' => 2, 'type' => 'story'); - $this->databaseContents['node'][] = array('nid' => 3, 'type' => 'page'); + $this->databaseContents['node'][] = ['nid' => 2, 'type' => 'story']; + $this->databaseContents['node'][] = ['nid' => 3, 'type' => 'page']; parent::setUp(); } diff --git a/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariablePerCommentTypeTest.php b/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariablePerCommentTypeTest.php index 75d0932a99..892319a18e 100644 --- a/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariablePerCommentTypeTest.php +++ b/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariablePerCommentTypeTest.php @@ -13,46 +13,46 @@ class CommentVariablePerCommentTypeTest extends MigrateSqlSourceTestCase { const PLUGIN_CLASS = CommentVariablePerCommentType::class; - protected $migrationConfiguration = array( + protected $migrationConfiguration = [ 'id' => 'test', - 'source' => array( + 'source' => [ 'plugin' => 'd6_comment_variable_per_comment_type', - ), - ); + ], + ]; - protected $expectedResults = array( + protected $expectedResults = [ // Each result will also include a label and description, but those are // static values set by the source plugin and don't need to be asserted. - array( + [ 'comment_type' => 'comment', - ), - array( + ], + [ 'comment_type' => 'comment_no_subject', - ), - ); + ], + ]; /** * {@inheritdoc} */ protected function setUp() { - $this->databaseContents['node_type'] = array( - array( + $this->databaseContents['node_type'] = [ + [ 'type' => 'page', - ), - array( + ], + [ 'type' => 'story', - ), - ); - $this->databaseContents['variable'] = array( - array( + ], + ]; + $this->databaseContents['variable'] = [ + [ 'name' => 'comment_subject_field_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_subject_field_story', 'value' => serialize(0), - ), - ); + ], + ]; parent::setUp(); } diff --git a/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariableTest.php b/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariableTest.php index 6d25a2bd3e..406cd11f6f 100644 --- a/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariableTest.php +++ b/core/modules/comment/tests/src/Unit/Migrate/d6/CommentVariableTest.php @@ -13,15 +13,15 @@ class CommentVariableTest extends MigrateSqlSourceTestCase { const PLUGIN_CLASS = CommentVariable::class; - protected $migrationConfiguration = array( + protected $migrationConfiguration = [ 'id' => 'test', - 'source' => array( + 'source' => [ 'plugin' => 'd6_comment_variable', - ), - ); + ], + ]; - protected $expectedResults = array( - array( + protected $expectedResults = [ + [ 'comment' => '1', 'comment_default_mode' => '1', 'comment_default_order' => '1', @@ -33,56 +33,56 @@ class CommentVariableTest extends MigrateSqlSourceTestCase { 'comment_form_location' => '1', 'node_type' => 'page', 'comment_type' => 'comment', - ), - ); + ], + ]; /** * {@inheritdoc} */ protected function setUp() { - $this->databaseContents['node_type'] = array( - array( + $this->databaseContents['node_type'] = [ + [ 'type' => 'page', - ), - ); - $this->databaseContents['variable'] = array( - array( + ], + ]; + $this->databaseContents['variable'] = [ + [ 'name' => 'comment_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_default_mode_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_default_order_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_default_per_page_page', 'value' => serialize(50), - ), - array( + ], + [ 'name' => 'comment_controls_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_anonymous_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_subject_field_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_preview_page', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_form_location_page', 'value' => serialize(1), - ), - ); + ], + ]; parent::setUp(); } diff --git a/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTest.php b/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTest.php index 7793348690..aed2f28550 100644 --- a/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTest.php +++ b/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTest.php @@ -13,15 +13,15 @@ class CommentTest extends MigrateSqlSourceTestCase { const PLUGIN_CLASS = 'Drupal\comment\Plugin\migrate\source\d7\Comment'; - protected $migrationConfiguration = array( + protected $migrationConfiguration = [ 'id' => 'test', - 'source' => array( + 'source' => [ 'plugin' => 'd7_comment', - ), - ); + ], + ]; - protected $expectedResults = array( - array( + protected $expectedResults = [ + [ 'cid' => '1', 'pid' => '0', 'nid' => '1', @@ -36,14 +36,14 @@ class CommentTest extends MigrateSqlSourceTestCase { 'mail' => '', 'homepage' => '', 'language' => 'und', - 'comment_body' => array( - array( + 'comment_body' => [ + [ 'value' => 'This is a comment', 'format' => 'filtered_html', - ), - ), - ), - ); + ], + ], + ], + ]; /** * {@inheritdoc} @@ -52,8 +52,8 @@ protected function setUp() { $this->databaseContents['comment'] = $this->expectedResults; unset($this->databaseContents['comment'][0]['comment_body']); - $this->databaseContents['node'] = array( - array( + $this->databaseContents['node'] = [ + [ 'nid' => '1', 'vid' => '1', 'type' => 'test_content_type', @@ -68,10 +68,10 @@ protected function setUp() { 'sticky' => '0', 'tnid' => '0', 'translate' => '0', - ), - ); - $this->databaseContents['field_config_instance'] = array( - array( + ], + ]; + $this->databaseContents['field_config_instance'] = [ + [ 'id' => '14', 'field_id' => '1', 'field_name' => 'comment_body', @@ -79,10 +79,10 @@ protected function setUp() { 'bundle' => 'comment_node_test_content_type', 'data' => 'a:0:{}', 'deleted' => '0', - ), - ); - $this->databaseContents['field_data_comment_body'] = array( - array( + ], + ]; + $this->databaseContents['field_data_comment_body'] = [ + [ 'entity_type' => 'comment', 'bundle' => 'comment_node_test_content_type', 'deleted' => '0', @@ -92,8 +92,8 @@ protected function setUp() { 'delta' => '0', 'comment_body_value' => 'This is a comment', 'comment_body_format' => 'filtered_html', - ), - ); + ], + ]; parent::setUp(); } diff --git a/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTypeTest.php b/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTypeTest.php index 71c651bbe7..106716d8f2 100644 --- a/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTypeTest.php +++ b/core/modules/comment/tests/src/Unit/Migrate/d7/CommentTypeTest.php @@ -13,15 +13,15 @@ class CommentTypeTest extends MigrateSqlSourceTestCase { const PLUGIN_CLASS = 'Drupal\comment\Plugin\migrate\source\d7\CommentType'; - protected $migrationConfiguration = array( + protected $migrationConfiguration = [ 'id' => 'test', - 'source' => array( + 'source' => [ 'plugin' => 'd7_comment_type', - ), - ); + ], + ]; - protected $expectedResults = array( - array( + protected $expectedResults = [ + [ 'bundle' => 'comment_node_article', 'node_type' => 'article', 'default_mode' => '1', @@ -31,15 +31,15 @@ class CommentTypeTest extends MigrateSqlSourceTestCase { 'preview' => '0', 'subject' => '1', 'label' => 'Article comment', - ), - ); + ], + ]; /** * {@inheritdoc} */ protected function setUp() { - $this->databaseContents['node_type'] = array( - array( + $this->databaseContents['node_type'] = [ + [ 'type' => 'article', 'name' => 'Article', 'base' => 'node_content', @@ -53,10 +53,10 @@ protected function setUp() { 'locked' => '0', 'disabled' => '0', 'orig_type' => 'article', - ), - ); - $this->databaseContents['field_config_instance'] = array( - array( + ], + ]; + $this->databaseContents['field_config_instance'] = [ + [ 'id' => '14', 'field_id' => '1', 'field_name' => 'comment_body', @@ -64,34 +64,34 @@ protected function setUp() { 'bundle' => 'comment_node_article', 'data' => 'a:0:{}', 'deleted' => '0', - ), - ); - $this->databaseContents['variable'] = array( - array( + ], + ]; + $this->databaseContents['variable'] = [ + [ 'name' => 'comment_default_mode_article', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_per_page_article', 'value' => serialize(50), - ), - array( + ], + [ 'name' => 'comment_anonymous_article', 'value' => serialize(0), - ), - array( + ], + [ 'name' => 'comment_form_location_article', 'value' => serialize(1), - ), - array( + ], + [ 'name' => 'comment_preview_article', 'value' => serialize(0), - ), - array( + ], + [ 'name' => 'comment_subject_article', 'value' => serialize(1), - ), - ); + ], + ]; parent::setUp(); } diff --git a/core/modules/config/config.module b/core/modules/config/config.module index 874caac8b5..b280fe84fa 100644 --- a/core/modules/config/config.module +++ b/core/modules/config/config.module @@ -15,19 +15,19 @@ function config_help($route_name, RouteMatchInterface $route_match) { case 'help.page.config': $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Configuration Manager module provides a user interface for importing and exporting configuration changes between installations of your website in different environments. Configuration is stored in YAML format. For more information, see the online documentation for the Configuration Manager module.', array(':url' => 'https://www.drupal.org/documentation/administer/config')) . '

        '; + $output .= '

        ' . t('The Configuration Manager module provides a user interface for importing and exporting configuration changes between installations of your website in different environments. Configuration is stored in YAML format. For more information, see the online documentation for the Configuration Manager module.', [':url' => 'https://www.drupal.org/documentation/administer/config']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Exporting the full configuration') . '
        '; - $output .= '
        ' . t('You can create and download an archive consisting of all your site\'s configuration exported as *.yml files on the Export page.', array(':url' => \Drupal::url('config.export_full'))) . '
        '; + $output .= '
        ' . t('You can create and download an archive consisting of all your site\'s configuration exported as *.yml files on the Export page.', [':url' => \Drupal::url('config.export_full')]) . '
        '; $output .= '
        ' . t('Importing a full configuration') . '
        '; - $output .= '
        ' . t('You can upload a full site configuration from an archive file on the Import page. When importing data from a different environment, the site and import files must have matching configuration values for UUID in the system.site configuration item. That means that your other environments should initially be set up as clones of the target site. Migrations are not supported.', array(':url' => \Drupal::url('config.import_full'))) . '
        '; + $output .= '
        ' . t('You can upload a full site configuration from an archive file on the Import page. When importing data from a different environment, the site and import files must have matching configuration values for UUID in the system.site configuration item. That means that your other environments should initially be set up as clones of the target site. Migrations are not supported.', [':url' => \Drupal::url('config.import_full')]) . '
        '; $output .= '
        ' . t('Synchronizing configuration') . '
        '; - $output .= '
        ' . t('You can review differences between the active configuration and an imported configuration archive on the Synchronize page to ensure that the changes are as expected, before finalizing the import. The Synchronize page also shows configuration items that would be added or removed.', array(':synchronize' => \Drupal::url('config.sync'))) . '
        '; + $output .= '
        ' . t('You can review differences between the active configuration and an imported configuration archive on the Synchronize page to ensure that the changes are as expected, before finalizing the import. The Synchronize page also shows configuration items that would be added or removed.', [':synchronize' => \Drupal::url('config.sync')]) . '
        '; $output .= '
        ' . t('Exporting a single configuration item') . '
        '; - $output .= '
        ' . t('You can export a single configuration item by selecting a Configuration type and Configuration name on the Single export page. The configuration and its corresponding *.yml file name are then displayed on the page for you to copy.', array(':single-export' => \Drupal::url('config.export_single'))) . '
        '; + $output .= '
        ' . t('You can export a single configuration item by selecting a Configuration type and Configuration name on the Single export page. The configuration and its corresponding *.yml file name are then displayed on the page for you to copy.', [':single-export' => \Drupal::url('config.export_single')]) . '
        '; $output .= '
        ' . t('Importing a single configuration item') . '
        '; - $output .= '
        ' . t('You can import a single configuration item by pasting it in YAML format into the form on the Single import page.', array(':single-import' => \Drupal::url('config.import_single'))) . '
        '; + $output .= '
        ' . t('You can import a single configuration item by pasting it in YAML format into the form on the Single import page.', [':single-import' => \Drupal::url('config.import_single')]) . '
        '; $output .= '
        '; return $output; @@ -72,9 +72,9 @@ function config_file_download($uri) { $hostname = str_replace('.', '-', $request->getHttpHost()); $filename = 'config' . '-' . $hostname . '-' . $date_string . '.tar.gz'; $disposition = 'attachment; filename="' . $filename . '"'; - return array( + return [ 'Content-disposition' => $disposition, - ); + ]; } return -1; } diff --git a/core/modules/config/src/ConfigSubscriber.php b/core/modules/config/src/ConfigSubscriber.php index 9b6c842118..aebc86e61c 100644 --- a/core/modules/config/src/ConfigSubscriber.php +++ b/core/modules/config/src/ConfigSubscriber.php @@ -30,7 +30,7 @@ public function onConfigImporterValidate(ConfigImporterEvent $event) { * {@inheritdoc} */ static function getSubscribedEvents() { - $events[ConfigEvents::IMPORT_VALIDATE][] = array('onConfigImporterValidate', 20); + $events[ConfigEvents::IMPORT_VALIDATE][] = ['onConfigImporterValidate', 20]; return $events; } diff --git a/core/modules/config/src/Controller/ConfigController.php b/core/modules/config/src/Controller/ConfigController.php index 8b9dc2541d..bf47f72d4b 100644 --- a/core/modules/config/src/Controller/ConfigController.php +++ b/core/modules/config/src/Controller/ConfigController.php @@ -103,7 +103,7 @@ public function downloadExport() { } } - $request = new Request(array('file' => 'config.tar.gz')); + $request = new Request(['file' => 'config.tar.gz']); return $this->fileDownloadController->download($request, 'temporary'); } @@ -129,34 +129,34 @@ public function diff($source_name, $target_name = NULL, $collection = NULL) { $diff = $this->configManager->diff($this->targetStorage, $this->sourceStorage, $source_name, $target_name, $collection); $this->diffFormatter->show_header = FALSE; - $build = array(); + $build = []; - $build['#title'] = t('View changes of @config_file', array('@config_file' => $source_name)); + $build['#title'] = t('View changes of @config_file', ['@config_file' => $source_name]); // Add the CSS for the inline diff. $build['#attached']['library'][] = 'system/diff'; - $build['diff'] = array( + $build['diff'] = [ '#type' => 'table', - '#attributes' => array( - 'class' => array('diff'), - ), - '#header' => array( - array('data' => t('Active'), 'colspan' => '2'), - array('data' => t('Staged'), 'colspan' => '2'), - ), + '#attributes' => [ + 'class' => ['diff'], + ], + '#header' => [ + ['data' => t('Active'), 'colspan' => '2'], + ['data' => t('Staged'), 'colspan' => '2'], + ], '#rows' => $this->diffFormatter->format($diff), - ); + ]; - $build['back'] = array( + $build['back'] = [ '#type' => 'link', - '#attributes' => array( - 'class' => array( + '#attributes' => [ + 'class' => [ 'dialog-cancel', - ), - ), + ], + ], '#title' => "Back to 'Synchronize configuration' page.", '#url' => Url::fromRoute('config.sync'), - ); + ]; return $build; } diff --git a/core/modules/config/src/Form/ConfigExportForm.php b/core/modules/config/src/Form/ConfigExportForm.php index 0da43ff31c..e822f7fa42 100644 --- a/core/modules/config/src/Form/ConfigExportForm.php +++ b/core/modules/config/src/Form/ConfigExportForm.php @@ -21,10 +21,10 @@ public function getFormId() { * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { - $form['submit'] = array( + $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Export'), - ); + ]; return $form; } diff --git a/core/modules/config/src/Form/ConfigImportForm.php b/core/modules/config/src/Form/ConfigImportForm.php index 1d651d8bf0..0c3def8619 100644 --- a/core/modules/config/src/Form/ConfigImportForm.php +++ b/core/modules/config/src/Form/ConfigImportForm.php @@ -55,17 +55,17 @@ public function buildForm(array $form, FormStateInterface $form_state) { if (!$directory_is_writable) { drupal_set_message($this->t('The directory %directory is not writable.', ['%directory' => $directory]), 'error'); } - $form['import_tarball'] = array( + $form['import_tarball'] = [ '#type' => 'file', '#title' => $this->t('Configuration archive'), - '#description' => $this->t('Allowed types: @extensions.', array('@extensions' => 'tar.gz tgz tar.bz2')), - ); + '#description' => $this->t('Allowed types: @extensions.', ['@extensions' => 'tar.gz tgz tar.bz2']), + ]; - $form['submit'] = array( + $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Upload'), '#disabled' => !$directory_is_writable, - ); + ]; return $form; } @@ -93,7 +93,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $this->configStorage->deleteAll(); try { $archiver = new ArchiveTar($path, 'gz'); - $files = array(); + $files = []; foreach ($archiver->listContent() as $file) { $files[] = $file['filename']; } @@ -102,7 +102,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $form_state->setRedirect('config.sync'); } catch (\Exception $e) { - drupal_set_message($this->t('Could not extract the contents of the tar file. The error message is @message', array('@message' => $e->getMessage())), 'error'); + drupal_set_message($this->t('Could not extract the contents of the tar file. The error message is @message', ['@message' => $e->getMessage()]), 'error'); } drupal_unlink($path); } diff --git a/core/modules/config/src/Form/ConfigSingleExportForm.php b/core/modules/config/src/Form/ConfigSingleExportForm.php index 86f1047e59..8710655d7f 100644 --- a/core/modules/config/src/Form/ConfigSingleExportForm.php +++ b/core/modules/config/src/Form/ConfigSingleExportForm.php @@ -37,7 +37,7 @@ class ConfigSingleExportForm extends FormBase { * * @var \Drupal\Core\Entity\EntityTypeInterface[] */ - protected $definitions = array(); + protected $definitions = []; /** * Constructs a new ConfigSingleImportForm. @@ -83,40 +83,40 @@ public function buildForm(array $form, FormStateInterface $form_state, $config_t }, $this->definitions); // Sort the entity types by label, then add the simple config to the top. uasort($entity_types, 'strnatcasecmp'); - $config_types = array( + $config_types = [ 'system.simple' => $this->t('Simple configuration'), - ) + $entity_types; - $form['config_type'] = array( + ] + $entity_types; + $form['config_type'] = [ '#title' => $this->t('Configuration type'), '#type' => 'select', '#options' => $config_types, '#default_value' => $config_type, - '#ajax' => array( + '#ajax' => [ 'callback' => '::updateConfigurationType', 'wrapper' => 'edit-config-type-wrapper', - ), - ); + ], + ]; $default_type = $form_state->getValue('config_type', $config_type); - $form['config_name'] = array( + $form['config_name'] = [ '#title' => $this->t('Configuration name'), '#type' => 'select', '#options' => $this->findConfiguration($default_type), '#default_value' => $config_name, '#prefix' => '
        ', '#suffix' => '
        ', - '#ajax' => array( + '#ajax' => [ 'callback' => '::updateExport', 'wrapper' => 'edit-export-wrapper', - ), - ); + ], + ]; - $form['export'] = array( + $form['export'] = [ '#title' => $this->t('Here is your configuration:'), '#type' => 'textarea', '#rows' => 24, '#prefix' => '
        ', '#suffix' => '
        ', - ); + ]; if ($config_type && $config_name) { $fake_form_state = (new FormState())->setValues([ 'config_type' => $config_type, @@ -150,7 +150,7 @@ public function updateExport($form, FormStateInterface $form_state) { } // Read the raw data for this config name, encode it, and display it. $form['export']['#value'] = Yaml::encode($this->configStorage->read($name)); - $form['export']['#description'] = $this->t('Filename: %name', array('%name' => $name . '.yml')); + $form['export']['#description'] = $this->t('Filename: %name', ['%name' => $name . '.yml']); return $form['export']; } @@ -158,9 +158,9 @@ public function updateExport($form, FormStateInterface $form_state) { * Handles switching the configuration type selector. */ protected function findConfiguration($config_type) { - $names = array( + $names = [ '' => $this->t('- Select -'), - ); + ]; // For a given entity type, load all entities. if ($config_type && $config_type !== 'system.simple') { $entity_storage = $this->entityManager->getStorage($config_type); diff --git a/core/modules/config/src/Form/ConfigSingleImportForm.php b/core/modules/config/src/Form/ConfigSingleImportForm.php index e217957700..fcb388305e 100644 --- a/core/modules/config/src/Form/ConfigSingleImportForm.php +++ b/core/modules/config/src/Form/ConfigSingleImportForm.php @@ -111,7 +111,7 @@ class ConfigSingleImportForm extends ConfirmFormBase { * * @var array */ - protected $data = array(); + protected $data = []; /** * Constructs a new ConfigSingleImportForm. @@ -198,10 +198,10 @@ public function getQuestion() { $type = $definition->getLowercaseLabel(); } - $args = array( + $args = [ '%name' => $name, '@type' => strtolower($type), - ); + ]; if ($this->configExists) { $question = $this->t('Are you sure you want to update the %name @type?', $args); } @@ -220,7 +220,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { return parent::buildForm($form, $form_state); } - $entity_types = array(); + $entity_types = []; foreach ($this->entityManager->getDefinitions() as $entity_type => $definition) { if ($definition->entityClassImplements(ConfigEntityInterface::class)) { $entity_types[$entity_type] = $definition->getLabel(); @@ -228,49 +228,49 @@ public function buildForm(array $form, FormStateInterface $form_state) { } // Sort the entity types by label, then add the simple config to the top. uasort($entity_types, 'strnatcasecmp'); - $config_types = array( + $config_types = [ 'system.simple' => $this->t('Simple configuration'), - ) + $entity_types; - $form['config_type'] = array( + ] + $entity_types; + $form['config_type'] = [ '#title' => $this->t('Configuration type'), '#type' => 'select', '#options' => $config_types, '#required' => TRUE, - ); - $form['config_name'] = array( + ]; + $form['config_name'] = [ '#title' => $this->t('Configuration name'), '#description' => $this->t('Enter the name of the configuration file without the .yml extension. (e.g. system.site)'), '#type' => 'textfield', - '#states' => array( - 'required' => array( - ':input[name="config_type"]' => array('value' => 'system.simple'), - ), - 'visible' => array( - ':input[name="config_type"]' => array('value' => 'system.simple'), - ), - ), - ); - $form['import'] = array( + '#states' => [ + 'required' => [ + ':input[name="config_type"]' => ['value' => 'system.simple'], + ], + 'visible' => [ + ':input[name="config_type"]' => ['value' => 'system.simple'], + ], + ], + ]; + $form['import'] = [ '#title' => $this->t('Paste your configuration here'), '#type' => 'textarea', '#rows' => 24, '#required' => TRUE, - ); - $form['advanced'] = array( + ]; + $form['advanced'] = [ '#type' => 'details', '#title' => $this->t('Advanced'), - ); - $form['advanced']['custom_entity_id'] = array( + ]; + $form['advanced']['custom_entity_id'] = [ '#title' => $this->t('Custom Entity ID'), '#type' => 'textfield', '#description' => $this->t('Specify a custom entity ID. This will override the entity ID in the configuration above.'), - ); - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + ]; + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Import'), '#button_type' => 'primary', - ); + ]; return $form; } @@ -305,7 +305,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) { $entity_storage = $this->entityManager->getStorage($form_state->getValue('config_type')); // If an entity ID was not specified, set an error. if (!isset($data[$id_key])) { - $form_state->setErrorByName('import', $this->t('Missing ID key "@id_key" for this @entity_type import.', array('@id_key' => $id_key, '@entity_type' => $definition->getLabel()))); + $form_state->setErrorByName('import', $this->t('Missing ID key "@id_key" for this @entity_type import.', ['@id_key' => $id_key, '@entity_type' => $definition->getLabel()])); return; } @@ -323,7 +323,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) { } } // If there is no entity with a matching ID, check for a UUID match. - elseif (isset($data['uuid']) && $entity_storage->loadByProperties(array('uuid' => $data['uuid']))) { + elseif (isset($data['uuid']) && $entity_storage->loadByProperties(['uuid' => $data['uuid']])) { $form_state->setErrorByName('import', $this->t('An entity with this UUID already exists but the machine name does not match.')); } } diff --git a/core/modules/config/src/Form/ConfigSync.php b/core/modules/config/src/Form/ConfigSync.php index 51cded2690..fe1b2e496a 100644 --- a/core/modules/config/src/Form/ConfigSync.php +++ b/core/modules/config/src/Form/ConfigSync.php @@ -171,20 +171,20 @@ public function getFormId() { * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Import all'), - ); + ]; $source_list = $this->syncStorage->listAll(); $storage_comparer = new StorageComparer($this->syncStorage, $this->activeStorage, $this->configManager); if (empty($source_list) || !$storage_comparer->createChangelist()->hasChanges()) { - $form['no_changes'] = array( + $form['no_changes'] = [ '#type' => 'table', - '#header' => array($this->t('Name'), $this->t('Operations')), - '#rows' => array(), + '#header' => [$this->t('Name'), $this->t('Operations')], + '#rows' => [], '#empty' => $this->t('There are no configuration changes to import.'), - ); + ]; $form['actions']['#access'] = FALSE; return $form; } @@ -198,7 +198,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { if ($this->snapshotStorage->exists('core.extension')) { $snapshot_comparer = new StorageComparer($this->activeStorage, $this->snapshotStorage, $this->configManager); if (!$form_state->getUserInput() && $snapshot_comparer->createChangelist()->hasChanges()) { - $change_list = array(); + $change_list = []; foreach ($snapshot_comparer->getAllCollectionNames() as $collection) { foreach ($snapshot_comparer->getChangelist(NULL, $collection) as $config_names) { if (empty($config_names)) { @@ -231,11 +231,11 @@ public function buildForm(array $form, FormStateInterface $form_state) { foreach ($storage_comparer->getAllCollectionNames() as $collection) { if ($collection != StorageInterface::DEFAULT_COLLECTION) { - $form[$collection]['collection_heading'] = array( + $form[$collection]['collection_heading'] = [ '#type' => 'html_tag', '#tag' => 'h2', - '#value' => $this->t('@collection configuration collection', array('@collection' => $collection)), - ); + '#value' => $this->t('@collection configuration collection', ['@collection' => $collection]), + ]; } foreach ($storage_comparer->getChangelist(NULL, $collection) as $config_change_type => $config_names) { if (empty($config_names)) { @@ -244,10 +244,10 @@ public function buildForm(array $form, FormStateInterface $form_state) { // @todo A table caption would be more appropriate, but does not have the // visual importance of a heading. - $form[$collection][$config_change_type]['heading'] = array( + $form[$collection][$config_change_type]['heading'] = [ '#type' => 'html_tag', '#tag' => 'h3', - ); + ]; switch ($config_change_type) { case 'create': $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count new', '@count new'); @@ -265,19 +265,19 @@ public function buildForm(array $form, FormStateInterface $form_state) { $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count renamed', '@count renamed'); break; } - $form[$collection][$config_change_type]['list'] = array( + $form[$collection][$config_change_type]['list'] = [ '#type' => 'table', - '#header' => array($this->t('Name'), $this->t('Operations')), - ); + '#header' => [$this->t('Name'), $this->t('Operations')], + ]; foreach ($config_names as $config_name) { if ($config_change_type == 'rename') { $names = $storage_comparer->extractRenameNames($config_name); - $route_options = array('source_name' => $names['old_name'], 'target_name' => $names['new_name']); - $config_name = $this->t('@source_name to @target_name', array('@source_name' => $names['old_name'], '@target_name' => $names['new_name'])); + $route_options = ['source_name' => $names['old_name'], 'target_name' => $names['new_name']]; + $config_name = $this->t('@source_name to @target_name', ['@source_name' => $names['old_name'], '@target_name' => $names['new_name']]); } else { - $route_options = array('source_name' => $config_name); + $route_options = ['source_name' => $config_name]; } if ($collection != StorageInterface::DEFAULT_COLLECTION) { $route_name = 'config.diff_collection'; @@ -286,26 +286,26 @@ public function buildForm(array $form, FormStateInterface $form_state) { else { $route_name = 'config.diff'; } - $links['view_diff'] = array( + $links['view_diff'] = [ 'title' => $this->t('View differences'), 'url' => Url::fromRoute($route_name, $route_options), - 'attributes' => array( - 'class' => array('use-ajax'), + 'attributes' => [ + 'class' => ['use-ajax'], 'data-dialog-type' => 'modal', - 'data-dialog-options' => json_encode(array( + 'data-dialog-options' => json_encode([ 'width' => 700 - )), - ), - ); - $form[$collection][$config_change_type]['list']['#rows'][] = array( + ]), + ], + ]; + $form[$collection][$config_change_type]['list']['#rows'][] = [ 'name' => $config_name, - 'operations' => array( - 'data' => array( + 'operations' => [ + 'data' => [ '#type' => 'operations', '#links' => $links, - ), - ), - ); + ], + ], + ]; } } } @@ -333,17 +333,17 @@ public function submitForm(array &$form, FormStateInterface $form_state) { else { try { $sync_steps = $config_importer->initialize(); - $batch = array( - 'operations' => array(), - 'finished' => array(get_class($this), 'finishBatch'), + $batch = [ + 'operations' => [], + 'finished' => [get_class($this), 'finishBatch'], 'title' => t('Synchronizing configuration'), 'init_message' => t('Starting configuration synchronization.'), 'progress_message' => t('Completed step @current of @total.'), 'error_message' => t('Configuration synchronization has encountered an error.'), 'file' => __DIR__ . '/../../config.admin.inc', - ); + ]; foreach ($sync_steps as $sync_step) { - $batch['operations'][] = array(array(get_class($this), 'processBatch'), array($config_importer, $sync_step)); + $batch['operations'][] = [[get_class($this), 'processBatch'], [$config_importer, $sync_step]]; } batch_set($batch); @@ -377,7 +377,7 @@ public static function processBatch(ConfigImporter $config_importer, $sync_step, $config_importer->doSyncStep($sync_step, $context); if ($errors = $config_importer->getErrors()) { if (!isset($context['results']['errors'])) { - $context['results']['errors'] = array(); + $context['results']['errors'] = []; } $context['results']['errors'] += $errors; } @@ -406,7 +406,7 @@ public static function finishBatch($success, $results, $operations) { // An error occurred. // $operations contains the operations that remained unprocessed. $error_operation = reset($operations); - $message = \Drupal::translation()->translate('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE))); + $message = \Drupal::translation()->translate('An error occurred while processing %error_operation with arguments: @arguments', ['%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)]); drupal_set_message($message, 'error'); } } diff --git a/core/modules/config/src/Tests/ConfigEntityFormOverrideTest.php b/core/modules/config/src/Tests/ConfigEntityFormOverrideTest.php index 92693c4a9e..41419b031e 100644 --- a/core/modules/config/src/Tests/ConfigEntityFormOverrideTest.php +++ b/core/modules/config/src/Tests/ConfigEntityFormOverrideTest.php @@ -14,7 +14,7 @@ class ConfigEntityFormOverrideTest extends WebTestBase { /** * {@inheritdoc} */ - public static $modules = array('config_test'); + public static $modules = ['config_test']; /** * Tests that overrides do not affect forms or listing screens. @@ -29,10 +29,10 @@ public function testFormsWithOverrides() { $config_test_storage = $this->container->get('entity.manager')->getStorage('config_test'); // Set up an override. - $settings['config']['config_test.dynamic.dotted.default']['label'] = (object) array( + $settings['config']['config_test.dynamic.dotted.default']['label'] = (object) [ 'value' => $overridden_label, 'required' => TRUE, - ); + ]; $this->writeSettings($settings); // Test that the overridden label is loaded with the entity. @@ -50,9 +50,9 @@ public function testFormsWithOverrides() { $this->assertNoText($overridden_label); // Change to a new label and test that the listing now has the edited label. - $edit = array( + $edit = [ 'label' => $edited_label, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); $this->drupalGet('admin/structure/config_test'); $this->assertNoText($overridden_label); diff --git a/core/modules/config/src/Tests/ConfigEntityListTest.php b/core/modules/config/src/Tests/ConfigEntityListTest.php index 9d31de05cb..fbc7ad6a73 100644 --- a/core/modules/config/src/Tests/ConfigEntityListTest.php +++ b/core/modules/config/src/Tests/ConfigEntityListTest.php @@ -50,71 +50,71 @@ function testList() { $this->assertTrue($entity instanceof ConfigTest, '"Default" ConfigTest entity is an instance of ConfigTest.'); // Test getOperations() method. - $expected_operations = array( - 'edit' => array ( + $expected_operations = [ + 'edit' => [ 'title' => t('Edit'), 'weight' => 10, 'url' => $entity->urlInfo(), - ), - 'disable' => array( + ], + 'disable' => [ 'title' => t('Disable'), 'weight' => 40, 'url' => $entity->urlInfo('disable'), - ), - 'delete' => array ( + ], + 'delete' => [ 'title' => t('Delete'), 'weight' => 100, 'url' => $entity->urlInfo('delete-form'), - ), - ); + ], + ]; $actual_operations = $controller->getOperations($entity); // Sort the operations to normalize link order. - uasort($actual_operations, array('Drupal\Component\Utility\SortArray', 'sortByWeightElement')); + uasort($actual_operations, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']); $this->assertEqual($expected_operations, $actual_operations, 'The operations are identical.'); // Test buildHeader() method. - $expected_items = array( + $expected_items = [ 'label' => 'Label', 'id' => 'Machine name', 'operations' => 'Operations', - ); + ]; $actual_items = $controller->buildHeader(); $this->assertEqual($expected_items, $actual_items, 'Return value from buildHeader matches expected.'); // Test buildRow() method. $build_operations = $controller->buildOperations($entity); - $expected_items = array( + $expected_items = [ 'label' => 'Default', 'id' => 'dotted.default', - 'operations' => array( + 'operations' => [ 'data' => $build_operations, - ), - ); + ], + ]; $actual_items = $controller->buildRow($entity); $this->assertEqual($expected_items, $actual_items, 'Return value from buildRow matches expected.'); // Test sorting. $storage = $controller->getStorage(); - $entity = $storage->create(array( + $entity = $storage->create([ 'id' => 'alpha', 'label' => 'Alpha', 'weight' => 1, - )); + ]); $entity->save(); - $entity = $storage->create(array( + $entity = $storage->create([ 'id' => 'omega', 'label' => 'Omega', 'weight' => 1, - )); + ]); $entity->save(); - $entity = $storage->create(array( + $entity = $storage->create([ 'id' => 'beta', 'label' => 'Beta', 'weight' => 0, - )); + ]); $entity->save(); $list = $controller->load(); - $this->assertIdentical(array_keys($list), array('beta', 'dotted.default', 'alpha', 'omega')); + $this->assertIdentical(array_keys($list), ['beta', 'dotted.default', 'alpha', 'omega']); // Test that config entities that do not support status, do not have // enable/disable operations. @@ -125,22 +125,22 @@ function testList() { $entity = $list['default']; // Test getOperations() method. - $expected_operations = array( - 'edit' => array( + $expected_operations = [ + 'edit' => [ 'title' => t('Edit'), 'weight' => 10, 'url' => $entity->urlInfo(), - ), - 'delete' => array( + ], + 'delete' => [ 'title' => t('Delete'), 'weight' => 100, 'url' => $entity->urlInfo('delete-form'), - ), - ); + ], + ]; $actual_operations = $controller->getOperations($entity); // Sort the operations to normalize link order. - uasort($actual_operations, array('Drupal\Component\Utility\SortArray', 'sortByWeightElement')); + uasort($actual_operations, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']); $this->assertEqual($expected_operations, $actual_operations, 'The operations are identical.'); } @@ -149,7 +149,7 @@ function testList() { */ function testListUI() { // Log in as an administrative user to access the full menu trail. - $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer site configuration'))); + $this->drupalLogin($this->drupalCreateUser(['access administration pages', 'administer site configuration'])); // Get the list callback page. $this->drupalGet('admin/structure/config_test'); @@ -166,7 +166,7 @@ function testListUI() { $this->assertEqual(count($elements), 3, 'Correct number of table header cells found.'); // Test the contents of each th cell. - $expected_items = array('Label', 'Machine name', 'Operations'); + $expected_items = ['Label', 'Machine name', 'Operations']; foreach ($elements as $key => $element) { $this->assertIdentical((string) $element[0], $expected_items[$key]); } @@ -186,11 +186,11 @@ function testListUI() { $this->assertLink('Add test configuration'); $this->clickLink('Add test configuration'); $this->assertResponse(200); - $edit = array( + $edit = [ 'label' => 'Antelope', 'id' => 'antelope', 'weight' => 1, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); // Ensure that the entity's sort method was called. @@ -207,7 +207,7 @@ function testListUI() { $this->clickLink('Edit', 1); $this->assertResponse(200); $this->assertTitle('Edit Antelope | Drupal'); - $edit = array('label' => 'Albatross', 'id' => 'albatross'); + $edit = ['label' => 'Albatross', 'id' => 'albatross']; $this->drupalPostForm(NULL, $edit, t('Save')); // Confirm that the user is returned to the listing, and verify that the @@ -221,7 +221,7 @@ function testListUI() { $this->clickLink('Delete', 1); $this->assertResponse(200); $this->assertTitle('Are you sure you want to delete the test configuration Albatross? | Drupal'); - $this->drupalPostForm(NULL, array(), t('Delete')); + $this->drupalPostForm(NULL, [], t('Delete')); // Verify that the text of the label and machine name does not appear in // the list (though it may appear elsewhere on the page). @@ -232,7 +232,7 @@ function testListUI() { $this->clickLink('Delete'); $this->assertResponse(200); $this->assertTitle('Are you sure you want to delete the test configuration Default? | Drupal'); - $this->drupalPostForm(NULL, array(), t('Delete')); + $this->drupalPostForm(NULL, [], t('Delete')); // Verify that the text of the label and machine name does not appear in // the list (though it may appear elsewhere on the page). @@ -253,12 +253,12 @@ public function testPager() { // Create 51 test entities. for ($i = 1; $i < 52; $i++) { - $storage->create(array( + $storage->create([ 'id' => str_pad($i, 2, '0', STR_PAD_LEFT), 'label' => 'Test config entity ' . $i, 'weight' => $i, 'protected_property' => $i, - ))->save(); + ])->save(); } // Load the listing page. diff --git a/core/modules/config/src/Tests/ConfigEntityTest.php b/core/modules/config/src/Tests/ConfigEntityTest.php index a8a8f0f747..77b35cc040 100644 --- a/core/modules/config/src/Tests/ConfigEntityTest.php +++ b/core/modules/config/src/Tests/ConfigEntityTest.php @@ -27,7 +27,7 @@ class ConfigEntityTest extends WebTestBase { * * @var array */ - public static $modules = array('config_test'); + public static $modules = ['config_test']; /** * Tests CRUD operations. @@ -76,9 +76,9 @@ function testCRUD() { } // Verify that an entity with an empty ID string is considered empty, too. - $empty_id = entity_create('config_test', array( + $empty_id = entity_create('config_test', [ 'id' => '', - )); + ]); $this->assertIdentical($empty_id->isNew(), TRUE); try { $empty_id->save(); @@ -89,11 +89,11 @@ function testCRUD() { } // Verify properties on a newly created entity. - $config_test = entity_create('config_test', $expected = array( + $config_test = entity_create('config_test', $expected = [ 'id' => $this->randomMachineName(), 'label' => $this->randomString(), 'style' => $this->randomMachineName(), - )); + ]); $this->assertTrue($config_test->uuid()); $this->assertNotEqual($config_test->uuid(), $empty->uuid()); $this->assertIdentical($config_test->label, $expected['label']); @@ -141,13 +141,13 @@ function testCRUD() { // maximum allowed length, but not longer. // Test with a short ID. - $id_length_config_test = entity_create('config_test', array( + $id_length_config_test = entity_create('config_test', [ 'id' => $this->randomMachineName(8), - )); + ]); try { $id_length_config_test->save(); - $this->pass(SafeMarkup::format("config_test entity with ID length @length was saved.", array( - '@length' => strlen($id_length_config_test->id())) + $this->pass(SafeMarkup::format("config_test entity with ID length @length was saved.", [ + '@length' => strlen($id_length_config_test->id())] )); } catch (ConfigEntityIdLengthException $e) { @@ -155,42 +155,42 @@ function testCRUD() { } // Test with an ID of the maximum allowed length. - $id_length_config_test = entity_create('config_test', array( + $id_length_config_test = entity_create('config_test', [ 'id' => $this->randomMachineName(static::MAX_ID_LENGTH), - )); + ]); try { $id_length_config_test->save(); - $this->pass(SafeMarkup::format("config_test entity with ID length @length was saved.", array( + $this->pass(SafeMarkup::format("config_test entity with ID length @length was saved.", [ '@length' => strlen($id_length_config_test->id()), - ))); + ])); } catch (ConfigEntityIdLengthException $e) { $this->fail($e->getMessage()); } // Test with an ID exceeding the maximum allowed length. - $id_length_config_test = entity_create('config_test', array( + $id_length_config_test = entity_create('config_test', [ 'id' => $this->randomMachineName(static::MAX_ID_LENGTH + 1), - )); + ]); try { $status = $id_length_config_test->save(); - $this->fail(SafeMarkup::format("config_test entity with ID length @length exceeding the maximum allowed length of @max saved successfully", array( + $this->fail(SafeMarkup::format("config_test entity with ID length @length exceeding the maximum allowed length of @max saved successfully", [ '@length' => strlen($id_length_config_test->id()), '@max' => static::MAX_ID_LENGTH, - ))); + ])); } catch (ConfigEntityIdLengthException $e) { - $this->pass(SafeMarkup::format("config_test entity with ID length @length exceeding the maximum allowed length of @max failed to save", array( + $this->pass(SafeMarkup::format("config_test entity with ID length @length exceeding the maximum allowed length of @max failed to save", [ '@length' => strlen($id_length_config_test->id()), '@max' => static::MAX_ID_LENGTH, - ))); + ])); } // Ensure that creating an entity with the same id as an existing one is not // possible. - $same_id = entity_create('config_test', array( + $same_id = entity_create('config_test', [ 'id' => $config_test->id(), - )); + ]); $this->assertIdentical($same_id->isNew(), TRUE); try { $same_id->save(); @@ -201,7 +201,7 @@ function testCRUD() { } // Verify that renaming the ID returns correct status and properties. - $ids = array($expected['id'], 'second_' . $this->randomMachineName(4), 'third_' . $this->randomMachineName(4)); + $ids = [$expected['id'], 'second_' . $this->randomMachineName(4), 'third_' . $this->randomMachineName(4)]; for ($i = 1; $i < 3; $i++) { $old_id = $ids[$i - 1]; $new_id = $ids[$i]; @@ -223,7 +223,7 @@ function testCRUD() { // Test config entity prepopulation. \Drupal::state()->set('config_test.prepopulate', TRUE); - $config_test = entity_create('config_test', array('foo' => 'bar')); + $config_test = entity_create('config_test', ['foo' => 'bar']); $this->assertEqual($config_test->get('foo'), 'baz', 'Initial value correctly populated'); } @@ -237,15 +237,15 @@ function testCRUDUI() { $label1 = $this->randomMachineName(); $label2 = $this->randomMachineName(); $label3 = $this->randomMachineName(); - $message_insert = format_string('%label configuration has been created.', array('%label' => $label1)); - $message_update = format_string('%label configuration has been updated.', array('%label' => $label2)); - $message_delete = format_string('The test configuration %label has been deleted.', array('%label' => $label2)); + $message_insert = format_string('%label configuration has been created.', ['%label' => $label1]); + $message_update = format_string('%label configuration has been updated.', ['%label' => $label2]); + $message_delete = format_string('The test configuration %label has been deleted.', ['%label' => $label2]); // Create a configuration entity. - $edit = array( + $edit = [ 'id' => $id, 'label' => $label1, - ); + ]; $this->drupalPostForm('admin/structure/config_test/add', $edit, 'Save'); $this->assertUrl('admin/structure/config_test'); $this->assertResponse(200); @@ -254,9 +254,9 @@ function testCRUDUI() { $this->assertLinkByHref("admin/structure/config_test/manage/$id"); // Update the configuration entity. - $edit = array( + $edit = [ 'label' => $label2, - ); + ]; $this->drupalPostForm("admin/structure/config_test/manage/$id", $edit, 'Save'); $this->assertUrl('admin/structure/config_test'); $this->assertResponse(200); @@ -269,7 +269,7 @@ function testCRUDUI() { $this->drupalGet("admin/structure/config_test/manage/$id"); $this->clickLink(t('Delete')); $this->assertUrl("admin/structure/config_test/manage/$id/delete"); - $this->drupalPostForm(NULL, array(), 'Delete'); + $this->drupalPostForm(NULL, [], 'Delete'); $this->assertUrl('admin/structure/config_test'); $this->assertResponse(200); $this->assertNoRaw($message_update); @@ -278,10 +278,10 @@ function testCRUDUI() { $this->assertNoLinkByHref("admin/structure/config_test/manage/$id"); // Re-create a configuration entity. - $edit = array( + $edit = [ 'id' => $id, 'label' => $label1, - ); + ]; $this->drupalPostForm('admin/structure/config_test/add', $edit, 'Save'); $this->assertUrl('admin/structure/config_test'); $this->assertResponse(200); @@ -289,10 +289,10 @@ function testCRUDUI() { $this->assertLinkByHref("admin/structure/config_test/manage/$id"); // Rename the configuration entity's ID/machine name. - $edit = array( + $edit = [ 'id' => strtolower($this->randomMachineName()), 'label' => $label3, - ); + ]; $this->drupalPostForm("admin/structure/config_test/manage/$id", $edit, 'Save'); $this->assertUrl('admin/structure/config_test'); $this->assertResponse(200); @@ -304,17 +304,17 @@ function testCRUDUI() { $this->assertLinkByHref("admin/structure/config_test/manage/$id"); // Create a configuration entity with '0' machine name. - $edit = array( + $edit = [ 'id' => '0', 'label' => '0', - ); + ]; $this->drupalPostForm('admin/structure/config_test/add', $edit, 'Save'); $this->assertResponse(200); - $message_insert = format_string('%label configuration has been created.', array('%label' => $edit['label'])); + $message_insert = format_string('%label configuration has been created.', ['%label' => $edit['label']]); $this->assertRaw($message_insert); $this->assertLinkByHref('admin/structure/config_test/manage/0'); $this->assertLinkByHref('admin/structure/config_test/manage/0/delete'); - $this->drupalPostForm('admin/structure/config_test/manage/0/delete', array(), 'Delete'); + $this->drupalPostForm('admin/structure/config_test/manage/0/delete', [], 'Delete'); $this->assertFalse(entity_load('config_test', '0'), 'Test entity deleted'); // Create a configuration entity with a property that uses AJAX to show diff --git a/core/modules/config/src/Tests/ConfigExportImportUITest.php b/core/modules/config/src/Tests/ConfigExportImportUITest.php index 828d4aa07b..9ba59a85ca 100644 --- a/core/modules/config/src/Tests/ConfigExportImportUITest.php +++ b/core/modules/config/src/Tests/ConfigExportImportUITest.php @@ -67,7 +67,7 @@ class ConfigExportImportUITest extends WebTestBase { * * @var array */ - public static $modules = array('config', 'node', 'field'); + public static $modules = ['config', 'node', 'field']; /** * {@inheritdoc} @@ -103,11 +103,11 @@ public function testExportImport() { // Create a field. $this->fieldName = Unicode::strtolower($this->randomMachineName()); - $this->fieldStorage = FieldStorageConfig::create(array( + $this->fieldStorage = FieldStorageConfig::create([ 'field_name' => $this->fieldName, 'entity_type' => 'node', 'type' => 'text', - )); + ]); $this->fieldStorage->save(); FieldConfig::create([ 'field_storage' => $this->fieldStorage, @@ -116,9 +116,9 @@ public function testExportImport() { // Update the displays so that configuration does not change unexpectedly on // import. entity_get_form_display('node', $this->contentType->id(), 'default') - ->setComponent($this->fieldName, array( + ->setComponent($this->fieldName, [ 'type' => 'text_textfield', - )) + ]) ->save(); entity_get_display('node', $this->contentType->id(), 'full') ->setComponent($this->fieldName) @@ -134,7 +134,7 @@ public function testExportImport() { $this->assertFieldByName("{$this->fieldName}[0][value]", '', 'Widget is displayed'); // Export the configuration. - $this->drupalPostForm('admin/config/development/configuration/full/export', array(), 'Export'); + $this->drupalPostForm('admin/config/development/configuration/full/export', [], 'Export'); $this->tarball = $this->getRawContent(); $this->config('system.site') @@ -161,13 +161,13 @@ public function testExportImport() { // Import the configuration. $filename = 'temporary://' . $this->randomMachineName(); file_put_contents($filename, $this->tarball); - $this->drupalPostForm('admin/config/development/configuration/full/import', array('files[import_tarball]' => $filename), 'Upload'); + $this->drupalPostForm('admin/config/development/configuration/full/import', ['files[import_tarball]' => $filename], 'Upload'); // There is no snapshot yet because an import has never run. $this->assertNoText(t('Warning message')); $this->assertNoText(t('There are no configuration changes to import.')); $this->assertText($this->contentType->label()); - $this->drupalPostForm(NULL, array(), 'Import all'); + $this->drupalPostForm(NULL, [], 'Import all'); // After importing the snapshot has been updated an there are no warnings. $this->assertNoText(t('Warning message')); $this->assertText(t('There are no configuration changes to import.')); @@ -217,25 +217,25 @@ public function testExportImportCollections() { /** @var \Drupal\Core\Config\StorageInterface $active_storage */ $active_storage = \Drupal::service('config.storage'); $test1_storage = $active_storage->createCollection('collection.test1'); - $test1_storage->write('config_test.create', array('foo' => 'bar')); - $test1_storage->write('config_test.update', array('foo' => 'bar')); + $test1_storage->write('config_test.create', ['foo' => 'bar']); + $test1_storage->write('config_test.update', ['foo' => 'bar']); $test2_storage = $active_storage->createCollection('collection.test2'); - $test2_storage->write('config_test.another_create', array('foo' => 'bar')); - $test2_storage->write('config_test.another_update', array('foo' => 'bar')); + $test2_storage->write('config_test.another_create', ['foo' => 'bar']); + $test2_storage->write('config_test.another_update', ['foo' => 'bar']); // Export the configuration. - $this->drupalPostForm('admin/config/development/configuration/full/export', array(), 'Export'); + $this->drupalPostForm('admin/config/development/configuration/full/export', [], 'Export'); $this->tarball = $this->getRawContent(); $filename = file_directory_temp() . '/' . $this->randomMachineName(); file_put_contents($filename, $this->tarball); // Set up the active storage collections to test import. $test1_storage->delete('config_test.create'); - $test1_storage->write('config_test.update', array('foo' => 'baz')); - $test1_storage->write('config_test.delete', array('foo' => 'bar')); + $test1_storage->write('config_test.update', ['foo' => 'baz']); + $test1_storage->write('config_test.delete', ['foo' => 'bar']); $test2_storage->delete('config_test.another_create'); - $test2_storage->write('config_test.another_update', array('foo' => 'baz')); - $test2_storage->write('config_test.another_delete', array('foo' => 'bar')); + $test2_storage->write('config_test.another_update', ['foo' => 'baz']); + $test2_storage->write('config_test.another_delete', ['foo' => 'bar']); // Create a snapshot. $snapshot_storage = \Drupal::service('config.storage.snapshot'); @@ -244,22 +244,22 @@ public function testExportImportCollections() { // Ensure that the snapshot has the expected collection data before import. $test1_snapshot = $snapshot_storage->createCollection('collection.test1'); $data = $test1_snapshot->read('config_test.delete'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.delete in collection.test1 exists in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.delete in collection.test1 exists in the snapshot storage.'); $data = $test1_snapshot->read('config_test.update'); - $this->assertEqual($data, array('foo' => 'baz'), 'The config_test.update in collection.test1 exists in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'baz'], 'The config_test.update in collection.test1 exists in the snapshot storage.'); $this->assertFalse($test1_snapshot->read('config_test.create'), 'The config_test.create in collection.test1 does not exist in the snapshot storage.'); $test2_snapshot = $snapshot_storage->createCollection('collection.test2'); $data = $test2_snapshot->read('config_test.another_delete'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.another_delete in collection.test2 exists in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.another_delete in collection.test2 exists in the snapshot storage.'); $data = $test2_snapshot->read('config_test.another_update'); - $this->assertEqual($data, array('foo' => 'baz'), 'The config_test.another_update in collection.test2 exists in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'baz'], 'The config_test.another_update in collection.test2 exists in the snapshot storage.'); $this->assertFalse($test2_snapshot->read('config_test.another_create'), 'The config_test.another_create in collection.test2 does not exist in the snapshot storage.'); // Create the tar that contains the expected content for the collections. $tar = new ArchiveTar($filename, 'gz'); $content_list = $tar->listContent(); // Convert the list of files into something easy to search. - $files = array(); + $files = []; foreach ($content_list as $file) { $files[] = $file['filename']; } @@ -270,12 +270,12 @@ public function testExportImportCollections() { $this->assertFalse(in_array('collection/test1/config_test.delete.yml', $files), 'Config export does not contain collection/test1/config_test.delete.yml.'); $this->assertFalse(in_array('collection/test2/config_test.another_delete.yml', $files), 'Config export does not contain collection/test2/config_test.another_delete.yml.'); - $this->drupalPostForm('admin/config/development/configuration/full/import', array('files[import_tarball]' => $filename), 'Upload'); + $this->drupalPostForm('admin/config/development/configuration/full/import', ['files[import_tarball]' => $filename], 'Upload'); // Verify that there are configuration differences to import. $this->drupalGet('admin/config/development/configuration'); $this->assertNoText(t('There are no configuration changes to import.')); - $this->assertText(t('@collection configuration collection', array('@collection' => 'collection.test1'))); - $this->assertText(t('@collection configuration collection', array('@collection' => 'collection.test2'))); + $this->assertText(t('@collection configuration collection', ['@collection' => 'collection.test1'])); + $this->assertText(t('@collection configuration collection', ['@collection' => 'collection.test2'])); $this->assertText('config_test.create'); $this->assertLinkByHref('admin/config/development/configuration/sync/diff_collection/collection.test1/config_test.create'); $this->assertText('config_test.update'); @@ -289,35 +289,35 @@ public function testExportImportCollections() { $this->assertText('config_test.another_delete'); $this->assertLinkByHref('admin/config/development/configuration/sync/diff_collection/collection.test2/config_test.another_delete'); - $this->drupalPostForm(NULL, array(), 'Import all'); + $this->drupalPostForm(NULL, [], 'Import all'); $this->assertText(t('There are no configuration changes to import.')); // Test data in collections. $data = $test1_storage->read('config_test.create'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.create in collection.test1 has been created.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.create in collection.test1 has been created.'); $data = $test1_storage->read('config_test.update'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.update in collection.test1 has been updated.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.update in collection.test1 has been updated.'); $this->assertFalse($test1_storage->read('config_test.delete'), 'The config_test.delete in collection.test1 has been deleted.'); $data = $test2_storage->read('config_test.another_create'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.another_create in collection.test2 has been created.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.another_create in collection.test2 has been created.'); $data = $test2_storage->read('config_test.another_update'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.another_update in collection.test2 has been updated.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.another_update in collection.test2 has been updated.'); $this->assertFalse($test2_storage->read('config_test.another_delete'), 'The config_test.another_delete in collection.test2 has been deleted.'); // Ensure that the snapshot has been updated with the collection data. $snapshot_storage = \Drupal::service('config.storage.snapshot'); $test1_snapshot = $snapshot_storage->createCollection('collection.test1'); $data = $test1_snapshot->read('config_test.create'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.create in collection.test1 has been created in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.create in collection.test1 has been created in the snapshot storage.'); $data = $test1_snapshot->read('config_test.update'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.update in collection.test1 has been updated in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.update in collection.test1 has been updated in the snapshot storage.'); $this->assertFalse($test1_snapshot->read('config_test.delete'), 'The config_test.delete in collection.test1 does not exist in the snapshot storage.'); $test2_snapshot = $snapshot_storage->createCollection('collection.test2'); $data = $test2_snapshot->read('config_test.another_create'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.another_create in collection.test2 has been created in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.another_create in collection.test2 has been created in the snapshot storage.'); $data = $test2_snapshot->read('config_test.another_update'); - $this->assertEqual($data, array('foo' => 'bar'), 'The config_test.another_update in collection.test2 has been updated in the snapshot storage.'); + $this->assertEqual($data, ['foo' => 'bar'], 'The config_test.another_update in collection.test2 has been updated in the snapshot storage.'); $this->assertFalse($test2_snapshot->read('config_test.another_delete'), 'The config_test.another_delete in collection.test2 does not exist in the snapshot storage.'); } diff --git a/core/modules/config/src/Tests/ConfigExportUITest.php b/core/modules/config/src/Tests/ConfigExportUITest.php index d3133d8dfd..839aa26cad 100644 --- a/core/modules/config/src/Tests/ConfigExportUITest.php +++ b/core/modules/config/src/Tests/ConfigExportUITest.php @@ -18,7 +18,7 @@ class ConfigExportUITest extends WebTestBase { * * @var array */ - public static $modules = array('config', 'config_test'); + public static $modules = ['config', 'config_test']; /** * {@inheritdoc} @@ -27,13 +27,13 @@ protected function setUp() { parent::setUp(); // Set up an override. - $settings['config']['system.maintenance']['message'] = (object) array( + $settings['config']['system.maintenance']['message'] = (object) [ 'value' => 'Foo', 'required' => TRUE, - ); + ]; $this->writeSettings($settings); - $this->drupalLogin($this->drupalCreateUser(array('export configuration'))); + $this->drupalLogin($this->drupalCreateUser(['export configuration'])); } /** @@ -45,7 +45,7 @@ function testExport() { $this->assertFieldById('edit-submit', t('Export')); // Submit the export form and verify response. - $this->drupalPostForm('admin/config/development/configuration/full/export', array(), t('Export')); + $this->drupalPostForm('admin/config/development/configuration/full/export', [], t('Export')); $this->assertResponse(200, 'User can access the download callback.'); // Test if header contains file name with hostname and timestamp. @@ -70,7 +70,7 @@ function testExport() { // Prepare the list of config files from active storage, see // \Drupal\config\Controller\ConfigController::downloadExport(). $storage_active = $this->container->get('config.storage'); - $config_files = array(); + $config_files = []; foreach ($storage_active->listAll() as $config_name) { $config_files[] = $config_name . '.yml'; } @@ -80,7 +80,7 @@ function testExport() { // Ensure the test configuration override is in effect but was not exported. $this->assertIdentical(\Drupal::config('system.maintenance')->get('message'), 'Foo'); - $archiver->extract(file_directory_temp(), array('system.maintenance.yml')); + $archiver->extract(file_directory_temp(), ['system.maintenance.yml']); $file_contents = file_get_contents(file_directory_temp() . '/' . 'system.maintenance.yml'); $exported = Yaml::decode($file_contents); $this->assertNotIdentical($exported['message'], 'Foo'); diff --git a/core/modules/config/src/Tests/ConfigFormOverrideTest.php b/core/modules/config/src/Tests/ConfigFormOverrideTest.php index ffd4428209..f721eeba74 100644 --- a/core/modules/config/src/Tests/ConfigFormOverrideTest.php +++ b/core/modules/config/src/Tests/ConfigFormOverrideTest.php @@ -16,15 +16,15 @@ class ConfigFormOverrideTest extends WebTestBase { * Tests that overrides do not affect forms. */ public function testFormsWithOverrides() { - $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer site configuration'))); + $this->drupalLogin($this->drupalCreateUser(['access administration pages', 'administer site configuration'])); $overridden_name = 'Site name global conf override'; // Set up an override. - $settings['config']['system.site']['name'] = (object) array( + $settings['config']['system.site']['name'] = (object) [ 'value' => $overridden_name, 'required' => TRUE, - ); + ]; $this->writeSettings($settings); // Test that everything on the form is the same, but that the override @@ -35,9 +35,9 @@ public function testFormsWithOverrides() { $this->assertIdentical((string) $elements[0]['value'], 'Drupal'); // Submit the form and ensure the site name is not changed. - $edit = array( + $edit = [ 'site_name' => 'Custom site name', - ); + ]; $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration')); $this->assertTitle('Basic site settings | ' . $overridden_name); $elements = $this->xpath('//input[@name="site_name"]'); diff --git a/core/modules/config/src/Tests/ConfigImportAllTest.php b/core/modules/config/src/Tests/ConfigImportAllTest.php index baeacb966f..459be7a24f 100644 --- a/core/modules/config/src/Tests/ConfigImportAllTest.php +++ b/core/modules/config/src/Tests/ConfigImportAllTest.php @@ -36,7 +36,7 @@ class ConfigImportAllTest extends ModuleTestBase { protected function setUp() { parent::setUp(); - $this->webUser = $this->drupalCreateUser(array('synchronize configuration')); + $this->webUser = $this->drupalCreateUser(['synchronize configuration']); $this->drupalLogin($this->webUser); } @@ -124,12 +124,12 @@ public function testInstallUninstall() { } // Import the configuration thereby re-installing all the modules. - $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all')); + $this->drupalPostForm('admin/config/development/configuration', [], t('Import all')); // Modules have been installed that have services. $this->rebuildContainer(); // Check that there are no errors. - $this->assertIdentical($this->configImporter()->getErrors(), array()); + $this->assertIdentical($this->configImporter()->getErrors(), []); // Check that all modules that were uninstalled are now reinstalled. $this->assertModules(array_keys($modules_to_uninstall), TRUE); diff --git a/core/modules/config/src/Tests/ConfigImportInstallProfileTest.php b/core/modules/config/src/Tests/ConfigImportInstallProfileTest.php index 0c74c7fa10..eaece36db3 100644 --- a/core/modules/config/src/Tests/ConfigImportInstallProfileTest.php +++ b/core/modules/config/src/Tests/ConfigImportInstallProfileTest.php @@ -23,7 +23,7 @@ class ConfigImportInstallProfileTest extends WebTestBase { * * @var array */ - public static $modules = array('config'); + public static $modules = ['config']; /** * A user with the 'synchronize configuration' permission. @@ -35,7 +35,7 @@ class ConfigImportInstallProfileTest extends WebTestBase { protected function setUp() { parent::setUp(); - $this->webUser = $this->drupalCreateUser(array('synchronize configuration')); + $this->webUser = $this->drupalCreateUser(['synchronize configuration']); $this->drupalLogin($this->webUser); $this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync')); } @@ -54,7 +54,7 @@ public function testInstallProfileValidation() { unset($core['module']['testing_config_import']); $sync->write('core.extension', $core); - $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all')); + $this->drupalPostForm('admin/config/development/configuration', [], t('Import all')); $this->assertText('The configuration cannot be imported because it failed validation for the following reasons:'); $this->assertText('Unable to uninstall the Testing config import profile since it is the install profile.'); @@ -69,7 +69,7 @@ public function testInstallProfileValidation() { $theme = $sync->read('system.theme'); $theme['default'] = 'classy'; $sync->write('system.theme', $theme); - $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all')); + $this->drupalPostForm('admin/config/development/configuration', [], t('Import all')); $this->assertText('The configuration was imported successfully.'); $this->rebuildContainer(); $this->assertFalse(\Drupal::moduleHandler()->moduleExists('syslog'), 'The syslog module has been uninstalled.'); diff --git a/core/modules/config/src/Tests/ConfigImportUITest.php b/core/modules/config/src/Tests/ConfigImportUITest.php index afa9b99582..1b63c2abe6 100644 --- a/core/modules/config/src/Tests/ConfigImportUITest.php +++ b/core/modules/config/src/Tests/ConfigImportUITest.php @@ -19,7 +19,7 @@ class ConfigImportUITest extends WebTestBase { * * @var array */ - public static $modules = array('config', 'config_test', 'config_import_test', 'text', 'options'); + public static $modules = ['config', 'config_test', 'config_import_test', 'text', 'options']; /** * A user with the 'synchronize configuration' permission. @@ -31,7 +31,7 @@ class ConfigImportUITest extends WebTestBase { protected function setUp() { parent::setUp(); - $this->webUser = $this->drupalCreateUser(array('synchronize configuration')); + $this->webUser = $this->drupalCreateUser(['synchronize configuration']); $this->drupalLogin($this->webUser); $this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync')); } @@ -55,11 +55,11 @@ function testImport() { $this->assertIdentical($sync->exists($name), TRUE, $name . ' found.'); // Create new config entity. - $original_dynamic_data = array( + $original_dynamic_data = [ 'uuid' => '30df59bd-7b03-4cf7-bb35-d42fc49f0651', 'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(), 'status' => TRUE, - 'dependencies' => array(), + 'dependencies' => [], 'id' => 'new', 'label' => 'New', 'weight' => 0, @@ -67,7 +67,7 @@ function testImport() { 'size' => '', 'size_value' => '', 'protected_property' => '', - ); + ]; $sync->write($dynamic_name, $original_dynamic_data); $this->assertIdentical($sync->exists($dynamic_name), TRUE, $dynamic_name . ' found.'); @@ -102,11 +102,11 @@ function testImport() { // handled correctly. Options depends on Text so Text should be installed // first. Since they were enabled during the test setup the core.extension // file in sync will already contain them. - \Drupal::service('module_installer')->uninstall(array('text', 'options')); + \Drupal::service('module_installer')->uninstall(['text', 'options']); // Set the state system to record installations and uninstallations. - \Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', array()); - \Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', array()); + \Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', []); + \Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', []); // Verify that both appear as ready to import. $this->drupalGet('admin/config/development/configuration'); @@ -118,7 +118,7 @@ function testImport() { $this->assertFieldById('edit-submit', t('Import all')); // Import and verify that both do not appear anymore. - $this->drupalPostForm(NULL, array(), t('Import all')); + $this->drupalPostForm(NULL, [], t('Import all')); $this->assertNoRaw('' . $name); $this->assertNoRaw('' . $dynamic_name); $this->assertNoRaw('core.extension'); @@ -150,9 +150,9 @@ function testImport() { $this->assertTrue($theme_info['bartik']->status, 'Bartik theme installed during import.'); // Ensure installations and uninstallation occur as expected. - $installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', array()); - $uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', array()); - $expected = array('action', 'ban', 'text', 'options'); + $installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', []); + $uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', []); + $expected = ['action', 'ban', 'text', 'options']; $this->assertIdentical($expected, $installed, 'Action, Ban, Text and Options modules installed in the correct order.'); $this->assertTrue(empty($uninstalled), 'No modules uninstalled during import'); @@ -161,8 +161,8 @@ function testImport() { // configuration. This verifies that the module's default configuration is // used during configuration import and, additionally, that after installing // a module, that configuration is not synced twice. - $recursion_limit_values = \Drupal::state()->get('ConfigImportUITest.action.settings.recursion_limit', array()); - $this->assertIdentical($recursion_limit_values, array(50)); + $recursion_limit_values = \Drupal::state()->get('ConfigImportUITest.action.settings.recursion_limit', []); + $this->assertIdentical($recursion_limit_values, [50]); $core_extension = $this->config('core.extension')->get(); unset($core_extension['module']['action']); @@ -180,8 +180,8 @@ function testImport() { $sync->write('system.theme', $system_theme); // Set the state system to record installations and uninstallations. - \Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', array()); - \Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', array()); + \Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', []); + \Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', []); // Verify that both appear as ready to import. $this->drupalGet('admin/config/development/configuration'); @@ -190,7 +190,7 @@ function testImport() { $this->assertRaw('action.settings'); // Import and verify that both do not appear anymore. - $this->drupalPostForm(NULL, array(), t('Import all')); + $this->drupalPostForm(NULL, [], t('Import all')); $this->assertNoRaw('core.extension'); $this->assertNoRaw('system.theme'); $this->assertNoRaw('action.settings'); @@ -203,9 +203,9 @@ function testImport() { $this->assertFalse(\Drupal::moduleHandler()->moduleExists('text'), 'Text module uninstalled during import.'); // Ensure installations and uninstallation occur as expected. - $installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', array()); - $uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', array()); - $expected = array('options', 'text', 'ban', 'action'); + $installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', []); + $uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', []); + $expected = ['options', 'text', 'ban', 'action']; $this->assertIdentical($expected, $uninstalled, 'Options, Text, Ban and Action modules uninstalled in the correct order.'); $this->assertTrue(empty($installed), 'No modules installed during import'); @@ -235,7 +235,7 @@ function testImportLock() { $this->container->get('lock.persistent')->acquire($config_importer::LOCK_NAME); // Attempt to import configuration and verify that an error message appears. - $this->drupalPostForm(NULL, array(), t('Import all')); + $this->drupalPostForm(NULL, [], t('Import all')); $this->assertText(t('Another request may be synchronizing configuration already.')); // Release the lock, just to keep testing sane. @@ -273,11 +273,11 @@ function testImportDiff() { $add_key = 'biff'; $add_data = 'bangpow'; $change_data = '

        foobar

        '; - $original_data = array( + $original_data = [ 'foo' => '

        foobar

        ', 'baz' => 'no change', '404' => 'herp', - ); + ]; // Update active storage to have html in config data. $this->config($config_name)->setData($original_data)->save(); @@ -290,7 +290,7 @@ function testImportDiff() { // Load the diff UI and verify that the diff reflects the change. $this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name); - $this->assertTitle(format_string('View changes of @config_name | Drupal', array('@config_name' => $config_name))); + $this->assertTitle(format_string('View changes of @config_name | Drupal', ['@config_name' => $config_name])); // The following assertions do not use $this::assertEscaped() because // \Drupal\Component\Diff\DiffFormatter adds markup that signifies what has @@ -307,7 +307,7 @@ function testImportDiff() { $this->assertText(Html::escape("404: 'herp'")); // Verify diff colors are displayed. - $result = $this->xpath('//table[contains(@class, :class)]', array(':class' => 'diff')); + $result = $this->xpath('//table[contains(@class, :class)]', [':class' => 'diff']); $this->assertEqual(count($result), 1, "Diff UI is displaying colors."); // Reset data back to original, and remove a key @@ -351,7 +351,7 @@ public function testImportValidation() { $this->drupalGet('admin/config/development/configuration'); $this->assertNoText(t('There are no configuration changes to import.')); - $this->drupalPostForm(NULL, array(), t('Import all')); + $this->drupalPostForm(NULL, [], t('Import all')); // Verify that the validation messages appear. $this->assertText('The configuration cannot be imported because it failed validation for the following reasons:'); @@ -373,7 +373,7 @@ public function testConfigUninstallConfigException() { $this->assertText('core.extension'); // Import and verify that both do not appear anymore. - $this->drupalPostForm(NULL, array(), t('Import all')); + $this->drupalPostForm(NULL, [], t('Import all')); $this->assertText('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.'); } @@ -394,11 +394,11 @@ function testImportErrorLog() { $sync = $this->container->get('config.storage.sync'); $uuid = $this->container->get('uuid'); - $values_primary = array( + $values_primary = [ 'uuid' => $uuid->generate(), 'langcode' => 'en', 'status' => TRUE, - 'dependencies' => array(), + 'dependencies' => [], 'id' => 'primary', 'label' => 'Primary', 'weight' => 0, @@ -406,16 +406,16 @@ function testImportErrorLog() { 'size' => NULL, 'size_value' => NULL, 'protected_property' => NULL, - ); + ]; $sync->write($name_primary, $values_primary); - $values_secondary = array( + $values_secondary = [ 'uuid' => $uuid->generate(), 'langcode' => 'en', 'status' => TRUE, // Add a dependency on primary, to ensure that is synced first. - 'dependencies' => array( - 'config' => array($name_primary), - ), + 'dependencies' => [ + 'config' => [$name_primary], + ], 'id' => 'secondary', 'label' => 'Secondary Sync', 'weight' => 0, @@ -423,15 +423,15 @@ function testImportErrorLog() { 'size' => NULL, 'size_value' => NULL, 'protected_property' => NULL, - ); + ]; $sync->write($name_secondary, $values_secondary); // Verify that there are configuration differences to import. $this->drupalGet('admin/config/development/configuration'); $this->assertNoText(t('There are no configuration changes to import.')); // Attempt to import configuration and verify that an error message appears. - $this->drupalPostForm(NULL, array(), t('Import all')); - $this->assertText(SafeMarkup::format('Deleted and replaced configuration entity "@name"', array('@name' => $name_secondary))); + $this->drupalPostForm(NULL, [], t('Import all')); + $this->assertText(SafeMarkup::format('Deleted and replaced configuration entity "@name"', ['@name' => $name_secondary])); $this->assertText(t('The configuration was imported with errors.')); $this->assertNoText(t('The configuration was imported successfully.')); $this->assertText(t('There are no configuration changes to import.')); @@ -443,42 +443,42 @@ function testImportErrorLog() { * @see \Drupal\Core\Entity\Event\BundleConfigImportValidate */ public function testEntityBundleDelete() { - \Drupal::service('module_installer')->install(array('node')); + \Drupal::service('module_installer')->install(['node']); $this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync')); $node_type = $this->drupalCreateContentType(); - $node = $this->drupalCreateNode(array('type' => $node_type->id())); + $node = $this->drupalCreateNode(['type' => $node_type->id()]); $this->drupalGet('admin/config/development/configuration'); // The node type, body field and entity displays will be scheduled for // removal. - $this->assertText(format_string('node.type.@type', array('@type' => $node_type->id()))); - $this->assertText(format_string('field.field.node.@type.body', array('@type' => $node_type->id()))); - $this->assertText(format_string('core.entity_view_display.node.@type.teaser', array('@type' => $node_type->id()))); - $this->assertText(format_string('core.entity_view_display.node.@type.default', array('@type' => $node_type->id()))); - $this->assertText(format_string('core.entity_form_display.node.@type.default', array('@type' => $node_type->id()))); + $this->assertText(format_string('node.type.@type', ['@type' => $node_type->id()])); + $this->assertText(format_string('field.field.node.@type.body', ['@type' => $node_type->id()])); + $this->assertText(format_string('core.entity_view_display.node.@type.teaser', ['@type' => $node_type->id()])); + $this->assertText(format_string('core.entity_view_display.node.@type.default', ['@type' => $node_type->id()])); + $this->assertText(format_string('core.entity_form_display.node.@type.default', ['@type' => $node_type->id()])); // Attempt to import configuration and verify that an error message appears // and the node type, body field and entity displays are still scheduled for // removal. - $this->drupalPostForm(NULL, array(), t('Import all')); - $validation_message = t('Entities exist of type %entity_type and %bundle_label %bundle. These entities need to be deleted before importing.', array('%entity_type' => $node->getEntityType()->getLabel(), '%bundle_label' => $node->getEntityType()->getBundleLabel(), '%bundle' => $node_type->label())); + $this->drupalPostForm(NULL, [], t('Import all')); + $validation_message = t('Entities exist of type %entity_type and %bundle_label %bundle. These entities need to be deleted before importing.', ['%entity_type' => $node->getEntityType()->getLabel(), '%bundle_label' => $node->getEntityType()->getBundleLabel(), '%bundle' => $node_type->label()]); $this->assertRaw($validation_message); - $this->assertText(format_string('node.type.@type', array('@type' => $node_type->id()))); - $this->assertText(format_string('field.field.node.@type.body', array('@type' => $node_type->id()))); - $this->assertText(format_string('core.entity_view_display.node.@type.teaser', array('@type' => $node_type->id()))); - $this->assertText(format_string('core.entity_view_display.node.@type.default', array('@type' => $node_type->id()))); - $this->assertText(format_string('core.entity_form_display.node.@type.default', array('@type' => $node_type->id()))); + $this->assertText(format_string('node.type.@type', ['@type' => $node_type->id()])); + $this->assertText(format_string('field.field.node.@type.body', ['@type' => $node_type->id()])); + $this->assertText(format_string('core.entity_view_display.node.@type.teaser', ['@type' => $node_type->id()])); + $this->assertText(format_string('core.entity_view_display.node.@type.default', ['@type' => $node_type->id()])); + $this->assertText(format_string('core.entity_form_display.node.@type.default', ['@type' => $node_type->id()])); // Delete the node and try to import again. $node->delete(); - $this->drupalPostForm(NULL, array(), t('Import all')); + $this->drupalPostForm(NULL, [], t('Import all')); $this->assertNoRaw($validation_message); $this->assertText(t('There are no configuration changes to import.')); - $this->assertNoText(format_string('node.type.@type', array('@type' => $node_type->id()))); - $this->assertNoText(format_string('field.field.node.@type.body', array('@type' => $node_type->id()))); - $this->assertNoText(format_string('core.entity_view_display.node.@type.teaser', array('@type' => $node_type->id()))); - $this->assertNoText(format_string('core.entity_view_display.node.@type.default', array('@type' => $node_type->id()))); - $this->assertNoText(format_string('core.entity_form_display.node.@type.default', array('@type' => $node_type->id()))); + $this->assertNoText(format_string('node.type.@type', ['@type' => $node_type->id()])); + $this->assertNoText(format_string('field.field.node.@type.body', ['@type' => $node_type->id()])); + $this->assertNoText(format_string('core.entity_view_display.node.@type.teaser', ['@type' => $node_type->id()])); + $this->assertNoText(format_string('core.entity_view_display.node.@type.default', ['@type' => $node_type->id()])); + $this->assertNoText(format_string('core.entity_form_display.node.@type.default', ['@type' => $node_type->id()])); } /** @@ -508,7 +508,7 @@ public function testExtensionValidation() { $core['theme']['does_not_exist'] = 0; $sync->write('core.extension', $core); - $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all')); + $this->drupalPostForm('admin/config/development/configuration', [], t('Import all')); $this->assertText('The configuration cannot be imported because it failed validation for the following reasons:'); $this->assertText('Unable to uninstall the Text module since the Node module is installed.'); $this->assertText('Unable to uninstall the Classy theme since the Bartik theme is installed.'); diff --git a/core/modules/config/src/Tests/ConfigImportUploadTest.php b/core/modules/config/src/Tests/ConfigImportUploadTest.php index 9836d771dd..9792213a68 100644 --- a/core/modules/config/src/Tests/ConfigImportUploadTest.php +++ b/core/modules/config/src/Tests/ConfigImportUploadTest.php @@ -23,12 +23,12 @@ class ConfigImportUploadTest extends WebTestBase { * * @var array */ - public static $modules = array('config'); + public static $modules = ['config']; protected function setUp() { parent::setUp(); - $this->webUser = $this->drupalCreateUser(array('import configuration')); + $this->webUser = $this->drupalCreateUser(['import configuration']); $this->drupalLogin($this->webUser); } @@ -42,7 +42,7 @@ function testImport() { // Attempt to upload a non-tar file. $text_file = current($this->drupalGetTestFiles('text')); - $edit = array('files[import_tarball]' => drupal_realpath($text_file->uri)); + $edit = ['files[import_tarball]' => drupal_realpath($text_file->uri)]; $this->drupalPostForm('admin/config/development/configuration/full/import', $edit, t('Upload')); $this->assertText(t('Could not extract the contents of the tar file')); diff --git a/core/modules/config/src/Tests/ConfigInstallWebTest.php b/core/modules/config/src/Tests/ConfigInstallWebTest.php index 8f9e1a1b8f..79b50a0a67 100644 --- a/core/modules/config/src/Tests/ConfigInstallWebTest.php +++ b/core/modules/config/src/Tests/ConfigInstallWebTest.php @@ -26,7 +26,7 @@ class ConfigInstallWebTest extends WebTestBase { protected function setUp() { parent::setUp(); - $this->adminUser = $this->drupalCreateUser(array('administer modules', 'administer themes', 'administer site configuration')); + $this->adminUser = $this->drupalCreateUser(['administer modules', 'administer themes', 'administer site configuration']); // Ensure the global variable being asserted by this test does not exist; // a previous test executed in this request/process might have set it. @@ -41,7 +41,7 @@ function testIntegrationModuleReinstallation() { $default_configuration_entity = 'config_test.dynamic.config_integration_test'; // Install the config_test module we're integrating with. - \Drupal::service('module_installer')->install(array('config_test')); + \Drupal::service('module_installer')->install(['config_test']); // Verify the configuration does not exist prior to installation. $config_static = $this->config($default_config); @@ -50,7 +50,7 @@ function testIntegrationModuleReinstallation() { $this->assertIdentical($config_entity->isNew(), TRUE); // Install the integration module. - \Drupal::service('module_installer')->install(array('config_integration_test')); + \Drupal::service('module_installer')->install(['config_integration_test']); // Verify that default module config exists. \Drupal::configFactory()->reset($default_config); @@ -73,7 +73,7 @@ function testIntegrationModuleReinstallation() { $this->container->get('config.factory')->reset(); // Disable and uninstall the integration module. - $this->container->get('module_installer')->uninstall(array('config_integration_test')); + $this->container->get('module_installer')->uninstall(['config_integration_test']); // Verify the integration module's config was uninstalled. $config_static = $this->config($default_config); @@ -86,7 +86,7 @@ function testIntegrationModuleReinstallation() { // Reinstall the integration module. try { - \Drupal::service('module_installer')->install(array('config_integration_test')); + \Drupal::service('module_installer')->install(['config_integration_test']); $this->fail('Expected PreExistingConfigException not thrown.'); } catch (PreExistingConfigException $e) { @@ -97,7 +97,7 @@ function testIntegrationModuleReinstallation() { // Delete the configuration entity so that the install will work. $config_entity->delete(); - \Drupal::service('module_installer')->install(array('config_integration_test')); + \Drupal::service('module_installer')->install(['config_integration_test']); // Verify the integration module's config was re-installed. \Drupal::configFactory()->reset($default_config); @@ -122,19 +122,19 @@ public function testPreExistingConfigInstall() { // will install the config_test module first because it is a dependency of // config_install_fail_test. // @see \Drupal\system\Form\ModulesListForm::submitForm() - $this->drupalPostForm('admin/modules', array('modules[config_test][enable]' => TRUE, 'modules[config_install_fail_test][enable]' => TRUE), t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_test][enable]' => TRUE, 'modules[config_install_fail_test][enable]' => TRUE], t('Install')); $this->assertRaw('Unable to install Configuration install fail test, config_test.dynamic.dotted.default already exists in active configuration.'); // Uninstall the config_test module to test the confirm form. - $this->drupalPostForm('admin/modules/uninstall', array('uninstall[config_test]' => TRUE), t('Uninstall')); - $this->drupalPostForm(NULL, array(), t('Uninstall')); + $this->drupalPostForm('admin/modules/uninstall', ['uninstall[config_test]' => TRUE], t('Uninstall')); + $this->drupalPostForm(NULL, [], t('Uninstall')); // Try to install config_install_fail_test without selecting config_test. // The user is shown a confirm form because the config_test module is a // dependency. // @see \Drupal\system\Form\ModulesListConfirmForm::submitForm() - $this->drupalPostForm('admin/modules', array('modules[config_install_fail_test][enable]' => TRUE), t('Install')); - $this->drupalPostForm(NULL, array(), t('Continue')); + $this->drupalPostForm('admin/modules', ['modules[config_install_fail_test][enable]' => TRUE], t('Install')); + $this->drupalPostForm(NULL, [], t('Continue')); $this->assertRaw('Unable to install Configuration install fail test, config_test.dynamic.dotted.default already exists in active configuration.'); // Test that collection configuration clashes during a module install are @@ -147,7 +147,7 @@ public function testPreExistingConfigInstall() { ->set('label', 'Je suis Charlie') ->save(); - $this->drupalPostForm('admin/modules', array('modules[config_install_fail_test][enable]' => TRUE), t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_install_fail_test][enable]' => TRUE], t('Install')); $this->assertRaw('Unable to install Configuration install fail test, config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default already exist in active configuration.'); // Test installing a theme through the UI that has existing configuration. @@ -178,16 +178,16 @@ public function testUnmetDependenciesInstall() { $this->drupalLogin($this->adminUser); // We need to install separately since config_install_dependency_test does // not depend on config_test and order is important. - $this->drupalPostForm('admin/modules', array('modules[config_test][enable]' => TRUE), t('Install')); - $this->drupalPostForm('admin/modules', array('modules[config_install_dependency_test][enable]' => TRUE), t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_test][enable]' => TRUE], t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_install_dependency_test][enable]' => TRUE], t('Install')); $this->assertRaw('Unable to install Config install dependency test due to unmet dependencies: config_test.dynamic.other_module_test_with_dependency (config_other_module_config_test, config_test.dynamic.dotted.english)'); - $this->drupalPostForm('admin/modules', array('modules[config_test_language][enable]' => TRUE), t('Install')); - $this->drupalPostForm('admin/modules', array('modules[config_install_dependency_test][enable]' => TRUE), t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_test_language][enable]' => TRUE], t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_install_dependency_test][enable]' => TRUE], t('Install')); $this->assertRaw('Unable to install Config install dependency test due to unmet dependencies: config_test.dynamic.other_module_test_with_dependency (config_other_module_config_test)'); - $this->drupalPostForm('admin/modules', array('modules[config_other_module_config_test][enable]' => TRUE), t('Install')); - $this->drupalPostForm('admin/modules', array('modules[config_install_dependency_test][enable]' => TRUE), t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_other_module_config_test][enable]' => TRUE], t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config_install_dependency_test][enable]' => TRUE], t('Install')); $this->rebuildContainer(); $this->assertTrue(entity_load('config_test', 'other_module_test_with_dependency'), 'The config_test.dynamic.other_module_test_with_dependency configuration has been created during install.'); } @@ -197,12 +197,12 @@ public function testUnmetDependenciesInstall() { */ public function testConfigModuleRequirements() { $this->drupalLogin($this->adminUser); - $this->drupalPostForm('admin/modules', array('modules[config][enable]' => TRUE), t('Install')); + $this->drupalPostForm('admin/modules', ['modules[config][enable]' => TRUE], t('Install')); $directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY); file_unmanaged_delete_recursive($directory); $this->drupalGet('/admin/reports/status'); - $this->assertRaw(t('The directory %directory does not exist.', array('%directory' => $directory))); + $this->assertRaw(t('The directory %directory does not exist.', ['%directory' => $directory])); file_prepare_directory($directory, FILE_CREATE_DIRECTORY); \Drupal::service('file_system')->chmod($directory, 0555); diff --git a/core/modules/config/src/Tests/ConfigSingleImportExportTest.php b/core/modules/config/src/Tests/ConfigSingleImportExportTest.php index 53f6164cc6..16cff0aa8a 100644 --- a/core/modules/config/src/Tests/ConfigSingleImportExportTest.php +++ b/core/modules/config/src/Tests/ConfigSingleImportExportTest.php @@ -39,7 +39,7 @@ public function testImport() { $storage = \Drupal::entityManager()->getStorage('config_test'); $uuid = \Drupal::service('uuid'); - $this->drupalLogin($this->drupalCreateUser(array('import configuration'))); + $this->drupalLogin($this->drupalCreateUser(['import configuration'])); // Attempt an import with invalid YAML. $edit = [ @@ -57,20 +57,20 @@ public function testImport() { style: '' status: '1' EOD; - $edit = array( + $edit = [ 'config_type' => 'config_test', 'import' => $import, - ); + ]; // Attempt an import with a missing ID. $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); - $this->assertText(t('Missing ID key "@id_key" for this @entity_type import.', array('@id_key' => 'id', '@entity_type' => 'Test configuration'))); + $this->assertText(t('Missing ID key "@id_key" for this @entity_type import.', ['@id_key' => 'id', '@entity_type' => 'Test configuration'])); // Perform an import with no specified UUID and a unique ID. $this->assertNull($storage->load('first')); $edit['import'] = "id: first\n" . $edit['import']; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); - $this->assertRaw(t('Are you sure you want to create a new %name @type?', array('%name' => 'first', '@type' => 'test configuration'))); - $this->drupalPostForm(NULL, array(), t('Confirm')); + $this->assertRaw(t('Are you sure you want to create a new %name @type?', ['%name' => 'first', '@type' => 'test configuration'])); + $this->drupalPostForm(NULL, [], t('Confirm')); $entity = $storage->load('first'); $this->assertIdentical($entity->label(), 'First'); $this->assertIdentical($entity->id(), 'first'); @@ -89,8 +89,8 @@ public function testImport() { // Attempt an import with a custom ID. $edit['custom_entity_id'] = 'custom_id'; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); - $this->assertRaw(t('Are you sure you want to create a new %name @type?', array('%name' => 'custom_id', '@type' => 'test configuration'))); - $this->drupalPostForm(NULL, array(), t('Confirm')); + $this->assertRaw(t('Are you sure you want to create a new %name @type?', ['%name' => 'custom_id', '@type' => 'test configuration'])); + $this->drupalPostForm(NULL, [], t('Confirm')); $this->assertRaw(t('The configuration was imported successfully.')); // Perform an import with a unique ID and UUID. @@ -101,15 +101,15 @@ public function testImport() { style: '' status: '0' EOD; - $edit = array( + $edit = [ 'config_type' => 'config_test', 'import' => $import, - ); + ]; $second_uuid = $uuid->generate(); $edit['import'] .= "\nuuid: " . $second_uuid; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); - $this->assertRaw(t('Are you sure you want to create a new %name @type?', array('%name' => 'second', '@type' => 'test configuration'))); - $this->drupalPostForm(NULL, array(), t('Confirm')); + $this->assertRaw(t('Are you sure you want to create a new %name @type?', ['%name' => 'second', '@type' => 'test configuration'])); + $this->drupalPostForm(NULL, [], t('Confirm')); $entity = $storage->load('second'); $this->assertRaw(t('The configuration was imported successfully.')); $this->assertIdentical($entity->label(), 'Second'); @@ -126,13 +126,13 @@ public function testImport() { style: '' status: '0' EOD; - $edit = array( + $edit = [ 'config_type' => 'config_test', 'import' => $import, - ); + ]; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); - $this->assertRaw(t('Are you sure you want to update the %name @type?', array('%name' => 'second', '@type' => 'test configuration'))); - $this->drupalPostForm(NULL, array(), t('Confirm')); + $this->assertRaw(t('Are you sure you want to update the %name @type?', ['%name' => 'second', '@type' => 'test configuration'])); + $this->drupalPostForm(NULL, [], t('Confirm')); $entity = $storage->load('second'); $this->assertRaw(t('The configuration was imported successfully.')); $this->assertIdentical($entity->label(), 'Second updated'); @@ -149,10 +149,10 @@ public function testImport() { module: - does_not_exist EOD; - $edit = array( + $edit = [ 'config_type' => 'config_test', 'import' => $import, - ); + ]; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); $this->assertRaw(t('Configuration %name depends on the %owner module that will not be installed after import.', ['%name' => 'config_test.dynamic.second', '%owner' => 'does_not_exist'])); } @@ -161,20 +161,20 @@ public function testImport() { * Tests importing a simple configuration file. */ public function testImportSimpleConfiguration() { - $this->drupalLogin($this->drupalCreateUser(array('import configuration'))); + $this->drupalLogin($this->drupalCreateUser(['import configuration'])); $config = $this->config('system.site')->set('name', 'Test simple import'); // Place branding block with site name into header region. $this->drupalPlaceBlock('system_branding_block', ['region' => 'header']); - $edit = array( + $edit = [ 'config_type' => 'system.simple', 'config_name' => $config->getName(), 'import' => Yaml::encode($config->get()), - ); + ]; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); - $this->assertRaw(t('Are you sure you want to update the %name @type?', array('%name' => $config->getName(), '@type' => 'simple configuration'))); - $this->drupalPostForm(NULL, array(), t('Confirm')); + $this->assertRaw(t('Are you sure you want to update the %name @type?', ['%name' => $config->getName(), '@type' => 'simple configuration'])); + $this->drupalPostForm(NULL, [], t('Confirm')); $this->drupalGet(''); $this->assertText('Test simple import'); @@ -183,11 +183,11 @@ public function testImportSimpleConfiguration() { $config_data = $this->config('core.extension')->get(); // Simulate uninstalling the Config module. unset($config_data['module']['config']); - $edit = array( + $edit = [ 'config_type' => 'system.simple', 'config_name' => 'core.extension', 'import' => Yaml::encode($config_data), - ); + ]; $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import')); $this->assertText(t('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.')); @@ -197,14 +197,14 @@ public function testImportSimpleConfiguration() { * Tests exporting a single configuration file. */ public function testExport() { - $this->drupalLogin($this->drupalCreateUser(array('export configuration'))); + $this->drupalLogin($this->drupalCreateUser(['export configuration'])); $this->drupalGet('admin/config/development/configuration/single/export/system.simple'); $this->assertFieldByXPath('//select[@name="config_type"]//option[@selected="selected"]', t('Simple configuration'), 'The simple configuration option is selected when specified in the URL.'); // Spot check several known simple configuration files. $element = $this->xpath('//select[@name="config_name"]'); $options = $this->getAllOptions($element[0]); - $expected_options = array('system.site', 'user.settings'); + $expected_options = ['system.site', 'user.settings']; foreach ($options as &$option) { $option = (string) $option; } diff --git a/core/modules/config/src/Tests/LanguageNegotiationFormOverrideTest.php b/core/modules/config/src/Tests/LanguageNegotiationFormOverrideTest.php index 1aa4c9a2bf..ba67960650 100644 --- a/core/modules/config/src/Tests/LanguageNegotiationFormOverrideTest.php +++ b/core/modules/config/src/Tests/LanguageNegotiationFormOverrideTest.php @@ -12,7 +12,7 @@ */ class LanguageNegotiationFormOverrideTest extends WebTestBase { - public static $modules = array('language', 'locale', 'locale_test'); + public static $modules = ['language', 'locale', 'locale_test']; /** * Tests that overrides do not affect language-negotiation form values. @@ -23,16 +23,16 @@ public function testFormWithOverride() { $overridden_value_es = 'loquesea'; // Set up an override. - $settings['config']['language.negotiation']['url']['prefixes'] = (object) array( - 'value' => array('en' => $overridden_value_en, 'es' => $overridden_value_es), + $settings['config']['language.negotiation']['url']['prefixes'] = (object) [ + 'value' => ['en' => $overridden_value_en, 'es' => $overridden_value_es], 'required' => TRUE, - ); + ]; $this->writeSettings($settings); // Add predefined language. - $edit = array( + $edit = [ 'predefined_langcode' => 'es', - ); + ]; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); // Overridden string for language-negotiation should not exist in the form. diff --git a/core/modules/config/tests/config_collection_install_test/src/EventSubscriber.php b/core/modules/config/tests/config_collection_install_test/src/EventSubscriber.php index da3a9f1131..76714a5b97 100644 --- a/core/modules/config/tests/config_collection_install_test/src/EventSubscriber.php +++ b/core/modules/config/tests/config_collection_install_test/src/EventSubscriber.php @@ -33,7 +33,7 @@ public function __construct(StateInterface $state) { * The configuration collection info event. */ public function addCollections(ConfigCollectionInfo $collection_info) { - $collections = $this->state->get('config_collection_install_test.collection_names', array()); + $collections = $this->state->get('config_collection_install_test.collection_names', []); foreach ($collections as $collection) { $collection_info->addCollection($collection); } @@ -43,7 +43,7 @@ public function addCollections(ConfigCollectionInfo $collection_info) { * {@inheritdoc} */ static function getSubscribedEvents() { - $events[ConfigEvents::COLLECTION_INFO][] = array('addCollections'); + $events[ConfigEvents::COLLECTION_INFO][] = ['addCollections']; return $events; } diff --git a/core/modules/config/tests/config_entity_static_cache_test/src/ConfigOverrider.php b/core/modules/config/tests/config_entity_static_cache_test/src/ConfigOverrider.php index 2345d55175..8d21ee4e83 100644 --- a/core/modules/config/tests/config_entity_static_cache_test/src/ConfigOverrider.php +++ b/core/modules/config/tests/config_entity_static_cache_test/src/ConfigOverrider.php @@ -15,11 +15,11 @@ class ConfigOverrider implements ConfigFactoryOverrideInterface { * {@inheritdoc} */ public function loadOverrides($names) { - return array( - 'config_test.dynamic.test_1' => array( + return [ + 'config_test.dynamic.test_1' => [ 'label' => 'Overridden label', - ) - ); + ] + ]; } /** diff --git a/core/modules/config/tests/config_events_test/src/EventSubscriber.php b/core/modules/config/tests/config_events_test/src/EventSubscriber.php index bfa70db3ca..39e8eb80fc 100644 --- a/core/modules/config/tests/config_events_test/src/EventSubscriber.php +++ b/core/modules/config/tests/config_events_test/src/EventSubscriber.php @@ -37,21 +37,21 @@ public function __construct(StateInterface $state) { */ public function configEventRecorder(ConfigCrudEvent $event, $name) { $config = $event->getConfig(); - $this->state->set('config_events_test.event', array( + $this->state->set('config_events_test.event', [ 'event_name' => $name, 'current_config_data' => $config->get(), 'original_config_data' => $config->getOriginal(), 'raw_config_data' => $config->getRawData() - )); + ]); } /** * {@inheritdoc} */ static function getSubscribedEvents() { - $events[ConfigEvents::SAVE][] = array('configEventRecorder'); - $events[ConfigEvents::DELETE][] = array('configEventRecorder'); - $events[ConfigEvents::RENAME][] = array('configEventRecorder'); + $events[ConfigEvents::SAVE][] = ['configEventRecorder']; + $events[ConfigEvents::DELETE][] = ['configEventRecorder']; + $events[ConfigEvents::RENAME][] = ['configEventRecorder']; return $events; } diff --git a/core/modules/config/tests/config_import_test/src/EventSubscriber.php b/core/modules/config/tests/config_import_test/src/EventSubscriber.php index f4ae97f964..e0ef923a39 100644 --- a/core/modules/config/tests/config_import_test/src/EventSubscriber.php +++ b/core/modules/config/tests/config_import_test/src/EventSubscriber.php @@ -88,14 +88,14 @@ public function onConfigImporterMissingContentTwo(MissingContentEvent $event) { public function onConfigSave(ConfigCrudEvent $event) { $config = $event->getConfig(); if ($config->getName() == 'action.settings') { - $values = $this->state->get('ConfigImportUITest.action.settings.recursion_limit', array()); + $values = $this->state->get('ConfigImportUITest.action.settings.recursion_limit', []); $values[] = $config->get('recursion_limit'); $this->state->set('ConfigImportUITest.action.settings.recursion_limit', $values); } if ($config->getName() == 'core.extension') { - $installed = $this->state->get('ConfigImportUITest.core.extension.modules_installed', array()); - $uninstalled = $this->state->get('ConfigImportUITest.core.extension.modules_uninstalled', array()); + $installed = $this->state->get('ConfigImportUITest.core.extension.modules_installed', []); + $uninstalled = $this->state->get('ConfigImportUITest.core.extension.modules_uninstalled', []); $original = $config->getOriginal('module'); $data = $config->get('module'); $install = array_diff_key($data, $original); @@ -132,10 +132,10 @@ public function onConfigDelete(ConfigCrudEvent $event) { * An array of event listener definitions. */ static function getSubscribedEvents() { - $events[ConfigEvents::SAVE][] = array('onConfigSave', 40); - $events[ConfigEvents::DELETE][] = array('onConfigDelete', 40); - $events[ConfigEvents::IMPORT_VALIDATE] = array('onConfigImporterValidate'); - $events[ConfigEvents::IMPORT_MISSING_CONTENT] = array(array('onConfigImporterMissingContentOne'), array('onConfigImporterMissingContentTwo', -100)); + $events[ConfigEvents::SAVE][] = ['onConfigSave', 40]; + $events[ConfigEvents::DELETE][] = ['onConfigDelete', 40]; + $events[ConfigEvents::IMPORT_VALIDATE] = ['onConfigImporterValidate']; + $events[ConfigEvents::IMPORT_MISSING_CONTENT] = [['onConfigImporterMissingContentOne'], ['onConfigImporterMissingContentTwo', -100]]; return $events; } diff --git a/core/modules/config/tests/config_override_test/src/ConfigOverrider.php b/core/modules/config/tests/config_override_test/src/ConfigOverrider.php index 895f041b5b..c8ffc694b3 100644 --- a/core/modules/config/tests/config_override_test/src/ConfigOverrider.php +++ b/core/modules/config/tests/config_override_test/src/ConfigOverrider.php @@ -14,13 +14,13 @@ class ConfigOverrider implements ConfigFactoryOverrideInterface { * {@inheritdoc} */ public function loadOverrides($names) { - $overrides = array(); + $overrides = []; if (!empty($GLOBALS['config_test_run_module_overrides'])) { if (in_array('system.site', $names)) { - $overrides = $overrides + array('system.site' => array('name' => 'ZOMG overridden site name')); + $overrides = $overrides + ['system.site' => ['name' => 'ZOMG overridden site name']]; } if (in_array('config_override_test.new', $names)) { - $overrides = $overrides + array('config_override_test.new' => array('module' => 'override')); + $overrides = $overrides + ['config_override_test.new' => ['module' => 'override']]; } } return $overrides; diff --git a/core/modules/config/tests/config_override_test/src/ConfigOverriderLowPriority.php b/core/modules/config/tests/config_override_test/src/ConfigOverriderLowPriority.php index 6f0b12d1ef..b8109db682 100644 --- a/core/modules/config/tests/config_override_test/src/ConfigOverriderLowPriority.php +++ b/core/modules/config/tests/config_override_test/src/ConfigOverriderLowPriority.php @@ -15,17 +15,17 @@ class ConfigOverriderLowPriority implements ConfigFactoryOverrideInterface { * {@inheritdoc} */ public function loadOverrides($names) { - $overrides = array(); + $overrides = []; if (!empty($GLOBALS['config_test_run_module_overrides'])) { if (in_array('system.site', $names)) { - $overrides = array('system.site' => - array( + $overrides = ['system.site' => + [ 'name' => 'Should not apply because of higher priority listener', // This override should apply because it is not overridden by the // higher priority listener. 'slogan' => 'Yay for overrides!', - ) - ); + ] + ]; } } return $overrides; diff --git a/core/modules/config/tests/config_test/src/ConfigTestController.php b/core/modules/config/tests/config_test/src/ConfigTestController.php index d60c62e5ce..6799dc1b6f 100644 --- a/core/modules/config/tests/config_test/src/ConfigTestController.php +++ b/core/modules/config/tests/config_test/src/ConfigTestController.php @@ -21,7 +21,7 @@ class ConfigTestController extends ControllerBase { * The title for the ConfigTest edit form. */ public function editTitle(ConfigTest $config_test) { - return $this->t('Edit %label', array('%label' => $config_test->label())); + return $this->t('Edit %label', ['%label' => $config_test->label()]); } /** @@ -35,7 +35,7 @@ public function editTitle(ConfigTest $config_test) { */ function enable(ConfigTest $config_test) { $config_test->enable()->save(); - return new RedirectResponse($config_test->url('collection', array('absolute' => TRUE))); + return new RedirectResponse($config_test->url('collection', ['absolute' => TRUE])); } /** @@ -49,7 +49,7 @@ function enable(ConfigTest $config_test) { */ function disable(ConfigTest $config_test) { $config_test->disable()->save(); - return new RedirectResponse($config_test->url('collection', array('absolute' => TRUE))); + return new RedirectResponse($config_test->url('collection', ['absolute' => TRUE])); } } diff --git a/core/modules/config/tests/config_test/src/ConfigTestForm.php b/core/modules/config/tests/config_test/src/ConfigTestForm.php index 8384e6a66a..6a56c3dfb1 100644 --- a/core/modules/config/tests/config_test/src/ConfigTestForm.php +++ b/core/modules/config/tests/config_test/src/ConfigTestForm.php @@ -18,33 +18,33 @@ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); $entity = $this->entity; - $form['label'] = array( + $form['label'] = [ '#type' => 'textfield', '#title' => 'Label', '#default_value' => $entity->label(), '#required' => TRUE, - ); - $form['id'] = array( + ]; + $form['id'] = [ '#type' => 'machine_name', '#default_value' => $entity->id(), '#required' => TRUE, - '#machine_name' => array( + '#machine_name' => [ 'exists' => [$this, 'exists'], 'replace_pattern' => '[^a-z0-9_.]+', - ), - ); - $form['weight'] = array( + ], + ]; + $form['weight'] = [ '#type' => 'weight', '#title' => 'Weight', '#default_value' => $entity->get('weight'), - ); - $form['style'] = array( + ]; + $form['style'] = [ '#type' => 'select', '#title' => 'Image style', - '#options' => array(), + '#options' => [], '#default_value' => $entity->get('style'), '#access' => FALSE, - ); + ]; if ($this->moduleHandler->moduleExists('image')) { $form['style']['#access'] = TRUE; $form['style']['#options'] = image_style_options(); @@ -55,61 +55,61 @@ public function form(array $form, FormStateInterface $form_state) { // state. $size = $entity->get('size'); - $form['size_wrapper'] = array( + $form['size_wrapper'] = [ '#type' => 'container', - '#attributes' => array( + '#attributes' => [ 'id' => 'size-wrapper', - ), - ); - $form['size_wrapper']['size'] = array( + ], + ]; + $form['size_wrapper']['size'] = [ '#type' => 'select', '#title' => 'Size', - '#options' => array( + '#options' => [ 'custom' => 'Custom', - ), + ], '#empty_option' => '- None -', '#default_value' => $size, - '#ajax' => array( + '#ajax' => [ 'callback' => '::updateSize', 'wrapper' => 'size-wrapper', - ), - ); - $form['size_wrapper']['size_submit'] = array( + ], + ]; + $form['size_wrapper']['size_submit'] = [ '#type' => 'submit', '#value' => t('Change size'), - '#attributes' => array( - 'class' => array('js-hide'), - ), - '#submit' => array(array(get_class($this), 'changeSize')), - ); - $form['size_wrapper']['size_value'] = array( + '#attributes' => [ + 'class' => ['js-hide'], + ], + '#submit' => [[get_class($this), 'changeSize']], + ]; + $form['size_wrapper']['size_value'] = [ '#type' => 'select', '#title' => 'Custom size value', - '#options' => array( + '#options' => [ 'small' => 'Small', 'medium' => 'Medium', 'large' => 'Large', - ), + ], '#default_value' => $entity->get('size_value'), '#access' => !empty($size), - ); + ]; - $form['langcode'] = array( + $form['langcode'] = [ '#type' => 'language_select', '#title' => t('Language'), '#languages' => LanguageInterface::STATE_ALL, '#default_value' => $entity->language()->getId(), - ); + ]; - $form['actions'] = array('#type' => 'actions'); - $form['actions']['submit'] = array( + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => 'Save', - ); - $form['actions']['delete'] = array( + ]; + $form['actions']['delete'] = [ '#type' => 'submit', '#value' => 'Delete', - ); + ]; return $form; } @@ -136,10 +136,10 @@ public function save(array $form, FormStateInterface $form_state) { $status = $entity->save(); if ($status === SAVED_UPDATED) { - drupal_set_message(format_string('%label configuration has been updated.', array('%label' => $entity->label()))); + drupal_set_message(format_string('%label configuration has been updated.', ['%label' => $entity->label()])); } else { - drupal_set_message(format_string('%label configuration has been created.', array('%label' => $entity->label()))); + drupal_set_message(format_string('%label configuration has been created.', ['%label' => $entity->label()])); } $form_state->setRedirectUrl($this->entity->urlInfo('collection')); diff --git a/core/modules/config/tests/config_test/src/Entity/ConfigQueryTest.php b/core/modules/config/tests/config_test/src/Entity/ConfigQueryTest.php index 10914f0196..ca3b354984 100644 --- a/core/modules/config/tests/config_test/src/Entity/ConfigQueryTest.php +++ b/core/modules/config/tests/config_test/src/Entity/ConfigQueryTest.php @@ -38,6 +38,6 @@ class ConfigQueryTest extends ConfigTest { * * @var array */ - public $array = array(); + public $array = []; } diff --git a/core/modules/config/tests/config_test/src/Entity/ConfigTest.php b/core/modules/config/tests/config_test/src/Entity/ConfigTest.php index f19eb65ae2..1bd1d8dee9 100644 --- a/core/modules/config/tests/config_test/src/Entity/ConfigTest.php +++ b/core/modules/config/tests/config_test/src/Entity/ConfigTest.php @@ -88,10 +88,10 @@ public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b) public function postSave(EntityStorageInterface $storage, $update = TRUE) { // Used to test secondary writes during config sync. if ($this->id() == 'primary') { - $secondary = $storage->create(array( + $secondary = $storage->create([ 'id' => 'secondary', 'label' => 'Secondary Default', - )); + ]); $secondary->save(); } if ($this->id() == 'deleter') { @@ -126,7 +126,7 @@ public function onDependencyRemoval(array $dependencies) { if (!isset($this->dependencies['enforced']['config'])) { return $changed; } - $fix_deps = \Drupal::state()->get('config_test.fix_dependencies', array()); + $fix_deps = \Drupal::state()->get('config_test.fix_dependencies', []); foreach ($dependencies['config'] as $entity) { if (in_array($entity->getConfigDependencyName(), $fix_deps)) { $key = array_search($entity->getConfigDependencyName(), $this->dependencies['enforced']['config']); diff --git a/core/modules/config/tests/config_test/src/TestInstallStorage.php b/core/modules/config/tests/config_test/src/TestInstallStorage.php index 074e99ca61..e3c4918df4 100644 --- a/core/modules/config/tests/config_test/src/TestInstallStorage.php +++ b/core/modules/config/tests/config_test/src/TestInstallStorage.php @@ -20,7 +20,7 @@ protected function getAllFolders() { if (!isset($this->folders)) { $this->folders = $this->getCoreNames(); $listing = new ExtensionDiscovery(\Drupal::root()); - $listing->setProfileDirectories(array()); + $listing->setProfileDirectories([]); $this->folders += $this->getComponentNames($listing->scan('profile')); $this->folders += $this->getComponentNames($listing->scan('module')); $this->folders += $this->getComponentNames($listing->scan('theme')); diff --git a/core/modules/config/tests/src/Functional/ConfigDependencyWebTest.php b/core/modules/config/tests/src/Functional/ConfigDependencyWebTest.php index c243e9ac22..ba80401bc4 100644 --- a/core/modules/config/tests/src/Functional/ConfigDependencyWebTest.php +++ b/core/modules/config/tests/src/Functional/ConfigDependencyWebTest.php @@ -22,7 +22,7 @@ class ConfigDependencyWebTest extends BrowserTestBase { * * @var array */ - public static $modules = array('config_test'); + public static $modules = ['config_test']; /** * Tests ConfigDependencyDeleteFormTrait. @@ -36,10 +36,10 @@ function testConfigDependencyDeleteFormTrait() { $storage = $this->container->get('entity.manager')->getStorage('config_test'); // Entity1 will be deleted by the test. $entity1 = $storage->create( - array( + [ 'id' => 'entity1', 'label' => 'Entity One', - ) + ] ); $entity1->save(); @@ -47,14 +47,14 @@ function testConfigDependencyDeleteFormTrait() { // \Drupal\config_test\Entity::onDependencyRemoval() will remove the // dependency before config entities are deleted. $entity2 = $storage->create( - array( + [ 'id' => 'entity2', - 'dependencies' => array( - 'enforced' => array( - 'config' => array($entity1->getConfigDependencyName()), - ), - ), - ) + 'dependencies' => [ + 'enforced' => [ + 'config' => [$entity1->getConfigDependencyName()], + ], + ], + ] ); $entity2->save(); @@ -65,47 +65,47 @@ function testConfigDependencyDeleteFormTrait() { $this->assertNoText(t('Configuration updates'), 'No configuration updates found.'); $this->assertText(t('Configuration deletions'), 'Configuration deletions found.'); $this->assertText($entity2->id(), 'Entity2 id found'); - $this->drupalPostForm($entity1->urlInfo('delete-form'), array(), 'Delete'); + $this->drupalPostForm($entity1->urlInfo('delete-form'), [], 'Delete'); $storage->resetCache(); $this->assertFalse($storage->loadMultiple([$entity1->id(), $entity2->id()]), 'Test entities deleted'); // Set a more complicated test where dependencies will be fixed. // Entity1 will be deleted by the test. $entity1 = $storage->create( - array( + [ 'id' => 'entity1', - ) + ] ); $entity1->save(); - \Drupal::state()->set('config_test.fix_dependencies', array($entity1->getConfigDependencyName())); + \Drupal::state()->set('config_test.fix_dependencies', [$entity1->getConfigDependencyName()]); // Entity2 has a dependency on Entity1 but it can be fixed because // \Drupal\config_test\Entity::onDependencyRemoval() will remove the // dependency before config entities are deleted. $entity2 = $storage->create( - array( + [ 'id' => 'entity2', 'label' => 'Entity Two', - 'dependencies' => array( - 'enforced' => array( - 'config' => array($entity1->getConfigDependencyName()), - ), - ), - ) + 'dependencies' => [ + 'enforced' => [ + 'config' => [$entity1->getConfigDependencyName()], + ], + ], + ] ); $entity2->save(); // Entity3 will be unchanged because it is dependent on Entity2 which can // be fixed. $entity3 = $storage->create( - array( + [ 'id' => 'entity3', - 'dependencies' => array( - 'enforced' => array( - 'config' => array($entity2->getConfigDependencyName()), - ), - ), - ) + 'dependencies' => [ + 'enforced' => [ + 'config' => [$entity2->getConfigDependencyName()], + ], + ], + ] ); $entity3->save(); @@ -115,12 +115,12 @@ function testConfigDependencyDeleteFormTrait() { $this->assertNoText($entity2->id(), 'Entity2 id not found'); $this->assertText($entity2->label(), 'Entity2 label not found'); $this->assertNoText($entity3->id(), 'Entity3 id not found'); - $this->drupalPostForm($entity1->urlInfo('delete-form'), array(), 'Delete'); + $this->drupalPostForm($entity1->urlInfo('delete-form'), [], 'Delete'); $storage->resetCache(); $this->assertFalse($storage->load('entity1'), 'Test entity 1 deleted'); $entity2 = $storage->load('entity2'); $this->assertTrue($entity2, 'Entity 2 not deleted'); - $this->assertEqual($entity2->calculateDependencies()->getDependencies()['config'], array(), 'Entity 2 dependencies updated to remove dependency on Entity1.'); + $this->assertEqual($entity2->calculateDependencies()->getDependencies()['config'], [], 'Entity 2 dependencies updated to remove dependency on Entity1.'); $entity3 = $storage->load('entity3'); $this->assertTrue($entity3, 'Entity 3 not deleted'); $this->assertEqual($entity3->calculateDependencies()->getDependencies()['config'], [$entity2->getConfigDependencyName()], 'Entity 3 still depends on Entity 2.'); diff --git a/core/modules/config/tests/src/Functional/ConfigDraggableListBuilderTest.php b/core/modules/config/tests/src/Functional/ConfigDraggableListBuilderTest.php index 417e9f13cb..74829359a1 100644 --- a/core/modules/config/tests/src/Functional/ConfigDraggableListBuilderTest.php +++ b/core/modules/config/tests/src/Functional/ConfigDraggableListBuilderTest.php @@ -15,13 +15,13 @@ class ConfigDraggableListBuilderTest extends BrowserTestBase { /** * {@inheritdoc} */ - public static $modules = array('config_test'); + public static $modules = ['config_test']; /** * Test draggable lists. */ public function testDraggableList() { - $this->drupalLogin($this->drupalCreateUser(array('administer permissions'))); + $this->drupalLogin($this->drupalCreateUser(['administer permissions'])); // Create more than 50 roles. for ($i = 0; $i < 51; $i++) { diff --git a/core/modules/config/tests/src/Functional/ConfigEntityListMultilingualTest.php b/core/modules/config/tests/src/Functional/ConfigEntityListMultilingualTest.php index 6c40dedcd6..5d99252d9c 100644 --- a/core/modules/config/tests/src/Functional/ConfigEntityListMultilingualTest.php +++ b/core/modules/config/tests/src/Functional/ConfigEntityListMultilingualTest.php @@ -17,7 +17,7 @@ class ConfigEntityListMultilingualTest extends BrowserTestBase { * * @var array */ - public static $modules = array('config_test', 'language', 'block'); + public static $modules = ['config_test', 'language', 'block']; /** * {@inheritdoc} @@ -36,7 +36,7 @@ protected function setUp() { */ function testListUI() { // Log in as an administrative user to access the full menu trail. - $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer site configuration'))); + $this->drupalLogin($this->drupalCreateUser(['access administration pages', 'administer site configuration'])); // Get the list page. $this->drupalGet('admin/structure/config_test'); @@ -44,11 +44,11 @@ function testListUI() { // Add a new entity using the action link. $this->clickLink('Add test configuration'); - $edit = array( + $edit = [ 'label' => 'Antilop', 'id' => 'antilop', 'langcode' => 'hu', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); // Ensure that operations for editing the Hungarian entity appear in English. $this->assertLinkByHref('admin/structure/config_test/manage/antilop'); diff --git a/core/modules/config/tests/src/Functional/ConfigEntityStatusUITest.php b/core/modules/config/tests/src/Functional/ConfigEntityStatusUITest.php index 9ae9412547..4ad4d59b9d 100644 --- a/core/modules/config/tests/src/Functional/ConfigEntityStatusUITest.php +++ b/core/modules/config/tests/src/Functional/ConfigEntityStatusUITest.php @@ -16,7 +16,7 @@ class ConfigEntityStatusUITest extends BrowserTestBase { * * @var array */ - public static $modules = array('config_test'); + public static $modules = ['config_test']; /** * Tests status operations. @@ -25,10 +25,10 @@ function testCRUD() { $this->drupalLogin($this->drupalCreateUser(['administer site configuration'])); $id = strtolower($this->randomMachineName()); - $edit = array( + $edit = [ 'id' => $id, 'label' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm('admin/structure/config_test/add', $edit, 'Save'); $entity = entity_load('config_test', $id); diff --git a/core/modules/config/tests/src/Functional/ConfigInstallProfileOverrideTest.php b/core/modules/config/tests/src/Functional/ConfigInstallProfileOverrideTest.php index 9ed75a4e93..88218b9899 100644 --- a/core/modules/config/tests/src/Functional/ConfigInstallProfileOverrideTest.php +++ b/core/modules/config/tests/src/Functional/ConfigInstallProfileOverrideTest.php @@ -31,21 +31,21 @@ class ConfigInstallProfileOverrideTest extends BrowserTestBase { function testInstallProfileConfigOverwrite() { $config_name = 'system.cron'; // The expected configuration from the system module. - $expected_original_data = array( - 'threshold' => array( + $expected_original_data = [ + 'threshold' => [ 'requirements_warning' => 172800, 'requirements_error' => 1209600, - ), + ], 'logging' => 1, - ); + ]; // The expected active configuration altered by the install profile. - $expected_profile_data = array( - 'threshold' => array( + $expected_profile_data = [ + 'threshold' => [ 'requirements_warning' => 259200, 'requirements_error' => 1209600, - ), + ], 'logging' => 1, - ); + ]; $expected_profile_data['_core']['default_config_hash'] = Crypt::hashBase64(serialize($expected_profile_data)); // Verify that the original data matches. We have to read the module config diff --git a/core/modules/config/tests/src/Functional/ConfigLanguageOverrideWebTest.php b/core/modules/config/tests/src/Functional/ConfigLanguageOverrideWebTest.php index 5aa194edcf..5fdd1a1441 100644 --- a/core/modules/config/tests/src/Functional/ConfigLanguageOverrideWebTest.php +++ b/core/modules/config/tests/src/Functional/ConfigLanguageOverrideWebTest.php @@ -35,18 +35,18 @@ protected function setUp() { * Tests translating the site name. */ function testSiteNameTranslation() { - $adminUser = $this->drupalCreateUser(array('administer site configuration', 'administer languages')); + $adminUser = $this->drupalCreateUser(['administer site configuration', 'administer languages']); $this->drupalLogin($adminUser); // Add a custom language. $langcode = 'xx'; $name = $this->randomMachineName(16); - $edit = array( + $edit = [ 'predefined_langcode' => 'custom', 'langcode' => $langcode, 'label' => $name, 'direction' => LanguageInterface::DIRECTION_LTR, - ); + ]; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language')); \Drupal::languageManager() ->getLanguageConfigOverride($langcode, 'system.site') diff --git a/core/modules/config/tests/src/Functional/ConfigOtherModuleTest.php b/core/modules/config/tests/src/Functional/ConfigOtherModuleTest.php index e1d0d8d5be..a99676072b 100644 --- a/core/modules/config/tests/src/Functional/ConfigOtherModuleTest.php +++ b/core/modules/config/tests/src/Functional/ConfigOtherModuleTest.php @@ -87,14 +87,14 @@ public function testInstallConfigEntityModuleFirst() { public function testUninstall() { $this->installModule('views'); $storage = $this->container->get('entity_type.manager')->getStorage('view'); - $storage->resetCache(array('frontpage')); + $storage->resetCache(['frontpage']); $this->assertTrue($storage->load('frontpage') === NULL, 'After installing Views, frontpage view which is dependant on the Node and Views modules does not exist.'); $this->installModule('node'); - $storage->resetCache(array('frontpage')); + $storage->resetCache(['frontpage']); $this->assertTrue($storage->load('frontpage') !== NULL, 'After installing Node, frontpage view which is dependant on the Node and Views modules exists.'); $this->uninstallModule('node'); $storage = $this->container->get('entity_type.manager')->getStorage('view'); - $storage->resetCache(array('frontpage')); + $storage->resetCache(['frontpage']); $this->assertTrue($storage->load('frontpage') === NULL, 'After uninstalling Node, frontpage view which is dependant on the Node and Views modules does not exist.'); } @@ -105,7 +105,7 @@ public function testUninstall() { * The module name. */ protected function installModule($module) { - $this->container->get('module_installer')->install(array($module)); + $this->container->get('module_installer')->install([$module]); $this->container = \Drupal::getContainer(); } @@ -116,7 +116,7 @@ protected function installModule($module) { * The module name. */ protected function uninstallModule($module) { - $this->container->get('module_installer')->uninstall(array($module)); + $this->container->get('module_installer')->uninstall([$module]); $this->container = \Drupal::getContainer(); } diff --git a/core/modules/config/tests/src/Functional/SchemaConfigListenerWebTest.php b/core/modules/config/tests/src/Functional/SchemaConfigListenerWebTest.php index bab8a3e9ba..189d78fc63 100644 --- a/core/modules/config/tests/src/Functional/SchemaConfigListenerWebTest.php +++ b/core/modules/config/tests/src/Functional/SchemaConfigListenerWebTest.php @@ -15,7 +15,7 @@ class SchemaConfigListenerWebTest extends BrowserTestBase { /** * {@inheritdoc} */ - public static $modules = array('config_test'); + public static $modules = ['config_test']; /** * Tests \Drupal\Core\Config\Development\ConfigSchemaChecker. diff --git a/core/modules/config/tests/src/Unit/Menu/ConfigLocalTasksTest.php b/core/modules/config/tests/src/Unit/Menu/ConfigLocalTasksTest.php index 7dd8d7dac8..0bfb32e93f 100644 --- a/core/modules/config/tests/src/Unit/Menu/ConfigLocalTasksTest.php +++ b/core/modules/config/tests/src/Unit/Menu/ConfigLocalTasksTest.php @@ -12,7 +12,7 @@ class ConfigLocalTasksTest extends LocalTaskIntegrationTestBase { protected function setUp() { - $this->directoryList = array('config' => 'core/modules/config'); + $this->directoryList = ['config' => 'core/modules/config']; parent::setUp(); } @@ -29,13 +29,13 @@ public function testConfigAdminLocalTasks($route, $expected) { * Provides a list of routes to test. */ public function getConfigAdminRoutes() { - return array( - array('config.sync', array(array('config.sync', 'config.import', 'config.export'))), - array('config.import_full', array(array('config.sync', 'config.import', 'config.export'), array('config.import_full', 'config.import_single'))), - array('config.import_single', array(array('config.sync', 'config.import', 'config.export'), array('config.import_full', 'config.import_single'))), - array('config.export_full', array(array('config.sync', 'config.import', 'config.export'), array('config.export_full', 'config.export_single'))), - array('config.export_single', array(array('config.sync', 'config.import', 'config.export'), array('config.export_full', 'config.export_single'))), - ); + return [ + ['config.sync', [['config.sync', 'config.import', 'config.export']]], + ['config.import_full', [['config.sync', 'config.import', 'config.export'], ['config.import_full', 'config.import_single']]], + ['config.import_single', [['config.sync', 'config.import', 'config.export'], ['config.import_full', 'config.import_single']]], + ['config.export_full', [['config.sync', 'config.import', 'config.export'], ['config.export_full', 'config.export_single']]], + ['config.export_single', [['config.sync', 'config.import', 'config.export'], ['config.export_full', 'config.export_single']]], + ]; } } diff --git a/core/modules/config_translation/config_translation.api.php b/core/modules/config_translation/config_translation.api.php index f2ee4a290f..f97e25997a 100644 --- a/core/modules/config_translation/config_translation.api.php +++ b/core/modules/config_translation/config_translation.api.php @@ -50,14 +50,14 @@ function hook_config_translation_info(&$info) { // Make sure entity type has field UI enabled and has a base route. if ($entity_type->get('field_ui_base_route') && !empty($base_route)) { - $info[$entity_type_id . '_fields'] = array( + $info[$entity_type_id . '_fields'] = [ 'base_route_name' => 'entity.field_config.' . $entity_type_id . '_field_edit_form', 'entity_type' => 'field_config', 'title' => t('Title'), 'class' => '\Drupal\config_translation\ConfigFieldMapper', 'base_entity_type' => $entity_type_id, 'weight' => 10, - ); + ]; } } } diff --git a/core/modules/config_translation/config_translation.module b/core/modules/config_translation/config_translation.module index d018d6402b..344d90e27b 100644 --- a/core/modules/config_translation/config_translation.module +++ b/core/modules/config_translation/config_translation.module @@ -18,15 +18,15 @@ function config_translation_help($route_name, RouteMatchInterface $route_match) case 'help.page.config_translation': $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Configuration Translation module allows you to translate configuration text; for example, the site name, vocabularies, menus, or date formats. Together with the modules Language, Content Translation, and Interface Translation, it allows you to build multilingual websites. For more information, see the online documentation for the Configuration Translation module.', array(':doc_url' => 'https://www.drupal.org/documentation/modules/config_translation', ':config' => \Drupal::url('help.page', array('name' => 'config')), ':language' => \Drupal::url('help.page', array('name' => 'language')), ':locale' => \Drupal::url('help.page', array('name' => 'locale')), ':content-translation' => (\Drupal::moduleHandler()->moduleExists('content_translation')) ? \Drupal::url('help.page', array('name' => 'content_translation')) : '#')) . '

        '; + $output .= '

        ' . t('The Configuration Translation module allows you to translate configuration text; for example, the site name, vocabularies, menus, or date formats. Together with the modules Language, Content Translation, and Interface Translation, it allows you to build multilingual websites. For more information, see the online documentation for the Configuration Translation module.', [':doc_url' => 'https://www.drupal.org/documentation/modules/config_translation', ':config' => \Drupal::url('help.page', ['name' => 'config']), ':language' => \Drupal::url('help.page', ['name' => 'language']), ':locale' => \Drupal::url('help.page', ['name' => 'locale']), ':content-translation' => (\Drupal::moduleHandler()->moduleExists('content_translation')) ? \Drupal::url('help.page', ['name' => 'content_translation']) : '#']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Enabling translation') . '
        '; - $output .= '
        ' . t('In order to translate configuration, the website must have at least two languages.', array(':url' => \Drupal::url('entity.configurable_language.collection'))) . '
        '; + $output .= '
        ' . t('In order to translate configuration, the website must have at least two languages.', [':url' => \Drupal::url('entity.configurable_language.collection')]) . '
        '; $output .= '
        ' . t('Translating configuration text') . '
        '; - $output .= '
        ' . t('Users with the Translate user edited configuration permission can access the configuration translation overview, and manage translations for specific languages. The Configuration translation page shows a list of all configuration text that can be translated, either as individual items or as lists. After you click on Translate, you are provided with a list of all languages. You can add or edit a translation for a specific language. Users with specific configuration permissions can also edit the text for the site\'s default language. For some configuration text items (for example for the site information), the specific translation pages can also be accessed directly from their configuration pages.', array(':translation-page' => \Drupal::url('config_translation.mapper_list'))) . '
        '; + $output .= '
        ' . t('Users with the Translate user edited configuration permission can access the configuration translation overview, and manage translations for specific languages. The Configuration translation page shows a list of all configuration text that can be translated, either as individual items or as lists. After you click on Translate, you are provided with a list of all languages. You can add or edit a translation for a specific language. Users with specific configuration permissions can also edit the text for the site\'s default language. For some configuration text items (for example for the site information), the specific translation pages can also be accessed directly from their configuration pages.', [':translation-page' => \Drupal::url('config_translation.mapper_list')]) . '
        '; $output .= '
        ' . t('Translating date formats') . '
        '; - $output .= '
        ' . t('You can choose to translate date formats on the Configuration translation page. This allows you not only to translate the label text, but also to set a language-specific PHP date format.', array(':translation-page' => \Drupal::url('config_translation.mapper_list'))) . '
        '; + $output .= '
        ' . t('You can choose to translate date formats on the Configuration translation page. This allows you not only to translate the label text, but also to set a language-specific PHP date format.', [':translation-page' => \Drupal::url('config_translation.mapper_list')]) . '
        '; $output .= '
        '; return $output; @@ -40,12 +40,12 @@ function config_translation_help($route_name, RouteMatchInterface $route_match) * Implements hook_theme(). */ function config_translation_theme() { - return array( - 'config_translation_manage_form_element' => array( + return [ + 'config_translation_manage_form_element' => [ 'render element' => 'element', 'template' => 'config_translation_manage_form_element', - ), - ); + ], + ]; } /** @@ -110,13 +110,13 @@ function config_translation_config_translation_info(&$info) { foreach ($entity_manager->getDefinitions() as $entity_type_id => $entity_type) { // Make sure entity type has field UI enabled and has a base route. if ($entity_type->get('field_ui_base_route')) { - $info[$entity_type_id . '_fields'] = array( + $info[$entity_type_id . '_fields'] = [ 'base_route_name' => "entity.field_config.{$entity_type_id}_field_edit_form", 'entity_type' => 'field_config', 'class' => '\Drupal\config_translation\ConfigFieldMapper', 'base_entity_type' => $entity_type_id, 'weight' => 10, - ); + ]; } } } @@ -138,14 +138,14 @@ function config_translation_config_translation_info(&$info) { // Use the entity type as the plugin ID. $base_route_name = "entity.$entity_type_id.edit_form"; - $info[$entity_type_id] = array( + $info[$entity_type_id] = [ 'class' => '\Drupal\config_translation\ConfigEntityMapper', 'base_route_name' => $base_route_name, 'title' => $entity_type->getLowercaseLabel(), - 'names' => array(), + 'names' => [], 'entity_type' => $entity_type_id, 'weight' => 10, - ); + ]; } } @@ -153,7 +153,7 @@ function config_translation_config_translation_info(&$info) { * Implements hook_entity_operation(). */ function config_translation_entity_operation(EntityInterface $entity) { - $operations = array(); + $operations = []; $entity_type = $entity->getEntityType(); if ($entity_type->entityClassImplements(ConfigEntityInterface::class) && $entity->hasLinkTemplate('config-translation-overview') && @@ -164,11 +164,11 @@ function config_translation_entity_operation(EntityInterface $entity) { $link_template = "config-translation-overview.{$entity->getTargetEntityTypeId()}"; } - $operations['translate'] = array( + $operations['translate'] = [ 'title' => t('Translate'), 'weight' => 50, 'url' => $entity->urlInfo($link_template), - ); + ]; } return $operations; @@ -178,7 +178,7 @@ function config_translation_entity_operation(EntityInterface $entity) { * Implements hook_config_schema_info_alter(). */ function config_translation_config_schema_info_alter(&$definitions) { - $map = array( + $map = [ 'label' => '\Drupal\config_translation\FormElement\Textfield', 'text' => '\Drupal\config_translation\FormElement\Textarea', 'date_format' => '\Drupal\config_translation\FormElement\DateFormat', @@ -186,7 +186,7 @@ function config_translation_config_schema_info_alter(&$definitions) { 'mapping' => '\Drupal\config_translation\FormElement\ListElement', 'sequence' => '\Drupal\config_translation\FormElement\ListElement', 'plural_label' => '\Drupal\config_translation\FormElement\PluralVariants', - ); + ]; // Enhance the text and date type definitions with classes to generate proper // form elements in ConfigTranslationFormBase. Other translatable types will diff --git a/core/modules/config_translation/src/ConfigEntityMapper.php b/core/modules/config_translation/src/ConfigEntityMapper.php index d172e1b705..2ae3095933 100644 --- a/core/modules/config_translation/src/ConfigEntityMapper.php +++ b/core/modules/config_translation/src/ConfigEntityMapper.php @@ -165,7 +165,7 @@ public function getTitle() { * {@inheritdoc} */ public function getBaseRouteParameters() { - return array($this->entityType => $this->entity->id()); + return [$this->entityType => $this->entity->id()]; } /** @@ -220,14 +220,14 @@ public function getTypeLabel() { * {@inheritdoc} */ public function getOperations() { - return array( - 'list' => array( + return [ + 'list' => [ 'title' => $this->t('List'), 'url' => Url::fromRoute('config_translation.entity_list', [ 'mapper_id' => $this->getPluginId(), ]), - ), - ); + ], + ]; } /** @@ -259,12 +259,12 @@ public function getOverviewRouteName() { */ protected function processRoute(Route $route) { // Add entity upcasting information. - $parameters = $route->getOption('parameters') ?: array(); - $parameters += array( - $this->entityType => array( + $parameters = $route->getOption('parameters') ?: []; + $parameters += [ + $this->entityType => [ 'type' => 'entity:' . $this->entityType, - ) - ); + ] + ]; $route->setOption('parameters', $parameters); } diff --git a/core/modules/config_translation/src/ConfigFieldMapper.php b/core/modules/config_translation/src/ConfigFieldMapper.php index a9f6d76621..c0e085f115 100644 --- a/core/modules/config_translation/src/ConfigFieldMapper.php +++ b/core/modules/config_translation/src/ConfigFieldMapper.php @@ -44,7 +44,7 @@ public function getOverviewRouteName() { */ public function getTypeLabel() { $base_entity_info = $this->entityManager->getDefinition($this->pluginDefinition['base_entity_type']); - return $this->t('@label fields', array('@label' => $base_entity_info->getLabel())); + return $this->t('@label fields', ['@label' => $base_entity_info->getLabel()]); } /** diff --git a/core/modules/config_translation/src/ConfigMapperManager.php b/core/modules/config_translation/src/ConfigMapperManager.php index cd0b72f967..a43f08083a 100644 --- a/core/modules/config_translation/src/ConfigMapperManager.php +++ b/core/modules/config_translation/src/ConfigMapperManager.php @@ -39,12 +39,12 @@ class ConfigMapperManager extends DefaultPluginManager implements ConfigMapperMa /** * {@inheritdoc} */ - protected $defaults = array( + protected $defaults = [ 'title' => '', - 'names' => array(), + 'names' => [], 'weight' => 20, 'class' => '\Drupal\config_translation\ConfigNamesMapper', - ); + ]; /** * Constructs a ConfigMapperManager. @@ -72,7 +72,7 @@ public function __construct(CacheBackendInterface $cache_backend, LanguageManage $this->alterInfo('config_translation_info'); // Config translation only uses an info hook discovery, cache by language. $cache_key = 'config_translation_info_plugins' . ':' . $language_manager->getCurrentLanguage()->getId(); - $this->setCacheBackend($cache_backend, $cache_key, array('config_translation_info_plugins')); + $this->setCacheBackend($cache_backend, $cache_key, ['config_translation_info_plugins']); } /** @@ -90,7 +90,7 @@ protected function getDiscovery() { // request; when routes are being rebuilt at the end of the request, // this service only happens to get instantiated with the updated list // of installed themes. - $directories = array(); + $directories = []; foreach ($this->moduleHandler->getModuleList() as $name => $module) { $directories[$name] = $module->getPath(); } @@ -111,7 +111,7 @@ protected function getDiscovery() { * {@inheritdoc} */ public function getMappers(RouteCollection $collection = NULL) { - $mappers = array(); + $mappers = []; foreach ($this->getDefinitions() as $id => $definition) { $mappers[$id] = $this->createInstance($id); if ($collection) { @@ -155,7 +155,7 @@ protected function findDefinitions() { // If this plugin was provided by a module that does not exist, remove the // plugin definition. foreach ($definitions as $plugin_id => $plugin_definition) { - if (isset($plugin_definition['provider']) && !in_array($plugin_definition['provider'], array('core', 'component')) && (!$this->moduleHandler->moduleExists($plugin_definition['provider']) && !in_array($plugin_definition['provider'], array_keys($this->themeHandler->listInfo())))) { + if (isset($plugin_definition['provider']) && !in_array($plugin_definition['provider'], ['core', 'component']) && (!$this->moduleHandler->moduleExists($plugin_definition['provider']) && !in_array($plugin_definition['provider'], array_keys($this->themeHandler->listInfo())))) { unset($definitions[$plugin_id]); } } diff --git a/core/modules/config_translation/src/ConfigNamesMapper.php b/core/modules/config_translation/src/ConfigNamesMapper.php index 0784090daf..03716e9725 100644 --- a/core/modules/config_translation/src/ConfigNamesMapper.php +++ b/core/modules/config_translation/src/ConfigNamesMapper.php @@ -180,7 +180,7 @@ public function getBaseRouteName() { * {@inheritdoc} */ public function getBaseRouteParameters() { - return array(); + return []; } /** @@ -231,11 +231,11 @@ public function getOverviewRouteParameters() { public function getOverviewRoute() { $route = new Route( $this->getBaseRoute()->getPath() . '/translate', - array( + [ '_controller' => '\Drupal\config_translation\Controller\ConfigTranslationController::itemPage', 'plugin_id' => $this->getPluginId(), - ), - array('_config_translation_overview_access' => 'TRUE') + ], + ['_config_translation_overview_access' => 'TRUE'] ); $this->processRoute($route); return $route; @@ -272,11 +272,11 @@ public function getAddRouteParameters() { public function getAddRoute() { $route = new Route( $this->getBaseRoute()->getPath() . '/translate/{langcode}/add', - array( + [ '_form' => '\Drupal\config_translation\Form\ConfigTranslationAddForm', 'plugin_id' => $this->getPluginId(), - ), - array('_config_translation_form_access' => 'TRUE') + ], + ['_config_translation_form_access' => 'TRUE'] ); $this->processRoute($route); return $route; @@ -302,11 +302,11 @@ public function getEditRouteParameters() { public function getEditRoute() { $route = new Route( $this->getBaseRoute()->getPath() . '/translate/{langcode}/edit', - array( + [ '_form' => '\Drupal\config_translation\Form\ConfigTranslationEditForm', 'plugin_id' => $this->getPluginId(), - ), - array('_config_translation_form_access' => 'TRUE') + ], + ['_config_translation_form_access' => 'TRUE'] ); $this->processRoute($route); return $route; @@ -332,11 +332,11 @@ public function getDeleteRouteParameters() { public function getDeleteRoute() { $route = new Route( $this->getBaseRoute()->getPath() . '/translate/{langcode}/delete', - array( + [ '_form' => '\Drupal\config_translation\Form\ConfigTranslationDeleteForm', 'plugin_id' => $this->getPluginId(), - ), - array('_config_translation_form_access' => 'TRUE') + ], + ['_config_translation_form_access' => 'TRUE'] ); $this->processRoute($route); return $route; @@ -413,7 +413,7 @@ public function setLangcode($langcode) { * {@inheritdoc} */ public function getConfigData() { - $config_data = array(); + $config_data = []; foreach ($this->getConfigNames() as $name) { $config_data[$name] = $this->configFactory->getEditable($name)->get(); } @@ -467,12 +467,12 @@ public function getTypeName() { * {@inheritdoc} */ public function getOperations() { - return array( - 'translate' => array( + return [ + 'translate' => [ 'title' => $this->t('Translate'), 'url' => Url::fromRoute($this->getOverviewRouteName(), $this->getOverviewRouteParameters()), - ), - ); + ], + ]; } /** diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationBlockListBuilder.php b/core/modules/config_translation/src/Controller/ConfigTranslationBlockListBuilder.php index d0de3419ba..c226dfbd60 100644 --- a/core/modules/config_translation/src/Controller/ConfigTranslationBlockListBuilder.php +++ b/core/modules/config_translation/src/Controller/ConfigTranslationBlockListBuilder.php @@ -18,7 +18,7 @@ class ConfigTranslationBlockListBuilder extends ConfigTranslationEntityListBuild * * @var array */ - protected $themes = array(); + protected $themes = []; /** * {@inheritdoc} @@ -58,20 +58,20 @@ public function buildRow(EntityInterface $entity) { $theme = $entity->getTheme(); $plugin_definition = $entity->getPlugin()->getPluginDefinition(); - $row['label'] = array( + $row['label'] = [ 'data' => $entity->label(), 'class' => 'table-filter-text-source', - ); + ]; - $row['theme'] = array( + $row['theme'] = [ 'data' => $this->themes[$theme]->info['name'], 'class' => 'table-filter-text-source', - ); + ]; - $row['category'] = array( + $row['category'] = [ 'data' => $plugin_definition['category'], 'class' => 'table-filter-text-source', - ); + ]; $row['operations']['data'] = $this->buildOperations($entity); @@ -93,7 +93,7 @@ public function buildHeader() { * {@inheritdoc} */ public function sortRows($a, $b) { - return $this->sortRowsMultiple($a, $b, array('theme', 'category', 'label')); + return $this->sortRowsMultiple($a, $b, ['theme', 'category', 'label']); } } diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationController.php b/core/modules/config_translation/src/Controller/ConfigTranslationController.php index 927a1e2bf5..8d9bfe7bde 100644 --- a/core/modules/config_translation/src/Controller/ConfigTranslationController.php +++ b/core/modules/config_translation/src/Controller/ConfigTranslationController.php @@ -134,12 +134,12 @@ public function itemPage(Request $request, RouteMatchInterface $route_match, $pl $mapper = $this->configMapperManager->createInstance($plugin_id); $mapper->populateFromRouteMatch($route_match); - $page = array(); - $page['#title'] = $this->t('Translations for %label', array('%label' => $mapper->getTitle())); + $page = []; + $page['#title'] = $this->t('Translations for %label', ['%label' => $mapper->getTitle()]); $languages = $this->languageManager->getLanguages(); if (count($languages) == 1) { - drupal_set_message($this->t('In order to translate configuration, the website must have at least two languages.', array(':url' => $this->url('entity.configurable_language.collection'))), 'warning'); + drupal_set_message($this->t('In order to translate configuration, the website must have at least two languages.', [':url' => $this->url('entity.configurable_language.collection')]), 'warning'); } try { @@ -172,7 +172,7 @@ public function itemPage(Request $request, RouteMatchInterface $route_match, $pl // If the language is not configured on the site, create a dummy language // object for this listing only to ensure the user gets useful info. $language_name = $this->languageManager->getLanguageName($original_langcode); - $languages[$original_langcode] = new Language(array('id' => $original_langcode, 'name' => $language_name)); + $languages[$original_langcode] = new Language(['id' => $original_langcode, 'name' => $language_name]); } // We create a fake request object to pass into @@ -181,10 +181,10 @@ public function itemPage(Request $request, RouteMatchInterface $route_match, $pl // possible nor performant. $fake_request = $request->duplicate(); - $page['languages'] = array( + $page['languages'] = [ '#type' => 'table', - '#header' => array($this->t('Language'), $this->t('Operations')), - ); + '#header' => [$this->t('Language'), $this->t('Operations')], + ]; foreach ($languages as $language) { $langcode = $language->getId(); @@ -198,57 +198,57 @@ public function itemPage(Request $request, RouteMatchInterface $route_match, $pl // Prepare the language name and the operations depending on whether this // is the original language or not. if ($langcode == $original_langcode) { - $language_name = '' . $this->t('@language (original)', array('@language' => $language->getName())) . ''; + $language_name = '' . $this->t('@language (original)', ['@language' => $language->getName()]) . ''; // Check access for the path/route for editing, so we can decide to // include a link to edit or not. $edit_access = $this->accessManager->checkNamedRoute($mapper->getBaseRouteName(), $route_match->getRawParameters()->all(), $this->account); // Build list of operations. - $operations = array(); + $operations = []; if ($edit_access) { - $operations['edit'] = array( + $operations['edit'] = [ 'title' => $this->t('Edit'), 'url' => Url::fromRoute($mapper->getBaseRouteName(), $mapper->getBaseRouteParameters(), ['query' => ['destination' => $mapper->getOverviewPath()]]), - ); + ]; } } else { $language_name = $language->getName(); - $operations = array(); + $operations = []; // If no translation exists for this language, link to add one. if (!$mapper->hasTranslation($language)) { - $operations['add'] = array( + $operations['add'] = [ 'title' => $this->t('Add'), 'url' => Url::fromRoute($mapper->getAddRouteName(), $mapper->getAddRouteParameters()), - ); + ]; } else { // Otherwise, link to edit the existing translation. - $operations['edit'] = array( + $operations['edit'] = [ 'title' => $this->t('Edit'), 'url' => Url::fromRoute($mapper->getEditRouteName(), $mapper->getEditRouteParameters()), - ); + ]; - $operations['delete'] = array( + $operations['delete'] = [ 'title' => $this->t('Delete'), 'url' => Url::fromRoute($mapper->getDeleteRouteName(), $mapper->getDeleteRouteParameters()), - ); + ]; } } - $page['languages'][$langcode]['language'] = array( + $page['languages'][$langcode]['language'] = [ '#markup' => $language_name, - ); + ]; - $page['languages'][$langcode]['operations'] = array( + $page['languages'][$langcode]['operations'] = [ '#type' => 'operations', '#links' => $operations, // Even if the mapper contains multiple language codes, the source // configuration can still be edited. '#access' => ($langcode == $original_langcode) || $operations_access, - ); + ]; } return $page; } diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationEntityListBuilder.php b/core/modules/config_translation/src/Controller/ConfigTranslationEntityListBuilder.php index e86237e3c9..87cb2605c0 100644 --- a/core/modules/config_translation/src/Controller/ConfigTranslationEntityListBuilder.php +++ b/core/modules/config_translation/src/Controller/ConfigTranslationEntityListBuilder.php @@ -16,10 +16,10 @@ class ConfigTranslationEntityListBuilder extends ConfigEntityListBuilder impleme * @return array */ protected function getFilterLabels() { - return array( + return [ 'placeholder' => $this->t('Enter label'), 'description' => $this->t('Enter a part of the label or description to filter by.'), - ); + ]; } /** @@ -29,28 +29,28 @@ public function render() { $build = parent::render(); $filter = $this->getFilterLabels(); - usort($build['table']['#rows'], array($this, 'sortRows')); + usort($build['table']['#rows'], [$this, 'sortRows']); - $build['filters'] = array( + $build['filters'] = [ '#type' => 'container', - '#attributes' => array( - 'class' => array('table-filter', 'js-show'), - ), + '#attributes' => [ + 'class' => ['table-filter', 'js-show'], + ], '#weight' => -10, - ); + ]; - $build['filters']['text'] = array( + $build['filters']['text'] = [ '#type' => 'search', '#title' => $this->t('Search'), '#size' => 30, '#placeholder' => $filter['placeholder'], - '#attributes' => array( - 'class' => array('table-filter-text'), + '#attributes' => [ + 'class' => ['table-filter-text'], 'data-table' => '.config-translation-entity-list', 'autocomplete' => 'off', 'title' => $filter['description'], - ), - ); + ], + ]; $build['table']['#attributes']['class'][] = 'config-translation-entity-list'; $build['table']['#weight'] = 0; @@ -95,7 +95,7 @@ public function getOperations(EntityInterface $entity) { * {@inheritdoc} */ public function sortRows($a, $b) { - return $this->sortRowsMultiple($a, $b, array('label')); + return $this->sortRowsMultiple($a, $b, ['label']); } /** diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationFieldListBuilder.php b/core/modules/config_translation/src/Controller/ConfigTranslationFieldListBuilder.php index 6388c811df..566afdbb23 100644 --- a/core/modules/config_translation/src/Controller/ConfigTranslationFieldListBuilder.php +++ b/core/modules/config_translation/src/Controller/ConfigTranslationFieldListBuilder.php @@ -26,14 +26,14 @@ class ConfigTranslationFieldListBuilder extends ConfigTranslationEntityListBuild * * @var array */ - protected $baseEntityInfo = array(); + protected $baseEntityInfo = []; /** * The bundle info for the base entity type. * * @var array */ - protected $baseEntityBundles = array(); + protected $baseEntityBundles = []; /** * The entity manager. @@ -99,8 +99,8 @@ public function getFilterLabels() { $bundle = $this->baseEntityInfo->getBundleLabel() ?: $this->t('Bundle'); $bundle = Unicode::strtolower($bundle); - $info['placeholder'] = $this->t('Enter field or @bundle', array('@bundle' => $bundle)); - $info['description'] = $this->t('Enter a part of the field or @bundle to filter by.', array('@bundle' => $bundle)); + $info['placeholder'] = $this->t('Enter field or @bundle', ['@bundle' => $bundle]); + $info['description'] = $this->t('Enter a part of the field or @bundle to filter by.', ['@bundle' => $bundle]); return $info; } @@ -109,17 +109,17 @@ public function getFilterLabels() { * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { - $row['label'] = array( + $row['label'] = [ 'data' => $entity->label(), 'class' => 'table-filter-text-source', - ); + ]; if ($this->displayBundle()) { $bundle = $entity->get('bundle'); - $row['bundle'] = array( + $row['bundle'] = [ 'data' => $this->baseEntityBundles[$bundle]['label'], 'class' => 'table-filter-text-source', - ); + ]; } return $row + parent::buildRow($entity); @@ -165,7 +165,7 @@ public function displayBundle() { * {@inheritdoc} */ public function sortRows($a, $b) { - return $this->sortRowsMultiple($a, $b, array('bundle', 'label')); + return $this->sortRowsMultiple($a, $b, ['bundle', 'label']); } } diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationMapperList.php b/core/modules/config_translation/src/Controller/ConfigTranslationMapperList.php index f47d313c28..4e510aaf38 100644 --- a/core/modules/config_translation/src/Controller/ConfigTranslationMapperList.php +++ b/core/modules/config_translation/src/Controller/ConfigTranslationMapperList.php @@ -46,13 +46,13 @@ public static function create(ContainerInterface $container) { * Renderable array with config translation mappers. */ public function render() { - $build = array( + $build = [ '#type' => 'table', '#header' => $this->buildHeader(), - '#rows' => array(), - ); + '#rows' => [], + ]; - $mappers = array(); + $mappers = []; foreach ($this->mappers as $mapper) { if ($row = $this->buildRow($mapper)) { @@ -120,10 +120,10 @@ protected function buildOperations(ConfigMapperInterface $mapper) { // Retrieve and sort operations. $operations = $mapper->getOperations(); uasort($operations, 'Drupal\Component\Utility\SortArray::sortByWeightElement'); - $build = array( + $build = [ '#type' => 'operations', '#links' => $operations, - ); + ]; return $build; } diff --git a/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php b/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php index 3d0620218a..9edcb8c60a 100644 --- a/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php +++ b/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php @@ -22,10 +22,10 @@ public function getFormId() { */ public function buildForm(array $form, FormStateInterface $form_state, RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) { $form = parent::buildForm($form, $form_state, $route_match, $plugin_id, $langcode); - $form['#title'] = $this->t('Add @language translation for %label', array( + $form['#title'] = $this->t('Add @language translation for %label', [ '%label' => $this->mapper->getTitle(), '@language' => $this->language->getName(), - )); + ]); return $form; } @@ -34,7 +34,7 @@ public function buildForm(array $form, FormStateInterface $form_state, RouteMatc */ public function submitForm(array &$form, FormStateInterface $form_state) { parent::submitForm($form, $form_state); - drupal_set_message($this->t('Successfully saved @language translation.', array('@language' => $this->language->getName()))); + drupal_set_message($this->t('Successfully saved @language translation.', ['@language' => $this->language->getName()])); } } diff --git a/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php b/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php index 089ae27109..ca3ad28aa3 100644 --- a/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php +++ b/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php @@ -84,7 +84,7 @@ public static function create(ContainerInterface $container) { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to delete the @language translation of %label?', array('%label' => $this->mapper->getTitle(), '@language' => $this->language->getName())); + return $this->t('Are you sure you want to delete the @language translation of %label?', ['%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()]); } /** @@ -140,7 +140,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $cache_backend->deleteAll(); } - drupal_set_message($this->t('@language translation of %label was deleted', array('%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()))); + drupal_set_message($this->t('@language translation of %label was deleted', ['%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()])); $form_state->setRedirectUrl($this->getCancelUrl()); } diff --git a/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php b/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php index 5af4244349..86a8f1cac2 100644 --- a/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php +++ b/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php @@ -22,10 +22,10 @@ public function getFormId() { */ public function buildForm(array $form, FormStateInterface $form_state, RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) { $form = parent::buildForm($form, $form_state, $route_match, $plugin_id, $langcode); - $form['#title'] = $this->t('Edit @language translation for %label', array( + $form['#title'] = $this->t('Edit @language translation for %label', [ '%label' => $this->mapper->getTitle(), '@language' => $this->language->getName(), - )); + ]); return $form; } @@ -34,7 +34,7 @@ public function buildForm(array $form, FormStateInterface $form_state, RouteMatc */ public function submitForm(array &$form, FormStateInterface $form_state) { parent::submitForm($form, $form_state); - drupal_set_message($this->t('Successfully updated @language translation.', array('@language' => $this->language->getName()))); + drupal_set_message($this->t('Successfully updated @language translation.', ['@language' => $this->language->getName()])); } } diff --git a/core/modules/config_translation/src/Form/ConfigTranslationFormBase.php b/core/modules/config_translation/src/Form/ConfigTranslationFormBase.php index 12e0216283..82f01d714a 100644 --- a/core/modules/config_translation/src/Form/ConfigTranslationFormBase.php +++ b/core/modules/config_translation/src/Form/ConfigTranslationFormBase.php @@ -65,7 +65,7 @@ * * @var array */ - protected $baseConfigData = array(); + protected $baseConfigData = []; /** * Constructs a ConfigTranslationFormBase. @@ -164,26 +164,26 @@ public function buildForm(array $form, FormStateInterface $form_state, RouteMatc // Even though this is a nested form, we do not set #tree to TRUE because // the form value structure is generated by using #parents for each element. // @see \Drupal\config_translation\FormElement\FormElementBase::getElements() - $form['config_names'] = array('#type' => 'container'); + $form['config_names'] = ['#type' => 'container']; foreach ($this->mapper->getConfigNames() as $name) { - $form['config_names'][$name] = array('#type' => 'container'); + $form['config_names'][$name] = ['#type' => 'container']; $schema = $this->typedConfigManager->get($name); $source_config = $this->baseConfigData[$name]; $translation_config = $this->configFactory()->get($name)->get(); if ($form_element = $this->createFormElement($schema)) { - $parents = array('config_names', $name); + $parents = ['config_names', $name]; $form['config_names'][$name] += $form_element->getTranslationBuild($this->sourceLanguage, $this->language, $source_config, $translation_config, $parents); } } $form['actions']['#type'] = 'actions'; - $form['actions']['submit'] = array( + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save translation'), '#button_type' => 'primary', - ); + ]; // Set the configuration language back. $this->languageManager->setConfigOverrideLanguage($original_language); @@ -195,7 +195,7 @@ public function buildForm(array $form, FormStateInterface $form_state, RouteMatc * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { - $form_values = $form_state->getValue(array('translation', 'config_names')); + $form_values = $form_state->getValue(['translation', 'config_names']); foreach ($this->mapper->getConfigNames() as $name) { $schema = $this->typedConfigManager->get($name); diff --git a/core/modules/config_translation/src/FormElement/DateFormat.php b/core/modules/config_translation/src/FormElement/DateFormat.php index 4a4b995861..d0ae033a42 100644 --- a/core/modules/config_translation/src/FormElement/DateFormat.php +++ b/core/modules/config_translation/src/FormElement/DateFormat.php @@ -16,7 +16,7 @@ public function getTranslationElement(LanguageInterface $translation_language, $ /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */ $date_formatter = \Drupal::service('date.formatter'); $description = $this->t('A user-defined date format. See the PHP manual for available options.'); - $format = $this->t('Displayed as %date_format', array('%date_format' => $date_formatter->format(REQUEST_TIME, 'custom', $translation_config))); + $format = $this->t('Displayed as %date_format', ['%date_format' => $date_formatter->format(REQUEST_TIME, 'custom', $translation_config)]); return [ '#type' => 'textfield', diff --git a/core/modules/config_translation/src/FormElement/FormElementBase.php b/core/modules/config_translation/src/FormElement/FormElementBase.php index 2b5c8f4780..3c97daf1b4 100644 --- a/core/modules/config_translation/src/FormElement/FormElementBase.php +++ b/core/modules/config_translation/src/FormElement/FormElementBase.php @@ -64,8 +64,8 @@ public function getTranslationBuild(LanguageInterface $source_language, Language $build['source'] = $this->getSourceElement($source_language, $source_config); $build['translation'] = $this->getTranslationElement($translation_language, $source_config, $translation_config); - $build['source']['#parents'] = array_merge(array('source'), $parents); - $build['translation']['#parents'] = array_merge(array('translation'), $parents); + $build['source']['#parents'] = array_merge(['source'], $parents); + $build['translation']['#parents'] = array_merge(['translation'], $parents); return $build; } @@ -93,15 +93,15 @@ protected function getSourceElement(LanguageInterface $source_language, $source_ $value = $this->t('(Empty)'); } - return array( + return [ '#type' => 'item', - '#title' => $this->t('@label (@source_language)', array( + '#title' => $this->t('@label (@source_language)', [ // Labels originate from configuration schema and are translatable. '@label' => $this->t($this->definition->getLabel()), '@source_language' => $source_language->getName(), - )), + ]), '#markup' => $value, - ); + ]; } /** @@ -157,15 +157,15 @@ protected function getSourceElement(LanguageInterface $source_language, $source_ */ protected function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) { // Add basic properties that apply to all form elements. - return array( - '#title' => $this->t('@label (@source_language)', array( + return [ + '#title' => $this->t('@label (@source_language)', [ // Labels originate from configuration schema and are translatable. '@label' => $this->t($this->definition->getLabel()), '@source_language' => $translation_language->getName(), - )), + ]), '#default_value' => $translation_config, - '#attributes' => array('lang' => $translation_language->getId()), - ); + '#attributes' => ['lang' => $translation_language->getId()], + ]; } /** diff --git a/core/modules/config_translation/src/FormElement/ListElement.php b/core/modules/config_translation/src/FormElement/ListElement.php index e956536e78..1ea452362b 100644 --- a/core/modules/config_translation/src/FormElement/ListElement.php +++ b/core/modules/config_translation/src/FormElement/ListElement.php @@ -46,14 +46,14 @@ public static function create(TypedDataInterface $schema) { * {@inheritdoc} */ public function getTranslationBuild(LanguageInterface $source_language, LanguageInterface $translation_language, $source_config, $translation_config, array $parents, $base_key = NULL) { - $build = array(); + $build = []; foreach ($this->element as $key => $element) { - $sub_build = array(); + $sub_build = []; $element_key = isset($base_key) ? "$base_key.$key" : $key; $definition = $element->getDataDefinition(); if ($form_element = ConfigTranslationFormBase::createFormElement($element)) { - $element_parents = array_merge($parents, array($key)); + $element_parents = array_merge($parents, [$key]); $sub_build += $form_element->getTranslationBuild($source_language, $translation_language, $source_config[$key], $translation_config[$key], $element_parents, $element_key); if (empty($sub_build)) { @@ -62,13 +62,13 @@ public function getTranslationBuild(LanguageInterface $source_language, Language // Build the sub-structure and include it with a wrapper in the form if // there are any translatable elements there. - $build[$key] = array(); + $build[$key] = []; if ($element instanceof TraversableTypedDataInterface) { - $build[$key] = array( + $build[$key] = [ '#type' => 'details', '#title' => $this->getGroupTitle($definition, $sub_build), '#open' => empty($base_key), - ); + ]; } $build[$key] += $sub_build; } diff --git a/core/modules/config_translation/src/FormElement/PluralVariants.php b/core/modules/config_translation/src/FormElement/PluralVariants.php index 624ff77bc7..aabca8a557 100644 --- a/core/modules/config_translation/src/FormElement/PluralVariants.php +++ b/core/modules/config_translation/src/FormElement/PluralVariants.php @@ -18,25 +18,25 @@ class PluralVariants extends FormElementBase { protected function getSourceElement(LanguageInterface $source_language, $source_config) { $plurals = $this->getNumberOfPlurals($source_language->getId()); $values = explode(LOCALE_PLURAL_DELIMITER, $source_config); - $element = array( + $element = [ '#type' => 'fieldset', - '#title' => SafeMarkup::format('@label (@source_language)', array( + '#title' => SafeMarkup::format('@label (@source_language)', [ // Labels originate from configuration schema and are translatable. '@label' => $this->t($this->definition->getLabel()), '@source_language' => $source_language->getName(), - )), + ]), '#tree' => TRUE, - ); + ]; for ($i = 0; $i < $plurals; $i++) { - $element[$i] = array( + $element[$i] = [ '#type' => 'item', // @todo Should use better labels https://www.drupal.org/node/2499639 '#title' => $i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form'), - '#markup' => SafeMarkup::format('@value', array( + '#markup' => SafeMarkup::format('@value', [ '@langcode' => $source_language->getId(), '@value' => isset($values[$i]) ? $values[$i] : $this->t('(Empty)'), - )), - ); + ]), + ]; } return $element; } @@ -47,23 +47,23 @@ protected function getSourceElement(LanguageInterface $source_language, $source_ protected function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) { $plurals = $this->getNumberOfPlurals($translation_language->getId()); $values = explode(LOCALE_PLURAL_DELIMITER, $translation_config); - $element = array( + $element = [ '#type' => 'fieldset', - '#title' => SafeMarkup::format('@label (@translation_language)', array( + '#title' => SafeMarkup::format('@label (@translation_language)', [ // Labels originate from configuration schema and are translatable. '@label' => $this->t($this->definition->getLabel()), '@translation_language' => $translation_language->getName(), - )), + ]), '#tree' => TRUE, - ); + ]; for ($i = 0; $i < $plurals; $i++) { - $element[$i] = array( + $element[$i] = [ '#type' => 'textfield', // @todo Should use better labels https://www.drupal.org/node/2499639 '#title' => $i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form'), '#default_value' => isset($values[$i]) ? $values[$i] : '', - '#attributes' => array('lang' => $translation_language->getId()), - ); + '#attributes' => ['lang' => $translation_language->getId()], + ]; } return $element; } diff --git a/core/modules/config_translation/src/FormElement/TextFormat.php b/core/modules/config_translation/src/FormElement/TextFormat.php index e9d56f29b9..f9f6bc61bc 100644 --- a/core/modules/config_translation/src/FormElement/TextFormat.php +++ b/core/modules/config_translation/src/FormElement/TextFormat.php @@ -16,25 +16,25 @@ public function getSourceElement(LanguageInterface $source_language, $source_con // Instead of the formatted output show a disabled textarea. This allows for // easier side-by-side comparison, especially with formats with text // editors. - return $this->getTranslationElement($source_language, $source_config, $source_config) + array( + return $this->getTranslationElement($source_language, $source_config, $source_config) + [ '#value' => $source_config['value'], '#disabled' => TRUE, '#allow_focus' => TRUE, - ); + ]; } /** * {@inheritdoc} */ public function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) { - return array( + return [ '#type' => 'text_format', // Override the #default_value property from the parent class. '#default_value' => $translation_config['value'], '#format' => $translation_config['format'], // @see \Drupal\config_translation\Element\FormElementBase::getTranslationElement() - '#allowed_formats' => array($source_config['format']), - ) + parent::getTranslationElement($translation_language, $source_config, $translation_config); + '#allowed_formats' => [$source_config['format']], + ] + parent::getTranslationElement($translation_language, $source_config, $translation_config); } } diff --git a/core/modules/config_translation/src/FormElement/Textarea.php b/core/modules/config_translation/src/FormElement/Textarea.php index 174a70c5c3..ff9e4cde40 100644 --- a/core/modules/config_translation/src/FormElement/Textarea.php +++ b/core/modules/config_translation/src/FormElement/Textarea.php @@ -18,10 +18,10 @@ public function getTranslationElement(LanguageInterface $translation_language, $ $rows_newlines = substr_count($translation_config, "\n" ) + 1; $rows = max($rows_words, $rows_newlines); - return array( + return [ '#type' => 'textarea', '#rows' => $rows, - ) + parent::getTranslationElement($translation_language, $source_config, $translation_config); + ] + parent::getTranslationElement($translation_language, $source_config, $translation_config); } } diff --git a/core/modules/config_translation/src/FormElement/Textfield.php b/core/modules/config_translation/src/FormElement/Textfield.php index fa0c869a0a..cff1037183 100644 --- a/core/modules/config_translation/src/FormElement/Textfield.php +++ b/core/modules/config_translation/src/FormElement/Textfield.php @@ -13,9 +13,9 @@ class Textfield extends FormElementBase { * {@inheritdoc} */ public function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) { - return array( + return [ '#type' => 'textfield', - ) + parent::getTranslationElement($translation_language, $source_config, $translation_config); + ] + parent::getTranslationElement($translation_language, $source_config, $translation_config); } } diff --git a/core/modules/config_translation/src/Plugin/Menu/ContextualLink/ConfigTranslationContextualLink.php b/core/modules/config_translation/src/Plugin/Menu/ContextualLink/ConfigTranslationContextualLink.php index fb2bf24cc2..63145a5d3b 100644 --- a/core/modules/config_translation/src/Plugin/Menu/ContextualLink/ConfigTranslationContextualLink.php +++ b/core/modules/config_translation/src/Plugin/Menu/ContextualLink/ConfigTranslationContextualLink.php @@ -28,7 +28,7 @@ public function getTitle() { // storing the title on the plugin definition for the link) because it // contains translated parts that we need in the runtime language. $type_name = Unicode::strtolower($this->mapperManager()->createInstance($this->pluginDefinition['config_translation_plugin_id'])->getTypeLabel()); - return $this->t('Translate @type_name', array('@type_name' => $type_name)); + return $this->t('Translate @type_name', ['@type_name' => $type_name]); } /** diff --git a/core/modules/config_translation/src/Plugin/Menu/LocalTask/ConfigTranslationLocalTask.php b/core/modules/config_translation/src/Plugin/Menu/LocalTask/ConfigTranslationLocalTask.php index 63605c66ac..5a88d91d0a 100644 --- a/core/modules/config_translation/src/Plugin/Menu/LocalTask/ConfigTranslationLocalTask.php +++ b/core/modules/config_translation/src/Plugin/Menu/LocalTask/ConfigTranslationLocalTask.php @@ -28,7 +28,7 @@ public function getTitle() { // storing the title on the plugin definition for the link) because // it contains translated parts that we need in the runtime language. $type_name = Unicode::strtolower($this->mapperManager()->createInstance($this->pluginDefinition['config_translation_plugin_id'])->getTypeLabel()); - return $this->t('Translate @type_name', array('@type_name' => $type_name)); + return $this->t('Translate @type_name', ['@type_name' => $type_name]); } /** diff --git a/core/modules/config_translation/src/Plugin/migrate/source/d6/I18nProfileField.php b/core/modules/config_translation/src/Plugin/migrate/source/d6/I18nProfileField.php index ecdffd65b6..2989f967b5 100644 --- a/core/modules/config_translation/src/Plugin/migrate/source/d6/I18nProfileField.php +++ b/core/modules/config_translation/src/Plugin/migrate/source/d6/I18nProfileField.php @@ -31,12 +31,12 @@ public function query() { * {@inheritdoc} */ public function fields() { - return array( + return [ 'fid' => $this->t('Profile field ID.'), 'lid' => $this->t('Locales target language ID.'), 'language' => $this->t('Language for this field.'), 'translation' => $this->t('Translation of either the title or explanation.'), - ); + ]; } /** diff --git a/core/modules/config_translation/src/Routing/RouteSubscriber.php b/core/modules/config_translation/src/Routing/RouteSubscriber.php index b20c13fdca..10044aa7f8 100644 --- a/core/modules/config_translation/src/Routing/RouteSubscriber.php +++ b/core/modules/config_translation/src/Routing/RouteSubscriber.php @@ -48,7 +48,7 @@ protected function alterRoutes(RouteCollection $collection) { */ public static function getSubscribedEvents() { // Come after field_ui. - $events[RoutingEvents::ALTER] = array('onAlterRoutes', -110); + $events[RoutingEvents::ALTER] = ['onAlterRoutes', -110]; return $events; } diff --git a/core/modules/config_translation/src/Tests/ConfigTranslationFormTest.php b/core/modules/config_translation/src/Tests/ConfigTranslationFormTest.php index 648f04739a..387d686460 100644 --- a/core/modules/config_translation/src/Tests/ConfigTranslationFormTest.php +++ b/core/modules/config_translation/src/Tests/ConfigTranslationFormTest.php @@ -17,7 +17,7 @@ class ConfigTranslationFormTest extends WebTestBase { * * @var array */ - public static $modules = array('config_translation', 'config_translation_test', 'editor'); + public static $modules = ['config_translation', 'config_translation_test', 'editor']; /** * The plugin ID of the mapper to test. @@ -40,7 +40,7 @@ protected function setUp() { $this->pluginId = key($definitions); $this->langcode = 'xx'; - ConfigurableLanguage::create(array('id' => $this->langcode, 'label' => 'XX'))->save(); + ConfigurableLanguage::create(['id' => $this->langcode, 'label' => 'XX'])->save(); \Drupal::state()->set('config_translation_test_alter_form_alter', TRUE); } diff --git a/core/modules/config_translation/src/Tests/ConfigTranslationOverviewTest.php b/core/modules/config_translation/src/Tests/ConfigTranslationOverviewTest.php index e7c58fd97d..d593a69d38 100644 --- a/core/modules/config_translation/src/Tests/ConfigTranslationOverviewTest.php +++ b/core/modules/config_translation/src/Tests/ConfigTranslationOverviewTest.php @@ -35,7 +35,7 @@ class ConfigTranslationOverviewTest extends WebTestBase { * * @var array */ - protected $langcodes = array('fr', 'ta'); + protected $langcodes = ['fr', 'ta']; /** * String translation storage object. @@ -46,7 +46,7 @@ class ConfigTranslationOverviewTest extends WebTestBase { protected function setUp() { parent::setUp(); - $permissions = array( + $permissions = [ 'translate configuration', 'administer languages', 'administer site configuration', @@ -54,7 +54,7 @@ protected function setUp() { 'access site-wide contact form', 'access contextual links', 'administer views', - ); + ]; // Create and log in user. $this->drupalLogin($this->drupalCreateUser($permissions)); @@ -83,17 +83,17 @@ public function testMapperListPage() { } } - $labels = array( + $labels = [ '&$nxd~i0', 'some "label" with quotes', $this->randomString(), - ); + ]; foreach ($labels as $label) { - $test_entity = entity_create('config_test', array( + $test_entity = entity_create('config_test', [ 'id' => $this->randomMachineName(), 'label' => $label, - )); + ]); $test_entity->save(); $base_url = 'admin/structure/config_test/manage/' . $test_entity->id(); @@ -119,7 +119,7 @@ public function testMapperListPage() { $this->assertRaw('' . t('Language') . ''); $this->drupalGet($base_url); - $this->assertLink(t('Translate @title', array('@title' => $entity_type->getLowercaseLabel()))); + $this->assertLink(t('Translate @title', ['@title' => $entity_type->getLowercaseLabel()])); } } @@ -154,10 +154,10 @@ public function testListingPageWithOverrides() { $config_test_storage = $this->container->get('entity.manager')->getStorage('config_test'); // Set up an override. - $settings['config']['config_test.dynamic.dotted.default']['label'] = (object) array( + $settings['config']['config_test.dynamic.dotted.default']['label'] = (object) [ 'value' => $overridden_label, 'required' => TRUE, - ); + ]; $this->writeSettings($settings); // Test that the overridden label is loaded with the entity. diff --git a/core/modules/config_translation/src/Tests/ConfigTranslationUiTest.php b/core/modules/config_translation/src/Tests/ConfigTranslationUiTest.php index 5018efa21f..7ec350ba2c 100644 --- a/core/modules/config_translation/src/Tests/ConfigTranslationUiTest.php +++ b/core/modules/config_translation/src/Tests/ConfigTranslationUiTest.php @@ -48,7 +48,7 @@ class ConfigTranslationUiTest extends WebTestBase { * * @var array */ - protected $langcodes = array('fr', 'ta'); + protected $langcodes = ['fr', 'ta']; /** * Administrator user for tests. @@ -157,13 +157,13 @@ public function testSiteInformationTranslationUi() { $this->assertRaw($site_slogan); // Update site name and slogan for French. - $edit = array( + $edit = [ 'translation[config_names][system.site][name]' => $fr_site_name, 'translation[config_names][system.site][slogan]' => $fr_site_slogan, - ); + ]; $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation')); - $this->assertRaw(t('Successfully saved @language translation.', array('@language' => 'French'))); + $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French'])); // Check for edit, delete links (and no 'add' link) for French language. $this->assertNoLinkByHref("$translation_base_url/fr/add"); @@ -189,18 +189,18 @@ public function testSiteInformationTranslationUi() { $this->assertText($site_slogan); // Translate 'Site name' label in French. - $search = array( + $search = [ 'string' => $site_name_label, 'langcode' => 'fr', 'translation' => 'untranslated', - ); + ]; $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter')); $textarea = current($this->xpath('//textarea')); $lid = (string) $textarea[0]['name']; - $edit = array( + $edit = [ $lid => $fr_site_name_label, - ); + ]; $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations')); // Ensure that the label is in French (and not in English). @@ -234,10 +234,10 @@ public function testSourceValueDuplicateSave() { $this->drupalGet($translation_base_url); // Case 1: Update new value for site slogan and site name. - $edit = array( + $edit = [ 'translation[config_names][system.site][name]' => 'FR ' . $site_name, 'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan, - ); + ]; // First time, no overrides, so just Add link. $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation')); @@ -245,10 +245,10 @@ public function testSourceValueDuplicateSave() { $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site'); // Expect both name and slogan in language specific file. - $expected = array( + $expected = [ 'name' => 'FR ' . $site_name, 'slogan' => 'FR ' . $site_slogan, - ); + ]; $this->assertEqual($expected, $override->get()); // Case 2: Update new value for site slogan and default value for site name. @@ -257,12 +257,12 @@ public function testSourceValueDuplicateSave() { // translation form into the actual site name and slogan. $this->assertNoText('FR ' . $site_name); $this->assertNoText('FR ' . $site_slogan); - $edit = array( + $edit = [ 'translation[config_names][system.site][name]' => $site_name, 'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save translation')); - $this->assertRaw(t('Successfully updated @language translation.', array('@language' => 'French'))); + $this->assertRaw(t('Successfully updated @language translation.', ['@language' => 'French'])); $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site'); // Expect only slogan in language specific file. @@ -272,10 +272,10 @@ public function testSourceValueDuplicateSave() { // Case 3: Keep default value for site name and slogan. $this->drupalGet("$translation_base_url/fr/edit"); $this->assertNoText('FR ' . $site_slogan); - $edit = array( + $edit = [ 'translation[config_names][system.site][name]' => $site_name, 'translation[config_names][system.site][slogan]' => $site_slogan, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save translation')); $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site'); @@ -310,11 +310,11 @@ public function testContactConfigEntityTranslation() { // Save default language configuration. $label = 'Send your feedback'; - $edit = array( + $edit = [ 'label' => $label, 'recipients' => 'sales@example.com,support@example.com', 'reply' => 'Thank you for your mail', - ); + ]; $this->drupalPostForm('admin/structure/contact/manage/feedback', $edit, t('Save')); // Ensure translation link is present. @@ -323,7 +323,7 @@ public function testContactConfigEntityTranslation() { // Make sure translate tab is present. $this->drupalGet('admin/structure/contact/manage/feedback'); - $this->assertLink(t('Translate @type', array('@type' => 'contact form'))); + $this->assertLink(t('Translate @type', ['@type' => 'contact form'])); // Visit the form to confirm the changes. $this->drupalGet('contact/feedback'); @@ -331,7 +331,7 @@ public function testContactConfigEntityTranslation() { foreach ($this->langcodes as $langcode) { $this->drupalGet($translation_base_url); - $this->assertLink(t('Translate @type', array('@type' => 'contact form'))); + $this->assertLink(t('Translate @type', ['@type' => 'contact form'])); // 'Add' link should be present for $langcode translation. $translation_page_url = "$translation_base_url/$langcode/add"; @@ -342,20 +342,20 @@ public function testContactConfigEntityTranslation() { $this->assertText($label); // Update translatable fields. - $edit = array( + $edit = [ 'translation[config_names][contact.form.feedback][label]' => 'Website feedback - ' . $langcode, 'translation[config_names][contact.form.feedback][reply]' => 'Thank you for your mail - ' . $langcode, - ); + ]; // Save language specific version of form. $this->drupalPostForm($translation_page_url, $edit, t('Save translation')); // Expect translated values in language specific file. $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback'); - $expected = array( + $expected = [ 'label' => 'Website feedback - ' . $langcode, 'reply' => 'Thank you for your mail - ' . $langcode, - ); + ]; $this->assertEqual($expected, $override->get()); // Check for edit, delete links (and no 'add' link) for $langcode. @@ -368,10 +368,10 @@ public function testContactConfigEntityTranslation() { $this->assertText('Website feedback - ' . $langcode); // Submit feedback. - $edit = array( + $edit = [ 'subject[0][value]' => 'Test subject', 'message[0][value]' => 'Test message', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Send message')); } @@ -379,7 +379,7 @@ public function testContactConfigEntityTranslation() { // original text all appear in any translated page on the translation // forms. foreach ($this->langcodes as $langcode) { - $langcode_prefixes = array_merge(array(''), $this->langcodes); + $langcode_prefixes = array_merge([''], $this->langcodes); foreach ($langcode_prefixes as $langcode_prefix) { $this->drupalGet(ltrim("$langcode_prefix/$translation_base_url/$langcode/edit", '/')); $this->assertFieldByName('translation[config_names][contact.form.feedback][label]', 'Website feedback - ' . $langcode); @@ -400,14 +400,14 @@ public function testContactConfigEntityTranslation() { // Test that delete links work and operations perform properly. foreach ($this->langcodes as $langcode) { - $replacements = array('%label' => t('@label @entity_type', array('@label' => $label, '@entity_type' => Unicode::strtolower(t('Contact form')))), '@language' => \Drupal::languageManager()->getLanguage($langcode)->getName()); + $replacements = ['%label' => t('@label @entity_type', ['@label' => $label, '@entity_type' => Unicode::strtolower(t('Contact form'))]), '@language' => \Drupal::languageManager()->getLanguage($langcode)->getName()]; $this->drupalGet("$translation_base_url/$langcode/delete"); $this->assertRaw(t('Are you sure you want to delete the @language translation of %label?', $replacements)); // Assert link back to list page to cancel delete is present. $this->assertLinkByHref($translation_base_url); - $this->drupalPostForm(NULL, array(), t('Delete')); + $this->drupalPostForm(NULL, [], t('Delete')); $this->assertRaw(t('@language translation of %label was deleted', $replacements)); $this->assertLinkByHref("$translation_base_url/$langcode/add"); $this->assertNoLinkByHref("translation_base_url/$langcode/edit"); @@ -445,18 +445,18 @@ public function testDateFormatTranslation() { $this->assertLinkByHref('admin/config/regional/date-time/formats/manage/medium'); // Save default language configuration for a new format. - $edit = array( + $edit = [ 'label' => 'Custom medium date', 'id' => 'custom_medium', 'date_format_pattern' => 'Y. m. d. H:i', - ); + ]; $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format')); // Test translating a default shipped format and our custom format. - $formats = array( + $formats = [ 'medium' => 'Default medium date', 'custom_medium' => 'Custom medium date', - ); + ]; foreach ($formats as $id => $label) { $translation_base_url = 'admin/config/regional/date-time/formats/manage/' . $id . '/translate'; @@ -474,20 +474,20 @@ public function testDateFormatTranslation() { $this->assertRaw('core/modules/system/js/system.date.js'); // Update translatable fields. - $edit = array( + $edit = [ 'translation[config_names][core.date_format.' . $id . '][label]' => $id . ' - FR', 'translation[config_names][core.date_format.' . $id . '][pattern]' => 'D', - ); + ]; // Save language specific version of form. $this->drupalPostForm($translation_page_url, $edit, t('Save translation')); // Get translation and check we've got the right value. $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'core.date_format.' . $id); - $expected = array( + $expected = [ 'label' => $id . ' - FR', 'pattern' => 'D', - ); + ]; $this->assertEqual($expected, $override->get()); // Formatting the date 8 / 27 / 1985 @ 13:37 EST with pattern D should @@ -508,18 +508,18 @@ public function testAccountSettingsConfigurationTranslation() { $this->drupalLogin($this->adminUser); $this->drupalGet('admin/config/people/accounts'); - $this->assertLink(t('Translate @type', array('@type' => 'account settings'))); + $this->assertLink(t('Translate @type', ['@type' => 'account settings'])); $this->drupalGet('admin/config/people/accounts/translate'); - $this->assertLink(t('Translate @type', array('@type' => 'account settings'))); + $this->assertLink(t('Translate @type', ['@type' => 'account settings'])); $this->assertLinkByHref('admin/config/people/accounts/translate/fr/add'); // Update account settings fields for French. - $edit = array( + $edit = [ 'translation[config_names][user.settings][anonymous]' => 'Anonyme', 'translation[config_names][user.mail][status_blocked][subject]' => 'Testing, your account is blocked.', 'translation[config_names][user.mail][status_blocked][body]' => 'Testing account blocked body.', - ); + ]; $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation')); @@ -588,7 +588,7 @@ public function testViewsTranslationUI() { $this->drupalLogin($this->adminUser); // Assert contextual link related to views. - $ids = array('entity.view.edit_form:view=frontpage:location=page&name=frontpage&display_id=page_1'); + $ids = ['entity.view.edit_form:view=frontpage:location=page&name=frontpage&display_id=page_1']; $response = $this->renderContextualLinks($ids, 'node'); $this->assertResponse(200); $json = Json::decode($response); @@ -611,14 +611,14 @@ public function testViewsTranslationUI() { $this->assertRaw($human_readable_name); // Update Views Fields for French. - $edit = array( + $edit = [ 'translation[config_names][views.view.frontpage][description]' => $description . " FR", 'translation[config_names][views.view.frontpage][label]' => $human_readable_name . " FR", 'translation[config_names][views.view.frontpage][display][default][display_title]' => $display_settings_master . " FR", 'translation[config_names][views.view.frontpage][display][default][display_options][title]' => $display_options_master . " FR", - ); + ]; $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation')); - $this->assertRaw(t('Successfully saved @language translation.', array('@language' => 'French'))); + $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French'])); // Check for edit, delete links (and no 'add' link) for French language. $this->assertNoLinkByHref("$translation_base_url/fr/add"); @@ -640,20 +640,20 @@ public function testPluralConfigStringsSourceElements() { $this->drupalLogin($this->adminUser); // Languages to test, with various number of plural forms. - $languages = array( - 'vi' => array('plurals' => 1, 'expected' => array(TRUE, FALSE, FALSE, FALSE)), - 'fr' => array('plurals' => 2, 'expected' => array(TRUE, TRUE, FALSE, FALSE)), - 'sl' => array('plurals' => 4, 'expected' => array(TRUE, TRUE, TRUE, TRUE)), - ); + $languages = [ + 'vi' => ['plurals' => 1, 'expected' => [TRUE, FALSE, FALSE, FALSE]], + 'fr' => ['plurals' => 2, 'expected' => [TRUE, TRUE, FALSE, FALSE]], + 'sl' => ['plurals' => 4, 'expected' => [TRUE, TRUE, TRUE, TRUE]], + ]; foreach ($languages as $langcode => $data) { // Import a .po file to add a new language with a given number of plural forms $name = \Drupal::service('file_system')->tempnam('temporary://', $langcode . '_') . '.po'; file_put_contents($name, $this->getPoFile($data['plurals'])); - $this->drupalPostForm('admin/config/regional/translate/import', array( + $this->drupalPostForm('admin/config/regional/translate/import', [ 'langcode' => $langcode, 'files[file]' => $name, - ), t('Import')); + ], t('Import')); // Change the config langcode of the 'files' view. $config = \Drupal::service('config.factory')->getEditable('views.view.files'); @@ -686,10 +686,10 @@ public function testPluralConfigStrings() { // This will also automatically add the 'sl' language. $name = \Drupal::service('file_system')->tempnam('temporary://', "sl_") . '.po'; file_put_contents($name, $this->getPoFile(4)); - $this->drupalPostForm('admin/config/regional/translate/import', array( + $this->drupalPostForm('admin/config/regional/translate/import', [ 'langcode' => 'sl', 'files[file]' => $name, - ), t('Import')); + ], t('Import')); // Translate the files view, as this one uses numeric formatters. $description = 'Singular form'; @@ -817,12 +817,12 @@ public function testLocaleDBStorage() { $langcode = 'xx'; $name = $this->randomMachineName(16); - $edit = array( + $edit = [ 'predefined_langcode' => 'custom', 'langcode' => $langcode, 'label' => $name, 'direction' => Language::DIRECTION_LTR, - ); + ]; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language')); // Make sure there is no translation stored in locale storage before edit. @@ -830,9 +830,9 @@ public function testLocaleDBStorage() { $this->assertTrue(empty($translation)); // Add custom translation. - $edit = array( + $edit = [ 'translation[config_names][user.settings][anonymous]' => 'Anonyme', - ); + ]; $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation')); // Make sure translation stored in locale storage after saved language @@ -841,9 +841,9 @@ public function testLocaleDBStorage() { $this->assertEqual('Anonyme', $translation->getString()); // revert custom translations to base translation. - $edit = array( + $edit = [ 'translation[config_names][user.settings][anonymous]' => 'Anonymous', - ); + ]; $this->drupalPostForm('admin/config/people/accounts/translate/fr/edit', $edit, t('Save translation')); // Make sure there is no translation stored in locale storage after revert. @@ -858,19 +858,19 @@ public function testSingleLanguageUI() { $this->drupalLogin($this->adminUser); // Delete French language - $this->drupalPostForm('admin/config/regional/language/delete/fr', array(), t('Delete')); - $this->assertRaw(t('The %language (%langcode) language has been removed.', array('%language' => 'French', '%langcode' => 'fr'))); + $this->drupalPostForm('admin/config/regional/language/delete/fr', [], t('Delete')); + $this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'French', '%langcode' => 'fr'])); // Change default language to Tamil. - $edit = array( + $edit = [ 'site_default_language' => 'ta', - ); + ]; $this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration')); $this->assertRaw(t('Configuration saved.')); // Delete English language - $this->drupalPostForm('admin/config/regional/language/delete/en', array(), t('Delete')); - $this->assertRaw(t('The %language (%langcode) language has been removed.', array('%language' => 'English', '%langcode' => 'en'))); + $this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete')); + $this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'English', '%langcode' => 'en'])); // Visit account setting translation page, this should not // throw any notices. @@ -907,32 +907,32 @@ public function testSequenceTranslation() { /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */ $config_factory = $this->container->get('config.factory'); - $expected = array( + $expected = [ 'kitten', 'llama', 'elephant' - ); + ]; $actual = $config_factory ->getEditable('config_translation_test.content') ->get('animals'); $this->assertEqual($expected, $actual); - $edit = array( + $edit = [ 'translation[config_names][config_translation_test.content][content][value]' => '

        Hello World - FR

        ', 'translation[config_names][config_translation_test.content][animals][0]' => 'kitten - FR', 'translation[config_names][config_translation_test.content][animals][1]' => 'llama - FR', 'translation[config_names][config_translation_test.content][animals][2]' => 'elephant - FR', - ); + ]; $this->drupalPostForm('admin/config/media/file-system/translate/fr/add', $edit, t('Save translation')); $this->container->get('language.config_factory_override') - ->setLanguage(new Language(array('id' => 'fr'))); + ->setLanguage(new Language(['id' => 'fr'])); - $expected = array( + $expected = [ 'kitten - FR', 'llama - FR', 'elephant - FR', - ); + ]; $actual = $config_factory ->get('config_translation_test.content') ->get('animals'); @@ -947,10 +947,10 @@ public function testTextFormatTranslation() { /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */ $config_factory = $this->container->get('config.factory'); - $expected = array( + $expected = [ 'value' => '

        Hello World

        ', 'format' => 'plain_text', - ); + ]; $actual = $config_factory ->get('config_translation_test.content') ->getOriginal('content', FALSE); @@ -970,20 +970,20 @@ public function testTextFormatTranslation() { $this->assertNoFieldByName('translation[config_names][config_translation_test.content][content][format]'); // Update translatable fields. - $edit = array( + $edit = [ 'translation[config_names][config_translation_test.content][content][value]' => '

        Hello World - FR

        ', - ); + ]; // Save language specific version of form. $this->drupalPostForm($translation_page_url, $edit, t('Save translation')); // Get translation and check we've got the right value. - $expected = array( + $expected = [ 'value' => '

        Hello World - FR

        ', 'format' => 'plain_text', - ); + ]; $this->container->get('language.config_factory_override') - ->setLanguage(new Language(array('id' => 'fr'))); + ->setLanguage(new Language(['id' => 'fr'])); $actual = $config_factory ->get('config_translation_test.content') ->get('content'); @@ -1009,7 +1009,7 @@ public function testTextFormatTranslation() { $this->drupalLogin($this->translatorUser); $this->drupalGet($translation_page_url); $this->assertDisabledTextarea('edit-translation-config-names-config-translation-testcontent-content-value'); - $this->drupalPostForm(NULL, array(), t('Save translation')); + $this->drupalPostForm(NULL, [], t('Save translation')); // Check that submitting the form did not update the text format of the // translation. $actual = $config_factory @@ -1019,14 +1019,14 @@ public function testTextFormatTranslation() { // The administrator must explicitly change the text format. $this->drupalLogin($this->adminUser); - $edit = array( + $edit = [ 'translation[config_names][config_translation_test.content][content][format]' => 'full_html', - ); + ]; $this->drupalPostForm($translation_page_url, $edit, t('Save translation')); - $expected = array( + $expected = [ 'value' => '

        Hello World - FR

        ', 'format' => 'full_html', - ); + ]; $actual = $config_factory ->get('config_translation_test.content') ->get('content'); @@ -1047,20 +1047,20 @@ public function testTextFormatTranslation() { * Returns translation if exists, FALSE otherwise. */ protected function getTranslation($config_name, $key, $langcode) { - $settings_locations = $this->localeStorage->getLocations(array('type' => 'configuration', 'name' => $config_name)); - $this->assertTrue(!empty($settings_locations), format_string('Configuration locations found for %config_name.', array('%config_name' => $config_name))); + $settings_locations = $this->localeStorage->getLocations(['type' => 'configuration', 'name' => $config_name]); + $this->assertTrue(!empty($settings_locations), format_string('Configuration locations found for %config_name.', ['%config_name' => $config_name])); if (!empty($settings_locations)) { $source = $this->container->get('config.factory')->get($config_name)->get($key); - $source_string = $this->localeStorage->findString(array('source' => $source, 'type' => 'configuration')); - $this->assertTrue(!empty($source_string), format_string('Found string for %config_name.%key.', array('%config_name' => $config_name, '%key' => $key))); + $source_string = $this->localeStorage->findString(['source' => $source, 'type' => 'configuration']); + $this->assertTrue(!empty($source_string), format_string('Found string for %config_name.%key.', ['%config_name' => $config_name, '%key' => $key])); if (!empty($source_string)) { - $conditions = array( + $conditions = [ 'lid' => $source_string->lid, 'language' => $langcode, - ); - $translations = $this->localeStorage->getTranslations($conditions + array('translated' => TRUE)); + ]; + $translations = $this->localeStorage->getTranslations($conditions + ['translated' => TRUE]); return reset($translations); } } @@ -1074,10 +1074,10 @@ protected function getTranslation($config_name, $key, $langcode) { * @param string $site_slogan */ protected function setSiteInformation($site_name, $site_slogan) { - $edit = array( + $edit = [ 'site_name' => $site_name, 'site_slogan' => $site_slogan, - ); + ]; $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration')); $this->assertRaw(t('The configuration options have been saved.')); } @@ -1094,11 +1094,11 @@ protected function setSiteInformation($site_name, $site_slogan) { * The response body. */ protected function renderContextualLinks($ids, $current_path) { - $post = array(); + $post = []; for ($i = 0; $i < count($ids); $i++) { $post['ids[' . $i . ']'] = $ids[$i]; } - return $this->drupalPostWithFormat('contextual/render', 'json', $post, array('query' => array('destination' => $current_path))); + return $this->drupalPostWithFormat('contextual/render', 'json', $post, ['query' => ['destination' => $current_path]]); } /** @@ -1111,30 +1111,30 @@ protected function renderContextualLinks($ids, $current_path) { * TRUE if the assertion passed; FALSE otherwise. */ protected function assertDisabledTextarea($id) { - $textarea = $this->xpath('//textarea[@id=:id and contains(@disabled, "disabled")]', array( + $textarea = $this->xpath('//textarea[@id=:id and contains(@disabled, "disabled")]', [ ':id' => $id, - )); + ]); $textarea = reset($textarea); - $passed = $this->assertTrue($textarea instanceof \SimpleXMLElement, SafeMarkup::format('Disabled field @id exists.', array( + $passed = $this->assertTrue($textarea instanceof \SimpleXMLElement, SafeMarkup::format('Disabled field @id exists.', [ '@id' => $id, - ))); + ])); $expected = 'This field has been disabled because you do not have sufficient permissions to edit it.'; - $passed = $passed && $this->assertEqual((string) $textarea, $expected, SafeMarkup::format('Disabled textarea @id hides text in an inaccessible text format.', array( + $passed = $passed && $this->assertEqual((string) $textarea, $expected, SafeMarkup::format('Disabled textarea @id hides text in an inaccessible text format.', [ '@id' => $id, - ))); + ])); // Make sure the text format select is not shown. $select_id = str_replace('value', 'format--2', $id); - $select = $this->xpath('//select[@id=:id]', array(':id' => $select_id)); - return $passed && $this->assertFalse($select, SafeMarkup::format('Field @id does not exist.', array( + $select = $this->xpath('//select[@id=:id]', [':id' => $select_id]); + return $passed && $this->assertFalse($select, SafeMarkup::format('Field @id does not exist.', [ '@id' => $id, - ))); + ])); } /** * Helper function that returns a .po file with a given number of plural forms. */ public function getPoFile($plurals) { - $po_file = array(); + $po_file = []; $po_file[1] = <<< EOF msgid "" diff --git a/core/modules/config_translation/src/Tests/ConfigTranslationUiThemeTest.php b/core/modules/config_translation/src/Tests/ConfigTranslationUiThemeTest.php index ab51a43efa..53713a9238 100644 --- a/core/modules/config_translation/src/Tests/ConfigTranslationUiThemeTest.php +++ b/core/modules/config_translation/src/Tests/ConfigTranslationUiThemeTest.php @@ -24,7 +24,7 @@ class ConfigTranslationUiThemeTest extends WebTestBase { * * @var array */ - protected $langcodes = array('fr', 'ta'); + protected $langcodes = ['fr', 'ta']; /** * Administrator user for tests. diff --git a/core/modules/config_translation/tests/modules/config_translation_test/config_translation_test.module b/core/modules/config_translation/tests/modules/config_translation_test/config_translation_test.module index eb41793ab4..8c00b90d05 100644 --- a/core/modules/config_translation/tests/modules/config_translation_test/config_translation_test.module +++ b/core/modules/config_translation/tests/modules/config_translation_test/config_translation_test.module @@ -33,7 +33,7 @@ function config_translation_test_entity_type_alter(array &$entity_types) { function config_translation_test_config_translation_info_alter(&$info) { if (\Drupal::state()->get('config_translation_test_config_translation_info_alter')) { // Limit account settings config files to only one of them. - $info['entity.user.admin_form']['names'] = array('user.settings'); + $info['entity.user.admin_form']['names'] = ['user.settings']; // Add one more config file to the site information page. $info['system.site_information_settings']['names'][] = 'system.rss'; diff --git a/core/modules/config_translation/tests/src/Functional/ConfigTranslationDateFormatUiTest.php b/core/modules/config_translation/tests/src/Functional/ConfigTranslationDateFormatUiTest.php index 9ddbdf3a91..95af49eea9 100644 --- a/core/modules/config_translation/tests/src/Functional/ConfigTranslationDateFormatUiTest.php +++ b/core/modules/config_translation/tests/src/Functional/ConfigTranslationDateFormatUiTest.php @@ -12,11 +12,11 @@ */ class ConfigTranslationDateFormatUiTest extends BrowserTestBase { - public static $modules = array( + public static $modules = [ 'language', 'config_translation', 'system' - ); + ]; protected function setUp() { parent::setUp(); @@ -27,10 +27,10 @@ protected function setUp() { ConfigurableLanguage::createFromLangcode($langcode)->save(); } - $user = $this->drupalCreateUser(array( + $user = $this->drupalCreateUser([ 'administer site configuration', 'translate configuration', - )); + ]); $this->drupalLogin($user); } diff --git a/core/modules/config_translation/tests/src/Functional/ConfigTranslationListUiTest.php b/core/modules/config_translation/tests/src/Functional/ConfigTranslationListUiTest.php index db4af565bc..586d197579 100644 --- a/core/modules/config_translation/tests/src/Functional/ConfigTranslationListUiTest.php +++ b/core/modules/config_translation/tests/src/Functional/ConfigTranslationListUiTest.php @@ -26,7 +26,7 @@ class ConfigTranslationListUiTest extends BrowserTestBase { * * @var array */ - public static $modules = array( + public static $modules = [ 'block', 'config_translation', 'contact', @@ -40,7 +40,7 @@ class ConfigTranslationListUiTest extends BrowserTestBase { 'image', 'responsive_image', 'toolbar', - ); + ]; /** * Admin user with all needed permissions. @@ -52,7 +52,7 @@ class ConfigTranslationListUiTest extends BrowserTestBase { protected function setUp() { parent::setUp(); - $permissions = array( + $permissions = [ 'access site-wide contact form', 'administer blocks', 'administer contact forms', @@ -70,7 +70,7 @@ protected function setUp() { 'administer image styles', 'administer responsive images', 'translate configuration', - ); + ]; // Create and log in user. $this->adminUser = $this->drupalCreateUser($permissions); @@ -94,7 +94,7 @@ protected function doBlockListTest() { // Add a test block, any block will do. // Set the machine name so the translate link can be built later. $id = Unicode::strtolower($this->randomMachineName(16)); - $this->drupalPlaceBlock('system_powered_by_block', array('id' => $id)); + $this->drupalPlaceBlock('system_powered_by_block', ['id' => $id]); // Get the Block listing. $this->drupalGet('admin/structure/block'); @@ -118,11 +118,11 @@ protected function doMenuListTest() { // Lowercase the machine name. $menu_name = Unicode::strtolower($this->randomMachineName(16)); $label = $this->randomMachineName(16); - $edit = array( + $edit = [ 'id' => $menu_name, 'description' => '', 'label' => $label, - ); + ]; // Create the menu by posting the form. $this->drupalPostForm('admin/structure/menu/add', $edit, t('Save')); @@ -135,9 +135,9 @@ protected function doMenuListTest() { // Check if the Link is not added if you are missing 'translate // configuration' permission. - $permissions = array( + $permissions = [ 'administer menu', - ); + ]; $this->drupalLogin($this->drupalCreateUser($permissions)); // Get the Menu listing. @@ -186,11 +186,11 @@ protected function doVocabularyListTest() { public function doCustomContentTypeListTest() { // Create a test custom block type to decouple looking for translate // operations link so this does not test more than necessary. - $block_content_type = BlockContentType::create(array( + $block_content_type = BlockContentType::create([ 'id' => Unicode::strtolower($this->randomMachineName(16)), 'label' => $this->randomMachineName(), 'revision' => FALSE - )); + ]); $block_content_type->save(); // Get the custom block type listing. @@ -235,10 +235,10 @@ public function doContactFormsListTest() { public function doContentTypeListTest() { // Create a test content type to decouple looking for translate operations // link so this does not test more than necessary. - $content_type = $this->drupalCreateContentType(array( + $content_type = $this->drupalCreateContentType([ 'type' => Unicode::strtolower($this->randomMachineName(16)), 'name' => $this->randomMachineName(), - )); + ]); // Get the content type listing. $this->drupalGet('admin/structure/types'); @@ -258,10 +258,10 @@ public function doContentTypeListTest() { public function doFormatsListTest() { // Create a test format to decouple looking for translate operations // link so this does not test more than necessary. - $filter_format = FilterFormat::create(array( + $filter_format = FilterFormat::create([ 'format' => Unicode::strtolower($this->randomMachineName(16)), 'name' => $this->randomMachineName(), - )); + ]); $filter_format->save(); // Get the format listing. @@ -282,10 +282,10 @@ public function doFormatsListTest() { public function doShortcutListTest() { // Create a test shortcut to decouple looking for translate operations // link so this does not test more than necessary. - $shortcut = ShortcutSet::create(array( + $shortcut = ShortcutSet::create([ 'id' => Unicode::strtolower($this->randomMachineName(16)), 'label' => $this->randomString(), - )); + ]); $shortcut->save(); // Get the shortcut listing. @@ -307,7 +307,7 @@ public function doUserRoleListTest() { // Create a test role to decouple looking for translate operations // link so this does not test more than necessary. $role_id = Unicode::strtolower($this->randomMachineName(16)); - $this->drupalCreateRole(array(), $role_id); + $this->drupalCreateRole([], $role_id); // Get the role listing. $this->drupalGet('admin/people/roles'); @@ -361,13 +361,13 @@ public function doImageStyleListTest() { * Tests the responsive image mapping listing for the translate operation. */ public function doResponsiveImageListTest() { - $edit = array(); + $edit = []; $edit['label'] = $this->randomMachineName(); $edit['id'] = strtolower($edit['label']); $edit['fallback_image_style'] = 'thumbnail'; $this->drupalPostForm('admin/config/media/responsive-image-style/add', $edit, t('Save')); - $this->assertRaw(t('Responsive image style %label saved.', array('%label' => $edit['label']))); + $this->assertRaw(t('Responsive image style %label saved.', ['%label' => $edit['label']])); // Get the responsive image style listing. $this->drupalGet('admin/config/media/responsive-image-style'); @@ -386,17 +386,17 @@ public function doResponsiveImageListTest() { */ public function doFieldListTest() { // Create a base content type. - $content_type = $this->drupalCreateContentType(array( + $content_type = $this->drupalCreateContentType([ 'type' => Unicode::strtolower($this->randomMachineName(16)), 'name' => $this->randomMachineName(), - )); + ]); // Create a block content type. - $block_content_type = BlockContentType::create(array( + $block_content_type = BlockContentType::create([ 'id' => 'basic', 'label' => 'Basic', 'revision' => FALSE - )); + ]); $block_content_type->save(); $field = FieldConfig::create([ // The field storage is guaranteed to exist because it is supplied by the @@ -404,21 +404,21 @@ public function doFieldListTest() { 'field_storage' => FieldStorageConfig::loadByName('block_content', 'body'), 'bundle' => $block_content_type->id(), 'label' => 'Body', - 'settings' => array('display_summary' => FALSE), + 'settings' => ['display_summary' => FALSE], ]); $field->save(); // Look at a few fields on a few entity types. - $pages = array( - array( + $pages = [ + [ 'list' => 'admin/structure/types/manage/' . $content_type->id() . '/fields', 'field' => 'node.' . $content_type->id() . '.body', - ), - array( + ], + [ 'list' => 'admin/structure/block/block-content/manage/basic/fields', 'field' => 'block_content.basic.body', - ), - ); + ], + ]; foreach ($pages as $values) { // Get fields listing. diff --git a/core/modules/config_translation/tests/src/Functional/ConfigTranslationViewListUiTest.php b/core/modules/config_translation/tests/src/Functional/ConfigTranslationViewListUiTest.php index 9a9aee3d26..066dcd52bd 100644 --- a/core/modules/config_translation/tests/src/Functional/ConfigTranslationViewListUiTest.php +++ b/core/modules/config_translation/tests/src/Functional/ConfigTranslationViewListUiTest.php @@ -16,22 +16,22 @@ class ConfigTranslationViewListUiTest extends UITestBase { * * @var array */ - public static $testViews = array('node', 'test_view'); + public static $testViews = ['node', 'test_view']; /** * Modules to enable. * * @var array */ - public static $modules = array('config_translation', 'views_ui'); + public static $modules = ['config_translation', 'views_ui']; protected function setUp() { parent::setUp(); - $permissions = array( + $permissions = [ 'administer views', 'translate configuration', - ); + ]; // Create and log in user. $this->drupalLogin($this->drupalCreateUser($permissions)); diff --git a/core/modules/config_translation/tests/src/Unit/ConfigEntityMapperTest.php b/core/modules/config_translation/tests/src/Unit/ConfigEntityMapperTest.php index dc56e8db91..11e72c2dff 100644 --- a/core/modules/config_translation/tests/src/Unit/ConfigEntityMapperTest.php +++ b/core/modules/config_translation/tests/src/Unit/ConfigEntityMapperTest.php @@ -62,14 +62,14 @@ protected function setUp() { ->with('entity.configurable_language.edit_form') ->will($this->returnValue(new Route('/admin/config/regional/language/edit/{configurable_language}'))); - $definition = array( + $definition = [ 'class' => '\Drupal\config_translation\ConfigEntityMapper', 'base_route_name' => 'entity.configurable_language.edit_form', 'title' => '@label language', - 'names' => array(), + 'names' => [], 'entity_type' => 'configurable_language', 'route_name' => 'config_translation.item.overview.entity.configurable_language.edit_form', - ); + ]; $typed_config_manager = $this->getMock('Drupal\Core\Config\TypedConfigManagerInterface'); @@ -152,7 +152,7 @@ public function testGetOverviewRouteParameters() { $result = $this->configEntityMapper->getOverviewRouteParameters(); - $this->assertSame(array('configurable_language' => 'entity_id'), $result); + $this->assertSame(['configurable_language' => 'entity_id'], $result); } /** @@ -205,12 +205,12 @@ public function testGetTypeLabel() { public function testGetOperations() { $result = $this->configEntityMapper->getOperations(); - $expected = array( - 'list' => array( + $expected = [ + 'list' => [ 'title' => 'List', 'url' => Url::fromRoute('config_translation.entity_list', ['mapper_id' => 'configurable_language']), - ), - ); + ], + ]; $this->assertEquals($expected, $result); } diff --git a/core/modules/config_translation/tests/src/Unit/ConfigFieldMapperTest.php b/core/modules/config_translation/tests/src/Unit/ConfigFieldMapperTest.php index 204d84e1ed..8e6d0b903b 100644 --- a/core/modules/config_translation/tests/src/Unit/ConfigFieldMapperTest.php +++ b/core/modules/config_translation/tests/src/Unit/ConfigFieldMapperTest.php @@ -42,13 +42,13 @@ protected function setUp() { $this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface'); $this->entity = $this->getMock('Drupal\field\FieldConfigInterface'); - $definition = array( + $definition = [ 'class' => '\Drupal\config_translation\ConfigFieldMapper', 'base_route_name' => 'entity.field_config.node_field_edit_form', 'title' => '@label field', - 'names' => array(), + 'names' => [], 'entity_type' => 'field_config', - ); + ]; $locale_config_manager = $this->getMockBuilder('Drupal\locale\LocaleConfigManager') ->disableOriginalConstructor() diff --git a/core/modules/config_translation/tests/src/Unit/ConfigMapperManagerTest.php b/core/modules/config_translation/tests/src/Unit/ConfigMapperManagerTest.php index 10bbf7da88..9f064aca21 100644 --- a/core/modules/config_translation/tests/src/Unit/ConfigMapperManagerTest.php +++ b/core/modules/config_translation/tests/src/Unit/ConfigMapperManagerTest.php @@ -31,7 +31,7 @@ class ConfigMapperManagerTest extends UnitTestCase { protected $typedConfigManager; protected function setUp() { - $language = new Language(array('id' => 'en')); + $language = new Language(['id' => 'en']); $language_manager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface'); $language_manager->expects($this->once()) ->method('getCurrentLanguage') @@ -83,50 +83,50 @@ public function testHasTranslatable(TypedDataInterface $element, $expected) { * ConfigMapperManager::hasTranslatable() as the second key. */ public function providerTestHasTranslatable() { - return array( - array($this->getElement(array()), FALSE), - array($this->getElement(array('aaa' => 'bbb')), FALSE), - array($this->getElement(array('translatable' => FALSE)), FALSE), - array($this->getElement(array('translatable' => TRUE)), TRUE), - array($this->getNestedElement(array( - $this->getElement(array()), - )), FALSE), - array($this->getNestedElement(array( - $this->getElement(array('translatable' => TRUE)), - )), TRUE), - array($this->getNestedElement(array( - $this->getElement(array('aaa' => 'bbb')), - $this->getElement(array('ccc' => 'ddd')), - $this->getElement(array('eee' => 'fff')), - )), FALSE), - array($this->getNestedElement(array( - $this->getElement(array('aaa' => 'bbb')), - $this->getElement(array('ccc' => 'ddd')), - $this->getElement(array('translatable' => TRUE)), - )), TRUE), - array($this->getNestedElement(array( - $this->getElement(array('aaa' => 'bbb')), - $this->getNestedElement(array( - $this->getElement(array('ccc' => 'ddd')), - $this->getElement(array('eee' => 'fff')), - )), - $this->getNestedElement(array( - $this->getElement(array('ggg' => 'hhh')), - $this->getElement(array('iii' => 'jjj')), - )), - )), FALSE), - array($this->getNestedElement(array( - $this->getElement(array('aaa' => 'bbb')), - $this->getNestedElement(array( - $this->getElement(array('ccc' => 'ddd')), - $this->getElement(array('eee' => 'fff')), - )), - $this->getNestedElement(array( - $this->getElement(array('ggg' => 'hhh')), - $this->getElement(array('translatable' => TRUE)), - )), - )), TRUE), - ); + return [ + [$this->getElement([]), FALSE], + [$this->getElement(['aaa' => 'bbb']), FALSE], + [$this->getElement(['translatable' => FALSE]), FALSE], + [$this->getElement(['translatable' => TRUE]), TRUE], + [$this->getNestedElement([ + $this->getElement([]), + ]), FALSE], + [$this->getNestedElement([ + $this->getElement(['translatable' => TRUE]), + ]), TRUE], + [$this->getNestedElement([ + $this->getElement(['aaa' => 'bbb']), + $this->getElement(['ccc' => 'ddd']), + $this->getElement(['eee' => 'fff']), + ]), FALSE], + [$this->getNestedElement([ + $this->getElement(['aaa' => 'bbb']), + $this->getElement(['ccc' => 'ddd']), + $this->getElement(['translatable' => TRUE]), + ]), TRUE], + [$this->getNestedElement([ + $this->getElement(['aaa' => 'bbb']), + $this->getNestedElement([ + $this->getElement(['ccc' => 'ddd']), + $this->getElement(['eee' => 'fff']), + ]), + $this->getNestedElement([ + $this->getElement(['ggg' => 'hhh']), + $this->getElement(['iii' => 'jjj']), + ]), + ]), FALSE], + [$this->getNestedElement([ + $this->getElement(['aaa' => 'bbb']), + $this->getNestedElement([ + $this->getElement(['ccc' => 'ddd']), + $this->getElement(['eee' => 'fff']), + ]), + $this->getNestedElement([ + $this->getElement(['ggg' => 'hhh']), + $this->getElement(['translatable' => TRUE]), + ]), + ]), TRUE], + ]; } /** diff --git a/core/modules/config_translation/tests/src/Unit/ConfigNamesMapperTest.php b/core/modules/config_translation/tests/src/Unit/ConfigNamesMapperTest.php index cbf42c809c..e7a06794f8 100644 --- a/core/modules/config_translation/tests/src/Unit/ConfigNamesMapperTest.php +++ b/core/modules/config_translation/tests/src/Unit/ConfigNamesMapperTest.php @@ -91,13 +91,13 @@ class ConfigNamesMapperTest extends UnitTestCase { protected function setUp() { $this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface'); - $this->pluginDefinition = array( + $this->pluginDefinition = [ 'class' => '\Drupal\config_translation\ConfigNamesMapper', 'base_route_name' => 'system.site_information_settings', 'title' => 'System information', - 'names' => array('system.site'), + 'names' => ['system.site'], 'weight' => 42, - ); + ]; $this->typedConfigManager = $this->getMock('Drupal\Core\Config\TypedConfigManagerInterface'); @@ -156,7 +156,7 @@ public function testGetBaseRouteName() { */ public function testGetBaseRouteParameters() { $result = $this->configNamesMapper->getBaseRouteParameters(); - $this->assertSame(array(), $result); + $this->assertSame([], $result); } /** @@ -193,7 +193,7 @@ public function testGetOverviewRouteName() { */ public function testGetOverviewRouteParameters() { $result = $this->configNamesMapper->getOverviewRouteParameters(); - $this->assertSame(array(), $result); + $this->assertSame([], $result); } /** @@ -201,13 +201,13 @@ public function testGetOverviewRouteParameters() { */ public function testGetOverviewRoute() { $expected = new Route('/admin/config/system/site-information/translate', - array( + [ '_controller' => '\Drupal\config_translation\Controller\ConfigTranslationController::itemPage', 'plugin_id' => 'system.site_information_settings', - ), - array( + ], + [ '_config_translation_overview_access' => 'TRUE', - ) + ] ); $result = $this->configNamesMapper->getOverviewRoute(); $this->assertSame(serialize($expected), serialize($result)); @@ -242,7 +242,7 @@ public function testGetAddRouteParameters() { $route_match = new RouteMatch('example', new Route('/test/{langcode}'), ['langcode' => 'xx']); $this->configNamesMapper->populateFromRouteMatch($route_match); - $expected = array('langcode' => 'xx'); + $expected = ['langcode' => 'xx']; $result = $this->configNamesMapper->getAddRouteParameters(); $this->assertSame($expected, $result); } @@ -252,13 +252,13 @@ public function testGetAddRouteParameters() { */ public function testGetAddRoute() { $expected = new Route('/admin/config/system/site-information/translate/{langcode}/add', - array( + [ '_form' => '\Drupal\config_translation\Form\ConfigTranslationAddForm', 'plugin_id' => 'system.site_information_settings', - ), - array( + ], + [ '_config_translation_form_access' => 'TRUE', - ) + ] ); $result = $this->configNamesMapper->getAddRoute(); $this->assertSame(serialize($expected), serialize($result)); @@ -280,7 +280,7 @@ public function testGetEditRouteParameters() { $route_match = new RouteMatch('example', new Route('/test/{langcode}'), ['langcode' => 'xx']); $this->configNamesMapper->populateFromRouteMatch($route_match); - $expected = array('langcode' => 'xx'); + $expected = ['langcode' => 'xx']; $result = $this->configNamesMapper->getEditRouteParameters(); $this->assertSame($expected, $result); } @@ -290,13 +290,13 @@ public function testGetEditRouteParameters() { */ public function testGetEditRoute() { $expected = new Route('/admin/config/system/site-information/translate/{langcode}/edit', - array( + [ '_form' => '\Drupal\config_translation\Form\ConfigTranslationEditForm', 'plugin_id' => 'system.site_information_settings', - ), - array( + ], + [ '_config_translation_form_access' => 'TRUE', - ) + ] ); $result = $this->configNamesMapper->getEditRoute(); $this->assertSame(serialize($expected), serialize($result)); @@ -318,7 +318,7 @@ public function testGetDeleteRouteParameters() { $route_match = new RouteMatch('example', new Route('/test/{langcode}'), ['langcode' => 'xx']); $this->configNamesMapper->populateFromRouteMatch($route_match); - $expected = array('langcode' => 'xx'); $result = $this->configNamesMapper->getDeleteRouteParameters(); + $expected = ['langcode' => 'xx']; $result = $this->configNamesMapper->getDeleteRouteParameters(); $this->assertSame($expected, $result); } @@ -327,13 +327,13 @@ public function testGetDeleteRouteParameters() { */ public function testGetDeleteRoute() { $expected = new Route('/admin/config/system/site-information/translate/{langcode}/delete', - array( + [ '_form' => '\Drupal\config_translation\Form\ConfigTranslationDeleteForm', 'plugin_id' => 'system.site_information_settings', - ), - array( + ], + [ '_config_translation_form_access' => 'TRUE', - ) + ] ); $result = $this->configNamesMapper->getDeleteRoute(); $this->assertSame(serialize($expected), serialize($result)); @@ -403,38 +403,38 @@ public function testGetTypeLabel() { public function testGetLangcode() { // Test that the getLangcode() falls back to 'en', if no explicit language // code is provided. - $config_factory = $this->getConfigFactoryStub(array( - 'system.site' => array('key' => 'value'), - )); + $config_factory = $this->getConfigFactoryStub([ + 'system.site' => ['key' => 'value'], + ]); $this->configNamesMapper->setConfigFactory($config_factory); $result = $this->configNamesMapper->getLangcode(); $this->assertSame('en', $result); // Test that getLangcode picks up the language code provided by the // configuration. - $config_factory = $this->getConfigFactoryStub(array( - 'system.site' => array('langcode' => 'xx'), - )); + $config_factory = $this->getConfigFactoryStub([ + 'system.site' => ['langcode' => 'xx'], + ]); $this->configNamesMapper->setConfigFactory($config_factory); $result = $this->configNamesMapper->getLangcode(); $this->assertSame('xx', $result); // Test that getLangcode() works for multiple configuration names. $this->configNamesMapper->addConfigName('system.maintenance'); - $config_factory = $this->getConfigFactoryStub(array( - 'system.site' => array('langcode' => 'xx'), - 'system.maintenance' => array('langcode' => 'xx'), - )); + $config_factory = $this->getConfigFactoryStub([ + 'system.site' => ['langcode' => 'xx'], + 'system.maintenance' => ['langcode' => 'xx'], + ]); $this->configNamesMapper->setConfigFactory($config_factory); $result = $this->configNamesMapper->getLangcode(); $this->assertSame('xx', $result); // Test that getLangcode() throws an exception when different language codes // are given. - $config_factory = $this->getConfigFactoryStub(array( - 'system.site' => array('langcode' => 'xx'), - 'system.maintenance' => array('langcode' => 'yy'), - )); + $config_factory = $this->getConfigFactoryStub([ + 'system.site' => ['langcode' => 'xx'], + 'system.maintenance' => ['langcode' => 'yy'], + ]); $this->configNamesMapper->setConfigFactory($config_factory); try { $this->configNamesMapper->getLangcode(); @@ -448,22 +448,22 @@ public function testGetLangcode() { * Tests ConfigNamesMapper::getConfigData(). */ public function testGetConfigData() { - $configs = array( - 'system.site' => array( + $configs = [ + 'system.site' => [ 'name' => 'Drupal', 'slogan' => 'Come for the software, stay for the community!', - ), - 'system.maintenance' => array( + ], + 'system.maintenance' => [ 'enabled' => FALSE, 'message' => '@site is currently under maintenance.', - ), - 'system.rss' => array( - 'items' => array( + ], + 'system.rss' => [ + 'items' => [ 'limit' => 10, 'view_mode' => 'rss', - ), - ), - ); + ], + ], + ]; $this->configNamesMapper->setConfigNames(array_keys($configs)); $config_factory = $this->getConfigFactoryStub($configs); @@ -489,9 +489,9 @@ public function testHasSchema(array $mock_return_values, $expected) { $config_names = range(1, count($mock_return_values)); $this->configNamesMapper->setConfigNames($config_names); - $map = array(); + $map = []; foreach ($config_names as $i => $config_name) { - $map[] = array($config_name, $mock_return_values[$i]); + $map[] = [$config_name, $mock_return_values[$i]]; } $this->typedConfigManager ->expects($this->any()) @@ -512,12 +512,12 @@ public function testHasSchema(array $mock_return_values, $expected) { * ConfigNamesMapper::hasSchema() as the second value. */ public function providerTestHasSchema() { - return array( - array(array(TRUE), TRUE), - array(array(FALSE), FALSE), - array(array(TRUE, TRUE, TRUE), TRUE), - array(array(TRUE, FALSE, TRUE), FALSE), - ); + return [ + [[TRUE], TRUE], + [[FALSE], FALSE], + [[TRUE, TRUE, TRUE], TRUE], + [[TRUE, FALSE, TRUE], FALSE], + ]; } /** @@ -536,9 +536,9 @@ public function testHasTranslatable(array $mock_return_values, $expected) { $config_names = range(1, count($mock_return_values)); $this->configNamesMapper->setConfigNames($config_names); - $map = array(); + $map = []; foreach ($config_names as $i => $config_name) { - $map[] = isset($mock_return_values[$i]) ? array($config_name, $mock_return_values[$i]) : array(); + $map[] = isset($mock_return_values[$i]) ? [$config_name, $mock_return_values[$i]] : []; } $this->configMapperManager ->expects($this->any()) @@ -559,14 +559,14 @@ public function testHasTranslatable(array $mock_return_values, $expected) { * ConfigNamesMapper::hasTranslatable() as the second value. */ public function providerTestHasTranslatable() { - return array( - array(array(), FALSE), - array(array(TRUE), TRUE), - array(array(FALSE), FALSE), - array(array(TRUE, TRUE, TRUE), TRUE), - array(array(FALSE, FALSE, FALSE), FALSE), - array(array(TRUE, FALSE, TRUE), TRUE), - ); + return [ + [[], FALSE], + [[TRUE], TRUE], + [[FALSE], FALSE], + [[TRUE, TRUE, TRUE], TRUE], + [[FALSE, FALSE, FALSE], FALSE], + [[TRUE, FALSE, TRUE], TRUE], + ]; } /** @@ -587,9 +587,9 @@ public function testHasTranslation(array $mock_return_values, $expected) { $config_names = range(1, count($mock_return_values)); $this->configNamesMapper->setConfigNames($config_names); - $map = array(); + $map = []; foreach ($config_names as $i => $config_name) { - $map[] = array($config_name, $language->getId(), $mock_return_values[$i]); + $map[] = [$config_name, $language->getId(), $mock_return_values[$i]]; } $this->localeConfigManager ->expects($this->any()) @@ -610,13 +610,13 @@ public function testHasTranslation(array $mock_return_values, $expected) { * ConfigNamesMapper::hasTranslation() as the second value. */ public function providerTestHasTranslation() { - return array( - array(array(TRUE), TRUE), - array(array(FALSE), FALSE), - array(array(TRUE, TRUE, TRUE), TRUE), - array(array(FALSE, FALSE, TRUE), TRUE), - array(array(FALSE, FALSE, FALSE), FALSE), - ); + return [ + [[TRUE], TRUE], + [[FALSE], FALSE], + [[TRUE, TRUE, TRUE], TRUE], + [[FALSE, FALSE, TRUE], TRUE], + [[FALSE, FALSE, FALSE], FALSE], + ]; } /** @@ -631,12 +631,12 @@ public function testGetTypeName() { * Tests ConfigNamesMapper::hasTranslation(). */ public function testGetOperations() { - $expected = array( - 'translate' => array( + $expected = [ + 'translate' => [ 'title' => 'Translate', 'url' => Url::fromRoute('config_translation.item.overview.system.site_information_settings'), - ), - ); + ], + ]; $result = $this->configNamesMapper->getOperations(); $this->assertEquals($expected, $result); } diff --git a/core/modules/contact/contact.module b/core/modules/contact/contact.module index 4306e3beb8..65e7592cce 100644 --- a/core/modules/contact/contact.module +++ b/core/modules/contact/contact.module @@ -21,17 +21,17 @@ function contact_help($route_name, RouteMatchInterface $route_match) { $contact_page = \Drupal::url('entity.contact_form.collection'); $output = ''; $output .= '

        ' . t('About') . '

        '; - $output .= '

        ' . t('The Contact module allows visitors to contact registered users on your site, using the personal contact form, and also allows you to set up site-wide contact forms. For more information, see the online documentation for the Contact module.', array(':contact' => 'https://www.drupal.org/documentation/modules/contact')) . '

        '; + $output .= '

        ' . t('The Contact module allows visitors to contact registered users on your site, using the personal contact form, and also allows you to set up site-wide contact forms. For more information, see the online documentation for the Contact module.', [':contact' => 'https://www.drupal.org/documentation/modules/contact']) . '

        '; $output .= '

        ' . t('Uses') . '

        '; $output .= '
        '; $output .= '
        ' . t('Using the personal contact form') . '
        '; $output .= '
        ' . t("Site visitors can email registered users on your site by using the personal contact form, without knowing or learning the email address of the recipient. When a site visitor is viewing a user profile, the viewer will see a Contact tab or link, which leads to the personal contact form. The personal contact link is not shown when you are viewing your own profile, and users must have both View user information (to see user profiles) and Use users' personal contact forms permission to see the link. The user whose profile is being viewed must also have their personal contact form enabled (this is a user account setting); viewers with Administer users permission can bypass this setting.") . '
        '; $output .= '
        ' . t('Configuring contact forms') . '
        '; - $output .= '
        ' . t('On the Contact forms page, you can configure the fields and display of the personal contact form, and you can set up one or more site-wide contact forms. Each site-wide contact form has a machine name, a label, and one or more defined recipients; when a site visitor submits the form, the field values are sent to those recipients.', array(':contact_admin' => $contact_page)) . '
        '; + $output .= '
        ' . t('On the Contact forms page, you can configure the fields and display of the personal contact form, and you can set up one or more site-wide contact forms. Each site-wide contact form has a machine name, a label, and one or more defined recipients; when a site visitor submits the form, the field values are sent to those recipients.', [':contact_admin' => $contact_page]) . '
        '; $output .= '
        ' . t('Linking to contact forms') . '
        '; - $output .= '
        ' . t('One site-wide contact form can be designated as the default contact form. If you choose to designate a default form, the Contact menu link in the Footer menu will link to it. You can modify this link from the Menus page if you have the Menu UI module installed. You can also create links to other contact forms; the URL for each form you have set up has format contact/machine_name_of_form.', array(':menu-settings' => $menu_page)) . '

        '; + $output .= '
        ' . t('One site-wide contact form can be designated as the default contact form. If you choose to designate a default form, the Contact menu link in the Footer menu will link to it. You can modify this link from the Menus page if you have the Menu UI module installed. You can also create links to other contact forms; the URL for each form you have set up has format contact/machine_name_of_form.', [':menu-settings' => $menu_page]) . '

        '; $output .= '
        ' . t('Adding content to contact forms') . '
        '; - $output .= '
        ' . t('From the Contact forms page, you can configure the fields to be shown on contact forms, including their labels and help text. If you would like other content (such as text or images) to appear on a contact form, use a block. You can create and edit blocks on the Block layout page, if the Block module is installed.', array(':blocks' => $block_page, ':contact_admin' => $contact_page)) . '
        '; + $output .= '
        ' . t('From the Contact forms page, you can configure the fields to be shown on contact forms, including their labels and help text. If you would like other content (such as text or images) to appear on a contact form, use a block. You can create and edit blocks on the Block layout page, if the Block module is installed.', [':blocks' => $block_page, ':contact_admin' => $contact_page]) . '
        '; $output .= '
        '; return $output; @@ -50,42 +50,42 @@ function contact_entity_type_alter(array &$entity_types) { * Implements hook_entity_extra_field_info(). */ function contact_entity_extra_field_info() { - $fields = array(); + $fields = []; foreach (array_keys(\Drupal::service('entity_type.bundle.info')->getBundleInfo('contact_message')) as $bundle) { - $fields['contact_message'][$bundle]['form']['name'] = array( + $fields['contact_message'][$bundle]['form']['name'] = [ 'label' => t('Sender name'), 'description' => t('Text'), 'weight' => -50, - ); - $fields['contact_message'][$bundle]['form']['mail'] = array( + ]; + $fields['contact_message'][$bundle]['form']['mail'] = [ 'label' => t('Sender email'), 'description' => t('Email'), 'weight' => -40, - ); + ]; if ($bundle == 'personal') { - $fields['contact_message'][$bundle]['form']['recipient'] = array( + $fields['contact_message'][$bundle]['form']['recipient'] = [ 'label' => t('Recipient username'), 'description' => t('User'), 'weight' => -30, - ); + ]; } - $fields['contact_message'][$bundle]['form']['preview'] = array( + $fields['contact_message'][$bundle]['form']['preview'] = [ 'label' => t('Preview sender message'), 'description' => t('Preview'), 'weight' => 40, - ); - $fields['contact_message'][$bundle]['form']['copy'] = array( + ]; + $fields['contact_message'][$bundle]['form']['copy'] = [ 'label' => t('Send copy to sender'), 'description' => t('Option'), 'weight' => 50, - ); + ]; } - $fields['user']['user']['form']['contact'] = array( + $fields['user']['user']['form']['contact'] = [ 'label' => t('Contact settings'), 'description' => t('Contact module form element.'), 'weight' => 5, - ); + ]; return $fields; } @@ -118,21 +118,21 @@ function contact_mail($key, &$message, $params) { $sender = $params['sender']; $language = \Drupal::languageManager()->getLanguage($message['langcode']); - $variables = array( + $variables = [ '@site-name' => \Drupal::config('system.site')->get('name'), '@subject' => $contact_message->getSubject(), '@form' => !empty($params['contact_form']) ? $params['contact_form']->label() : NULL, '@form-url' => \Drupal::url('', [], ['absolute' => TRUE, 'language' => $language]), '@sender-name' => $sender->getDisplayName(), - ); + ]; if ($sender->isAuthenticated()) { - $variables['@sender-url'] = $sender->url('canonical', array('absolute' => TRUE, 'language' => $language)); + $variables['@sender-url'] = $sender->url('canonical', ['absolute' => TRUE, 'language' => $language]); } else { $variables['@sender-url'] = $params['sender']->getEmail(); } - $options = array('langcode' => $language->getId()); + $options = ['langcode' => $language->getId()]; switch ($key) { case 'page_mail': @@ -150,10 +150,10 @@ function contact_mail($key, &$message, $params) { case 'user_mail': case 'user_copy': - $variables += array( + $variables += [ '@recipient-name' => $params['recipient']->getDisplayName(), - '@recipient-edit-url' => $params['recipient']->url('edit-form', array('absolute' => TRUE, 'language' => $language)), - ); + '@recipient-edit-url' => $params['recipient']->url('edit-form', ['absolute' => TRUE, 'language' => $language]), + ]; $message['subject'] .= t('[@site-name] @subject', $variables, $options); $message['body'][] = t('Hello @recipient-name,', $variables, $options); $message['body'][] = t("@sender-name (@sender-url) has sent you a message via your contact form at @site-name.", $variables, $options); @@ -172,22 +172,22 @@ function contact_mail($key, &$message, $params) { * @see \Drupal\user\ProfileForm::form() */ function contact_form_user_form_alter(&$form, FormStateInterface $form_state) { - $form['contact'] = array( + $form['contact'] = [ '#type' => 'details', '#title' => t('Contact settings'), '#open' => TRUE, '#weight' => 5, - ); + ]; $account = $form_state->getFormObject()->getEntity(); if (!\Drupal::currentUser()->isAnonymous() && $account->id()) { $account_data = \Drupal::service('user.data')->get('contact', $account->id(), 'enabled'); } - $form['contact']['contact'] = array( + $form['contact']['contact'] = [ '#type' => 'checkbox', '#title' => t('Personal contact form'), '#default_value' => isset($account_data) ? $account_data : \Drupal::config('contact.settings')->get('user_default_enabled'), '#description' => t('Allow other users to contact you via a personal contact form which keeps your email address hidden. Note that some privileged users such as site administrators are still able to contact you even if you choose to disable this feature.'), - ); + ]; $form['actions']['submit']['#submit'][] = 'contact_user_profile_form_submit'; } @@ -209,18 +209,18 @@ function contact_user_profile_form_submit($form, FormStateInterface $form_state) * @see \Drupal\user\AccountSettingsForm */ function contact_form_user_admin_settings_alter(&$form, FormStateInterface $form_state) { - $form['contact'] = array( + $form['contact'] = [ '#type' => 'details', '#title' => t('Contact settings'), '#open' => TRUE, '#weight' => 0, - ); - $form['contact']['contact_default_status'] = array( + ]; + $form['contact']['contact_default_status'] = [ '#type' => 'checkbox', '#title' => t('Enable the personal contact form by default for new users'), '#description' => t('Changing this setting will not affect existing users.'), '#default_value' => \Drupal::configFactory()->getEditable('contact.settings')->get('user_default_enabled'), - ); + ]; // Add submit handler to save contact configuration. $form['#submit'][] = 'contact_form_user_admin_settings_submit'; } diff --git a/core/modules/contact/contact.views.inc b/core/modules/contact/contact.views.inc index 15603624d3..a18c9e796f 100644 --- a/core/modules/contact/contact.views.inc +++ b/core/modules/contact/contact.views.inc @@ -9,11 +9,11 @@ * Implements hook_views_data_alter(). */ function contact_views_data_alter(&$data) { - $data['users']['contact'] = array( - 'field' => array( + $data['users']['contact'] = [ + 'field' => [ 'title' => t('Contact link'), 'help' => t('Provide a simple link to the user contact page.'), 'id' => 'contact_link', - ), - ); + ], + ]; } diff --git a/core/modules/contact/src/ContactFormEditForm.php b/core/modules/contact/src/ContactFormEditForm.php index 01ca025108..aa94540bb9 100644 --- a/core/modules/contact/src/ContactFormEditForm.php +++ b/core/modules/contact/src/ContactFormEditForm.php @@ -72,60 +72,60 @@ public function form(array $form, FormStateInterface $form_state) { $contact_form = $this->entity; $default_form = $this->config('contact.settings')->get('default_form'); - $form['label'] = array( + $form['label'] = [ '#type' => 'textfield', '#title' => $this->t('Label'), '#maxlength' => 255, '#default_value' => $contact_form->label(), '#description' => $this->t("Example: 'website feedback' or 'product information'."), '#required' => TRUE, - ); - $form['id'] = array( + ]; + $form['id'] = [ '#type' => 'machine_name', '#default_value' => $contact_form->id(), '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, - '#machine_name' => array( + '#machine_name' => [ 'exists' => '\Drupal\contact\Entity\ContactForm::load', - ), + ], '#disabled' => !$contact_form->isNew(), - ); - $form['recipients'] = array( + ]; + $form['recipients'] = [ '#type' => 'textarea', '#title' => $this->t('Recipients'), '#default_value' => implode(', ', $contact_form->getRecipients()), '#description' => $this->t("Example: 'webmaster@example.com' or 'sales@example.com,support@example.com' . To specify multiple recipients, separate each email address with a comma."), '#required' => TRUE, - ); - $form['message'] = array( + ]; + $form['message'] = [ '#type' => 'textarea', '#title' => $this->t('Message'), '#default_value' => $contact_form->getMessage(), '#description' => $this->t('The message to display to the user after submission of this form. Leave blank for no message.'), - ); - $form['redirect'] = array( + ]; + $form['redirect'] = [ '#type' => 'path', '#title' => $this->t('Redirect path'), '#convert_path' => PathElement::CONVERT_NONE, '#default_value' => $contact_form->getRedirectPath(), '#description' => $this->t('Path to redirect the user to after submission of this form. For example, type "/about" to redirect to that page. Use a relative path with a slash in front.'), - ); - $form['reply'] = array( + ]; + $form['reply'] = [ '#type' => 'textarea', '#title' => $this->t('Auto-reply'), '#default_value' => $contact_form->getReply(), '#description' => $this->t('Optional auto-reply. Leave empty if you do not want to send the user an auto-reply message.'), - ); - $form['weight'] = array( + ]; + $form['weight'] = [ '#type' => 'weight', '#title' => $this->t('Weight'), '#default_value' => $contact_form->getWeight(), '#description' => $this->t('When listing forms, those with lighter (smaller) weights get listed before forms with heavier (larger) weights. Forms with equal weights are sorted alphabetically.'), - ); - $form['selected'] = array( + ]; + $form['selected'] = [ '#type' => 'checkbox', '#title' => $this->t('Make this the default form'), '#default_value' => $default_form === $contact_form->id(), - ); + ]; return $form; } @@ -142,7 +142,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) { foreach ($recipients as &$recipient) { $recipient = trim($recipient); if (!$this->emailValidator->isValid($recipient)) { - $form_state->setErrorByName('recipients', $this->t('%recipient is an invalid email address.', array('%recipient' => $recipient))); + $form_state->setErrorByName('recipients', $this->t('%recipient is an invalid email address.', ['%recipient' => $recipient])); } } $form_state->setValue('recipients', $recipients); @@ -165,12 +165,12 @@ public function save(array $form, FormStateInterface $form_state) { $edit_link = $this->entity->link($this->t('Edit')); $view_link = $contact_form->link($contact_form->label(), 'canonical'); if ($status == SAVED_UPDATED) { - drupal_set_message($this->t('Contact form %label has been updated.', array('%label' => $view_link))); - $this->logger('contact')->notice('Contact form %label has been updated.', array('%label' => $contact_form->label(), 'link' => $edit_link)); + drupal_set_message($this->t('Contact form %label has been updated.', ['%label' => $view_link])); + $this->logger('contact')->notice('Contact form %label has been updated.', ['%label' => $contact_form->label(), 'link' => $edit_link]); } else { - drupal_set_message($this->t('Contact form %label has been added.', array('%label' => $view_link))); - $this->logger('contact')->notice('Contact form %label has been added.', array('%label' => $contact_form->label(), 'link' => $edit_link)); + drupal_set_message($this->t('Contact form %label has been added.', ['%label' => $view_link])); + $this->logger('contact')->notice('Contact form %label has been added.', ['%label' => $contact_form->label(), 'link' => $edit_link]); } // Update the default form. diff --git a/core/modules/contact/src/Controller/ContactController.php b/core/modules/contact/src/Controller/ContactController.php index 4d46f83d04..b8b69d5f19 100644 --- a/core/modules/contact/src/Controller/ContactController.php +++ b/core/modules/contact/src/Controller/ContactController.php @@ -64,9 +64,9 @@ public function contactSitePage(ContactFormInterface $contact_form = NULL) { // If there are no forms, do not display the form. if (empty($contact_form)) { if ($this->currentUser()->hasPermission('administer contact forms')) { - drupal_set_message($this->t('The contact form has not been configured. Add one or more forms .', array( - ':add' => $this->url('contact.form_add'))), 'error'); - return array(); + drupal_set_message($this->t('The contact form has not been configured. Add one or more forms .', [ + ':add' => $this->url('contact.form_add')]), 'error'); + return []; } else { throw new NotFoundHttpException(); @@ -76,9 +76,9 @@ public function contactSitePage(ContactFormInterface $contact_form = NULL) { $message = $this->entityManager() ->getStorage('contact_message') - ->create(array( + ->create([ 'contact_form' => $contact_form->id(), - )); + ]); $form = $this->entityFormBuilder()->getForm($message); $form['#title'] = $contact_form->label(); @@ -106,13 +106,13 @@ public function contactPersonalPage(UserInterface $user) { throw new NotFoundHttpException(); } - $message = $this->entityManager()->getStorage('contact_message')->create(array( + $message = $this->entityManager()->getStorage('contact_message')->create([ 'contact_form' => 'personal', 'recipient' => $user->id(), - )); + ]); $form = $this->entityFormBuilder()->getForm($message); - $form['#title'] = $this->t('Contact @username', array('@username' => $user->getDisplayName())); + $form['#title'] = $this->t('Contact @username', ['@username' => $user->getDisplayName()]); $form['#cache']['contexts'][] = 'user.permissions'; return $form; } diff --git a/core/modules/contact/src/Entity/ContactForm.php b/core/modules/contact/src/Entity/ContactForm.php index 9c63747065..00e5416bc8 100644 --- a/core/modules/contact/src/Entity/ContactForm.php +++ b/core/modules/contact/src/Entity/ContactForm.php @@ -73,7 +73,7 @@ class ContactForm extends ConfigEntityBundleBase implements ContactFormInterface * * @var array */ - protected $recipients = array(); + protected $recipients = []; /** * The path to redirect to on form submission. diff --git a/core/modules/contact/src/Entity/Message.php b/core/modules/contact/src/Entity/Message.php index 20f360f6a4..d75496ba72 100644 --- a/core/modules/contact/src/Entity/Message.php +++ b/core/modules/contact/src/Entity/Message.php @@ -153,29 +153,29 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ->setLabel(t('Subject')) ->setRequired(TRUE) ->setSetting('max_length', 100) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'string_textfield', 'weight' => -10, - )) + ]) ->setDisplayConfigurable('form', TRUE); // The text of the contact message. $fields['message'] = BaseFieldDefinition::create('string_long') ->setLabel(t('Message')) ->setRequired(TRUE) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'string_textarea', 'weight' => 0, - 'settings' => array( + 'settings' => [ 'rows' => 12, - ), - )) + ], + ]) ->setDisplayConfigurable('form', TRUE) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'type' => 'string', 'weight' => 0, 'label' => 'above', - )) + ]) ->setDisplayConfigurable('view', TRUE); $fields['copy'] = BaseFieldDefinition::create('boolean') diff --git a/core/modules/contact/src/MailHandler.php b/core/modules/contact/src/MailHandler.php index bb3b95e8d3..b57864c059 100644 --- a/core/modules/contact/src/MailHandler.php +++ b/core/modules/contact/src/MailHandler.php @@ -73,7 +73,7 @@ public function __construct(MailManagerInterface $mail_manager, LanguageManagerI public function sendMailMessages(MessageInterface $message, AccountInterface $sender) { // Clone the sender, as we make changes to mail and name properties. $sender_cloned = clone $this->userStorage->load($sender->id()); - $params = array(); + $params = []; $current_langcode = $this->languageManager->getCurrentLanguage()->getId(); $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId(); $contact_form = $message->getContactForm(); @@ -86,7 +86,7 @@ public function sendMailMessages(MessageInterface $message, AccountInterface $se // For the email message, clarify that the sender name is not verified; it // could potentially clash with a username on this site. - $sender_cloned->name = $this->t('@name (not verified)', array('@name' => $message->getSenderName())); + $sender_cloned->name = $this->t('@name (not verified)', ['@name' => $message->getSenderName()]); } // Build email parameters. @@ -133,18 +133,18 @@ public function sendMailMessages(MessageInterface $message, AccountInterface $se } if (!$message->isPersonal()) { - $this->logger->notice('%sender-name (@sender-from) sent an email regarding %contact_form.', array( + $this->logger->notice('%sender-name (@sender-from) sent an email regarding %contact_form.', [ '%sender-name' => $sender_cloned->getUsername(), '@sender-from' => $sender_cloned->getEmail(), '%contact_form' => $contact_form->label(), - )); + ]); } else { - $this->logger->notice('%sender-name (@sender-from) sent %recipient-name an email.', array( + $this->logger->notice('%sender-name (@sender-from) sent %recipient-name an email.', [ '%sender-name' => $sender_cloned->getUsername(), '@sender-from' => $sender_cloned->getEmail(), '%recipient-name' => $message->getPersonalRecipient()->getUsername(), - )); + ]); } } diff --git a/core/modules/contact/src/MessageForm.php b/core/modules/contact/src/MessageForm.php index da221ff835..16d41b5acc 100644 --- a/core/modules/contact/src/MessageForm.php +++ b/core/modules/contact/src/MessageForm.php @@ -103,24 +103,24 @@ public function form(array $form, FormStateInterface $form_state) { $form['#attributes']['class'][] = 'contact-form'; if (!empty($message->preview)) { - $form['preview'] = array( - '#theme_wrappers' => array('container__preview'), - '#attributes' => array('class' => array('preview')), - ); + $form['preview'] = [ + '#theme_wrappers' => ['container__preview'], + '#attributes' => ['class' => ['preview']], + ]; $form['preview']['message'] = $this->entityManager->getViewBuilder('contact_message')->view($message, 'full'); } - $form['name'] = array( + $form['name'] = [ '#type' => 'textfield', '#title' => $this->t('Your name'), '#maxlength' => 255, '#required' => TRUE, - ); - $form['mail'] = array( + ]; + $form['mail'] = [ '#type' => 'email', '#title' => $this->t('Your email address'), '#required' => TRUE, - ); + ]; if ($user->isAnonymous()) { $form['#attached']['library'][] = 'core/drupal.form'; $form['#attributes']['data-user-info-from-browser'] = TRUE; @@ -141,24 +141,24 @@ public function form(array $form, FormStateInterface $form_state) { // The user contact form has a preset recipient. if ($message->isPersonal()) { - $form['recipient'] = array( + $form['recipient'] = [ '#type' => 'item', '#title' => $this->t('To'), '#value' => $message->getPersonalRecipient()->id(), - 'name' => array( + 'name' => [ '#theme' => 'username', '#account' => $message->getPersonalRecipient(), - ), - ); + ], + ]; } - $form['copy'] = array( + $form['copy'] = [ '#type' => 'checkbox', '#title' => $this->t('Send yourself a copy'), // Do not allow anonymous users to send themselves a copy, because it can // be abused to spam people. '#access' => $user->isAuthenticated(), - ); + ]; return $form; } @@ -168,11 +168,11 @@ public function form(array $form, FormStateInterface $form_state) { public function actions(array $form, FormStateInterface $form_state) { $elements = parent::actions($form, $form_state); $elements['submit']['#value'] = $this->t('Send message'); - $elements['preview'] = array( + $elements['preview'] = [ '#type' => 'submit', '#value' => $this->t('Preview'), - '#submit' => array('::submitForm', '::preview'), - ); + '#submit' => ['::submitForm', '::preview'], + ]; return $elements; } @@ -197,10 +197,10 @@ public function validateForm(array &$form, FormStateInterface $form_state) { $interval = $this->config('contact.settings')->get('flood.interval'); if (!$this->flood->isAllowed('contact', $limit, $interval)) { - $form_state->setErrorByName('', $this->t('You cannot send more than %limit messages in @interval. Try again later.', array( + $form_state->setErrorByName('', $this->t('You cannot send more than %limit messages in @interval. Try again later.', [ '%limit' => $limit, '@interval' => $this->dateFormatter->formatInterval($interval), - ))); + ])); } } diff --git a/core/modules/contact/src/MessageViewBuilder.php b/core/modules/contact/src/MessageViewBuilder.php index 3024f62912..6cbf0e738e 100644 --- a/core/modules/contact/src/MessageViewBuilder.php +++ b/core/modules/contact/src/MessageViewBuilder.php @@ -33,11 +33,11 @@ public function buildComponents(array &$build, array $entities, array $displays, // Add the message extra field, if enabled. $display = $displays[$entity->bundle()]; if ($entity->getMessage() && $display->getComponent('message')) { - $build[$id]['message'] = array( + $build[$id]['message'] = [ '#type' => 'item', '#title' => t('Message'), '#plain_text' => $entity->getMessage(), - ); + ]; } } } @@ -54,7 +54,7 @@ public function view(EntityInterface $entity, $view_mode = 'full', $langcode = N // convert DIVs correctly. foreach (Element::children($build) as $key) { if (isset($build[$key]['#label_display']) && $build[$key]['#label_display'] == 'above') { - $build[$key] += array('#prefix' => ''); + $build[$key] += ['#prefix' => '']; $build[$key]['#prefix'] = $build[$key]['#title'] . ":\n"; $build[$key]['#label_display'] = 'hidden'; } diff --git a/core/modules/contact/src/Plugin/migrate/source/ContactCategory.php b/core/modules/contact/src/Plugin/migrate/source/ContactCategory.php index 2975431ad5..0b9f7b3b83 100644 --- a/core/modules/contact/src/Plugin/migrate/source/ContactCategory.php +++ b/core/modules/contact/src/Plugin/migrate/source/ContactCategory.php @@ -20,14 +20,14 @@ class ContactCategory extends DrupalSqlBase { */ public function query() { $query = $this->select('contact', 'c') - ->fields('c', array( + ->fields('c', [ 'cid', 'category', 'recipients', 'reply', 'weight', 'selected', - ) + ] ); $query->orderBy('c.cid'); return $query; @@ -45,14 +45,14 @@ public function prepareRow(Row $row) { * {@inheritdoc} */ public function fields() { - return array( + return [ 'cid' => $this->t('Primary Key: Unique category ID.'), 'category' => $this->t('Category name.'), 'recipients' => $this->t('Comma-separated list of recipient email addresses.'), 'reply' => $this->t('Text of the auto-reply message.'), 'weight' => $this->t("The category's weight."), 'selected' => $this->t('Flag to indicate whether or not category is selected by default. (1 = Yes, 0 = No)'), - ); + ]; } /** diff --git a/core/modules/contact/src/Plugin/views/field/ContactLink.php b/core/modules/contact/src/Plugin/views/field/ContactLink.php index ecc4cea9fa..a98be137dd 100644 --- a/core/modules/contact/src/Plugin/views/field/ContactLink.php +++ b/core/modules/contact/src/Plugin/views/field/ContactLink.php @@ -42,8 +42,8 @@ protected function renderLink(ResultRow $row) { $this->options['alter']['make_link'] = TRUE; $this->options['alter']['url'] = $this->getUrlInfo($row); - $title = $this->t('Contact %user', array('%user' => $entity->label())); - $this->options['alter']['attributes'] = array('title' => $title); + $title = $this->t('Contact %user', ['%user' => $entity->label()]); + $this->options['alter']['attributes'] = ['title' => $title]; if (!empty($this->options['text'])) { return $this->options['text']; diff --git a/core/modules/contact/src/Tests/ContactPersonalTest.php b/core/modules/contact/src/Tests/ContactPersonalTest.php index 936aed5892..d80484f429 100644 --- a/core/modules/contact/src/Tests/ContactPersonalTest.php +++ b/core/modules/contact/src/Tests/ContactPersonalTest.php @@ -20,7 +20,7 @@ class ContactPersonalTest extends WebTestBase { * * @var array */ - public static $modules = array('contact', 'dblog'); + public static $modules = ['contact', 'dblog']; /** * A user with some administrative permissions. @@ -47,11 +47,11 @@ protected function setUp() { parent::setUp(); // Create an admin user. - $this->adminUser = $this->drupalCreateUser(array('administer contact forms', 'administer users', 'administer account settings', 'access site reports')); + $this->adminUser = $this->drupalCreateUser(['administer contact forms', 'administer users', 'administer account settings', 'access site reports']); // Create some normal users with their contact forms enabled by default. $this->config('contact.settings')->set('user_default_enabled', TRUE)->save(); - $this->webUser = $this->drupalCreateUser(array('access user profiles', 'access user contact forms')); + $this->webUser = $this->drupalCreateUser(['access user profiles', 'access user contact forms']); $this->contactUser = $this->drupalCreateUser(); } @@ -74,11 +74,11 @@ function testSendPersonalContactMessage() { $this->assertEqual($mail['from'], $this->config('system.site')->get('mail')); $this->assertEqual($mail['reply-to'], $this->webUser->getEmail()); $this->assertEqual($mail['key'], 'user_mail'); - $variables = array( + $variables = [ '@site-name' => $this->config('system.site')->get('name'), '@subject' => $message['subject[0][value]'], '@recipient-name' => $this->contactUser->getDisplayName(), - ); + ]; $subject = PlainTextOutput::renderFromHtml(t('[@site-name] @subject', $variables)); $this->assertEqual($mail['subject'], $subject, 'Subject is in sent message.'); $this->assertTrue(strpos($mail['body'], 'Hello ' . $variables['@recipient-name']) !== FALSE, 'Recipient name is in sent message.'); @@ -90,11 +90,11 @@ function testSendPersonalContactMessage() { $this->drupalLogin($this->adminUser); // Verify that the correct watchdog message has been logged. $this->drupalGet('/admin/reports/dblog'); - $placeholders = array( + $placeholders = [ '@sender_name' => $this->webUser->username, '@sender_email' => $this->webUser->getEmail(), '@recipient_name' => $this->contactUser->getUsername() - ); + ]; $this->assertRaw(SafeMarkup::format('@sender_name (@sender_email) sent @recipient_name an email.', $placeholders)); // Ensure an unescaped version of the email does not exist anywhere. $this->assertNoRaw($this->webUser->getEmail()); @@ -109,7 +109,7 @@ function testPersonalContactAccess() { $this->drupalGet('user/' . $this->adminUser->id() . '/contact'); $this->assertResponse(200); // Check the page title is properly displayed. - $this->assertRaw(t('Contact @username', array('@username' => $this->adminUser->getDisplayName()))); + $this->assertRaw(t('Contact @username', ['@username' => $this->adminUser->getDisplayName()])); // Test denied access to admin user's own contact form. $this->drupalLogout(); @@ -149,7 +149,7 @@ function testPersonalContactAccess() { // Test that anonymous users can access the contact form. $this->drupalLogout(); - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access user contact forms')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access user contact forms']); $this->drupalGet('user/' . $this->contactUser->id() . '/contact'); $this->assertResponse(200); @@ -159,7 +159,7 @@ function testPersonalContactAccess() { $this->assertCacheContext('user'); // Revoke the personal contact permission for the anonymous user. - user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access user contact forms')); + user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access user contact forms']); $this->drupalGet('user/' . $this->contactUser->id() . '/contact'); $this->assertResponse(403); $this->assertCacheContext('user'); @@ -168,7 +168,7 @@ function testPersonalContactAccess() { // Disable the personal contact form. $this->drupalLogin($this->adminUser); - $edit = array('contact_default_status' => FALSE); + $edit = ['contact_default_status' => FALSE]; $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.'), 'Setting successfully saved.'); $this->drupalLogout(); @@ -206,7 +206,7 @@ function testPersonalContactAccess() { $this->drupalGet('user/' . $this->webUser->id() . '/edit'); $this->assertNoFieldChecked('edit-contact--2'); $this->assertFalse(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form disabled'); - $this->drupalPostForm(NULL, array('contact' => TRUE), t('Save')); + $this->drupalPostForm(NULL, ['contact' => TRUE], t('Save')); $this->assertFieldChecked('edit-contact--2'); $this->assertTrue(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form enabled'); @@ -237,7 +237,7 @@ function testPersonalContactFlood() { // Submit contact form one over limit. $this->submitPersonalContact($this->contactUser); - $this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => $flood_limit, '@interval' => \Drupal::service('date.formatter')->formatInterval($this->config('contact.settings')->get('flood.interval')))), 'Normal user denied access to flooded contact form.'); + $this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', ['%number' => $flood_limit, '@interval' => \Drupal::service('date.formatter')->formatInterval($this->config('contact.settings')->get('flood.interval'))]), 'Normal user denied access to flooded contact form.'); // Test that the admin user can still access the contact form even though // the flood limit was reached. @@ -249,7 +249,7 @@ function testPersonalContactFlood() { * Tests the personal contact form based access when an admin adds users. */ function testAdminContact() { - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access user contact forms')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access user contact forms']); $this->checkContactAccess(200); $this->checkContactAccess(403, FALSE); $config = $this->config('contact.settings'); @@ -276,13 +276,13 @@ protected function checkContactAccess($response, $contact_value = NULL) { $this->assertNoFieldChecked('edit-contact--2'); } $name = $this->randomMachineName(); - $edit = array( + $edit = [ 'name' => $name, 'mail' => $this->randomMachineName() . '@example.com', 'pass[pass1]' => $pass = $this->randomString(), 'pass[pass2]' => $pass, 'notify' => FALSE, - ); + ]; if (isset($contact_value)) { $edit['contact'] = $contact_value; } @@ -306,11 +306,11 @@ protected function checkContactAccess($response, $contact_value = NULL) { * @return array * An array with the form fields being used. */ - protected function submitPersonalContact(AccountInterface $account, array $message = array()) { - $message += array( + protected function submitPersonalContact(AccountInterface $account, array $message = []) { + $message += [ 'subject[0][value]' => $this->randomMachineName(16), 'message[0][value]' => $this->randomMachineName(64), - ); + ]; $this->drupalPostForm('user/' . $account->id() . '/contact', $message, t('Send message')); return $message; } diff --git a/core/modules/contact/src/Tests/ContactSitewideTest.php b/core/modules/contact/src/Tests/ContactSitewideTest.php index ffc2e9091c..0721cf4dc9 100644 --- a/core/modules/contact/src/Tests/ContactSitewideTest.php +++ b/core/modules/contact/src/Tests/ContactSitewideTest.php @@ -65,7 +65,7 @@ function testSiteWideContact() { ->save(); // Set settings. - $edit = array(); + $edit = []; $edit['contact_default_status'] = TRUE; $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); @@ -77,11 +77,11 @@ function testSiteWideContact() { // Cannot use ::assertNoLinkByHref as it does partial url matching and with // field_ui enabled admin/structure/contact/manage/personal/fields exists. // @todo: See https://www.drupal.org/node/2031223 for the above. - $edit_link = $this->xpath('//a[@href=:href]', array( - ':href' => \Drupal::url('entity.contact_form.edit_form', array('contact_form' => 'personal')) - )); + $edit_link = $this->xpath('//a[@href=:href]', [ + ':href' => \Drupal::url('entity.contact_form.edit_form', ['contact_form' => 'personal']) + ]); $this->assertTrue(empty($edit_link), format_string('No link containing href %href found.', - array('%href' => 'admin/structure/contact/manage/personal') + ['%href' => 'admin/structure/contact/manage/personal'] )); $this->assertNoLinkByHref('admin/structure/contact/manage/personal/delete'); @@ -95,7 +95,7 @@ function testSiteWideContact() { $this->assertNoLinkByHref('admin/structure/contact/manage/feedback'); // Ensure that the contact form won't be shown without forms. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']); $this->drupalLogout(); $this->drupalGet('contact'); $this->assertResponse(404); @@ -110,10 +110,10 @@ function testSiteWideContact() { // Add forms. // Test invalid recipients. - $invalid_recipients = array('invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com'); + $invalid_recipients = ['invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com']; foreach ($invalid_recipients as $invalid_recipient) { $this->addContactForm($this->randomMachineName(16), $this->randomMachineName(16), $invalid_recipient, '', FALSE); - $this->assertRaw(t('%recipient is an invalid email address.', array('%recipient' => $invalid_recipient))); + $this->assertRaw(t('%recipient is an invalid email address.', ['%recipient' => $invalid_recipient])); } // Test validation of empty form and recipients fields. @@ -123,24 +123,24 @@ function testSiteWideContact() { $this->assertText(t('Recipients field is required.')); // Test validation of max_length machine name. - $recipients = array('simpletest&@example.com', 'simpletest2@example.com', 'simpletest3@example.com'); + $recipients = ['simpletest&@example.com', 'simpletest2@example.com', 'simpletest3@example.com']; $max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH; $max_length_exceeded = $max_length + 1; - $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', array($recipients[0])), '', TRUE); - $this->assertText(format_string('Machine-readable name cannot be longer than @max characters but is currently @exceeded characters long.', array('@max' => $max_length, '@exceeded' => $max_length_exceeded))); - $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', array($recipients[0])), '', TRUE); - $this->assertText(t('Contact form @label has been added.', array('@label' => $label))); + $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', [$recipients[0]]), '', TRUE); + $this->assertText(format_string('Machine-readable name cannot be longer than @max characters but is currently @exceeded characters long.', ['@max' => $max_length, '@exceeded' => $max_length_exceeded])); + $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', [$recipients[0]]), '', TRUE); + $this->assertText(t('Contact form @label has been added.', ['@label' => $label])); // Verify that the creation message contains a link to a contact form. - $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'contact/')); + $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']); $this->assert(isset($view_link), 'The message area contains a link to a contact form.'); // Create first valid form. - $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0])), '', TRUE); - $this->assertText(t('Contact form @label has been added.', array('@label' => $label))); + $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0]]), '', TRUE); + $this->assertText(t('Contact form @label has been added.', ['@label' => $label])); // Verify that the creation message contains a link to a contact form. - $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'contact/')); + $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'contact/']); $this->assert(isset($view_link), 'The message area contains a link to a contact form.'); // Check that the form was created in site default language. @@ -156,13 +156,13 @@ function testSiteWideContact() { $this->assertEscaped($recipients[0]); // Test update contact form. - $this->updateContactForm($id, $label = $this->randomMachineName(16), $recipients_str = implode(',', array($recipients[0], $recipients[1])), $reply = $this->randomMachineName(30), FALSE, 'Your message has been sent.', '/user'); + $this->updateContactForm($id, $label = $this->randomMachineName(16), $recipients_str = implode(',', [$recipients[0], $recipients[1]]), $reply = $this->randomMachineName(30), FALSE, 'Your message has been sent.', '/user'); $config = $this->config('contact.form.' . $id)->get(); $this->assertEqual($config['label'], $label); - $this->assertEqual($config['recipients'], array($recipients[0], $recipients[1])); + $this->assertEqual($config['recipients'], [$recipients[0], $recipients[1]]); $this->assertEqual($config['reply'], $reply); $this->assertNotEqual($id, $this->config('contact.settings')->get('default_form')); - $this->assertText(t('Contact form @label has been updated.', array('@label' => $label))); + $this->assertText(t('Contact form @label has been updated.', ['@label' => $label])); // Ensure the label is displayed on the contact page for this form. $this->drupalGet('contact/' . $id); $this->assertText($label); @@ -171,7 +171,7 @@ function testSiteWideContact() { $this->config('contact.settings')->set('default_form', $id)->save(); // Ensure that the contact form is shown without a form selection input. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']); $this->drupalLogout(); $this->drupalGet('contact'); $this->assertText(t('Your email address')); @@ -179,26 +179,26 @@ function testSiteWideContact() { $this->drupalLogin($admin_user); // Add more forms. - $this->addContactForm(Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0], $recipients[1])), '', FALSE); - $this->assertText(t('Contact form @label has been added.', array('@label' => $label))); + $this->addContactForm(Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1]]), '', FALSE); + $this->assertText(t('Contact form @label has been added.', ['@label' => $label])); - $this->addContactForm($name = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0], $recipients[1], $recipients[2])), '', FALSE); - $this->assertText(t('Contact form @label has been added.', array('@label' => $label))); + $this->addContactForm($name = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$recipients[0], $recipients[1], $recipients[2]]), '', FALSE); + $this->assertText(t('Contact form @label has been added.', ['@label' => $label])); // Try adding a form that already exists. $this->addContactForm($name, $label, '', '', FALSE); - $this->assertNoText(t('Contact form @label has been added.', array('@label' => $label))); + $this->assertNoText(t('Contact form @label has been added.', ['@label' => $label])); $this->assertRaw(t('The machine-readable name is already in use. It must be unique.')); $this->drupalLogout(); // Check to see that anonymous user cannot see contact page without permission. - user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); + user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']); $this->drupalGet('contact'); $this->assertResponse(403); // Give anonymous user permission and see that page is viewable. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']); $this->drupalGet('contact'); $this->assertResponse(200); @@ -210,7 +210,7 @@ function testSiteWideContact() { $this->assertText(t('Your email address field is required.')); $this->submitContact($this->randomMachineName(16), $invalid_recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64)); - $this->assertRaw(t('The email address %mail is not valid.', array('%mail' => 'invalid'))); + $this->assertRaw(t('The email address %mail is not valid.', ['%mail' => 'invalid'])); $this->submitContact($this->randomMachineName(16), $recipients[0], '', $id, $this->randomMachineName(64)); $this->assertText(t('Subject field is required.')); @@ -238,7 +238,7 @@ function testSiteWideContact() { } // Submit contact form one over limit. $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64)); - $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', array('%number' => $this->config('contact.settings')->get('flood.limit')))); + $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', ['%number' => $this->config('contact.settings')->get('flood.limit')])); // Test listing controller. $this->drupalLogin($admin_user); @@ -246,7 +246,7 @@ function testSiteWideContact() { $this->deleteContactForms(); $label = $this->randomMachineName(16); - $recipients = implode(',', array($recipients[0], $recipients[1], $recipients[2])); + $recipients = implode(',', [$recipients[0], $recipients[1], $recipients[2]]); $contact_form = Unicode::strtolower($this->randomMachineName(16)); $this->addContactForm($contact_form, $label, $recipients, '', FALSE); $this->drupalGet('admin/structure/contact'); @@ -293,15 +293,15 @@ function testSiteWideContact() { $this->assertText($field_label); // Submit the contact form and verify the content. - $edit = array( + $edit = [ 'subject[0][value]' => $this->randomMachineName(), 'message[0][value]' => $this->randomMachineName(), $field_name . '[0][value]' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Send message')); $mails = $this->drupalGetMails(); $mail = array_pop($mails); - $this->assertEqual($mail['subject'], t('[@label] @subject', array('@label' => $label, '@subject' => $edit['subject[0][value]']))); + $this->assertEqual($mail['subject'], t('[@label] @subject', ['@label' => $label, '@subject' => $edit['subject[0][value]']])); $this->assertTrue(strpos($mail['body'], $field_label)); $this->assertTrue(strpos($mail['body'], $edit[$field_name . '[0][value]'])); @@ -315,11 +315,11 @@ function testSiteWideContact() { $this->drupalGet('contact/' . $contact_form); // Submit the contact form and verify the content. - $edit = array( + $edit = [ 'subject[0][value]' => $this->randomMachineName(), 'message[0][value]' => $this->randomMachineName(), $field_name . '[0][value]' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Send message')); $this->assertText('Thanks for your submission.'); $this->assertUrl('user/' . $admin_user->id()); @@ -335,13 +335,13 @@ function testSiteWideContact() { $this->drupalGet('contact/' . $contact_form); // Submit the contact form and verify the content. - $edit = array( + $edit = [ 'subject[0][value]' => $this->randomMachineName(), 'message[0][value]' => $this->randomMachineName(), $field_name . '[0][value]' => $this->randomMachineName(), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Send message')); - $result = $this->xpath('//div[@role=:role]', array(':role' => 'contentinfo')); + $result = $this->xpath('//div[@role=:role]', [':role' => 'contentinfo']); $this->assertEqual(count($result), 0, 'Messages not found.'); $this->assertUrl('user/' . $admin_user->id()); } @@ -369,7 +369,7 @@ function testAutoReply() { // Log the current user out in order to test the name and email fields. $this->drupalLogout(); - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']); // Test the auto-reply for form 'foo'. $email = $this->randomMachineName(32) . '@example.com'; @@ -377,7 +377,7 @@ function testAutoReply() { $this->submitContact($this->randomMachineName(16), $email, $subject, 'foo', $this->randomString(128)); // We are testing the auto-reply, so there should be one email going to the sender. - $captured_emails = $this->drupalGetMails(array('id' => 'contact_page_autoreply', 'to' => $email)); + $captured_emails = $this->drupalGetMails(['id' => 'contact_page_autoreply', 'to' => $email]); $this->assertEqual(count($captured_emails), 1); $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($foo_autoreply))); @@ -386,14 +386,14 @@ function testAutoReply() { $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'bar', $this->randomString(128)); // Auto-reply for form 'bar' should result in one auto-reply email to the sender. - $captured_emails = $this->drupalGetMails(array('id' => 'contact_page_autoreply', 'to' => $email)); + $captured_emails = $this->drupalGetMails(['id' => 'contact_page_autoreply', 'to' => $email]); $this->assertEqual(count($captured_emails), 1); $this->assertEqual(trim($captured_emails[0]['body']), trim(MailFormatHelper::htmlToText($bar_autoreply))); // Verify that no auto-reply is sent when the auto-reply field is left blank. $email = $this->randomMachineName(32) . '@example.com'; $this->submitContact($this->randomMachineName(16), $email, $this->randomString(64), 'no_autoreply', $this->randomString(128)); - $captured_emails = $this->drupalGetMails(array('id' => 'contact_page_autoreply', 'to' => $email)); + $captured_emails = $this->drupalGetMails(['id' => 'contact_page_autoreply', 'to' => $email]); $this->assertEqual(count($captured_emails), 0); // Verify that the current error message doesn't show, that the auto-reply @@ -432,7 +432,7 @@ function testAutoReply() { * Array of third party settings to be added to the posted form data. */ function addContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $third_party_settings = []) { - $edit = array(); + $edit = []; $edit['label'] = $label; $edit['id'] = $id; $edit['message'] = $message; @@ -464,7 +464,7 @@ function addContactForm($id, $label, $recipients, $reply, $selected, $message = * The path where user will be redirect after this form has been submitted.. */ function updateContactForm($id, $label, $recipients, $reply, $selected, $message = 'Your message has been sent.', $redirect = '/') { - $edit = array(); + $edit = []; $edit['label'] = $label; $edit['recipients'] = $recipients; $edit['reply'] = $reply; @@ -489,7 +489,7 @@ function updateContactForm($id, $label, $recipients, $reply, $selected, $message * The message body. */ function submitContact($name, $mail, $subject, $id, $message) { - $edit = array(); + $edit = []; $edit['name'] = $name; $edit['mail'] = $mail; $edit['subject[0][value]'] = $subject; @@ -514,9 +514,9 @@ function deleteContactForms() { $this->assertResponse(403); } else { - $this->drupalPostForm("admin/structure/contact/manage/$id/delete", array(), t('Delete')); - $this->assertRaw(t('The contact form %label has been deleted.', array('%label' => $contact_form->label()))); - $this->assertFalse(ContactForm::load($id), format_string('Form %contact_form not found', array('%contact_form' => $contact_form->label()))); + $this->drupalPostForm("admin/structure/contact/manage/$id/delete", [], t('Delete')); + $this->assertRaw(t('The contact form %label has been deleted.', ['%label' => $contact_form->label()])); + $this->assertFalse(ContactForm::load($id), format_string('Form %contact_form not found', ['%contact_form' => $contact_form->label()])); } } } diff --git a/core/modules/contact/src/Tests/ContactStorageTest.php b/core/modules/contact/src/Tests/ContactStorageTest.php index ad0e8d46c5..f9165a8534 100644 --- a/core/modules/contact/src/Tests/ContactStorageTest.php +++ b/core/modules/contact/src/Tests/ContactStorageTest.php @@ -37,23 +37,23 @@ class ContactStorageTest extends ContactSitewideTest { */ public function testContactStorage() { // Create and log in administrative user. - $admin_user = $this->drupalCreateUser(array( + $admin_user = $this->drupalCreateUser([ 'access site-wide contact form', 'administer contact forms', 'administer users', 'administer account settings', 'administer contact_message fields', - )); + ]); $this->drupalLogin($admin_user); // Create first valid contact form. $mail = 'simpletest@example.com'; - $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($mail)), '', TRUE, 'Your message has been sent.', [ + $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', [$mail]), '', TRUE, 'Your message has been sent.', [ 'send_a_pony' => 1, ]); - $this->assertText(t('Contact form @label has been added.', array('@label' => $label))); + $this->assertText(t('Contact form @label has been added.', ['@label' => $label])); // Ensure that anonymous can submit site-wide contact form. - user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); + user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']); $this->drupalLogout(); $this->drupalGet('contact'); $this->assertText(t('Your email address')); diff --git a/core/modules/contact/src/Tests/Views/ContactFieldsTest.php b/core/modules/contact/src/Tests/Views/ContactFieldsTest.php index cf707996f1..fafe451be5 100644 --- a/core/modules/contact/src/Tests/Views/ContactFieldsTest.php +++ b/core/modules/contact/src/Tests/Views/ContactFieldsTest.php @@ -19,7 +19,7 @@ class ContactFieldsTest extends ViewTestBase { * * @var array */ - public static $modules = array('field', 'text', 'contact'); + public static $modules = ['field', 'text', 'contact']; /** * Contains the field storage definition for contact used for this test. @@ -31,11 +31,11 @@ class ContactFieldsTest extends ViewTestBase { protected function setUp() { parent::setUp(); - $this->fieldStorage = FieldStorageConfig::create(array( + $this->fieldStorage = FieldStorageConfig::create([ 'field_name' => strtolower($this->randomMachineName()), 'entity_type' => 'contact_message', 'type' => 'text' - )); + ]); $this->fieldStorage->save(); ContactForm::create([ diff --git a/core/modules/contact/src/Tests/Views/ContactLinkTest.php b/core/modules/contact/src/Tests/Views/ContactLinkTest.php index 738f67c1b4..f6b6013b43 100644 --- a/core/modules/contact/src/Tests/Views/ContactLinkTest.php +++ b/core/modules/contact/src/Tests/Views/ContactLinkTest.php @@ -27,14 +27,14 @@ class ContactLinkTest extends ViewTestBase { * * @var array */ - public static $modules = array('contact_test_views'); + public static $modules = ['contact_test_views']; /** * Views used by this test. * * @var array */ - public static $testViews = array('test_contact_link'); + public static $testViews = ['test_contact_link']; /** * {@inheritdoc} @@ -42,7 +42,7 @@ class ContactLinkTest extends ViewTestBase { protected function setUp() { parent::setUp(); - ViewTestData::createTestViews(get_class($this), array('contact_test_views')); + ViewTestData::createTestViews(get_class($this), ['contact_test_views']); $this->userData = $this->container->get('user.data'); } @@ -51,39 +51,39 @@ protected function setUp() { * Tests contact link. */ public function testContactLink() { - $accounts = array(); + $accounts = []; $accounts['root'] = User::load(1); // Create an account with access to all contact pages. - $admin_account = $this->drupalCreateUser(array('administer users')); + $admin_account = $this->drupalCreateUser(['administer users']); $accounts['admin'] = $admin_account; // Create an account with no access to contact pages. $no_contact_account = $this->drupalCreateUser(); $accounts['no_contact'] = $no_contact_account; // Create an account with access to contact pages. - $contact_account = $this->drupalCreateUser(array('access user contact forms')); + $contact_account = $this->drupalCreateUser(['access user contact forms']); $accounts['contact'] = $contact_account; $this->drupalLogin($admin_account); $this->drupalGet('test-contact-link'); // The admin user has access to all contact links beside his own. - $this->assertContactLinks($accounts, array('root', 'no_contact', 'contact')); + $this->assertContactLinks($accounts, ['root', 'no_contact', 'contact']); $this->drupalLogin($no_contact_account); $this->drupalGet('test-contact-link'); // Ensure that the user without the permission doesn't see any link. - $this->assertContactLinks($accounts, array()); + $this->assertContactLinks($accounts, []); $this->drupalLogin($contact_account); $this->drupalGet('test-contact-link'); - $this->assertContactLinks($accounts, array('root', 'admin', 'no_contact')); + $this->assertContactLinks($accounts, ['root', 'admin', 'no_contact']); // Disable contact link for no_contact. $this->userData->set('contact', $no_contact_account->id(), 'enabled', FALSE); // @todo Remove cache invalidation in https://www.drupal.org/node/2477903. Cache::invalidateTags($no_contact_account->getCacheTagsToInvalidate()); $this->drupalGet('test-contact-link'); - $this->assertContactLinks($accounts, array('root', 'admin')); + $this->assertContactLinks($accounts, ['root', 'admin']); } /** @@ -100,7 +100,7 @@ public function assertContactLinks(array $accounts, array $names) { foreach ($names as $name) { $account = $accounts[$name]; - $result = $this->xpath('//div[contains(@class, "views-field-contact")]//a[contains(@href, :url)]', array(':url' => $account->url('contact-form'))); + $result = $this->xpath('//div[contains(@class, "views-field-contact")]//a[contains(@href, :url)]', [':url' => $account->url('contact-form')]); $this->assertTrue(count($result)); } } diff --git a/core/modules/contact/tests/drupal-7.contact.database.php b/core/modules/contact/tests/drupal-7.contact.database.php index 115f83c17c..bd36384d7e 100644 --- a/core/modules/contact/tests/drupal-7.contact.database.php +++ b/core/modules/contact/tests/drupal-7.contact.database.php @@ -11,23 +11,23 @@ // Update the default category to that it is not selected. db_update('contact') - ->fields(array('selected' => '0')) + ->fields(['selected' => '0']) ->condition('cid', '1') ->execute(); // Add a custom contact category. -db_insert('contact')->fields(array( +db_insert('contact')->fields([ 'category', 'recipients', 'reply', 'weight', 'selected' -)) - ->values(array( +]) + ->values([ 'category' => 'Upgrade test', 'recipients' => 'test1@example.com,test2@example.com', 'reply' => 'Test reply', 'weight' => 1, 'selected' => 1, -)) +]) ->execute(); diff --git a/core/modules/contact/tests/modules/contact_storage_test/contact_storage_test.module b/core/modules/contact/tests/modules/contact_storage_test/contact_storage_test.module index e20dc436fc..cef976c6ff 100644 --- a/core/modules/contact/tests/modules/contact_storage_test/contact_storage_test.module +++ b/core/modules/contact/tests/modules/contact_storage_test/contact_storage_test.module @@ -15,7 +15,7 @@ */ function contact_storage_test_entity_base_field_info(EntityTypeInterface $entity_type) { if ($entity_type->id() == 'contact_message') { - $fields = array(); + $fields = []; $fields['id'] = BaseFieldDefinition::create('integer') ->setLabel(t('Message ID')) @@ -48,12 +48,12 @@ function contact_storage_test_entity_type_alter(array &$entity_types) { function contact_storage_test_form_contact_form_form_alter(&$form, FormStateInterface $form_state) { /** @var \Drupal\contact\ContactFormInterface $contact_form */ $contact_form = $form_state->getFormObject()->getEntity(); - $form['send_a_pony'] = array( + $form['send_a_pony'] = [ '#type' => 'checkbox', '#title' => t('Send submitters a voucher for a free pony.'), '#description' => t('Enable to send an additional email with a free pony voucher to anyone who submits the form.'), '#default_value' => $contact_form->getThirdPartySetting('contact_storage_test', 'send_a_pony', FALSE), - ); + ]; $form['#entity_builders'][] = 'contact_storage_test_contact_form_form_builder'; } /** diff --git a/core/modules/contact/tests/src/Functional/ContactAuthenticatedUserTest.php b/core/modules/contact/tests/src/Functional/ContactAuthenticatedUserTest.php index 4b4a520de6..306fe5d41c 100644 --- a/core/modules/contact/tests/src/Functional/ContactAuthenticatedUserTest.php +++ b/core/modules/contact/tests/src/Functional/ContactAuthenticatedUserTest.php @@ -16,20 +16,20 @@ class ContactAuthenticatedUserTest extends BrowserTestBase { * * @var array */ - public static $modules = array('contact'); + public static $modules = ['contact']; /** * Tests that name and email fields are not present for authenticated users. */ function testContactSiteWideTextfieldsLoggedInTestCase() { - $this->drupalLogin($this->drupalCreateUser(array('access site-wide contact form'))); + $this->drupalLogin($this->drupalCreateUser(['access site-wide contact form'])); $this->drupalGet('contact'); // Ensure that there is no textfield for name. - $this->assertFalse($this->xpath('//input[@name=:name]', array(':name' => 'name'))); + $this->assertFalse($this->xpath('//input[@name=:name]', [':name' => 'name'])); // Ensure that there is no textfield for email. - $this->assertFalse($this->xpath('//input[@name=:name]', array(':name' => 'mail'))); + $this->assertFalse($this->xpath('//input[@name=:name]', [':name' => 'mail'])); } } diff --git a/core/modules/contact/tests/src/Functional/ContactLanguageTest.php b/core/modules/contact/tests/src/Functional/ContactLanguageTest.php index 47d15332d4..0c34884503 100644 --- a/core/modules/contact/tests/src/Functional/ContactLanguageTest.php +++ b/core/modules/contact/tests/src/Functional/ContactLanguageTest.php @@ -20,11 +20,11 @@ class ContactLanguageTest extends BrowserTestBase { * * @var array */ - public static $modules = array( + public static $modules = [ 'contact', 'language', 'contact_test', - ); + ]; /** * {@inheritdoc} @@ -33,10 +33,10 @@ protected function setUp() { parent::setUp(); // Create and log in administrative user. - $admin_user = $this->drupalCreateUser(array( + $admin_user = $this->drupalCreateUser([ 'access site-wide contact form', 'administer languages', - )); + ]); $this->drupalLogin($admin_user); } diff --git a/core/modules/contact/tests/src/Kernel/MessageEntityTest.php b/core/modules/contact/tests/src/Kernel/MessageEntityTest.php index 70ddea194e..e7343b9166 100644 --- a/core/modules/contact/tests/src/Kernel/MessageEntityTest.php +++ b/core/modules/contact/tests/src/Kernel/MessageEntityTest.php @@ -17,17 +17,17 @@ class MessageEntityTest extends EntityKernelTestBase { * * @var array */ - public static $modules = array( + public static $modules = [ 'system', 'contact', 'field', 'user', 'contact_test', - ); + ]; protected function setUp() { parent::setUp(); - $this->installConfig(array('contact', 'contact_test')); + $this->installConfig(['contact', 'contact_test']); } /** @@ -35,7 +35,7 @@ protected function setUp() { */ public function testMessageMethods() { $message_storage = $this->container->get('entity.manager')->getStorage('contact_message'); - $message = $message_storage->create(array('contact_form' => 'feedback')); + $message = $message_storage->create(['contact_form' => 'feedback']); // Check for empty values first. $this->assertEqual($message->getMessage(), ''); diff --git a/core/modules/contact/tests/src/Kernel/Migrate/MigrateContactCategoryTest.php b/core/modules/contact/tests/src/Kernel/Migrate/MigrateContactCategoryTest.php index 89f98b1739..ffadad409c 100644 --- a/core/modules/contact/tests/src/Kernel/Migrate/MigrateContactCategoryTest.php +++ b/core/modules/contact/tests/src/Kernel/Migrate/MigrateContactCategoryTest.php @@ -18,7 +18,7 @@ class MigrateContactCategoryTest extends MigrateDrupal6TestBase { * * @var array */ - public static $modules = array('contact'); + public static $modules = ['contact']; /** * {@inheritdoc} diff --git a/core/modules/contact/tests/src/Unit/MailHandlerTest.php b/core/modules/contact/tests/src/Unit/MailHandlerTest.php index 9e5c82c0c6..ce24cf4848 100644 --- a/core/modules/contact/tests/src/Unit/MailHandlerTest.php +++ b/core/modules/contact/tests/src/Unit/MailHandlerTest.php @@ -80,7 +80,7 @@ protected function setUp() { $string_translation = $this->getStringTranslationStub(); $this->contactMailHandler = new MailHandler($this->mailManager, $this->languageManager, $this->logger, $string_translation, $this->entityManager); - $language = new Language(array('id' => 'en')); + $language = new Language(['id' => 'en']); $this->languageManager->expects($this->any()) ->method('getDefaultLanguage') @@ -156,76 +156,76 @@ function($module, $key, $to, $langcode, $params, $from) use (&$results) { * Data provider for ::testSendMailMessages. */ public function getSendMailMessages() { - $data = array(); - $recipients = array('admin@drupal.org', 'user@drupal.org'); - $default_result = array( + $data = []; + $recipients = ['admin@drupal.org', 'user@drupal.org']; + $default_result = [ 'module' => 'contact', 'key' => '', 'to' => implode(', ', $recipients), 'langcode' => 'en', - 'params' => array(), + 'params' => [], 'from' => 'anonymous@drupal.org', - ); - $results = array(); + ]; + $results = []; $message = $this->getAnonymousMockMessage($recipients, ''); $sender = $this->getMockSender(); - $result = array( + $result = [ 'key' => 'page_mail', - 'params' => array( + 'params' => [ 'contact_message' => $message, 'sender' => $sender, 'contact_form' => $message->getContactForm(), - ), - ); + ], + ]; $results[] = $result + $default_result; - $data[] = array($message, $sender, $results); + $data[] = [$message, $sender, $results]; - $results = array(); + $results = []; $message = $this->getAnonymousMockMessage($recipients, 'reply'); $sender = $this->getMockSender(); - $result = array( + $result = [ 'key' => 'page_mail', - 'params' => array( + 'params' => [ 'contact_message' => $message, 'sender' => $sender, 'contact_form' => $message->getContactForm(), - ), - ); + ], + ]; $results[] = $result + $default_result; $result['key'] = 'page_autoreply'; $result['to'] = 'anonymous@drupal.org'; $result['from'] = NULL; $results[] = $result + $default_result; - $data[] = array($message, $sender, $results); + $data[] = [$message, $sender, $results]; - $results = array(); + $results = []; $message = $this->getAnonymousMockMessage($recipients, '', TRUE); $sender = $this->getMockSender(); - $result = array( + $result = [ 'key' => 'page_mail', - 'params' => array( + 'params' => [ 'contact_message' => $message, 'sender' => $sender, 'contact_form' => $message->getContactForm(), - ), - ); + ], + ]; $results[] = $result + $default_result; $result['key'] = 'page_copy'; $result['to'] = 'anonymous@drupal.org'; $results[] = $result + $default_result; - $data[] = array($message, $sender, $results); + $data[] = [$message, $sender, $results]; - $results = array(); + $results = []; $message = $this->getAnonymousMockMessage($recipients, 'reply', TRUE); $sender = $this->getMockSender(); - $result = array( + $result = [ 'key' => 'page_mail', - 'params' => array( + 'params' => [ 'contact_message' => $message, 'sender' => $sender, 'contact_form' => $message->getContactForm(), - ), - ); + ], + ]; $results[] = $result + $default_result; $result['key'] = 'page_copy'; $result['to'] = 'anonymous@drupal.org'; @@ -233,48 +233,48 @@ public function getSendMailMessages() { $result['key'] = 'page_autoreply'; $result['from'] = NULL; $results[] = $result + $default_result; - $data[] = array($message, $sender, $results); + $data[] = [$message, $sender, $results]; //For authenticated user. - $results = array(); + $results = []; $message = $this->getAuthenticatedMockMessage(); $sender = $this->getMockSender(FALSE, 'user@drupal.org'); - $result = array( + $result = [ 'module' => 'contact', 'key' => 'user_mail', 'to' => 'user2@drupal.org', 'langcode' => 'en', - 'params' => array( + 'params' => [ 'contact_message' => $message, 'sender' => $sender, 'recipient' => $message->getPersonalRecipient(), - ), + ], 'from' => 'user@drupal.org', - ); + ]; $results[] = $result; - $data[] = array($message, $sender, $results); + $data[] = [$message, $sender, $results]; - $results = array(); + $results = []; $message = $this->getAuthenticatedMockMessage(TRUE); $sender = $this->getMockSender(FALSE, 'user@drupal.org'); - $result = array( + $result = [ 'module' => 'contact', 'key' => 'user_mail', 'to' => 'user2@drupal.org', 'langcode' => 'en', - 'params' => array( + 'params' => [ 'contact_message' => $message, 'sender' => $sender, 'recipient' => $message->getPersonalRecipient(), - ), + ], 'from' => 'user@drupal.org', - ); + ]; $results[] = $result; $result['key'] = 'user_copy'; $result['to'] = $result['from']; $results[] = $result; - $data[] = array($message, $sender, $results); + $data[] = [$message, $sender, $results]; return $data; } diff --git a/core/modules/content_moderation/src/ContentModerationStateStorageSchema.php b/core/modules/content_moderation/src/ContentModerationStateStorageSchema.php index 19ec324c1a..cb87cc19ab 100644 --- a/core/modules/content_moderation/src/ContentModerationStateStorageSchema.php +++ b/core/modules/content_moderation/src/ContentModerationStateStorageSchema.php @@ -19,9 +19,9 @@ protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $res // Creates an index to ensure that the lookup in // \Drupal\content_moderation\Plugin\Field\ModerationStateFieldItemList::getModerationState() // is performant. - $schema['content_moderation_state_field_data']['indexes'] += array( - 'content_moderation_state__lookup' => array('content_entity_type_id', 'content_entity_id', 'content_entity_revision_id'), - ); + $schema['content_moderation_state_field_data']['indexes'] += [ + 'content_moderation_state__lookup' => ['content_entity_type_id', 'content_entity_id', 'content_entity_revision_id'], + ]; return $schema; } diff --git a/core/modules/content_moderation/src/Entity/ContentModerationState.php b/core/modules/content_moderation/src/Entity/ContentModerationState.php index 6d5b39c2b4..cb1bc1fe9f 100644 --- a/core/modules/content_moderation/src/Entity/ContentModerationState.php +++ b/core/modules/content_moderation/src/Entity/ContentModerationState.php @@ -148,7 +148,7 @@ public static function updateOrCreateFromEntity(ContentModerationState $content_ * An array of default values. */ public static function getCurrentUserId() { - return array(\Drupal::currentUser()->id()); + return [\Drupal::currentUser()->id()]; } /** diff --git a/core/modules/content_moderation/src/ParamConverter/EntityRevisionConverter.php b/core/modules/content_moderation/src/ParamConverter/EntityRevisionConverter.php index 980c61ebd8..94f10e9f00 100644 --- a/core/modules/content_moderation/src/ParamConverter/EntityRevisionConverter.php +++ b/core/modules/content_moderation/src/ParamConverter/EntityRevisionConverter.php @@ -95,7 +95,7 @@ public function convert($value, $definition, $name, array $defaults) { // If the entity type is translatable, ensure we return the proper // translation object for the current context. if ($latest_revision instanceof EntityInterface && $entity instanceof TranslatableInterface) { - $latest_revision = $this->entityManager->getTranslationFromContext($latest_revision, NULL, array('operation' => 'entity_upcast')); + $latest_revision = $this->entityManager->getTranslationFromContext($latest_revision, NULL, ['operation' => 'entity_upcast']); } if ($latest_revision->isRevisionTranslationAffected()) { diff --git a/core/modules/content_moderation/src/Plugin/Field/FieldFormatter/ContentModerationStateFormatter.php b/core/modules/content_moderation/src/Plugin/Field/FieldFormatter/ContentModerationStateFormatter.php index 4e9da164c0..e4c283fac3 100644 --- a/core/modules/content_moderation/src/Plugin/Field/FieldFormatter/ContentModerationStateFormatter.php +++ b/core/modules/content_moderation/src/Plugin/Field/FieldFormatter/ContentModerationStateFormatter.php @@ -23,7 +23,7 @@ class ContentModerationStateFormatter extends FormatterBase { * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; $entity = $items->getEntity(); $workflow = $entity->workflow->entity; diff --git a/core/modules/content_moderation/src/Plugin/Field/FieldWidget/ModerationStateWidget.php b/core/modules/content_moderation/src/Plugin/Field/FieldWidget/ModerationStateWidget.php index 7fe5a6db9a..970ac33a5d 100644 --- a/core/modules/content_moderation/src/Plugin/Field/FieldWidget/ModerationStateWidget.php +++ b/core/modules/content_moderation/src/Plugin/Field/FieldWidget/ModerationStateWidget.php @@ -139,7 +139,7 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen '#published' => $default->isPublishedState(), '#key_column' => $this->column, ]; - $element['#element_validate'][] = array(get_class($this), 'validateElement'); + $element['#element_validate'][] = [get_class($this), 'validateElement']; // Use the dropbutton. $element['#process'][] = [get_called_class(), 'processActions']; diff --git a/core/modules/content_moderation/src/Tests/ModerationStateBlockTest.php b/core/modules/content_moderation/src/Tests/ModerationStateBlockTest.php index e42f536b91..593a9f9618 100644 --- a/core/modules/content_moderation/src/Tests/ModerationStateBlockTest.php +++ b/core/modules/content_moderation/src/Tests/ModerationStateBlockTest.php @@ -73,11 +73,11 @@ public function testCustomBlockModeration() { $this->assertText(t('basic Moderated block has been created.')); // Place the block in the Sidebar First region. - $instance = array( + $instance = [ 'id' => 'moderated_block', 'settings[label]' => $edit['info[0][value]'], 'region' => 'sidebar_first', - ); + ]; $block = BlockContent::load(1); $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default'); $this->drupalPostForm($url, $instance, t('Save block')); diff --git a/core/modules/content_moderation/src/Tests/ModerationStateNodeTest.php b/core/modules/content_moderation/src/Tests/ModerationStateNodeTest.php index fe36336176..49eee6d527 100644 --- a/core/modules/content_moderation/src/Tests/ModerationStateNodeTest.php +++ b/core/modules/content_moderation/src/Tests/ModerationStateNodeTest.php @@ -48,7 +48,7 @@ public function testCreatingContent() { $this->assertNoText('Published'); // Delete the node. - $this->drupalPostForm('node/' . $node->id() . '/delete', array(), t('Delete')); + $this->drupalPostForm('node/' . $node->id() . '/delete', [], t('Delete')); $this->assertText(t('The Moderated content moderated content has been deleted.')); // Disable content moderation. diff --git a/core/modules/content_translation/content_translation.admin.inc b/core/modules/content_translation/content_translation.admin.inc index 39e3247ca1..f29a7e6556 100644 --- a/core/modules/content_translation/content_translation.admin.inc +++ b/core/modules/content_translation/content_translation.admin.inc @@ -29,10 +29,10 @@ function content_translation_field_sync_widget(FieldDefinitionInterface $field, $element_name = 'third_party_settings[content_translation][translation_sync]') { // No way to store field sync information on this field. if (!($field instanceof ThirdPartySettingsInterface)) { - return array(); + return []; } - $element = array(); + $element = []; $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($field->getType()); $column_groups = $definition['column_groups']; if (!empty($column_groups) && count($column_groups) > 1) { @@ -50,12 +50,12 @@ function content_translation_field_sync_widget(FieldDefinitionInterface $field, $default = $field->getThirdPartySetting('content_translation', 'translation_sync', $default); - $element = array( + $element = [ '#type' => 'checkboxes', '#title' => t('Translatable elements'), '#options' => $options, '#default_value' => $default, - ); + ]; if ($require_all_groups_for_translation) { // The actual checkboxes are sometimes rendered separately and the parent @@ -96,7 +96,7 @@ function _content_translation_form_language_content_settings_form_alter(array &$ $bundle_info_service = \Drupal::service('entity_type.bundle.info'); foreach ($form['#labels'] as $entity_type_id => $label) { $entity_type = $entity_manager->getDefinition($entity_type_id); - $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $entity_manager->getFieldStorageDefinitions($entity_type_id) : array(); + $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $entity_manager->getFieldStorageDefinitions($entity_type_id) : []; $entity_type_translatable = $content_translation_manager->isSupported($entity_type_id); foreach ($bundle_info_service->getBundleInfo($entity_type_id) as $bundle => $bundle_info) { @@ -106,7 +106,7 @@ function _content_translation_form_language_content_settings_form_alter(array &$ // about UI integration. $form['settings'][$entity_type_id][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE; if (!$entity_type_translatable) { - $form['settings'][$entity_type_id]['#title'] = t('@label (Translation is not supported).', array('@label' => $entity_type->getLabel())); + $form['settings'][$entity_type_id]['#title'] = t('@label (Translation is not supported).', ['@label' => $entity_type->getLabel()]); continue; } @@ -114,11 +114,11 @@ function _content_translation_form_language_content_settings_form_alter(array &$ if ($fields) { foreach ($fields as $field_name => $definition) { if ($definition->isComputed() || (!empty($storage_definitions[$field_name]) && _content_translation_is_field_translatability_configurable($entity_type, $storage_definitions[$field_name]))) { - $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = array( + $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = [ '#label' => $definition->getLabel(), '#type' => 'checkbox', '#default_value' => $definition->isTranslatable(), - ); + ]; // Display the column translatability configuration widget. $column_element = content_translation_field_sync_widget($definition, "settings[{$entity_type_id}][{$bundle}][columns][{$field_name}]"); if ($column_element) { @@ -129,10 +129,10 @@ function _content_translation_form_language_content_settings_form_alter(array &$ if (!empty($form['settings'][$entity_type_id][$bundle]['fields'])) { // Only show the checkbox to enable translation if the bundles in the // entity might have fields and if there are fields to translate. - $form['settings'][$entity_type_id][$bundle]['translatable'] = array( + $form['settings'][$entity_type_id][$bundle]['translatable'] = [ '#type' => 'checkbox', '#default_value' => $content_translation_manager->isEnabled($entity_type_id, $bundle), - ); + ]; } } } @@ -177,102 +177,102 @@ function _content_translation_preprocess_language_content_settings_table(&$varia $element = $variables['element']; $build = &$variables['build']; - array_unshift($build['#header'], array('data' => t('Translatable'), 'class' => array('translatable'))); - $rows = array(); + array_unshift($build['#header'], ['data' => t('Translatable'), 'class' => ['translatable']]); + $rows = []; foreach (Element::children($element) as $bundle) { - $field_names = !empty($element[$bundle]['fields']) ? Element::children($element[$bundle]['fields']) : array(); + $field_names = !empty($element[$bundle]['fields']) ? Element::children($element[$bundle]['fields']) : []; if (!empty($element[$bundle]['translatable'])) { $checkbox_id = $element[$bundle]['translatable']['#id']; } $rows[$bundle] = $build['#rows'][$bundle]; if (!empty($element[$bundle]['translatable'])) { - $translatable = array( + $translatable = [ 'data' => $element[$bundle]['translatable'], - 'class' => array('translatable'), - ); + 'class' => ['translatable'], + ]; array_unshift($rows[$bundle]['data'], $translatable); $rows[$bundle]['data'][1]['data']['#prefix'] = '
    '; $output .= t('Once the contextual links button for the area of interest is visible, click the button to display the links.'); $output .= '
  • '; @@ -132,10 +132,10 @@ function contextual_preprocess(&$variables, $hook, $info) { // users, contextual_page_attachments() only adds the asset library for // users with the 'access contextual links' permission, thus preventing // unnecessary HTTP requests for users without that permission. - $variables['title_suffix']['contextual_links'] = array( + $variables['title_suffix']['contextual_links'] = [ '#type' => 'contextual_links_placeholder', '#id' => _contextual_links_to_id($element['#contextual_links']), - ); + ]; } } @@ -172,7 +172,7 @@ function contextual_contextual_links_view_alter(&$element, $items) { * use in a data- attribute. */ function _contextual_links_to_id($contextual_links) { - $ids = array(); + $ids = []; $langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(); foreach ($contextual_links as $group => $args) { $route_parameters = UrlHelper::buildQuery($args['route_parameters']); @@ -199,17 +199,17 @@ function _contextual_links_to_id($contextual_links) { * The value for a #contextual_links property. */ function _contextual_id_to_links($id) { - $contextual_links = array(); + $contextual_links = []; $contexts = explode('|', $id); foreach ($contexts as $context) { list($group, $route_parameters_raw, $metadata_raw) = explode(':', $context); parse_str($route_parameters_raw, $route_parameters); - $metadata = array(); + $metadata = []; parse_str($metadata_raw, $metadata); - $contextual_links[$group] = array( + $contextual_links[$group] = [ 'route_parameters' => $route_parameters, 'metadata' => $metadata, - ); + ]; } return $contextual_links; } diff --git a/core/modules/contextual/contextual.views.inc b/core/modules/contextual/contextual.views.inc index 528b3bbed0..bac5522f15 100644 --- a/core/modules/contextual/contextual.views.inc +++ b/core/modules/contextual/contextual.views.inc @@ -9,11 +9,11 @@ * Implements hook_views_data_alter(). */ function contextual_views_data_alter(&$data) { - $data['views']['contextual_links'] = array( + $data['views']['contextual_links'] = [ 'title' => t('Contextual Links'), 'help' => t('Display fields in a contextual links menu.'), - 'field' => array( + 'field' => [ 'id' => 'contextual_links', - ), - ); + ], + ]; } diff --git a/core/modules/contextual/src/ContextualController.php b/core/modules/contextual/src/ContextualController.php index 0812ad13d2..b1fe245c04 100644 --- a/core/modules/contextual/src/ContextualController.php +++ b/core/modules/contextual/src/ContextualController.php @@ -32,12 +32,12 @@ public function render(Request $request) { throw new BadRequestHttpException(t('No contextual ids specified.')); } - $rendered = array(); + $rendered = []; foreach ($ids as $id) { - $element = array( + $element = [ '#type' => 'contextual_links', '#contextual_links' => _contextual_id_to_links($id), - ); + ]; $rendered[$id] = $this->container->get('renderer')->renderRoot($element); } diff --git a/core/modules/contextual/src/Element/ContextualLinks.php b/core/modules/contextual/src/Element/ContextualLinks.php index 8f670236fd..62e8966afa 100644 --- a/core/modules/contextual/src/Element/ContextualLinks.php +++ b/core/modules/contextual/src/Element/ContextualLinks.php @@ -18,19 +18,19 @@ class ContextualLinks extends RenderElement { */ public function getInfo() { $class = get_class($this); - return array( - '#pre_render' => array( - array($class, 'preRenderLinks'), - ), + return [ + '#pre_render' => [ + [$class, 'preRenderLinks'], + ], '#theme' => 'links__contextual', - '#links' => array(), - '#attributes' => array('class' => array('contextual-links')), - '#attached' => array( - 'library' => array( + '#links' => [], + '#attributes' => ['class' => ['contextual-links']], + '#attached' => [ + 'library' => [ 'contextual/drupal.contextual-links', - ), - ), - ); + ], + ], + ]; } /** @@ -60,26 +60,26 @@ public function getInfo() { */ public static function preRenderLinks(array $element) { // Retrieve contextual menu links. - $items = array(); + $items = []; $contextual_links_manager = static::contextualLinkManager(); foreach ($element['#contextual_links'] as $group => $args) { - $args += array( - 'route_parameters' => array(), - 'metadata' => array(), - ); + $args += [ + 'route_parameters' => [], + 'metadata' => [], + ]; $items += $contextual_links_manager->getContextualLinksArrayByGroup($group, $args['route_parameters'], $args['metadata']); } // Transform contextual links into parameters suitable for links.html.twig. - $links = array(); + $links = []; foreach ($items as $class => $item) { $class = Html::getClass($class); - $links[$class] = array( + $links[$class] = [ 'title' => $item['title'], 'url' => Url::fromRoute(isset($item['route_name']) ? $item['route_name'] : '', isset($item['route_parameters']) ? $item['route_parameters'] : []), - ); + ]; } $element['#links'] = $links; diff --git a/core/modules/contextual/src/Element/ContextualLinksPlaceholder.php b/core/modules/contextual/src/Element/ContextualLinksPlaceholder.php index 92f4b2bed5..2fba8db3f1 100644 --- a/core/modules/contextual/src/Element/ContextualLinksPlaceholder.php +++ b/core/modules/contextual/src/Element/ContextualLinksPlaceholder.php @@ -18,12 +18,12 @@ class ContextualLinksPlaceholder extends RenderElement { */ public function getInfo() { $class = get_class($this); - return array( - '#pre_render' => array( - array($class, 'preRenderPlaceholder'), - ), + return [ + '#pre_render' => [ + [$class, 'preRenderPlaceholder'], + ], '#id' => NULL, - ); + ]; } /** diff --git a/core/modules/contextual/src/Plugin/views/field/ContextualLinks.php b/core/modules/contextual/src/Plugin/views/field/ContextualLinks.php index 585b7f6691..6bd5c01a43 100644 --- a/core/modules/contextual/src/Plugin/views/field/ContextualLinks.php +++ b/core/modules/contextual/src/Plugin/views/field/ContextualLinks.php @@ -35,8 +35,8 @@ public function usesGroupBy() { protected function defineOptions() { $options = parent::defineOptions(); - $options['fields'] = array('default' => array()); - $options['destination'] = array('default' => 1); + $options['fields'] = ['default' => []]; + $options['destination'] = ['default' => 1]; return $options; } @@ -48,23 +48,23 @@ public function buildOptionsForm(&$form, FormStateInterface $form_state) { $all_fields = $this->view->display_handler->getFieldLabels(); // Offer to include only those fields that follow this one. $field_options = array_slice($all_fields, 0, array_search($this->options['id'], array_keys($all_fields))); - $form['fields'] = array( + $form['fields'] = [ '#type' => 'checkboxes', '#title' => $this->t('Fields'), '#description' => $this->t('Fields to be included as contextual links.'), '#options' => $field_options, '#default_value' => $this->options['fields'], - ); - $form['destination'] = array( + ]; + $form['destination'] = [ '#type' => 'select', '#title' => $this->t('Include destination'), '#description' => $this->t('Include a "destination" parameter in the link to return the user to the original view upon completing the contextual action.'), - '#options' => array( + '#options' => [ '0' => $this->t('No'), '1' => $this->t('Yes'), - ), + ], '#default_value' => $this->options['destination'], - ); + ]; } /** @@ -93,7 +93,7 @@ public function preRender(&$values) { * @see contextual_contextual_links_view_alter() */ public function render(ResultRow $values) { - $links = array(); + $links = []; foreach ($this->options['fields'] as $field) { $rendered_field = $this->view->style_plugin->getField($values->index, $field); if (empty($rendered_field)) { @@ -109,13 +109,13 @@ public function render(ResultRow $values) { } if (!empty($title) && !empty($path)) { // Make sure that tokens are replaced for this paths as well. - $tokens = $this->getRenderTokens(array()); + $tokens = $this->getRenderTokens([]); $path = strip_tags(Html::decodeEntities(strtr($path, $tokens))); - $links[$field] = array( + $links[$field] = [ 'href' => $path, 'title' => $title, - ); + ]; if (!empty($this->options['destination'])) { $links[$field]['query'] = $this->getDestinationArray(); } @@ -124,20 +124,20 @@ public function render(ResultRow $values) { // Renders a contextual links placeholder. if (!empty($links)) { - $contextual_links = array( - 'contextual' => array( + $contextual_links = [ + 'contextual' => [ '', - array(), - array( + [], + [ 'contextual-views-field-links' => UrlHelper::encodePath(Json::encode($links)), - ) - ) - ); + ] + ] + ]; - $element = array( + $element = [ '#type' => 'contextual_links_placeholder', '#id' => _contextual_links_to_id($contextual_links), - ); + ]; return drupal_render($element); } else { diff --git a/core/modules/contextual/src/Tests/ContextualDynamicContextTest.php b/core/modules/contextual/src/Tests/ContextualDynamicContextTest.php index e5d2c85469..e2c57fc168 100644 --- a/core/modules/contextual/src/Tests/ContextualDynamicContextTest.php +++ b/core/modules/contextual/src/Tests/ContextualDynamicContextTest.php @@ -42,20 +42,20 @@ class ContextualDynamicContextTest extends WebTestBase { * * @var array */ - public static $modules = array('contextual', 'node', 'views', 'views_ui', 'language', 'menu_test'); + public static $modules = ['contextual', 'node', 'views', 'views_ui', 'language', 'menu_test']; protected function setUp() { parent::setUp(); - $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); ConfigurableLanguage::createFromLangcode('it')->save(); $this->rebuildContainer(); - $this->editorUser = $this->drupalCreateUser(array('access content', 'access contextual links', 'edit any article content')); - $this->authenticatedUser = $this->drupalCreateUser(array('access content', 'access contextual links')); - $this->anonymousUser = $this->drupalCreateUser(array('access content')); + $this->editorUser = $this->drupalCreateUser(['access content', 'access contextual links', 'edit any article content']); + $this->authenticatedUser = $this->drupalCreateUser(['access content', 'access contextual links']); + $this->anonymousUser = $this->drupalCreateUser(['access content']); } /** @@ -71,9 +71,9 @@ function testDifferentPermissions() { // - An article, which should be user-editable. // - A page, which should not be user-editable. // - A second article, which should also be user-editable. - $node1 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); - $node2 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 1)); - $node3 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); + $node1 = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]); + $node2 = $this->drupalCreateNode(['type' => 'page', 'promote' => 1]); + $node3 = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]); // Now, on the front page, all article nodes should have contextual links // placeholders, as should the view that contains them. @@ -89,7 +89,7 @@ function testDifferentPermissions() { for ($i = 0; $i < count($ids); $i++) { $this->assertContextualLinkPlaceHolder($ids[$i]); } - $this->renderContextualLinks(array(), 'node'); + $this->renderContextualLinks([], 'node'); $this->assertResponse(400); $this->assertRaw('No contextual ids specified.'); $response = $this->renderContextualLinks($ids, 'node'); @@ -112,7 +112,7 @@ function testDifferentPermissions() { for ($i = 0; $i < count($ids); $i++) { $this->assertContextualLinkPlaceHolder($ids[$i]); } - $this->renderContextualLinks(array(), 'node'); + $this->renderContextualLinks([], 'node'); $this->assertResponse(400); $this->assertRaw('No contextual ids specified.'); $response = $this->renderContextualLinks($ids, 'node'); @@ -129,7 +129,7 @@ function testDifferentPermissions() { for ($i = 0; $i < count($ids); $i++) { $this->assertNoContextualLinkPlaceHolder($ids[$i]); } - $this->renderContextualLinks(array(), 'node'); + $this->renderContextualLinks([], 'node'); $this->assertResponse(403); $this->renderContextualLinks($ids, 'node'); $this->assertResponse(403); @@ -150,7 +150,7 @@ function testDifferentPermissions() { * The result of the assertion. */ protected function assertContextualLinkPlaceHolder($id) { - return $this->assertRaw(' $id)) . '>', format_string('Contextual link placeholder with id @id exists.', array('@id' => $id))); + return $this->assertRaw(' $id]) . '>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $id])); } /** @@ -163,7 +163,7 @@ protected function assertContextualLinkPlaceHolder($id) { * The result of the assertion. */ protected function assertNoContextualLinkPlaceHolder($id) { - return $this->assertNoRaw(' $id)) . '>', format_string('Contextual link placeholder with id @id does not exist.', array('@id' => $id))); + return $this->assertNoRaw(' $id]) . '>', format_string('Contextual link placeholder with id @id does not exist.', ['@id' => $id])); } /** @@ -178,11 +178,11 @@ protected function assertNoContextualLinkPlaceHolder($id) { * The response body. */ protected function renderContextualLinks($ids, $current_path) { - $post = array(); + $post = []; for ($i = 0; $i < count($ids); $i++) { $post['ids[' . $i . ']'] = $ids[$i]; } - return $this->drupalPostWithFormat('contextual/render', 'json', $post, array('query' => array('destination' => $current_path))); + return $this->drupalPostWithFormat('contextual/render', 'json', $post, ['query' => ['destination' => $current_path]]); } } diff --git a/core/modules/contextual/tests/src/Kernel/ContextualUnitTest.php b/core/modules/contextual/tests/src/Kernel/ContextualUnitTest.php index 680303db32..1d86da06f0 100644 --- a/core/modules/contextual/tests/src/Kernel/ContextualUnitTest.php +++ b/core/modules/contextual/tests/src/Kernel/ContextualUnitTest.php @@ -17,7 +17,7 @@ class ContextualUnitTest extends KernelTestBase { * * @var array */ - public static $modules = array('contextual'); + public static $modules = ['contextual']; /** * Provides testcases for testContextualLinksToId() and @@ -27,82 +27,82 @@ function _contextual_links_id_testcases() { // - one group. // - one dynamic path argument. // - no metadata. - $tests[] = array( - 'links' => array( - 'node' => array( - 'route_parameters' => array( + $tests[] = [ + 'links' => [ + 'node' => [ + 'route_parameters' => [ 'node' => '14031991', - ), - 'metadata' => array('langcode' => 'en'), - ), - ), + ], + 'metadata' => ['langcode' => 'en'], + ], + ], 'id' => 'node:node=14031991:langcode=en', - ); + ]; // Test branch conditions: // - one group. // - multiple dynamic path arguments. // - no metadata. - $tests[] = array( - 'links' => array( - 'foo' => array( - 'route_parameters' => array( + $tests[] = [ + 'links' => [ + 'foo' => [ + 'route_parameters' => [ 'bar', 'key' => 'baz', 'qux', - ), - 'metadata' => array('langcode' => 'en'), - ), - ), + ], + 'metadata' => ['langcode' => 'en'], + ], + ], 'id' => 'foo:0=bar&key=baz&1=qux:langcode=en', - ); + ]; // Test branch conditions: // - one group. // - one dynamic path argument. // - metadata. - $tests[] = array( - 'links' => array( - 'views_ui_edit' => array( - 'route_parameters' => array( + $tests[] = [ + 'links' => [ + 'views_ui_edit' => [ + 'route_parameters' => [ 'view' => 'frontpage' - ), - 'metadata' => array( + ], + 'metadata' => [ 'location' => 'page', 'display' => 'page_1', 'langcode' => 'en', - ), - ), - ), + ], + ], + ], 'id' => 'views_ui_edit:view=frontpage:location=page&display=page_1&langcode=en', - ); + ]; // Test branch conditions: // - multiple groups. // - multiple dynamic path arguments. - $tests[] = array( - 'links' => array( - 'node' => array( - 'route_parameters' => array( + $tests[] = [ + 'links' => [ + 'node' => [ + 'route_parameters' => [ 'node' => '14031991', - ), - 'metadata' => array('langcode' => 'en'), - ), - 'foo' => array( - 'route_parameters' => array( + ], + 'metadata' => ['langcode' => 'en'], + ], + 'foo' => [ + 'route_parameters' => [ 'bar', 'key' => 'baz', 'qux', - ), - 'metadata' => array('langcode' => 'en'), - ), - 'edge' => array( - 'route_parameters' => array('20011988'), - 'metadata' => array('langcode' => 'en'), - ), - ), + ], + 'metadata' => ['langcode' => 'en'], + ], + 'edge' => [ + 'route_parameters' => ['20011988'], + 'metadata' => ['langcode' => 'en'], + ], + ], 'id' => 'node:node=14031991:langcode=en|foo:0=bar&key=baz&1=qux:langcode=en|edge:0=20011988:langcode=en', - ); + ]; return $tests; } diff --git a/core/modules/datetime/datetime.module b/core/modules/datetime/datetime.module index 1078541992..bb10d13a6c 100644 --- a/core/modules/datetime/datetime.module +++ b/core/modules/datetime/datetime.module @@ -30,13 +30,13 @@ function datetime_help($route_name, RouteMatchInterface $route_match) { case 'help.page.datetime': $output = ''; $output .= '

    ' . t('About') . '

    '; - $output .= '

    ' . t('The Datetime module provides a Date field that stores dates and times. It also provides the Form API elements datetime and datelist for use in programming modules. See the Field module help and the Field UI module help pages for general information on fields and how to create and manage them. For more information, see the online documentation for the Datetime module.', array(':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#', ':datetime_do' => 'https://www.drupal.org/documentation/modules/datetime')) . '

    '; + $output .= '

    ' . t('The Datetime module provides a Date field that stores dates and times. It also provides the Form API elements datetime and datelist for use in programming modules. See the Field module help and the Field UI module help pages for general information on fields and how to create and manage them. For more information, see the online documentation for the Datetime module.', [':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#', ':datetime_do' => 'https://www.drupal.org/documentation/modules/datetime']) . '

    '; $output .= '

    ' . t('Uses') . '

    '; $output .= '
    '; $output .= '
    ' . t('Managing and displaying date fields') . '
    '; - $output .= '
    ' . t('The settings and the display of the Date field can be configured separately. See the Field UI help for more information on how to manage fields and their display.', array(':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '
    '; + $output .= '
    ' . t('The settings and the display of the Date field can be configured separately. See the Field UI help for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '
    '; $output .= '
    ' . t('Displaying dates') . '
    '; - $output .= '
    ' . t('Dates can be displayed using the Plain or the Default formatter. The Plain formatter displays the date in the ISO 8601 format. If you choose the Default formatter, you can choose a format from a predefined list that can be managed on the Date and time formats page.', array(':date_format_list' => \Drupal::url('entity.date_format.collection'))) . '
    '; + $output .= '
    ' . t('Dates can be displayed using the Plain or the Default formatter. The Plain formatter displays the date in the ISO 8601 format. If you choose the Default formatter, you can choose a format from a predefined list that can be managed on the Date and time formats page.', [':date_format_list' => \Drupal::url('entity.date_format.collection')]) . '
    '; $output .= '
    '; return $output; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeCustomFormatter.php b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeCustomFormatter.php index 678ddc8338..445b7ee706 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeCustomFormatter.php +++ b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeCustomFormatter.php @@ -23,16 +23,16 @@ class DateTimeCustomFormatter extends DateTimeFormatterBase { * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'date_format' => DATETIME_DATETIME_STORAGE_FORMAT, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($items as $delta => $item) { $output = ''; @@ -76,12 +76,12 @@ protected function formatDate($date) { public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); - $form['date_format'] = array( + $form['date_format'] = [ '#type' => 'textfield', '#title' => $this->t('Date/time format'), '#description' => $this->t('See the documentation for PHP date formats.'), '#default_value' => $this->getSetting('date_format'), - ); + ]; return $form; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeDefaultFormatter.php b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeDefaultFormatter.php index 3d30e68c1e..7ddecec551 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeDefaultFormatter.php +++ b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeDefaultFormatter.php @@ -23,16 +23,16 @@ class DateTimeDefaultFormatter extends DateTimeFormatterBase { * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'format_type' => 'medium', - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($items as $delta => $item) { $output = ''; @@ -56,7 +56,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) { } // Display the date using theme datetime. - $elements[$delta] = array( + $elements[$delta] = [ '#cache' => [ 'contexts' => [ 'timezone', @@ -65,10 +65,10 @@ public function viewElements(FieldItemListInterface $items, $langcode) { '#theme' => 'time', '#text' => $output, '#html' => FALSE, - '#attributes' => array( + '#attributes' => [ 'datetime' => $iso_date, - ), - ); + ], + ]; if (!empty($item->_attributes)) { $elements[$delta]['#attributes'] += $item->_attributes; // Unset field item attributes since they have been included in the @@ -104,13 +104,13 @@ public function settingsForm(array $form, FormStateInterface $form_state) { $options[$type] = $type_info->label() . ' (' . $format . ')'; } - $form['format_type'] = array( + $form['format_type'] = [ '#type' => 'select', '#title' => t('Date format'), '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."), '#options' => $options, '#default_value' => $this->getSetting('format_type'), - ); + ]; return $form; } @@ -122,7 +122,7 @@ public function settingsSummary() { $summary = parent::settingsSummary(); $date = new DrupalDateTime(); - $summary[] = t('Format: @display', array('@display' => $this->formatDate($date, $this->getFormatSettings()))); + $summary[] = t('Format: @display', ['@display' => $this->formatDate($date, $this->getFormatSettings())]); return $summary; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeFormatterBase.php b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeFormatterBase.php index be9df38fc2..f4e5ff5353 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeFormatterBase.php +++ b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeFormatterBase.php @@ -82,9 +82,9 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'timezone_override' => '', - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -93,13 +93,13 @@ public static function defaultSettings() { public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); - $form['timezone_override'] = array( + $form['timezone_override'] = [ '#type' => 'select', '#title' => $this->t('Time zone override'), '#description' => $this->t('The time zone selected here will always be used'), '#options' => system_time_zones(TRUE), '#default_value' => $this->getSetting('timezone_override'), - ); + ]; return $form; } @@ -111,7 +111,7 @@ public function settingsSummary() { $summary = parent::settingsSummary(); if ($override = $this->getSetting('timezone_override')) { - $summary[] = $this->t('Time zone: @timezone', array('@timezone' => $override)); + $summary[] = $this->t('Time zone: @timezone', ['@timezone' => $override]); } return $summary; diff --git a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimePlainFormatter.php b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimePlainFormatter.php index 683d75cecd..d35d3801da 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimePlainFormatter.php +++ b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimePlainFormatter.php @@ -22,7 +22,7 @@ class DateTimePlainFormatter extends DateTimeFormatterBase { * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($items as $delta => $item) { $output = ''; diff --git a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php index 859ea5da72..3fc3157616 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php +++ b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php @@ -74,11 +74,11 @@ public function __construct($plugin_id, $plugin_definition, FieldDefinitionInter * {@inheritdoc} */ public static function defaultSettings() { - $settings = array( + $settings = [ 'future_format' => '@interval hence', 'past_format' => '@interval ago', 'granularity' => 2, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); return $settings; } @@ -104,7 +104,7 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { - $elements = array(); + $elements = []; foreach ($items as $delta => $item) { $date = $item->date; @@ -128,26 +128,26 @@ public function viewElements(FieldItemListInterface $items, $langcode) { public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); - $form['future_format'] = array( + $form['future_format'] = [ '#type' => 'textfield', '#title' => $this->t('Future format'), '#default_value' => $this->getSetting('future_format'), '#description' => $this->t('Use @interval where you want the formatted interval text to appear.'), - ); + ]; - $form['past_format'] = array( + $form['past_format'] = [ '#type' => 'textfield', '#title' => $this->t('Past format'), '#default_value' => $this->getSetting('past_format'), '#description' => $this->t('Use @interval where you want the formatted interval text to appear.'), - ); + ]; - $form['granularity'] = array( + $form['granularity'] = [ '#type' => 'number', '#title' => $this->t('Granularity'), '#default_value' => $this->getSetting('granularity'), '#description' => $this->t('How many time units should be shown in the formatted output.'), - ); + ]; return $form; } @@ -160,8 +160,8 @@ public function settingsSummary() { $future_date = new DrupalDateTime('1 year 1 month 1 week 1 day 1 hour 1 minute'); $past_date = new DrupalDateTime('-1 year -1 month -1 week -1 day -1 hour -1 minute'); - $summary[] = t('Future date: %display', array('%display' => $this->formatDate($future_date))); - $summary[] = t('Past date: %display', array('%display' => $this->formatDate($past_date))); + $summary[] = t('Future date: %display', ['%display' => $this->formatDate($future_date)]); + $summary[] = t('Past date: %display', ['%display' => $this->formatDate($past_date)]); return $summary; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeFieldItemList.php b/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeFieldItemList.php index d246011ae2..45a781b4b9 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeFieldItemList.php +++ b/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeFieldItemList.php @@ -30,31 +30,31 @@ public function defaultValuesForm(array &$form, FormStateInterface $form_state) if (empty($this->getFieldDefinition()->getDefaultValueCallback())) { $default_value = $this->getFieldDefinition()->getDefaultValueLiteral(); - $element = array( - '#parents' => array('default_value_input'), - 'default_date_type' => array( + $element = [ + '#parents' => ['default_value_input'], + 'default_date_type' => [ '#type' => 'select', '#title' => t('Default date'), '#description' => t('Set a default value for this date.'), '#default_value' => isset($default_value[0]['default_date_type']) ? $default_value[0]['default_date_type'] : '', - '#options' => array( + '#options' => [ static::DEFAULT_VALUE_NOW => t('Current date'), static::DEFAULT_VALUE_CUSTOM => t('Relative date'), - ), + ], '#empty_value' => '', - ), - 'default_date' => array( + ], + 'default_date' => [ '#type' => 'textfield', '#title' => t('Relative default value'), '#description' => t("Describe a time by reference to the current day, like '+90 days' (90 days from the day the field is created) or '+1 Saturday' (the next Saturday). See strtotime for more details."), '#default_value' => (isset($default_value[0]['default_date_type']) && $default_value[0]['default_date_type'] == static::DEFAULT_VALUE_CUSTOM) ? $default_value[0]['default_date'] : '', - '#states' => array( - 'visible' => array( - ':input[id="edit-default-value-input-default-date-type"]' => array('value' => static::DEFAULT_VALUE_CUSTOM), - ) - ) - ) - ); + '#states' => [ + 'visible' => [ + ':input[id="edit-default-value-input-default-date-type"]' => ['value' => static::DEFAULT_VALUE_CUSTOM], + ] + ] + ] + ]; return $element; } @@ -65,7 +65,7 @@ public function defaultValuesForm(array &$form, FormStateInterface $form_state) */ public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) { if ($form_state->getValue(['default_value_input', 'default_date_type']) == static::DEFAULT_VALUE_CUSTOM) { - $is_strtotime = @strtotime($form_state->getValue(array('default_value_input', 'default_date'))); + $is_strtotime = @strtotime($form_state->getValue(['default_value_input', 'default_date'])); if (!$is_strtotime) { $form_state->setErrorByName('default_value_input][default_date', t('The relative date value entered is invalid.')); } @@ -76,13 +76,13 @@ public function defaultValuesFormValidate(array $element, array &$form, FormStat * {@inheritdoc} */ public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) { - if ($form_state->getValue(array('default_value_input', 'default_date_type'))) { - if ($form_state->getValue(array('default_value_input', 'default_date_type')) == static::DEFAULT_VALUE_NOW) { + if ($form_state->getValue(['default_value_input', 'default_date_type'])) { + if ($form_state->getValue(['default_value_input', 'default_date_type']) == static::DEFAULT_VALUE_NOW) { $form_state->setValueForElement($element['default_date'], static::DEFAULT_VALUE_NOW); } - return array($form_state->getValue('default_value_input')); + return [$form_state->getValue('default_value_input')]; } - return array(); + return []; } /** @@ -108,12 +108,12 @@ public static function processDefaultValue($default_value, FieldableEntityInterf // We only provide a default value for the first item, as do all fields. // Otherwise, there is no way to clear out unwanted values on multiple value // fields. - $default_value = array( - array( + $default_value = [ + [ 'value' => $value, 'date' => $date, - ) - ); + ] + ]; } return $default_value; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php b/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php index f07d56409f..f5c06e6e5d 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php +++ b/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php @@ -26,9 +26,9 @@ class DateTimeItem extends FieldItemBase { * {@inheritdoc} */ public static function defaultStorageSettings() { - return array( + return [ 'datetime_type' => 'datetime', - ) + parent::defaultStorageSettings(); + ] + parent::defaultStorageSettings(); } /** @@ -63,37 +63,37 @@ public static function propertyDefinitions(FieldStorageDefinitionInterface $fiel * {@inheritdoc} */ public static function schema(FieldStorageDefinitionInterface $field_definition) { - return array( - 'columns' => array( - 'value' => array( + return [ + 'columns' => [ + 'value' => [ 'description' => 'The date value.', 'type' => 'varchar', 'length' => 20, - ), - ), - 'indexes' => array( - 'value' => array('value'), - ), - ); + ], + ], + 'indexes' => [ + 'value' => ['value'], + ], + ]; } /** * {@inheritdoc} */ public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) { - $element = array(); + $element = []; - $element['datetime_type'] = array( + $element['datetime_type'] = [ '#type' => 'select', '#title' => t('Date type'), '#description' => t('Choose the type of date to create.'), '#default_value' => $this->getSetting('datetime_type'), - '#options' => array( + '#options' => [ static::DATETIME_TYPE_DATETIME => t('Date and time'), static::DATETIME_TYPE_DATE => t('Date only'), - ), + ], '#disabled' => $has_data, - ); + ]; return $element; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDatelistWidget.php b/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDatelistWidget.php index 8cdabf1396..f7c9394cf2 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDatelistWidget.php +++ b/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDatelistWidget.php @@ -22,11 +22,11 @@ class DateTimeDatelistWidget extends DateTimeWidgetBase { * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'increment' => '15', 'date_order' => 'YMD', 'time_type' => '24', - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -49,35 +49,35 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen // Set up the date part order array. switch ($date_order) { case 'YMD': - $date_part_order = array('year', 'month', 'day'); + $date_part_order = ['year', 'month', 'day']; break; case 'MDY': - $date_part_order = array('month', 'day', 'year'); + $date_part_order = ['month', 'day', 'year']; break; case 'DMY': - $date_part_order = array('day', 'month', 'year'); + $date_part_order = ['day', 'month', 'year']; break; } switch ($time_type) { case '24': - $date_part_order = array_merge($date_part_order, array('hour', 'minute')); + $date_part_order = array_merge($date_part_order, ['hour', 'minute']); break; case '12': - $date_part_order = array_merge($date_part_order, array('hour', 'minute', 'ampm')); + $date_part_order = array_merge($date_part_order, ['hour', 'minute', 'ampm']); break; case 'none': break; } - $element['value'] = array( + $element['value'] = [ '#type' => 'datelist', '#date_increment' => $increment, '#date_part_order' => $date_part_order, - ) + $element['value']; + ] + $element['value']; return $element; } @@ -88,20 +88,20 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen function settingsForm(array $form, FormStateInterface $form_state) { $element = parent::settingsForm($form, $form_state); - $element['date_order'] = array( + $element['date_order'] = [ '#type' => 'select', '#title' => t('Date part order'), '#default_value' => $this->getSetting('date_order'), - '#options' => array('MDY' => t('Month/Day/Year'), 'DMY' => t('Day/Month/Year'), 'YMD' => t('Year/Month/Day')), - ); + '#options' => ['MDY' => t('Month/Day/Year'), 'DMY' => t('Day/Month/Year'), 'YMD' => t('Year/Month/Day')], + ]; if ($this->getFieldSetting('datetime_type') == 'datetime') { - $element['time_type'] = array( + $element['time_type'] = [ '#type' => 'select', '#title' => t('Time type'), '#default_value' => $this->getSetting('time_type'), - '#options' => array('24' => t('24 hour time'), '12' => t('12 hour time')), - ); + '#options' => ['24' => t('24 hour time'), '12' => t('12 hour time')], + ]; $element['increment'] = [ '#type' => 'select', @@ -117,10 +117,10 @@ function settingsForm(array $form, FormStateInterface $form_state) { ]; } else { - $element['time_type'] = array( + $element['time_type'] = [ '#type' => 'hidden', '#value' => 'none', - ); + ]; $element['increment'] = [ '#type' => 'hidden', @@ -135,12 +135,12 @@ function settingsForm(array $form, FormStateInterface $form_state) { * {@inheritdoc} */ public function settingsSummary() { - $summary = array(); + $summary = []; - $summary[] = t('Date part order: @order', array('@order' => $this->getSetting('date_order'))); + $summary[] = t('Date part order: @order', ['@order' => $this->getSetting('date_order')]); if ($this->getFieldSetting('datetime_type') == 'datetime') { - $summary[] = t('Time type: @time_type', array('@time_type' => $this->getSetting('time_type'))); - $summary[] = t('Time increments: @increment', array('@increment' => $this->getSetting('increment'))); + $summary[] = t('Time type: @time_type', ['@time_type' => $this->getSetting('time_type')]); + $summary[] = t('Time increments: @increment', ['@increment' => $this->getSetting('increment')]); } return $summary; diff --git a/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDefaultWidget.php b/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDefaultWidget.php index 89381ab7cd..09342ad231 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDefaultWidget.php +++ b/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeDefaultWidget.php @@ -76,14 +76,14 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen break; } - $element['value'] += array( + $element['value'] += [ '#date_date_format' => $date_format, '#date_date_element' => $date_type, - '#date_date_callbacks' => array(), + '#date_date_callbacks' => [], '#date_time_format' => $time_format, '#date_time_element' => $time_type, - '#date_time_callbacks' => array(), - ); + '#date_time_callbacks' => [], + ]; return $element; } diff --git a/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php b/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php index aa6175a072..5add274136 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php +++ b/core/modules/datetime/src/Plugin/Field/FieldWidget/DateTimeWidgetBase.php @@ -26,13 +26,13 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen $element['#theme_wrappers'][] = 'datetime_wrapper'; $element['#attributes']['class'][] = 'container-inline'; - $element['value'] = array( + $element['value'] = [ '#type' => 'datetime', '#default_value' => NULL, '#date_increment' => 1, '#date_timezone' => drupal_get_user_timezone(), '#required' => $element['#required'], - ); + ]; if ($this->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE) { // A date-only field should have no timezone conversion performed, so diff --git a/core/modules/datetime/src/Tests/DateTimeFieldTest.php b/core/modules/datetime/src/Tests/DateTimeFieldTest.php index f7aeae819e..e280fd27bd 100644 --- a/core/modules/datetime/src/Tests/DateTimeFieldTest.php +++ b/core/modules/datetime/src/Tests/DateTimeFieldTest.php @@ -60,13 +60,13 @@ function testDateField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date->format($date_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertRaw($date->format($date_format)); $this->assertNoRaw($date->format($time_format)); @@ -84,15 +84,15 @@ function testDateField() { $this->assertEqual('2012-12-31', $entity->{$field_name}->value); // Reset display options since these get changed below. - $this->displayOptions = array( + $this->displayOptions = [ 'type' => 'datetime_default', 'label' => 'hidden', - 'settings' => array('format_type' => 'medium') + $this->defaultSettings, - ); + 'settings' => ['format_type' => 'medium'] + $this->defaultSettings, + ]; // Verify that the date is output according to the formatter settings. - $options = array( - 'format_type' => array('short', 'medium', 'long'), - ); + $options = [ + 'format_type' => ['short', 'medium', 'long'], + ]; // Formats that display a time component for date-only fields will display // the default time, so that is applied before calculating the expected // value. @@ -100,7 +100,7 @@ function testDateField() { foreach ($options as $setting => $values) { foreach ($values as $new_value) { // Update the entity display settings. - $this->displayOptions['settings'] = array($setting => $new_value) + $this->defaultSettings; + $this->displayOptions['settings'] = [$setting => $new_value] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); @@ -113,7 +113,7 @@ function testDateField() { $expected = format_date($date->getTimestamp(), $new_value, '', DATETIME_STORAGE_TIMEZONE); $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', DATETIME_STORAGE_TIMEZONE); $this->renderTestEntity($id); - $this->assertFieldByXPath('//time[@datetime="' . $expected_iso . '"]', $expected, SafeMarkup::format('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', array('%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso))); + $this->assertFieldByXPath('//time[@datetime="' . $expected_iso . '"]', $expected, SafeMarkup::format('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso])); break; } } @@ -127,17 +127,17 @@ function testDateField() { ->save(); $expected = $date->format(DATETIME_DATE_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_custom' formatter works. $this->displayOptions['type'] = 'datetime_custom'; - $this->displayOptions['settings'] = array('date_format' => 'm/d/Y') + $this->defaultSettings; + $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); $expected = $date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_time_ago' formatter works for intervals in the // past. First update the test entity so that the date difference always @@ -152,11 +152,11 @@ function testDateField() { $entity->save(); $this->displayOptions['type'] = 'datetime_time_ago'; - $this->displayOptions['settings'] = array( + $this->displayOptions['settings'] = [ 'future_format' => '@interval in the future', 'past_format' => '@interval in the past', 'granularity' => 3, - ); + ]; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); @@ -164,7 +164,7 @@ function testDateField() { '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]) ]); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_time_ago' formatter works for intervals in the // future. First update the test entity so that the date difference always @@ -185,7 +185,7 @@ function testDateField() { '@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]) ]); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected])); } } @@ -214,25 +214,25 @@ function testDatetimeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date->format($date_format), "{$field_name}[0][value][time]" => $date->format($time_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertRaw($date->format($date_format)); $this->assertRaw($date->format($time_format)); // Verify that the date is output according to the formatter settings. - $options = array( - 'format_type' => array('short', 'medium', 'long'), - ); + $options = [ + 'format_type' => ['short', 'medium', 'long'], + ]; foreach ($options as $setting => $values) { foreach ($values as $new_value) { // Update the entity display settings. - $this->displayOptions['settings'] = array($setting => $new_value) + $this->defaultSettings; + $this->displayOptions['settings'] = [$setting => $new_value] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); @@ -244,7 +244,7 @@ function testDatetimeField() { $expected = format_date($date->getTimestamp(), $new_value); $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\TH:i:s\Z', 'UTC'); $this->renderTestEntity($id); - $this->assertFieldByXPath('//time[@datetime="' . $expected_iso . '"]', $expected, SafeMarkup::format('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', array('%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso))); + $this->assertFieldByXPath('//time[@datetime="' . $expected_iso . '"]', $expected, SafeMarkup::format('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso])); break; } } @@ -258,27 +258,27 @@ function testDatetimeField() { ->save(); $expected = $date->format(DATETIME_DATETIME_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_custom' formatter works. $this->displayOptions['type'] = 'datetime_custom'; - $this->displayOptions['settings'] = array('date_format' => 'm/d/Y g:i:s A') + $this->defaultSettings; + $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A'] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); $expected = $date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'timezone_override' setting works. $this->displayOptions['type'] = 'datetime_custom'; - $this->displayOptions['settings'] = array('date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York') + $this->defaultSettings; + $this->displayOptions['settings'] = ['date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York'] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); - $expected = $date->format($this->displayOptions['settings']['date_format'], array('timezone' => 'America/New_York')); + $expected = $date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_time_ago' formatter works for intervals in the // past. First update the test entity so that the date difference always @@ -293,11 +293,11 @@ function testDatetimeField() { $entity->save(); $this->displayOptions['type'] = 'datetime_time_ago'; - $this->displayOptions['settings'] = array( + $this->displayOptions['settings'] = [ 'future_format' => '@interval from now', 'past_format' => '@interval earlier', 'granularity' => 3, - ); + ]; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); @@ -305,7 +305,7 @@ function testDatetimeField() { '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]) ]); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_time_ago' formatter works for intervals in the // future. First update the test entity so that the date difference always @@ -326,7 +326,7 @@ function testDatetimeField() { '@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']]) ]); $this->renderTestEntity($id); - $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', ['%expected' => $expected])); } /** @@ -341,12 +341,12 @@ function testDatelistWidget() { // Change the widget to a datelist widget. entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default') - ->setComponent($field_name, array( + ->setComponent($field_name, [ 'type' => 'datetime_datelist', - 'settings' => array( + 'settings' => [ 'date_order' => 'YMD', - ), - )) + ], + ]) ->save(); \Drupal::entityManager()->clearCachedFieldDefinitions(); @@ -362,7 +362,7 @@ function testDatelistWidget() { $this->drupalGet($fieldEditUrl); // Click on the widget settings button to open the widget settings form. - $this->drupalPostAjaxForm(NULL, array(), $field_name . "_settings_edit"); + $this->drupalPostAjaxForm(NULL, [], $field_name . "_settings_edit"); $xpathIncr = "//select[starts-with(@id, \"edit-fields-$field_name-settings-edit-form-settings-increment\")]"; $this->assertNoFieldByXPath($xpathIncr, NULL, 'Increment element not found for Date Only.'); @@ -372,14 +372,14 @@ function testDatelistWidget() { // Change the widget to a datelist widget. entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default') - ->setComponent($field_name, array( + ->setComponent($field_name, [ 'type' => 'datetime_datelist', - 'settings' => array( + 'settings' => [ 'increment' => 1, 'date_order' => 'YMD', 'time_type' => '12', - ), - )) + ], + ]) ->save(); \Drupal::entityManager()->clearCachedFieldDefinitions(); @@ -388,7 +388,7 @@ function testDatelistWidget() { $this->drupalGet($fieldEditUrl); // Click on the widget settings button to open the widget settings form. - $this->drupalPostAjaxForm(NULL, array(), $field_name . "_settings_edit"); + $this->drupalPostAjaxForm(NULL, [], $field_name . "_settings_edit"); $this->assertFieldByXPath($xpathIncr, NULL, 'Increment element found for Date and time.'); // Display creation form. @@ -415,9 +415,9 @@ function testDatelistWidget() { $this->assertOptionByText("edit-$field_name-0-value-ampm", t('AM/PM')); // Submit a valid date and ensure it is accepted. - $date_value = array('year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15); + $date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 5, 'minute' => 15]; - $edit = array(); + $edit = []; // Add the ampm indicator since we are testing 12 hour time. $date_value['ampm'] = 'am'; foreach ($date_value as $part => $value) { @@ -427,7 +427,7 @@ function testDatelistWidget() { $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.'); $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.'); @@ -438,14 +438,14 @@ function testDatelistWidget() { // Test the widget using increment other than 1 and 24 hour mode. entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default') - ->setComponent($field_name, array( + ->setComponent($field_name, [ 'type' => 'datetime_datelist', - 'settings' => array( + 'settings' => [ 'increment' => 15, 'date_order' => 'YMD', 'time_type' => '24', - ), - )) + ], + ]) ->save(); \Drupal::entityManager()->clearCachedFieldDefinitions(); @@ -458,9 +458,9 @@ function testDatelistWidget() { $this->assertNoFieldByXPath("//*[@id=\"edit-$field_name-0-value-ampm\"]", NULL, 'AMPM element not found.'); // Submit a valid date and ensure it is accepted. - $date_value = array('year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 17, 'minute' => 15); + $date_value = ['year' => 2012, 'month' => 12, 'day' => 31, 'hour' => 17, 'minute' => 15]; - $edit = array(); + $edit = []; foreach ($date_value as $part => $value) { $edit["{$field_name}[0][value][$part]"] = $value; } @@ -468,7 +468,7 @@ function testDatelistWidget() { $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertOptionSelected("edit-$field_name-0-value-year", '2012', 'Correct year selected.'); $this->assertOptionSelected("edit-$field_name-0-value-month", '12', 'Correct month selected.'); @@ -478,14 +478,14 @@ function testDatelistWidget() { // Test the widget for partial completion of fields. entity_get_form_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'default') - ->setComponent($field_name, array( + ->setComponent($field_name, [ 'type' => 'datetime_datelist', - 'settings' => array( + 'settings' => [ 'increment' => 1, 'date_order' => 'YMD', 'time_type' => '24', - ), - )) + ], + ]) ->save(); \Drupal::entityManager()->clearCachedFieldDefinitions(); @@ -497,7 +497,7 @@ function testDatelistWidget() { $this->drupalGet('entity_test/add'); // Submit a partial date and ensure and error message is provided. - $edit = array(); + $edit = []; foreach ($date_value as $part => $value) { $edit["{$field_name}[0][value][$part]"] = $value; } @@ -512,8 +512,8 @@ function testDatelistWidget() { // Test the widget for complete input with zeros as part of selections. $this->drupalGet('entity_test/add'); - $date_value = array('year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0'); - $edit = array(); + $date_value = ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '0', 'minute' => '0']; + $edit = []; foreach ($date_value as $part => $value) { $edit["{$field_name}[0][value][$part]"] = $value; } @@ -522,13 +522,13 @@ function testDatelistWidget() { $this->assertResponse(200); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); // Test the widget to ensure zeros are not deselected on validation. $this->drupalGet('entity_test/add'); - $date_value = array('year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => '0'); - $edit = array(); + $date_value = ['year' => 2012, 'month' => '12', 'day' => '31', 'hour' => '', 'minute' => '0']; + $edit = []; foreach ($date_value as $part => $value) { $edit["{$field_name}[0][value][$part]"] = $value; } @@ -576,16 +576,16 @@ protected function datelistDataProvider() { */ function testDefaultValue() { // Create a test content type. - $this->drupalCreateContentType(array('type' => 'date_content')); + $this->drupalCreateContentType(['type' => 'date_content']); // Create a field storage with settings to validate. $field_name = Unicode::strtolower($this->randomMachineName()); - $field_storage = FieldStorageConfig::create(array( + $field_storage = FieldStorageConfig::create([ 'field_name' => $field_name, 'entity_type' => 'node', 'type' => 'datetime', - 'settings' => array('datetime_type' => 'date'), - )); + 'settings' => ['datetime_type' => 'date'], + ]); $field_storage->save(); $field = FieldConfig::create([ @@ -601,9 +601,9 @@ function testDefaultValue() { $this->setSiteTimezone($timezone); // Set now as default_value. - $field_edit = array( + $field_edit = [ 'default_value_input[default_date_type]' => 'now', - ); + ]; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. @@ -614,10 +614,10 @@ function testDefaultValue() { // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name) ->get(); - $this->assertEqual($config_entity['default_value'][0], array( + $this->assertEqual($config_entity['default_value'][0], [ 'default_date_type' => 'now', 'default_date' => 'now', - ), 'Default value has been stored successfully'); + ], 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); @@ -629,19 +629,19 @@ function testDefaultValue() { ->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Set an invalid relative default_value to test validation. - $field_edit = array( + $field_edit = [ 'default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => 'invalid date', - ); + ]; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); $this->assertText('The relative date value entered is invalid.'); // Set a relative default_value. - $field_edit = array( + $field_edit = [ 'default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => '+90 days', - ); + ]; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. @@ -652,10 +652,10 @@ function testDefaultValue() { // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name) ->get(); - $this->assertEqual($config_entity['default_value'][0], array( + $this->assertEqual($config_entity['default_value'][0], [ 'default_date_type' => 'relative', 'default_date' => '+90 days', - ), 'Default value has been stored successfully'); + ], 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); @@ -668,9 +668,9 @@ function testDefaultValue() { ->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Remove default value. - $field_edit = array( + $field_edit = [ 'default_value_input[default_date_type]' => '', - ); + ]; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. @@ -709,72 +709,72 @@ function testInvalidField() { // Submit invalid dates and ensure they is not accepted. $date_value = ''; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => '12:00:00', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText('date is invalid', 'Empty date value has been caught.'); $date_value = 'aaaa-12-01'; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => '00:00:00', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertText('date is invalid', format_string('Invalid year value %date has been caught.', array('%date' => $date_value))); + $this->assertText('date is invalid', format_string('Invalid year value %date has been caught.', ['%date' => $date_value])); $date_value = '2012-75-01'; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => '00:00:00', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertText('date is invalid', format_string('Invalid month value %date has been caught.', array('%date' => $date_value))); + $this->assertText('date is invalid', format_string('Invalid month value %date has been caught.', ['%date' => $date_value])); $date_value = '2012-12-99'; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => '00:00:00', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertText('date is invalid', format_string('Invalid day value %date has been caught.', array('%date' => $date_value))); + $this->assertText('date is invalid', format_string('Invalid day value %date has been caught.', ['%date' => $date_value])); $date_value = '2012-12-01'; $time_value = ''; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => $time_value, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText('date is invalid', 'Empty time value has been caught.'); $date_value = '2012-12-01'; $time_value = '49:00:00'; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => $time_value, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertText('date is invalid', format_string('Invalid hour value %time has been caught.', array('%time' => $time_value))); + $this->assertText('date is invalid', format_string('Invalid hour value %time has been caught.', ['%time' => $time_value])); $date_value = '2012-12-01'; $time_value = '12:99:00'; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => $time_value, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertText('date is invalid', format_string('Invalid minute value %time has been caught.', array('%time' => $time_value))); + $this->assertText('date is invalid', format_string('Invalid minute value %time has been caught.', ['%time' => $time_value])); $date_value = '2012-12-01'; $time_value = '12:15:99'; - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $date_value, "{$field_name}[0][value][time]" => $time_value, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); - $this->assertText('date is invalid', format_string('Invalid second value %time has been caught.', array('%time' => $time_value))); + $this->assertText('date is invalid', format_string('Invalid second value %time has been caught.', ['%time' => $time_value])); } /** diff --git a/core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php b/core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php index 424cbd98c6..e28667f072 100644 --- a/core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php +++ b/core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php @@ -36,25 +36,25 @@ class DateTimeItemTest extends FieldKernelTestBase { * * @var array */ - public static $modules = array('datetime'); + public static $modules = ['datetime']; protected function setUp() { parent::setUp(); // Create a field with settings to validate. - $this->fieldStorage = FieldStorageConfig::create(array( + $this->fieldStorage = FieldStorageConfig::create([ 'field_name' => 'field_datetime', 'type' => 'datetime', 'entity_type' => 'entity_test', - 'settings' => array('datetime_type' => DateTimeItem::DATETIME_TYPE_DATETIME), - )); + 'settings' => ['datetime_type' => DateTimeItem::DATETIME_TYPE_DATETIME], + ]); $this->fieldStorage->save(); $this->field = FieldConfig::create([ 'field_storage' => $this->fieldStorage, 'bundle' => 'entity_test', - 'settings' => array( + 'settings' => [ 'default_value' => 'blank', - ), + ], ]); $this->field->save(); } diff --git a/core/modules/datetime_range/datetime_range.module b/core/modules/datetime_range/datetime_range.module index ceeb99dd8a..b2b87dae7a 100644 --- a/core/modules/datetime_range/datetime_range.module +++ b/core/modules/datetime_range/datetime_range.module @@ -15,13 +15,13 @@ function datetime_range_help($route_name, RouteMatchInterface $route_match) { case 'help.page.datetime_range': $output = ''; $output .= '

    ' . t('About') . '

    '; - $output .= '

    ' . t('The Datetime Range module provides a Date field that stores start dates and times, as well as end dates and times. See the Field module help and the Field UI module help pages for general information on fields and how to create and manage them. For more information, see the online documentation for the Datetime Range module.', array(':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#', ':datetime_do' => 'https://www.drupal.org/documentation/modules/datetime_range')) . '

    '; + $output .= '

    ' . t('The Datetime Range module provides a Date field that stores start dates and times, as well as end dates and times. See the Field module help and the Field UI module help pages for general information on fields and how to create and manage them. For more information, see the online documentation for the Datetime Range module.', [':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#', ':datetime_do' => 'https://www.drupal.org/documentation/modules/datetime_range']) . '

    '; $output .= '

    ' . t('Uses') . '

    '; $output .= '
    '; $output .= '
    ' . t('Managing and displaying date fields') . '
    '; - $output .= '
    ' . t('The settings and the display of the Date field can be configured separately. See the Field UI help for more information on how to manage fields and their display.', array(':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '
    '; + $output .= '
    ' . t('The settings and the display of the Date field can be configured separately. See the Field UI help for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '
    '; $output .= '
    ' . t('Displaying dates') . '
    '; - $output .= '
    ' . t('Dates can be displayed using the Plain or the Default formatter. The Plain formatter displays the date in the ISO 8601 format. If you choose the Default formatter, you can choose a format from a predefined list that can be managed on the Date and time formats page.', array(':date_format_list' => \Drupal::url('entity.date_format.collection'))) . '
    '; + $output .= '
    ' . t('Dates can be displayed using the Plain or the Default formatter. The Plain formatter displays the date in the ISO 8601 format. If you choose the Default formatter, you can choose a format from a predefined list that can be managed on the Date and time formats page.', [':date_format_list' => \Drupal::url('entity.date_format.collection')]) . '
    '; $output .= '
    '; return $output; } diff --git a/core/modules/datetime_range/src/Tests/DateRangeFieldTest.php b/core/modules/datetime_range/src/Tests/DateRangeFieldTest.php index 759352e8de..9038b58046 100644 --- a/core/modules/datetime_range/src/Tests/DateRangeFieldTest.php +++ b/core/modules/datetime_range/src/Tests/DateRangeFieldTest.php @@ -75,14 +75,14 @@ public function testDateRangeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][date]" => $end_date->format($date_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertRaw($start_date->format($date_format)); $this->assertNoRaw($start_date->format($time_format)); $this->assertRaw($end_date->format($date_format)); @@ -153,17 +153,17 @@ public function testDateRangeField() { ->save(); $expected = $start_date->format(DATETIME_DATE_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATE_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); // Verify that the custom formatter works. $this->displayOptions['type'] = 'daterange_custom'; - $this->displayOptions['settings'] = array('date_format' => 'm/d/Y') + $this->defaultSettings; + $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); // Test formatters when start date and end date are the same $this->drupalGet('entity_test/add'); @@ -173,15 +173,15 @@ public function testDateRangeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][date]" => $start_date->format($date_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); datetime_date_default_time($start_date); @@ -220,17 +220,17 @@ public function testDateRangeField() { ->save(); $expected = $start_date->format(DATETIME_DATE_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); $this->displayOptions['type'] = 'daterange_custom'; - $this->displayOptions['settings'] = array('date_format' => 'm/d/Y') + $this->defaultSettings; + $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); } } @@ -266,16 +266,16 @@ public function testDatetimeRangeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][value][time]" => $start_date->format($time_format), "{$field_name}[0][end_value][date]" => $end_date->format($date_format), "{$field_name}[0][end_value][time]" => $end_date->format($time_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertRaw($start_date->format($date_format)); $this->assertRaw($start_date->format($time_format)); $this->assertRaw($end_date->format($date_format)); @@ -312,7 +312,7 @@ public function testDatetimeRangeField() { ->save(); $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATETIME_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'datetime_custom' formatter works. $this->displayOptions['type'] = 'daterange_custom'; @@ -322,7 +322,7 @@ public function testDatetimeRangeField() { ->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'timezone_override' setting works. $this->displayOptions['type'] = 'daterange_custom'; @@ -333,7 +333,7 @@ public function testDatetimeRangeField() { $expected = $start_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']); $expected .= ' - ' . $end_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); // Test formatters when start date and end date are the same $this->drupalGet('entity_test/add'); @@ -344,17 +344,17 @@ public function testDatetimeRangeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][value][time]" => $start_date->format($time_format), "{$field_name}[0][end_value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][time]" => $start_date->format($time_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->displayOptions = [ 'type' => 'daterange_default', @@ -387,7 +387,7 @@ public function testDatetimeRangeField() { ->save(); $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); $this->displayOptions['type'] = 'daterange_custom'; @@ -397,7 +397,7 @@ public function testDatetimeRangeField() { ->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); } @@ -429,14 +429,14 @@ public function testAlldayRangeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][date]" => $end_date->format($date_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->assertRaw($start_date->format($date_format)); $this->assertNoRaw($start_date->format($time_format)); $this->assertRaw($end_date->format($date_format)); @@ -473,17 +473,17 @@ public function testAlldayRangeField() { ->save(); $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATETIME_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); // Verify that the custom formatter works. $this->displayOptions['type'] = 'daterange_custom'; - $this->displayOptions['settings'] = array('date_format' => 'm/d/Y') + $this->defaultSettings; + $this->displayOptions['settings'] = ['date_format' => 'm/d/Y'] + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full') ->setComponent($field_name, $this->displayOptions) ->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); // Verify that the 'timezone_override' setting works. $this->displayOptions['type'] = 'daterange_custom'; @@ -494,7 +494,7 @@ public function testAlldayRangeField() { $expected = $start_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']); $expected .= ' - ' . $end_date->format($this->displayOptions['settings']['date_format'], ['timezone' => 'America/New_York']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); // Test formatters when start date and end date are the same $this->drupalGet('entity_test/add'); @@ -507,14 +507,14 @@ public function testAlldayRangeField() { $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); - $edit = array( + $edit = [ "{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][date]" => $start_date->format($date_format), - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->url, $match); $id = $match[1]; - $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); + $this->assertText(t('entity_test @id has been created.', ['@id' => $id])); $this->displayOptions = [ 'type' => 'daterange_default', @@ -549,7 +549,7 @@ public function testAlldayRangeField() { ->save(); $expected = $start_date->format(DATETIME_DATETIME_STORAGE_FORMAT) . ' THESEPARATOR ' . $end_date->format(DATETIME_DATETIME_STORAGE_FORMAT); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', ['%expected' => $expected])); $this->assertText(' THESEPARATOR ', 'Found proper separator'); $this->displayOptions['type'] = 'daterange_custom'; @@ -559,7 +559,7 @@ public function testAlldayRangeField() { ->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' THESEPARATOR ' . $end_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); - $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); + $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', ['%expected' => $expected])); $this->assertText(' THESEPARATOR ', 'Found proper separator'); } diff --git a/core/modules/dblog/dblog.admin.inc b/core/modules/dblog/dblog.admin.inc index 2b08878c5c..1af89a63ae 100644 --- a/core/modules/dblog/dblog.admin.inc +++ b/core/modules/dblog/dblog.admin.inc @@ -19,25 +19,25 @@ * - options: Array of options for the select list for the filter. */ function dblog_filters() { - $filters = array(); + $filters = []; foreach (_dblog_get_message_types() as $type) { $types[$type] = t($type); } if (!empty($types)) { - $filters['type'] = array( + $filters['type'] = [ 'title' => t('Type'), 'where' => "w.type = ?", 'options' => $types, - ); + ]; } - $filters['severity'] = array( + $filters['severity'] = [ 'title' => t('Severity'), 'where' => 'w.severity = ?', 'options' => RfcLogLevel::getLevels(), - ); + ]; return $filters; } diff --git a/core/modules/dblog/dblog.install b/core/modules/dblog/dblog.install index 08270d2b4d..f226ed04d9 100644 --- a/core/modules/dblog/dblog.install +++ b/core/modules/dblog/dblog.install @@ -9,84 +9,84 @@ * Implements hook_schema(). */ function dblog_schema() { - $schema['watchdog'] = array( + $schema['watchdog'] = [ 'description' => 'Table that contains logs of all system events.', - 'fields' => array( - 'wid' => array( + 'fields' => [ + 'wid' => [ 'type' => 'serial', 'not null' => TRUE, 'description' => 'Primary Key: Unique watchdog event ID.', - ), - 'uid' => array( + ], + 'uid' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'description' => 'The {users}.uid of the user who triggered the event.', - ), - 'type' => array( + ], + 'type' => [ 'type' => 'varchar_ascii', 'length' => 64, 'not null' => TRUE, 'default' => '', 'description' => 'Type of log message, for example "user" or "page not found."', - ), - 'message' => array( + ], + 'message' => [ 'type' => 'text', 'not null' => TRUE, 'size' => 'big', 'description' => 'Text of log message to be passed into the t() function.', - ), - 'variables' => array( + ], + 'variables' => [ 'type' => 'blob', 'not null' => TRUE, 'size' => 'big', 'description' => 'Serialized array of variables that match the message string and that is passed into the t() function.', - ), - 'severity' => array( + ], + 'severity' => [ 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'size' => 'tiny', 'description' => 'The severity level of the event; ranges from 0 (Emergency) to 7 (Debug)', - ), - 'link' => array( + ], + 'link' => [ 'type' => 'text', 'not null' => FALSE, 'description' => 'Link to view the result of the event.', - ), - 'location' => array( + ], + 'location' => [ 'type' => 'text', 'not null' => TRUE, 'description' => 'URL of the origin of the event.', - ), - 'referer' => array( + ], + 'referer' => [ 'type' => 'text', 'not null' => FALSE, 'description' => 'URL of referring page.', - ), - 'hostname' => array( + ], + 'hostname' => [ 'type' => 'varchar_ascii', 'length' => 128, 'not null' => TRUE, 'default' => '', 'description' => 'Hostname of the user who triggered the event.', - ), - 'timestamp' => array( + ], + 'timestamp' => [ 'type' => 'int', 'not null' => TRUE, 'default' => 0, 'description' => 'Unix timestamp of when event occurred.', - ), - ), - 'primary key' => array('wid'), - 'indexes' => array( - 'type' => array('type'), - 'uid' => array('uid'), - 'severity' => array('severity'), - ), - ); + ], + ], + 'primary key' => ['wid'], + 'indexes' => [ + 'type' => ['type'], + 'uid' => ['uid'], + 'severity' => ['severity'], + ], + ]; return $schema; } diff --git a/core/modules/dblog/dblog.module b/core/modules/dblog/dblog.module index 06fef103fe..ed92d6c8f2 100644 --- a/core/modules/dblog/dblog.module +++ b/core/modules/dblog/dblog.module @@ -21,13 +21,13 @@ function dblog_help($route_name, RouteMatchInterface $route_match) { case 'help.page.dblog': $output = ''; $output .= '

    ' . t('About') . '

    '; - $output .= '

    ' . t('The Database Logging module logs system events in the Drupal database. For more information, see the online documentation for the Database Logging module.', array(':dblog' => 'https://www.drupal.org/documentation/modules/dblog')) . '

    '; + $output .= '

    ' . t('The Database Logging module logs system events in the Drupal database. For more information, see the online documentation for the Database Logging module.', [':dblog' => 'https://www.drupal.org/documentation/modules/dblog']) . '

    '; $output .= '

    ' . t('Uses') . '

    '; $output .= '
    '; $output .= '
    ' . t('Monitoring your site') . '
    '; - $output .= '
    ' . t('The Database Logging module allows you to view an event log on the Recent log messages page. The log is a chronological list of recorded events containing usage data, performance data, errors, warnings and operational information. Administrators should check the log on a regular basis to ensure their site is working properly.', array(':dblog' => \Drupal::url('dblog.overview'))) . '
    '; + $output .= '
    ' . t('The Database Logging module allows you to view an event log on the Recent log messages page. The log is a chronological list of recorded events containing usage data, performance data, errors, warnings and operational information. Administrators should check the log on a regular basis to ensure their site is working properly.', [':dblog' => \Drupal::url('dblog.overview')]) . '
    '; $output .= '
    ' . t('Debugging site problems') . '
    '; - $output .= '
    ' . t('In case of errors or problems with the site, the Recent log messages page can be useful for debugging, since it shows the sequence of events. The log messages include usage information, warnings, and errors.', array(':dblog' => \Drupal::url('dblog.overview'))) . '
    '; + $output .= '
    ' . t('In case of errors or problems with the site, the Recent log messages page can be useful for debugging, since it shows the sequence of events. The log messages include usage information, warnings, and errors.', [':dblog' => \Drupal::url('dblog.overview')]) . '
    '; $output .= '
    '; return $output; @@ -41,12 +41,12 @@ function dblog_help($route_name, RouteMatchInterface $route_match) { */ function dblog_menu_links_discovered_alter(&$links) { if (\Drupal::moduleHandler()->moduleExists('search')) { - $links['dblog.search'] = array( + $links['dblog.search'] = [ 'title' => new TranslatableMarkup('Top search phrases'), 'route_name' => 'dblog.search', 'description' => new TranslatableMarkup('View most popular search phrases.'), 'parent' => 'system.admin_reports', - ); + ]; } return $links; @@ -66,7 +66,7 @@ function dblog_cron() { // e.g. auto_increment value > 1 or rows deleted directly from the table. if ($row_limit > 0) { $min_row = db_select('watchdog', 'w') - ->fields('w', array('wid')) + ->fields('w', ['wid']) ->orderBy('wid', 'DESC') ->range($row_limit - 1, 1) ->execute()->fetchField(); @@ -95,14 +95,14 @@ function _dblog_get_message_types() { * Implements hook_form_FORM_ID_alter() for system_logging_settings(). */ function dblog_form_system_logging_settings_alter(&$form, FormStateInterface $form_state) { - $row_limits = array(100, 1000, 10000, 100000, 1000000); - $form['dblog_row_limit'] = array( + $row_limits = [100, 1000, 10000, 100000, 1000000]; + $form['dblog_row_limit'] = [ '#type' => 'select', '#title' => t('Database log messages to keep'), '#default_value' => \Drupal::configFactory()->getEditable('dblog.settings')->get('row_limit'), - '#options' => array(0 => t('All')) + array_combine($row_limits, $row_limits), - '#description' => t('The maximum number of messages to keep in the database log. Requires a cron maintenance task.', array(':cron' => \Drupal::url('system.status'))) - ); + '#options' => [0 => t('All')] + array_combine($row_limits, $row_limits), + '#description' => t('The maximum number of messages to keep in the database log. Requires a cron maintenance task.', [':cron' => \Drupal::url('system.status')]) + ]; $form['#submit'][] = 'dblog_logging_settings_submit'; } diff --git a/core/modules/dblog/dblog.views.inc b/core/modules/dblog/dblog.views.inc index dfc1fdec3f..20ad9ceb29 100644 --- a/core/modules/dblog/dblog.views.inc +++ b/core/modules/dblog/dblog.views.inc @@ -9,208 +9,208 @@ * Implements hook_views_data(). */ function dblog_views_data() { - $data = array(); + $data = []; $data['watchdog']['table']['group'] = t('Watchdog'); $data['watchdog']['table']['wizard_id'] = 'watchdog'; - $data['watchdog']['table']['base'] = array( + $data['watchdog']['table']['base'] = [ 'field' => 'wid', 'title' => t('Log entries'), 'help' => t('Contains a list of log entries.'), - ); + ]; - $data['watchdog']['wid'] = array( + $data['watchdog']['wid'] = [ 'title' => t('WID'), 'help' => t('Unique watchdog event ID.'), - 'field' => array( + 'field' => [ 'id' => 'numeric', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'numeric', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'numeric', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['uid'] = array( + $data['watchdog']['uid'] = [ 'title' => t('UID'), 'help' => t('The user ID of the user on which the log entry was written..'), - 'field' => array( + 'field' => [ 'id' => 'numeric', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'numeric', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'numeric', - ), - 'relationship' => array( + ], + 'relationship' => [ 'title' => t('User'), 'help' => t('The user on which the log entry as written.'), 'base' => 'users', 'base field' => 'uid', 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['type'] = array( + $data['watchdog']['type'] = [ 'title' => t('Type'), 'help' => t('The type of the log entry, for example "user" or "page not found".'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'in_operator', 'options callback' => '_dblog_get_message_types', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['message'] = array( + $data['watchdog']['message'] = [ 'title' => t('Message'), 'help' => t('The actual message of the log entry.'), - 'field' => array( + 'field' => [ 'id' => 'dblog_message', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['variables'] = array( + $data['watchdog']['variables'] = [ 'title' => t('Variables'), 'help' => t('The variables of the log entry in a serialized format.'), - 'field' => array( + 'field' => [ 'id' => 'serialized', 'click sortable' => FALSE, - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['severity'] = array( + $data['watchdog']['severity'] = [ 'title' => t('Severity level'), 'help' => t('The severity level of the event; ranges from 0 (Emergency) to 7 (Debug).'), - 'field' => array( + 'field' => [ 'id' => 'machine_name', 'options callback' => 'Drupal\dblog\Controller\DbLogController::getLogLevelClassMap', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'in_operator', 'options callback' => 'Drupal\dblog\Controller\DbLogController::getLogLevelClassMap', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['link'] = array( + $data['watchdog']['link'] = [ 'title' => t('Operations'), 'help' => t('Operation links for the event.'), - 'field' => array( + 'field' => [ 'id' => 'dblog_operations', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['location'] = array( + $data['watchdog']['location'] = [ 'title' => t('Location'), 'help' => t('URL of the origin of the event.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['referer'] = array( + $data['watchdog']['referer'] = [ 'title' => t('Referer'), 'help' => t('URL of the previous page.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['hostname'] = array( + $data['watchdog']['hostname'] = [ 'title' => t('Hostname'), 'help' => t('Hostname of the user who triggered the event.'), - 'field' => array( + 'field' => [ 'id' => 'standard', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'string', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'string', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'standard', - ), - ); + ], + ]; - $data['watchdog']['timestamp'] = array( + $data['watchdog']['timestamp'] = [ 'title' => t('Timestamp'), 'help' => t('Date when the event occurred.'), - 'field' => array( + 'field' => [ 'id' => 'date', - ), - 'argument' => array( + ], + 'argument' => [ 'id' => 'date', - ), - 'filter' => array( + ], + 'filter' => [ 'id' => 'date', - ), - 'sort' => array( + ], + 'sort' => [ 'id' => 'date', - ), - ); + ], + ]; return $data; } diff --git a/core/modules/dblog/src/Controller/DbLogController.php b/core/modules/dblog/src/Controller/DbLogController.php index 36ee20411e..946a73c9f2 100644 --- a/core/modules/dblog/src/Controller/DbLogController.php +++ b/core/modules/dblog/src/Controller/DbLogController.php @@ -94,7 +94,7 @@ public function __construct(Connection $database, ModuleHandlerInterface $module * An array of log level classes. */ public static function getLogLevelClassMap() { - return array( + return [ RfcLogLevel::DEBUG => 'dblog-debug', RfcLogLevel::INFO => 'dblog-info', RfcLogLevel::NOTICE => 'dblog-notice', @@ -103,7 +103,7 @@ public static function getLogLevelClassMap() { RfcLogLevel::CRITICAL => 'dblog-critical', RfcLogLevel::ALERT => 'dblog-alert', RfcLogLevel::EMERGENCY => 'dblog-emergency', - ); + ]; } /** @@ -121,7 +121,7 @@ public static function getLogLevelClassMap() { public function overview() { $filter = $this->buildFilterQuery(); - $rows = array(); + $rows = []; $classes = static::getLogLevelClassMap(); @@ -129,32 +129,32 @@ public function overview() { $build['dblog_filter_form'] = $this->formBuilder->getForm('Drupal\dblog\Form\DblogFilterForm'); - $header = array( + $header = [ // Icon column. '', - array( + [ 'data' => $this->t('Type'), 'field' => 'w.type', - 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), - array( + 'class' => [RESPONSIVE_PRIORITY_MEDIUM]], + [ 'data' => $this->t('Date'), 'field' => 'w.wid', 'sort' => 'desc', - 'class' => array(RESPONSIVE_PRIORITY_LOW)), + 'class' => [RESPONSIVE_PRIORITY_LOW]], $this->t('Message'), - array( + [ 'data' => $this->t('User'), 'field' => 'ufd.name', - 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), - array( + 'class' => [RESPONSIVE_PRIORITY_MEDIUM]], + [ 'data' => $this->t('Operations'), - 'class' => array(RESPONSIVE_PRIORITY_LOW)), - ); + 'class' => [RESPONSIVE_PRIORITY_LOW]], + ]; $query = $this->database->select('watchdog', 'w') ->extend('\Drupal\Core\Database\Query\PagerSelectExtender') ->extend('\Drupal\Core\Database\Query\TableSortExtender'); - $query->fields('w', array( + $query->fields('w', [ 'wid', 'uid', 'severity', @@ -163,7 +163,7 @@ public function overview() { 'message', 'variables', 'link', - )); + ]); $query->leftJoin('users_field_data', 'ufd', 'w.uid = ufd.uid'); if (!empty($filter['where'])) { @@ -181,45 +181,45 @@ public function overview() { $log_text = Unicode::truncate($title, 56, TRUE, TRUE); // The link generator will escape any unsafe HTML entities in the final // text. - $message = $this->l($log_text, new Url('dblog.event', array('event_id' => $dblog->wid), array( - 'attributes' => array( + $message = $this->l($log_text, new Url('dblog.event', ['event_id' => $dblog->wid], [ + 'attributes' => [ // Provide a title for the link for useful hover hints. The // Attribute object will escape any unsafe HTML entities in the // final text. 'title' => $title, - ), - ))); + ], + ])); } - $username = array( + $username = [ '#theme' => 'username', '#account' => $this->userStorage->load($dblog->uid), - ); - $rows[] = array( - 'data' => array( + ]; + $rows[] = [ + 'data' => [ // Cells. - array('class' => array('icon')), + ['class' => ['icon']], $this->t($dblog->type), $this->dateFormatter->format($dblog->timestamp, 'short'), $message, - array('data' => $username), - array('data' => array('#markup' => $dblog->link)), - ), + ['data' => $username], + ['data' => ['#markup' => $dblog->link]], + ], // Attributes for table row. - 'class' => array(Html::getClass('dblog-' . $dblog->type), $classes[$dblog->severity]), - ); + 'class' => [Html::getClass('dblog-' . $dblog->type), $classes[$dblog->severity]], + ]; } - $build['dblog_table'] = array( + $build['dblog_table'] = [ '#type' => 'table', '#header' => $header, '#rows' => $rows, - '#attributes' => array('id' => 'admin-dblog', 'class' => array('admin-dblog')), + '#attributes' => ['id' => 'admin-dblog', 'class' => ['admin-dblog']], '#empty' => $this->t('No log messages available.'), - '#attached' => array( - 'library' => array('dblog/drupal.dblog'), - ), - ); - $build['dblog_pager'] = array('#type' => 'pager'); + '#attached' => [ + 'library' => ['dblog/drupal.dblog'], + ], + ]; + $build['dblog_pager'] = ['#type' => 'pager']; return $build; @@ -236,60 +236,60 @@ public function overview() { * format expected by drupal_render(); */ public function eventDetails($event_id) { - $build = array(); - if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) { + $build = []; + if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [':id' => $event_id])->fetchObject()) { $severity = RfcLogLevel::getLevels(); $message = $this->formatMessage($dblog); - $username = array( + $username = [ '#theme' => 'username', '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser(), - ); - $rows = array( - array( - array('data' => $this->t('Type'), 'header' => TRUE), + ]; + $rows = [ + [ + ['data' => $this->t('Type'), 'header' => TRUE], $this->t($dblog->type), - ), - array( - array('data' => $this->t('Date'), 'header' => TRUE), + ], + [ + ['data' => $this->t('Date'), 'header' => TRUE], $this->dateFormatter->format($dblog->timestamp, 'long'), - ), - array( - array('data' => $this->t('User'), 'header' => TRUE), - array('data' => $username), - ), - array( - array('data' => $this->t('Location'), 'header' => TRUE), + ], + [ + ['data' => $this->t('User'), 'header' => TRUE], + ['data' => $username], + ], + [ + ['data' => $this->t('Location'), 'header' => TRUE], $this->l($dblog->location, $dblog->location ? Url::fromUri($dblog->location) : Url::fromRoute('')), - ), - array( - array('data' => $this->t('Referrer'), 'header' => TRUE), + ], + [ + ['data' => $this->t('Referrer'), 'header' => TRUE], $this->l($dblog->referer, $dblog->referer ? Url::fromUri($dblog->referer) : Url::fromRoute('')), - ), - array( - array('data' => $this->t('Message'), 'header' => TRUE), + ], + [ + ['data' => $this->t('Message'), 'header' => TRUE], $message, - ), - array( - array('data' => $this->t('Severity'), 'header' => TRUE), + ], + [ + ['data' => $this->t('Severity'), 'header' => TRUE], $severity[$dblog->severity], - ), - array( - array('data' => $this->t('Hostname'), 'header' => TRUE), + ], + [ + ['data' => $this->t('Hostname'), 'header' => TRUE], $dblog->hostname, - ), - array( - array('data' => $this->t('Operations'), 'header' => TRUE), - array('data' => array('#markup' => $dblog->link)), - ), - ); - $build['dblog_table'] = array( + ], + [ + ['data' => $this->t('Operations'), 'header' => TRUE], + ['data' => ['#markup' => $dblog->link]], + ], + ]; + $build['dblog_table'] = [ '#type' => 'table', '#rows' => $rows, - '#attributes' => array('class' => array('dblog-event')), - '#attached' => array( - 'library' => array('dblog/drupal.dblog'), - ), - ); + '#attributes' => ['class' => ['dblog-event']], + '#attached' => [ + 'library' => ['dblog/drupal.dblog'], + ], + ]; } return $build; @@ -311,9 +311,9 @@ protected function buildFilterQuery() { $filters = dblog_filters(); // Build query. - $where = $args = array(); + $where = $args = []; foreach ($_SESSION['dblog_overview_filter'] as $key => $filter) { - $filter_where = array(); + $filter_where = []; foreach ($filter as $value) { $filter_where[] = $filters[$key]['where']; $args[] = $value; @@ -324,10 +324,10 @@ protected function buildFilterQuery() { } $where = !empty($where) ? implode(' AND ', $where) : ''; - return array( + return [ 'where' => $where, 'args' => $args, - ); + ]; } /** @@ -378,10 +378,10 @@ public function formatMessage($row) { * A build array in the format expected by drupal_render(). */ public function topLogMessages($type) { - $header = array( - array('data' => $this->t('Count'), 'field' => 'count', 'sort' => 'desc'), - array('data' => $this->t('Message'), 'field' => 'message'), - ); + $header = [ + ['data' => $this->t('Count'), 'field' => 'count', 'sort' => 'desc'], + ['data' => $this->t('Message'), 'field' => 'message'], + ]; $count_query = $this->database->select('watchdog'); $count_query->addExpression('COUNT(DISTINCT(message))'); @@ -392,7 +392,7 @@ public function topLogMessages($type) { ->extend('\Drupal\Core\Database\Query\TableSortExtender'); $query->addExpression('COUNT(wid)', 'count'); $query = $query - ->fields('w', array('message', 'variables')) + ->fields('w', ['message', 'variables']) ->condition('w.type', $type) ->groupBy('message') ->groupBy('variables') @@ -401,23 +401,23 @@ public function topLogMessages($type) { $query->setCountQuery($count_query); $result = $query->execute(); - $rows = array(); + $rows = []; foreach ($result as $dblog) { if ($message = $this->formatMessage($dblog)) { - $rows[] = array($dblog->count, $message); + $rows[] = [$dblog->count, $message]; } } - $build['dblog_top_table'] = array( + $build['dblog_top_table'] = [ '#type' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => $this->t('No log messages available.'), - '#attached' => array( - 'library' => array('dblog/drupal.dblog'), - ), - ); - $build['dblog_top_pager'] = array('#type' => 'pager'); + '#attached' => [ + 'library' => ['dblog/drupal.dblog'], + ], + ]; + $build['dblog_top_pager'] = ['#type' => 'pager']; return $build; } diff --git a/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php b/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php index b1710df298..0f420f0568 100644 --- a/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php +++ b/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php @@ -64,7 +64,7 @@ public function getCancelUrl() { * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { - $_SESSION['dblog_overview_filter'] = array(); + $_SESSION['dblog_overview_filter'] = []; $this->connection->truncate('watchdog')->execute(); drupal_set_message($this->t('Database log cleared.')); $form_state->setRedirectUrl($this->getCancelUrl()); diff --git a/core/modules/dblog/src/Form/DblogFilterForm.php b/core/modules/dblog/src/Form/DblogFilterForm.php index 0434f121a0..c8de0fc68b 100644 --- a/core/modules/dblog/src/Form/DblogFilterForm.php +++ b/core/modules/dblog/src/Form/DblogFilterForm.php @@ -23,39 +23,39 @@ public function getFormId() { public function buildForm(array $form, FormStateInterface $form_state) { $filters = dblog_filters(); - $form['filters'] = array( + $form['filters'] = [ '#type' => 'details', '#title' => $this->t('Filter log messages'), '#open' => TRUE, - ); + ]; foreach ($filters as $key => $filter) { - $form['filters']['status'][$key] = array( + $form['filters']['status'][$key] = [ '#title' => $filter['title'], '#type' => 'select', '#multiple' => TRUE, '#size' => 8, '#options' => $filter['options'], - ); + ]; if (!empty($_SESSION['dblog_overview_filter'][$key])) { $form['filters']['status'][$key]['#default_value'] = $_SESSION['dblog_overview_filter'][$key]; } } - $form['filters']['actions'] = array( + $form['filters']['actions'] = [ '#type' => 'actions', - '#attributes' => array('class' => array('container-inline')), - ); - $form['filters']['actions']['submit'] = array( + '#attributes' => ['class' => ['container-inline']], + ]; + $form['filters']['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Filter'), - ); + ]; if (!empty($_SESSION['dblog_overview_filter'])) { - $form['filters']['actions']['reset'] = array( + $form['filters']['actions']['reset'] = [ '#type' => 'submit', '#value' => $this->t('Reset'), - '#limit_validation_errors' => array(), - '#submit' => array('::resetForm'), - ); + '#limit_validation_errors' => [], + '#submit' => ['::resetForm'], + ]; } return $form; } @@ -90,7 +90,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { * The current state of the form. */ public function resetForm(array &$form, FormStateInterface $form_state) { - $_SESSION['dblog_overview_filter'] = array(); + $_SESSION['dblog_overview_filter'] = []; } } diff --git a/core/modules/dblog/src/Logger/DbLog.php b/core/modules/dblog/src/Logger/DbLog.php index af77be4d1c..97b0b7b305 100644 --- a/core/modules/dblog/src/Logger/DbLog.php +++ b/core/modules/dblog/src/Logger/DbLog.php @@ -53,7 +53,7 @@ public function __construct(Connection $connection, LogMessageParserInterface $p /** * {@inheritdoc} */ - public function log($level, $message, array $context = array()) { + public function log($level, $message, array $context = []) { // Remove any backtraces since they may contain an unserializable variable. unset($context['backtrace']); @@ -64,7 +64,7 @@ public function log($level, $message, array $context = array()) { try { $this->connection ->insert('watchdog') - ->fields(array( + ->fields([ 'uid' => $context['uid'], 'type' => Unicode::substr($context['channel'], 0, 64), 'message' => $message, @@ -75,7 +75,7 @@ public function log($level, $message, array $context = array()) { 'referer' => $context['referer'], 'hostname' => Unicode::substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp'], - )) + ]) ->execute(); } catch (\Exception $e) { diff --git a/core/modules/dblog/src/Plugin/rest/resource/DBLogResource.php b/core/modules/dblog/src/Plugin/rest/resource/DBLogResource.php index 4ac76f046b..ed801fcecc 100644 --- a/core/modules/dblog/src/Plugin/rest/resource/DBLogResource.php +++ b/core/modules/dblog/src/Plugin/rest/resource/DBLogResource.php @@ -38,13 +38,13 @@ class DBLogResource extends ResourceBase { */ public function get($id = NULL) { if ($id) { - $record = db_query("SELECT * FROM {watchdog} WHERE wid = :wid", array(':wid' => $id)) + $record = db_query("SELECT * FROM {watchdog} WHERE wid = :wid", [':wid' => $id]) ->fetchAssoc(); if (!empty($record)) { return new ResourceResponse($record); } - throw new NotFoundHttpException(t('Log entry with ID @id was not found', array('@id' => $id))); + throw new NotFoundHttpException(t('Log entry with ID @id was not found', ['@id' => $id])); } throw new BadRequestHttpException(t('No log entry ID was provided')); diff --git a/core/modules/dblog/src/Plugin/views/field/DblogMessage.php b/core/modules/dblog/src/Plugin/views/field/DblogMessage.php index e0558d897c..3c68242843 100644 --- a/core/modules/dblog/src/Plugin/views/field/DblogMessage.php +++ b/core/modules/dblog/src/Plugin/views/field/DblogMessage.php @@ -34,7 +34,7 @@ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$o */ protected function defineOptions() { $options = parent::defineOptions(); - $options['replace_variables'] = array('default' => TRUE); + $options['replace_variables'] = ['default' => TRUE]; return $options; } @@ -45,11 +45,11 @@ protected function defineOptions() { public function buildOptionsForm(&$form, FormStateInterface $form_state) { parent::buildOptionsForm($form, $form_state); - $form['replace_variables'] = array( + $form['replace_variables'] = [ '#title' => $this->t('Replace variables'), '#type' => 'checkbox', '#default_value' => $this->options['replace_variables'], - ); + ]; } /** diff --git a/core/modules/dblog/src/Tests/DbLogTest.php b/core/modules/dblog/src/Tests/DbLogTest.php index daa9421b73..878f632b00 100644 --- a/core/modules/dblog/src/Tests/DbLogTest.php +++ b/core/modules/dblog/src/Tests/DbLogTest.php @@ -22,7 +22,7 @@ class DbLogTest extends WebTestBase { * * @var array */ - public static $modules = array('dblog', 'node', 'forum', 'help', 'block'); + public static $modules = ['dblog', 'node', 'forum', 'help', 'block']; /** * A user with some relevant administrative permissions. @@ -47,8 +47,8 @@ protected function setUp() { $this->drupalPlaceBlock('page_title_block'); // Create users with specific permissions. - $this->adminUser = $this->drupalCreateUser(array('administer site configuration', 'access administration pages', 'access site reports', 'administer users')); - $this->webUser = $this->drupalCreateUser(array()); + $this->adminUser = $this->drupalCreateUser(['administer site configuration', 'access administration pages', 'access site reports', 'administer users']); + $this->webUser = $this->drupalCreateUser([]); } /** @@ -70,8 +70,8 @@ function testDbLog() { $this->verifyBreadcrumbs(); $this->verifyLinkEscaping(); // Verify the overview table sorting. - $orders = array('Date', 'Type', 'User'); - $sorts = array('asc', 'desc'); + $orders = ['Date', 'Type', 'User']; + $sorts = ['asc', 'desc']; foreach ($orders as $order) { foreach ($sorts as $sort) { $this->verifySort($sort, $order); @@ -124,14 +124,14 @@ public function testLogEventPage() { */ private function verifyRowLimit($row_limit) { // Change the database log row limit. - $edit = array(); + $edit = []; $edit['dblog_row_limit'] = $row_limit; $this->drupalPostForm('admin/config/development/logging', $edit, t('Save configuration')); $this->assertResponse(200); // Check row limit variable. $current_limit = $this->config('dblog.settings')->get('row_limit'); - $this->assertTrue($current_limit == $row_limit, format_string('[Cache] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit))); + $this->assertTrue($current_limit == $row_limit, format_string('[Cache] Row limit variable of @count equals row limit of @limit', ['@count' => $current_limit, '@limit' => $row_limit])); } /** @@ -145,18 +145,18 @@ private function verifyCron($row_limit) { $this->generateLogEntries($row_limit + 10); // Verify that the database log row count exceeds the row limit. $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField(); - $this->assertTrue($count > $row_limit, format_string('Dblog row count of @count exceeds row limit of @limit', array('@count' => $count, '@limit' => $row_limit))); + $this->assertTrue($count > $row_limit, format_string('Dblog row count of @count exceeds row limit of @limit', ['@count' => $count, '@limit' => $row_limit])); // Get the number of enabled modules. Cron adds a log entry for each module. $list = \Drupal::moduleHandler()->getImplementations('cron'); $module_count = count($list); $cron_detailed_count = $this->runCron(); - $this->assertTrue($cron_detailed_count == $module_count + 2, format_string('Cron added @count of @expected new log entries', array('@count' => $cron_detailed_count, '@expected' => $module_count + 2))); + $this->assertTrue($cron_detailed_count == $module_count + 2, format_string('Cron added @count of @expected new log entries', ['@count' => $cron_detailed_count, '@expected' => $module_count + 2])); // Test disabling of detailed cron logging. $this->config('system.cron')->set('logging', 0)->save(); $cron_count = $this->runCron(); - $this->assertTrue($cron_count = 1, format_string('Cron added @count of @expected new log entries', array('@count' => $cron_count, '@expected' => 1))); + $this->assertTrue($cron_count = 1, format_string('Cron added @count of @expected new log entries', ['@count' => $cron_count, '@expected' => 1])); } /** @@ -203,7 +203,7 @@ private function runCron() { * entry. * - 'timestamp': Int unix timestamp. */ - private function generateLogEntries($count, $options = array()) { + private function generateLogEntries($count, $options = []) { global $base_root; // This long URL makes it just a little bit harder to pass the link part of @@ -212,10 +212,10 @@ private function generateLogEntries($count, $options = array()) { $link = urldecode('/content/xo%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A-lake-isabelle'); // Prepare the fields to be logged - $log = $options + array( + $log = $options + [ 'channel' => 'custom', 'message' => 'Dblog test log message', - 'variables' => array(), + 'variables' => [], 'severity' => RfcLogLevel::NOTICE, 'link' => $link, 'user' => $this->adminUser, @@ -224,7 +224,7 @@ private function generateLogEntries($count, $options = array()) { 'referer' => \Drupal::request()->server->get('HTTP_REFERER'), 'ip' => '127.0.0.1', 'timestamp' => REQUEST_TIME, - ); + ]; $logger = $this->container->get('logger.dblog'); $message = $log['message'] . ' Entry #'; @@ -250,7 +250,7 @@ protected function clearLogsEntries() { * (optional) The log entry severity. */ protected function filterLogsEntries($type = NULL, $severity = NULL) { - $edit = array(); + $edit = []; if (!is_null($type)) { $edit['type[]'] = $type; } @@ -321,8 +321,8 @@ private function verifyBreadcrumbs() { private function verifyEvents() { // Invoke events. $this->doUser(); - $this->drupalCreateContentType(array('type' => 'article', 'name' => t('Article'))); - $this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page'))); + $this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]); + $this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]); $this->doNode('article'); $this->doNode('page'); $this->doNode('forum'); @@ -341,7 +341,7 @@ private function verifyEvents() { * The order by which the table should be sorted. */ public function verifySort($sort = 'asc', $order = 'Date') { - $this->drupalGet('admin/reports/dblog', array('query' => array('sort' => $sort, 'order' => $order))); + $this->drupalGet('admin/reports/dblog', ['query' => ['sort' => $sort, 'order' => $order]]); $this->assertResponse(200); $this->assertText(t('Recent log messages'), 'DBLog report was displayed correctly and sorting went fine.'); } @@ -351,12 +351,12 @@ public function verifySort($sort = 'asc', $order = 'Date') { * page. */ private function verifyLinkEscaping() { - $link = \Drupal::l('View', Url::fromRoute('entity.node.canonical', array('node' => 1))); + $link = \Drupal::l('View', Url::fromRoute('entity.node.canonical', ['node' => 1])); $message = 'Log entry added to do the verifyLinkEscaping test.'; - $this->generateLogEntries(1, array( + $this->generateLogEntries(1, [ 'message' => $message, 'link' => $link, - )); + ]); $result = db_query_range('SELECT wid FROM {watchdog} ORDER BY wid DESC', 0, 1); $this->drupalGet('admin/reports/dblog/event/' . $result->fetchField()); @@ -374,7 +374,7 @@ private function doUser() { $pass = user_password(); // Add a user using the form to generate an add user event (which is not // triggered by drupalCreateUser). - $edit = array(); + $edit = []; $edit['name'] = $name; $edit['mail'] = $name . '@example.com'; $edit['pass[pass1]'] = $pass; @@ -384,7 +384,7 @@ private function doUser() { $this->assertResponse(200); // Retrieve the user object. $user = user_load_by_name($name); - $this->assertTrue($user != NULL, format_string('User @name was loaded', array('@name' => $name))); + $this->assertTrue($user != NULL, format_string('User @name was loaded', ['@name' => $name])); // pass_raw property is needed by drupalLogin. $user->pass_raw = $pass; // Log in user. @@ -392,18 +392,18 @@ private function doUser() { // Log out user. $this->drupalLogout(); // Fetch the row IDs in watchdog that relate to the user. - $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', array(':uid' => $user->id())); + $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', [':uid' => $user->id()]); foreach ($result as $row) { $ids[] = $row->wid; } $count_before = (isset($ids)) ? count($ids) : 0; - $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', array('@count' => $count_before, '@name' => $user->getUsername()))); + $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', ['@count' => $count_before, '@name' => $user->getUsername()])); // Log in the admin user. $this->drupalLogin($this->adminUser); // Delete the user created at the start of this test. // We need to POST here to invoke batch_process() in the internal browser. - $this->drupalPostForm('user/' . $user->id() . '/cancel', array('user_cancel_method' => 'user_cancel_reassign'), t('Cancel account')); + $this->drupalPostForm('user/' . $user->id() . '/cancel', ['user_cancel_method' => 'user_cancel_reassign'], t('Cancel account')); // View the database log report. $this->drupalGet('admin/reports/dblog'); @@ -413,13 +413,13 @@ private function doUser() { // Add user. // Default display includes name and email address; if too long, the email // address is replaced by three periods. - $this->assertLogMessage(t('New user: %name %email.', array('%name' => $name, '%email' => '<' . $user->getEmail() . '>')), 'DBLog event was recorded: [add user]'); + $this->assertLogMessage(t('New user: %name %email.', ['%name' => $name, '%email' => '<' . $user->getEmail() . '>']), 'DBLog event was recorded: [add user]'); // Log in user. - $this->assertLogMessage(t('Session opened for %name.', array('%name' => $name)), 'DBLog event was recorded: [login user]'); + $this->assertLogMessage(t('Session opened for %name.', ['%name' => $name]), 'DBLog event was recorded: [login user]'); // Log out user. - $this->assertLogMessage(t('Session closed for %name.', array('%name' => $name)), 'DBLog event was recorded: [logout user]'); + $this->assertLogMessage(t('Session closed for %name.', ['%name' => $name]), 'DBLog event was recorded: [logout user]'); // Delete user. - $message = t('Deleted user: %name %email.', array('%name' => $name, '%email' => '<' . $user->getEmail() . '>')); + $message = t('Deleted user: %name %email.', ['%name' => $name, '%email' => '<' . $user->getEmail() . '>']); $message_text = Unicode::truncate(Html::decodeEntities(strip_tags($message)), 56, TRUE, TRUE); // Verify that the full message displays on the details page. $link = FALSE; @@ -457,7 +457,7 @@ private function doUser() { */ private function doNode($type) { // Create user. - $perm = array('create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content'); + $perm = ['create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content']; $user = $this->drupalCreateUser($perm); // Log in user. $this->drupalLogin($user); @@ -470,13 +470,13 @@ private function doNode($type) { $this->assertResponse(200); // Retrieve the node object. $node = $this->drupalGetNodeByTitle($title); - $this->assertTrue($node != NULL, format_string('Node @title was loaded', array('@title' => $title))); + $this->assertTrue($node != NULL, format_string('Node @title was loaded', ['@title' => $title])); // Edit the node. $edit = $this->getContentUpdate($type); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->assertResponse(200); // Delete the node. - $this->drupalPostForm('node/' . $node->id() . '/delete', array(), t('Delete')); + $this->drupalPostForm('node/' . $node->id() . '/delete', [], t('Delete')); $this->assertResponse(200); // View the node (to generate page not found event). $this->drupalGet('node/' . $node->id()); @@ -493,11 +493,11 @@ private function doNode($type) { // Verify that node events were recorded. // Was node content added? - $this->assertLogMessage(t('@type: added %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content added]'); + $this->assertLogMessage(t('@type: added %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content added]'); // Was node content updated? - $this->assertLogMessage(t('@type: updated %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content updated]'); + $this->assertLogMessage(t('@type: updated %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content updated]'); // Was node content deleted? - $this->assertLogMessage(t('@type: deleted %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content deleted]'); + $this->assertLogMessage(t('@type: deleted %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content deleted]'); // View the database log access-denied report page. $this->drupalGet('admin/reports/access-denied'); @@ -524,18 +524,18 @@ private function doNode($type) { private function getContent($type) { switch ($type) { case 'forum': - $content = array( + $content = [ 'title[0][value]' => $this->randomMachineName(8), - 'taxonomy_forums' => array(1), + 'taxonomy_forums' => [1], 'body[0][value]' => $this->randomMachineName(32), - ); + ]; break; default: - $content = array( + $content = [ 'title[0][value]' => $this->randomMachineName(8), 'body[0][value]' => $this->randomMachineName(32), - ); + ]; break; } return $content; @@ -551,9 +551,9 @@ private function getContent($type) { * Random content needed by various node types. */ private function getContentUpdate($type) { - $content = array( + $content = [ 'body[0][value]' => $this->randomMachineName(32), - ); + ]; return $content; } @@ -567,10 +567,10 @@ public function testDBLogAddAndClear() { global $base_root; // Get a count of how many watchdog entries already exist. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(); - $log = array( + $log = [ 'channel' => 'system', 'message' => 'Log entry added to test the doClearTest clear down.', - 'variables' => array(), + 'variables' => [], 'severity' => RfcLogLevel::NOTICE, 'link' => NULL, 'user' => $this->adminUser, @@ -579,20 +579,20 @@ public function testDBLogAddAndClear() { 'referer' => \Drupal::request()->server->get('HTTP_REFERER'), 'ip' => '127.0.0.1', 'timestamp' => REQUEST_TIME, - ); + ]; // Add a watchdog entry. $this->container->get('logger.dblog')->log($log['severity'], $log['message'], $log); // Make sure the table count has actually been incremented. - $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('\Drupal\dblog\Logger\DbLog->log() added an entry to the dblog :count', array(':count' => $count))); + $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('\Drupal\dblog\Logger\DbLog->log() added an entry to the dblog :count', [':count' => $count])); // Log in the admin user. $this->drupalLogin($this->adminUser); // Post in order to clear the database table. $this->clearLogsEntries(); // Confirm that the logs should be cleared. - $this->drupalPostForm(NULL, array(), 'Confirm'); + $this->drupalPostForm(NULL, [], 'Confirm'); // Count the rows in watchdog that previously related to the deleted user. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(); - $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', array(':count' => $count))); + $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', [':count' => $count])); } /** @@ -605,21 +605,21 @@ public function testFilter() { db_delete('watchdog')->execute(); // Generate 9 random watchdog entries. - $type_names = array(); - $types = array(); + $type_names = []; + $types = []; for ($i = 0; $i < 3; $i++) { $type_names[] = $type_name = $this->randomMachineName(); $severity = RfcLogLevel::EMERGENCY; for ($j = 0; $j < 3; $j++) { - $types[] = $type = array( + $types[] = $type = [ 'count' => $j + 1, 'type' => $type_name, 'severity' => $severity++, - ); - $this->generateLogEntries($type['count'], array( + ]; + $this->generateLogEntries($type['count'], [ 'channel' => $type['type'], 'severity' => $type['severity'], - )); + ]); } } @@ -658,14 +658,14 @@ public function testFilter() { $this->assertEqual(array_sum($count), $type['count'], 'Count matched'); } - $this->drupalGet('admin/reports/dblog', array('query' => array('order' => 'Type'))); + $this->drupalGet('admin/reports/dblog', ['query' => ['order' => 'Type']]); $this->assertResponse(200); $this->assertText(t('Operations'), 'Operations text found'); // Clear all logs and make sure the confirmation message is found. $this->clearLogsEntries(); // Confirm that the logs should be cleared. - $this->drupalPostForm(NULL, array(), 'Confirm'); + $this->drupalPostForm(NULL, [], 'Confirm'); $this->assertText(t('Database log cleared.'), 'Confirmation message found'); } @@ -680,16 +680,16 @@ public function testFilter() { * - user: (string) The user associated with this database log event. */ protected function getLogEntries() { - $entries = array(); + $entries = []; if ($table = $this->getLogsEntriesTable()) { $table = array_shift($table); foreach ($table->tbody->tr as $row) { - $entries[] = array( + $entries[] = [ 'severity' => $this->getSeverityConstant($row['class']), 'type' => $this->asText($row->td[1]), 'message' => $this->asText($row->td[3]), 'user' => $this->asText($row->td[4]), - ); + ]; } } return $entries; @@ -795,7 +795,7 @@ public function testTemporaryUser() { $this->drupalLogin($this->adminUser); // Generate a single watchdog entry. - $this->generateLogEntries(1, array('user' => $tempuser, 'uid' => $tempuser_uid)); + $this->generateLogEntries(1, ['user' => $tempuser, 'uid' => $tempuser_uid]); $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField(); // Check if the full message displays on the details page. diff --git a/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php b/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php index 279d202a14..44dbe99dd1 100644 --- a/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php +++ b/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php @@ -18,7 +18,7 @@ class DbLogResourceTest extends RESTTestBase { * * @var array */ - public static $modules = array('hal', 'dblog'); + public static $modules = ['hal', 'dblog']; protected function setUp() { parent::setUp(); @@ -33,12 +33,12 @@ public function testWatchdog() { // Write a log message to the DB. $this->container->get('logger.channel.rest')->notice('Test message'); // Get the ID of the written message. - $id = db_query_range("SELECT wid FROM {watchdog} WHERE type = :type ORDER BY wid DESC", 0, 1, array(':type' => 'rest')) + $id = db_query_range("SELECT wid FROM {watchdog} WHERE type = :type ORDER BY wid DESC", 0, 1, [':type' => 'rest']) ->fetchField(); // Create a user account that has the required permissions to read // the watchdog resource via the REST API. - $account = $this->drupalCreateUser(array('restful get dblog')); + $account = $this->drupalCreateUser(['restful get dblog']); $this->drupalLogin($account); $response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => $id, '_format' => $this->defaultFormat]), 'GET'); diff --git a/core/modules/dblog/tests/src/Functional/ConnectionFailureTest.php b/core/modules/dblog/tests/src/Functional/ConnectionFailureTest.php index df088a3d25..44b045782d 100644 --- a/core/modules/dblog/tests/src/Functional/ConnectionFailureTest.php +++ b/core/modules/dblog/tests/src/Functional/ConnectionFailureTest.php @@ -12,7 +12,7 @@ */ class ConnectionFailureTest extends BrowserTestBase { - public static $modules = array('dblog'); + public static $modules = ['dblog']; /** * Tests logging of connection failures. diff --git a/core/modules/dblog/tests/src/Kernel/DbLogFormInjectionTest.php b/core/modules/dblog/tests/src/Kernel/DbLogFormInjectionTest.php index 569cdbf7d6..c0d97bee35 100644 --- a/core/modules/dblog/tests/src/Kernel/DbLogFormInjectionTest.php +++ b/core/modules/dblog/tests/src/Kernel/DbLogFormInjectionTest.php @@ -31,7 +31,7 @@ class DbLogFormInjectionTest extends KernelTestBase implements FormInterface { * * @var array */ - public static $modules = array('system', 'dblog', 'user'); + public static $modules = ['system', 'dblog', 'user']; /** * {@inheritdoc} @@ -82,10 +82,10 @@ protected function setUp() { $this->installSchema('system', ['key_value_expire', 'sequences']); $this->installEntitySchema('user'); $this->logger = \Drupal::logger('test_logger'); - $test_user = User::create(array( + $test_user = User::create([ 'name' => 'foobar', 'mail' => 'foobar@example.com', - )); + ]); $test_user->save(); \Drupal::service('current_user')->setAccount($test_user); } diff --git a/core/modules/dblog/tests/src/Kernel/Views/ViewsIntegrationTest.php b/core/modules/dblog/tests/src/Kernel/Views/ViewsIntegrationTest.php index 1968a12e96..7b63394d52 100644 --- a/core/modules/dblog/tests/src/Kernel/Views/ViewsIntegrationTest.php +++ b/core/modules/dblog/tests/src/Kernel/Views/ViewsIntegrationTest.php @@ -22,14 +22,14 @@ class ViewsIntegrationTest extends ViewsKernelTestBase { * * @var array */ - public static $testViews = array('test_dblog'); + public static $testViews = ['test_dblog']; /** * Modules to enable. * * @var array */ - public static $modules = array('dblog', 'dblog_test_views', 'user'); + public static $modules = ['dblog', 'dblog_test_views', 'user']; /** * {@inheritdoc} @@ -40,9 +40,9 @@ protected function setUp($import_test_views = TRUE) { // Rebuild the router, otherwise we can't generate links. $this->container->get('router.builder')->rebuild(); - $this->installSchema('dblog', array('watchdog')); + $this->installSchema('dblog', ['watchdog']); - ViewTestData::createTestViews(get_class($this), array('dblog_test_views')); + ViewTestData::createTestViews(get_class($this), ['dblog_test_views']); } /** @@ -53,35 +53,35 @@ public function testIntegration() { // Remove the watchdog entries added by the potential batch process. $this->container->get('database')->truncate('watchdog')->execute(); - $entries = array(); + $entries = []; // Setup a watchdog entry without tokens. - $entries[] = array( + $entries[] = [ 'message' => $this->randomMachineName(), - 'variables' => array('link' => \Drupal::l('Link', new Url(''))), - ); + 'variables' => ['link' => \Drupal::l('Link', new Url(''))], + ]; // Setup a watchdog entry with one token. - $entries[] = array( + $entries[] = [ 'message' => '@token1', - 'variables' => array('@token1' => $this->randomMachineName(), 'link' => \Drupal::l('Link', new Url(''))), - ); + 'variables' => ['@token1' => $this->randomMachineName(), 'link' => \Drupal::l('Link', new Url(''))], + ]; // Setup a watchdog entry with two tokens. - $entries[] = array( + $entries[] = [ 'message' => '@token1 @token2', // Setup a link with a tag which is filtered by // \Drupal\Component\Utility\Xss::filterAdmin() in order to make sure // that strings which are not marked as safe get filtered. - 'variables' => array( + 'variables' => [ '@token1' => $this->randomMachineName(), '@token2' => $this->randomMachineName(), 'link' => 'Link', - ), - ); + ], + ]; $logger_factory = $this->container->get('logger.factory'); foreach ($entries as $entry) { - $entry += array( + $entry += [ 'type' => 'test-views', 'severity' => RfcLogLevel::NOTICE, - ); + ]; $logger_factory->get($entry['type'])->log($entry['severity'], $entry['message'], $entry['variables']); } diff --git a/core/modules/dynamic_page_cache/tests/src/Functional/DynamicPageCacheIntegrationTest.php b/core/modules/dynamic_page_cache/tests/src/Functional/DynamicPageCacheIntegrationTest.php index 5b8e5d7332..ffa8f4375f 100644 --- a/core/modules/dynamic_page_cache/tests/src/Functional/DynamicPageCacheIntegrationTest.php +++ b/core/modules/dynamic_page_cache/tests/src/Functional/DynamicPageCacheIntegrationTest.php @@ -94,11 +94,11 @@ public function testDynamicPageCache() { // Controllers returning render arrays, rendered as anything except a HTML // response, are ignored by Dynamic Page Cache (but only because those // wrapper formats' responses do not implement CacheableResponseInterface). - $this->drupalGet('dynamic-page-cache-test/html', array('query' => array(MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax'))); + $this->drupalGet('dynamic-page-cache-test/html', ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]); $this->assertFalse($this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'Render array returned, rendered as AJAX response: Dynamic Page Cache is ignoring.'); - $this->drupalGet('dynamic-page-cache-test/html', array('query' => array(MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_dialog'))); + $this->drupalGet('dynamic-page-cache-test/html', ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_dialog']]); $this->assertFalse($this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'Render array returned, rendered as dialog response: Dynamic Page Cache is ignoring.'); - $this->drupalGet('dynamic-page-cache-test/html', array('query' => array(MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_modal'))); + $this->drupalGet('dynamic-page-cache-test/html', ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_modal']]); $this->assertFalse($this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'Render array returned, rendered as modal response: Dynamic Page Cache is ignoring.'); // Admin routes are ignored by Dynamic Page Cache. diff --git a/core/modules/editor/editor.admin.inc b/core/modules/editor/editor.admin.inc index 83bc2cf378..f91db4b961 100644 --- a/core/modules/editor/editor.admin.inc +++ b/core/modules/editor/editor.admin.inc @@ -27,77 +27,77 @@ function editor_image_upload_settings_form(Editor $editor) { // Defaults. $image_upload = $editor->getImageUploadSettings(); - $image_upload += array( + $image_upload += [ 'status' => FALSE, 'scheme' => file_default_scheme(), 'directory' => 'inline-images', 'max_size' => '', - 'max_dimensions' => array('width' => '', 'height' => ''), - ); + 'max_dimensions' => ['width' => '', 'height' => ''], + ]; - $form['status'] = array( + $form['status'] = [ '#type' => 'checkbox', '#title' => t('Enable image uploads'), '#default_value' => $image_upload['status'], - '#attributes' => array( + '#attributes' => [ 'data-editor-image-upload' => 'status', - ), - ); - $show_if_image_uploads_enabled = array( - 'visible' => array( - ':input[data-editor-image-upload="status"]' => array('checked' => TRUE), - ), - ); + ], + ]; + $show_if_image_uploads_enabled = [ + 'visible' => [ + ':input[data-editor-image-upload="status"]' => ['checked' => TRUE], + ], + ]; // Any visible, writable wrapper can potentially be used for uploads, // including a remote file system that integrates with a CDN. $options = \Drupal::service('stream_wrapper_manager')->getDescriptions(StreamWrapperInterface::WRITE_VISIBLE); if (!empty($options)) { - $form['scheme'] = array( + $form['scheme'] = [ '#type' => 'radios', '#title' => t('File storage'), '#default_value' => $image_upload['scheme'], '#options' => $options, '#states' => $show_if_image_uploads_enabled, '#access' => count($options) > 1, - ); + ]; } // Set data- attributes with human-readable names for all possible stream // wrappers, so that drupal.ckeditor.drupalimage.admin's summary rendering // can use that. foreach (\Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE) as $scheme => $name) { - $form['scheme'][$scheme]['#attributes']['data-label'] = t('Storage: @name', array('@name' => $name)); + $form['scheme'][$scheme]['#attributes']['data-label'] = t('Storage: @name', ['@name' => $name]); } - $form['directory'] = array( + $form['directory'] = [ '#type' => 'textfield', '#default_value' => $image_upload['directory'], '#title' => t('Upload directory'), '#description' => t("A directory relative to Drupal's files directory where uploaded images will be stored."), '#states' => $show_if_image_uploads_enabled, - ); + ]; $default_max_size = format_size(file_upload_max_size()); - $form['max_size'] = array( + $form['max_size'] = [ '#type' => 'textfield', '#default_value' => $image_upload['max_size'], '#title' => t('Maximum file size'), - '#description' => t('If this is left empty, then the file size will be limited by the PHP maximum upload size of @size.', array('@size' => $default_max_size)), + '#description' => t('If this is left empty, then the file size will be limited by the PHP maximum upload size of @size.', ['@size' => $default_max_size]), '#maxlength' => 20, '#size' => 10, '#placeholder' => $default_max_size, '#states' => $show_if_image_uploads_enabled, - ); + ]; - $form['max_dimensions'] = array( + $form['max_dimensions'] = [ '#type' => 'item', '#title' => t('Maximum dimensions'), '#field_prefix' => '
    ', '#field_suffix' => '
    ', '#description' => t('Images larger than these dimensions will be scaled down.'), '#states' => $show_if_image_uploads_enabled, - ); - $form['max_dimensions']['width'] = array( + ]; + $form['max_dimensions']['width'] = [ '#title' => t('Width'), '#title_display' => 'invisible', '#type' => 'number', @@ -109,8 +109,8 @@ function editor_image_upload_settings_form(Editor $editor) { '#placeholder' => t('width'), '#field_suffix' => ' x ', '#states' => $show_if_image_uploads_enabled, - ); - $form['max_dimensions']['height'] = array( + ]; + $form['max_dimensions']['height'] = [ '#title' => t('Height'), '#title_display' => 'invisible', '#type' => 'number', @@ -122,7 +122,7 @@ function editor_image_upload_settings_form(Editor $editor) { '#placeholder' => t('height'), '#field_suffix' => t('pixels'), '#states' => $show_if_image_uploads_enabled, - ); + ]; return $form; } diff --git a/core/modules/editor/editor.api.php b/core/modules/editor/editor.api.php index 2fd9fa41b9..6485a1e5fc 100644 --- a/core/modules/editor/editor.api.php +++ b/core/modules/editor/editor.api.php @@ -36,7 +36,7 @@ function hook_editor_info_alter(array &$editors) { function hook_editor_js_settings_alter(array &$settings) { if (isset($settings['editor']['formats']['basic_html'])) { $settings['editor']['formats']['basic_html']['editor'] = 'MyDifferentEditor'; - $settings['editor']['formats']['basic_html']['editorSettings']['buttons'] = array('strong', 'italic', 'underline'); + $settings['editor']['formats']['basic_html']['editorSettings']['buttons'] = ['strong', 'italic', 'underline']; } } diff --git a/core/modules/editor/editor.module b/core/modules/editor/editor.module index 8df1f0460a..04e4cd5a3c 100644 --- a/core/modules/editor/editor.module +++ b/core/modules/editor/editor.module @@ -25,13 +25,13 @@ function editor_help($route_name, RouteMatchInterface $route_match) { case 'help.page.editor': $output = ''; $output .= '

    ' . t('About') . '

    '; - $output .= '

    ' . t('The Text Editor module provides a framework that other modules (such as CKEditor module) can use to provide toolbars and other functionality that allow users to format text more easily than typing HTML tags directly. For more information, see the online documentation for the Text Editor module.', array(':documentation' => 'https://www.drupal.org/documentation/modules/editor', ':ckeditor' => (\Drupal::moduleHandler()->moduleExists('ckeditor')) ? \Drupal::url('help.page', array('name' => 'ckeditor')) : '#')) . '

    '; + $output .= '

    ' . t('The Text Editor module provides a framework that other modules (such as CKEditor module) can use to provide toolbars and other functionality that allow users to format text more easily than typing HTML tags directly. For more information, see the online documentation for the Text Editor module.', [':documentation' => 'https://www.drupal.org/documentation/modules/editor', ':ckeditor' => (\Drupal::moduleHandler()->moduleExists('ckeditor')) ? \Drupal::url('help.page', ['name' => 'ckeditor']) : '#']) . '

    '; $output .= '

    ' . t('Uses') . '

    '; $output .= '
    '; $output .= '
    ' . t('Installing text editors') . '
    '; - $output .= '
    ' . t('The Text Editor module provides a framework for managing editors. To use it, you also need to enable a text editor. This can either be the core CKEditor module, which can be enabled on the Extend page, or a contributed module for any other text editor. When installing a contributed text editor module, be sure to check the installation instructions, because you will most likely need to download and install an external library as well as the Drupal module.', array(':ckeditor' => (\Drupal::moduleHandler()->moduleExists('ckeditor')) ? \Drupal::url('help.page', array('name' => 'ckeditor')) : '#', ':extend' => \Drupal::url('system.modules_list'))) . '
    '; + $output .= '
    ' . t('The Text Editor module provides a framework for managing editors. To use it, you also need to enable a text editor. This can either be the core CKEditor module, which can be enabled on the Extend page, or a contributed module for any other text editor. When installing a contributed text editor module, be sure to check the installation instructions, because you will most likely need to download and install an external library as well as the Drupal module.', [':ckeditor' => (\Drupal::moduleHandler()->moduleExists('ckeditor')) ? \Drupal::url('help.page', ['name' => 'ckeditor']) : '#', ':extend' => \Drupal::url('system.modules_list')]) . '
    '; $output .= '
    ' . t('Enabling a text editor for a text format') . '
    '; - $output .= '
    ' . t('On the Text formats and editors page you can see which text editor is associated with each text format. You can change this by clicking on the Configure link, and then choosing a text editor or none from the Text editor drop-down list. The text editor will then be displayed with any text field for which this text format is chosen.', array(':formats' => \Drupal::url('filter.admin_overview'))) . '
    '; + $output .= '
    ' . t('On the Text formats and editors page you can see which text editor is associated with each text format. You can change this by clicking on the Configure link, and then choosing a text editor or none from the Text editor drop-down list. The text editor will then be displayed with any text field for which this text format is chosen.', [':formats' => \Drupal::url('filter.admin_overview')]) . '
    '; $output .= '
    ' . t('Configuring a text editor') . '
    '; $output .= '
    ' . t('Once a text editor is associated with a text format, you can configure it by clicking on the Configure link for this format. Depending on the specific text editor, you can configure it for example by adding buttons to its toolbar. Typically these buttons provide formatting or editing tools, and they often insert HTML tags into the field source. For details, see the help page of the specific text editor.') . '
    '; $output .= '
    ' . t('Using different text editors and formats') . '
    '; @@ -86,7 +86,7 @@ function editor_form_filter_admin_overview_alter(&$form, FormStateInterface $for // @todo Cleanup column injection: https://www.drupal.org/node/1876718. // Splice in the column for "Text editor" into the header. $position = array_search('name', $form['formats']['#header']) + 1; - $start = array_splice($form['formats']['#header'], 0, $position, array('editor' => t('Text editor'))); + $start = array_splice($form['formats']['#header'], 0, $position, ['editor' => t('Text editor')]); $form['formats']['#header'] = array_merge($start, $form['formats']['#header']); // Then splice in the name of each text editor for each text format. @@ -94,7 +94,7 @@ function editor_form_filter_admin_overview_alter(&$form, FormStateInterface $for foreach (Element::children($form['formats']) as $format_id) { $editor = editor_load($format_id); $editor_name = ($editor && isset($editors[$editor->getEditor()])) ? $editors[$editor->getEditor()]['label'] : '—'; - $editor_column['editor'] = array('#markup' => $editor_name); + $editor_column['editor'] = ['#markup' => $editor_name]; $position = array_search('name', array_keys($form['formats'][$format_id])) + 1; $start = array_splice($form['formats'][$format_id], 0, $position, $editor_column); $form['formats'][$format_id] = array_merge($start, $form['formats'][$format_id]); @@ -116,37 +116,37 @@ function editor_form_filter_format_form_alter(&$form, FormStateInterface $form_s // Associate a text editor with this text format. $manager = \Drupal::service('plugin.manager.editor'); $editor_options = $manager->listOptions(); - $form['editor'] = array( + $form['editor'] = [ // Position the editor selection before the filter settings (weight of 0), // but after the filter label and name (weight of -20). '#weight' => -9, - ); - $form['editor']['editor'] = array( + ]; + $form['editor']['editor'] = [ '#type' => 'select', '#title' => t('Text editor'), '#options' => $editor_options, '#empty_option' => t('None'), '#default_value' => $editor ? $editor->getEditor() : '', - '#ajax' => array( - 'trigger_as' => array('name' => 'editor_configure'), + '#ajax' => [ + 'trigger_as' => ['name' => 'editor_configure'], 'callback' => 'editor_form_filter_admin_form_ajax', 'wrapper' => 'editor-settings-wrapper', - ), + ], '#weight' => -10, - ); - $form['editor']['configure'] = array( + ]; + $form['editor']['configure'] = [ '#type' => 'submit', '#name' => 'editor_configure', '#value' => t('Configure'), - '#limit_validation_errors' => array(array('editor')), - '#submit' => array('editor_form_filter_admin_format_editor_configure'), - '#ajax' => array( + '#limit_validation_errors' => [['editor']], + '#submit' => ['editor_form_filter_admin_format_editor_configure'], + '#ajax' => [ 'callback' => 'editor_form_filter_admin_form_ajax', 'wrapper' => 'editor-settings-wrapper', - ), + ], '#weight' => -10, - '#attributes' => array('class' => array('js-hide')), - ); + '#attributes' => ['class' => ['js-hide']], + ]; // If there aren't any options (other than "None"), disable the select list. if (empty($editor_options)) { @@ -154,27 +154,27 @@ function editor_form_filter_format_form_alter(&$form, FormStateInterface $form_s $form['editor']['editor']['#description'] = t('This option is disabled because no modules that provide a text editor are currently enabled.'); } - $form['editor']['settings'] = array( + $form['editor']['settings'] = [ '#tree' => TRUE, '#weight' => -8, '#type' => 'container', '#id' => 'editor-settings-wrapper', - '#attached' => array( - 'library' => array( + '#attached' => [ + 'library' => [ 'editor/drupal.editor.admin', - ), - ), - ); + ], + ], + ]; // Add editor-specific validation and submit handlers. if ($editor) { /** @var $plugin \Drupal\editor\Plugin\EditorPluginInterface */ $plugin = $manager->createInstance($editor->getEditor()); - $settings_form = array(); - $settings_form['#element_validate'][] = array($plugin, 'validateConfigurationForm'); + $settings_form = []; + $settings_form['#element_validate'][] = [$plugin, 'validateConfigurationForm']; $form['editor']['settings']['subform'] = $plugin->buildConfigurationForm($settings_form, $form_state); - $form['editor']['settings']['subform']['#parents'] = array('editor', 'settings'); - $form['actions']['submit']['#submit'][] = array($plugin, 'submitConfigurationForm'); + $form['editor']['settings']['subform']['#parents'] = ['editor', 'settings']; + $form['actions']['submit']['#submit'][] = [$plugin, 'submitConfigurationForm']; } $form['#validate'][] = 'editor_form_filter_admin_format_validate'; @@ -186,7 +186,7 @@ function editor_form_filter_format_form_alter(&$form, FormStateInterface $form_s */ function editor_form_filter_admin_format_editor_configure($form, FormStateInterface $form_state) { $editor = $form_state->get('editor'); - $editor_value = $form_state->getValue(array('editor', 'editor')); + $editor_value = $form_state->getValue(['editor', 'editor']); if ($editor_value !== NULL) { if ($editor_value === '') { $form_state->set('editor', FALSE); @@ -236,7 +236,7 @@ function editor_form_filter_admin_format_submit($form, FormStateInterface $form_ $format = $form_state->getFormObject()->getEntity(); $format_id = $format->isNew() ? NULL : $format->id(); $original_editor = editor_load($format_id); - if ($original_editor && $original_editor->getEditor() != $form_state->getValue(array('editor', 'editor'))) { + if ($original_editor && $original_editor->getEditor() != $form_state->getValue(['editor', 'editor'])) { $original_editor->delete(); } @@ -550,7 +550,7 @@ function editor_file_download($uri) { * An array of file entity UUIDs. */ function _editor_get_file_uuids_by_field(EntityInterface $entity) { - $uuids = array(); + $uuids = []; $formatted_text_fields = _editor_get_formatted_text_fields($entity); foreach ($formatted_text_fields as $formatted_text_field) { @@ -579,12 +579,12 @@ function _editor_get_file_uuids_by_field(EntityInterface $entity) { function _editor_get_formatted_text_fields(FieldableEntityInterface $entity) { $field_definitions = $entity->getFieldDefinitions(); if (empty($field_definitions)) { - return array(); + return []; } // Only return formatted text fields. return array_keys(array_filter($field_definitions, function (FieldDefinitionInterface $definition) { - return in_array($definition->getType(), array('text', 'text_long', 'text_with_summary'), TRUE); + return in_array($definition->getType(), ['text', 'text_long', 'text_with_summary'], TRUE); })); } @@ -601,7 +601,7 @@ function _editor_get_formatted_text_fields(FieldableEntityInterface $entity) { function _editor_parse_file_uuids($text) { $dom = Html::load($text); $xpath = new \DOMXPath($dom); - $uuids = array(); + $uuids = []; foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) { $uuids[] = $node->getAttribute('data-entity-uuid'); } diff --git a/core/modules/editor/src/Ajax/EditorDialogSave.php b/core/modules/editor/src/Ajax/EditorDialogSave.php index b4d1c27363..48a7867ad6 100644 --- a/core/modules/editor/src/Ajax/EditorDialogSave.php +++ b/core/modules/editor/src/Ajax/EditorDialogSave.php @@ -33,10 +33,10 @@ public function __construct($values) { * {@inheritdoc} */ public function render() { - return array( + return [ 'command' => 'editorDialogSave', 'values' => $this->values, - ); + ]; } } diff --git a/core/modules/editor/src/EditorController.php b/core/modules/editor/src/EditorController.php index 2ef0b04182..995ff7c6c5 100644 --- a/core/modules/editor/src/EditorController.php +++ b/core/modules/editor/src/EditorController.php @@ -38,7 +38,7 @@ public function getUntransformedText(EntityInterface $entity, $field_name, $lang // Direct text editing is only supported for single-valued fields. $field = $entity->getTranslation($langcode)->$field_name; - $editable_text = check_markup($field->value, $field->format, $langcode, array(FilterInterface::TYPE_TRANSFORM_REVERSIBLE, FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE)); + $editable_text = check_markup($field->value, $field->format, $langcode, [FilterInterface::TYPE_TRANSFORM_REVERSIBLE, FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE]); $response->addCommand(new GetUntransformedTextCommand($editable_text)); return $response; diff --git a/core/modules/editor/src/EditorXssFilter/Standard.php b/core/modules/editor/src/EditorXssFilter/Standard.php index 9a8b2b1b1e..19d5c06c6f 100644 --- a/core/modules/editor/src/EditorXssFilter/Standard.php +++ b/core/modules/editor/src/EditorXssFilter/Standard.php @@ -35,7 +35,7 @@ public static function filterXss($html, FilterFormatInterface $format, FilterFor // directly. // ', ''); + $data[] = ['', '']; // IFRAME Event based. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#IFRAME_Event_based - $data[] = array('', ''); + $data[] = ['', '']; // FRAME. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#FRAME - $data[] = array('', ''); + $data[] = ['', '']; // TABLE. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#TABLE - $data[] = array('', '
    '); + $data[] = ['
    ', '
    ']; // TD. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#TD - $data[] = array('
    ', '
    '); + $data[] = ['
    ', '
    ']; // DIV background-image. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#DIV_background-image - $data[] = array('
    ', '
    '); + $data[] = ['
    ', '
    ']; // DIV background-image with unicoded XSS exploit. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#DIV_background-image_with_unicoded_XSS_exploit - $data[] = array('
    ', '
    '); + $data[] = ['
    ', '
    ']; // DIV background-image plus extra characters. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#DIV_background-image_plus_extra_characters - $data[] = array('
    ', '
    '); + $data[] = ['
    ', '
    ']; // DIV expression. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#DIV_expression - $data[] = array('
    ', '
    '); + $data[] = ['
    ', '
    ']; // Downlevel-Hidden block. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Downlevel-Hidden_block - $data[] = array('', "\n alert('XSS');\n "); + ', "\n alert('XSS');\n "]; // BASE tag. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#BASE_tag - $data[] = array('', ''); + $data[] = ['', '']; // OBJECT tag. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#OBJECT_tag - $data[] = array('', ''); + $data[] = ['', '']; // Using an EMBED tag you can embed a Flash movie that contains XSS. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Using_an_EMBED_tag_you_can_embed_a_Flash_movie_that_contains_XSS - $data[] = array('', ''); + $data[] = ['', '']; // You can EMBED SVG which can contain your XSS vector. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#You_can_EMBED_SVG_which_can_contain_your_XSS_vector - $data[] = array('', ''); + $data[] = ['', '']; // XML data island with CDATA obfuscation. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#XML_data_island_with_CDATA_obfuscation - $data[] = array('', 'cript:alert(\'XSS\')">'); + $data[] = ['', 'cript:alert(\'XSS\')">']; // Locally hosted XML with embedded JavaScript that is generated using an XML data island. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Locally_hosted_XML_with_embedded_JavaScript_that_is_generated_using_an_XML_data_island @@ -472,11 +472,11 @@ public function providerTestFilterXss() { // HTML+TIME in XML. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#HTML.2BTIME_in_XML - $data[] = array('">', '<?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time"><?import namespace="t" implementation="#default#time2">alert("XSS")">'); + $data[] = ['">', '<?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time"><?import namespace="t" implementation="#default#time2">alert("XSS")">']; // Assuming you can only fit in a few characters and it filters against ".js". // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Assuming_you_can_only_fit_in_a_few_characters_and_it_filters_against_.22.js.22 - $data[] = array('', ''); + $data[] = ['', '']; // IMG Embedded commands. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#IMG_Embedded_commands @@ -485,7 +485,7 @@ public function providerTestFilterXss() { // Cookie manipulation. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Cookie_manipulation - $data[] = array('', 'alert(\'XSS\')">'); + $data[] = ['', 'alert(\'XSS\')">']; // UTF-7 encoding. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#UTF-7_encoding @@ -493,13 +493,13 @@ public function providerTestFilterXss() { // XSS using HTML quote encapsulation. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#XSS_using_HTML_quote_encapsulation - $data[] = array('', '" SRC="http://ha.ckers.org/xss.js">'); - $data[] = array('', '" SRC="http://ha.ckers.org/xss.js">'); - $data[] = array('', '" \'\' SRC="http://ha.ckers.org/xss.js">'); - $data[] = array('', '\'" SRC="http://ha.ckers.org/xss.js">'); - $data[] = array('', '` SRC="http://ha.ckers.org/xss.js">'); - $data[] = array('', '\'>" SRC="http://ha.ckers.org/xss.js">'); - $data[] = array('PT SRC="http://ha.ckers.org/xss.js">', 'document.write("PT SRC="http://ha.ckers.org/xss.js">'); + $data[] = ['', '" SRC="http://ha.ckers.org/xss.js">']; + $data[] = ['', '" SRC="http://ha.ckers.org/xss.js">']; + $data[] = ['', '" \'\' SRC="http://ha.ckers.org/xss.js">']; + $data[] = ['', '\'" SRC="http://ha.ckers.org/xss.js">']; + $data[] = ['', '` SRC="http://ha.ckers.org/xss.js">']; + $data[] = ['', '\'>" SRC="http://ha.ckers.org/xss.js">']; + $data[] = ['PT SRC="http://ha.ckers.org/xss.js">', 'document.write("PT SRC="http://ha.ckers.org/xss.js">']; // URL string evasion. // @see https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#URL_string_evasion @@ -511,12 +511,12 @@ public function providerTestFilterXss() { // @see \Drupal\editor\EditorXssFilter::filterXssDataAttributes() // The following two test cases verify that XSS attack vectors are filtered. - $data[] = array('', ''); - $data[] = array('', ''); + $data[] = ['', '']; + $data[] = ['', '']; // When including HTML-tags as visible content, they are double-escaped. // This test case ensures that we leave that content unchanged. - $data[] = array('', ''); + $data[] = ['', '']; return $data; } @@ -573,27 +573,27 @@ public function testBlacklistMode($value, $expected, $message, array $disallowed * - (optional) The disallowed HTML tags to be passed to \Drupal\Component\Utility\Xss::filter(). */ public function providerTestBlackListMode() { - return array( - array( + return [ + [ 'Pink Fairy Armadillo