diff --git a/README.md b/README.md index d21f135..2799839 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ Implementations are provided for core entity types: content, taxonomy terms, and users (including blogs and forum pages). Pathauto also provides a way to delete large numbers of aliases. This feature -is available at Administer > Configuration > Search and metadata > URL aliases > -Delete aliases. +is available at Administer > Configuration > Search and metadata > URL aliases +> Delete aliases. ##Benefits @@ -59,9 +59,12 @@ for that content type. ## Installing Pathauto 1. Install the module as normal, note that there are two dependencies. -2. Configure the module at admin/config/search/path/patterns - add a new pattern by creating by clicking "Add Pathauto pattern". -3. Fill out "Path pattern" with fx [node:title], choose which content types this applies to, give it a label (the name) and save it. -4. When you save new content from now on, it should automatically be assigned an alternative URL +2. Configure the module at admin/config/search/path/patterns - add a new pattern +by creating by clicking "Add Pathauto pattern". +3. Fill out "Path pattern" with fx [node:title], choose which content types this +applies to, give it a label (the name) and save it. +4. When you save new content from now on, it should automatically be assigned an +alternative URL ##Credits: diff --git a/pathauto.api.php b/pathauto.api.php index fc9272f..49b09bc 100644 --- a/pathauto.api.php +++ b/pathauto.api.php @@ -8,6 +8,8 @@ use Drupal\Core\Language\Language; /** + * Pathauto API. + * * @todo Update for 8.x-1.x * * It may be helpful to review some examples of integration from @@ -133,7 +135,7 @@ function hook_pathauto_pattern_alter(&$pattern, array $context) { * - 'pattern': A string of the pattern used for aliasing the object. */ function hook_pathauto_alias_alter(&$alias, array &$context) { - // Add a suffix so that all aliases get saved as 'content/my-title.html' + // Add a suffix so that all aliases get saved as 'content/my-title.html'. $alias .= '.html'; // Force all aliases to be saved as language neutral. @@ -143,7 +145,7 @@ function hook_pathauto_alias_alter(&$alias, array &$context) { /** * Alter the list of punctuation characters for Pathauto control. * - * @param $punctuation + * @param array $punctuation * An array of punctuation to be controlled by Pathauto during replacement * keyed by punctuation name. Each punctuation record should be an array * with the following key/value pairs: @@ -153,7 +155,7 @@ function hook_pathauto_alias_alter(&$alias, array &$context) { */ function hook_pathauto_punctuation_chars_alter(array &$punctuation) { // Add the trademark symbol. - $punctuation['trademark'] = array('value' => '™', 'name' => t('Trademark symbol')); + $punctuation['trademark'] = ['value' => '™', 'name' => t('Trademark symbol')]; // Remove the dollar sign. unset($punctuation['dollar']); diff --git a/pathauto.install b/pathauto.install index f8de322..12b3396 100644 --- a/pathauto.install +++ b/pathauto.install @@ -8,15 +8,13 @@ */ use Drupal\Core\Entity\Entity\EntityFormDisplay; -use Drupal\Core\Plugin\Context\Context; -use Drupal\Core\Plugin\Context\ContextDefinition; use Drupal\pathauto\Entity\PathautoPattern; /** * Implements hook_install(). */ function pathauto_install() { - // Set the weight to 1 + // Set the weight to 1. module_set_weight('pathauto', 1); // Ensure the url_alias table exists. @@ -81,7 +79,7 @@ function pathauto_update_8001() { function pathauto_update_8100() { \Drupal::service('module_installer')->install(['ctools']); - $messages = array(); + $messages = []; /** @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_bundle_info */ $entity_bundle_info = \Drupal::service('entity_type.bundle.info'); $entity_type_manager = \Drupal::entityTypeManager(); @@ -98,10 +96,10 @@ function pathauto_update_8100() { foreach ($patterns as $entity_type => $entity_patterns) { if (!array_key_exists($entity_type, $entity_types)) { // We found an unknown entity type. Report it. - $messages[] = t('Entity of type @type was not processed. It defines the following patterns: @patterns', array( + $messages[] = t('Entity of type @type was not processed. It defines the following patterns: @patterns', [ '@type' => $entity_type, '@patterns' => print_r($entity_patterns, TRUE), - )); + ]); continue; } $entity_label = $entity_types[$entity_type]->getLabel(); @@ -141,9 +139,9 @@ function pathauto_update_8100() { // Add the bundle condition. $pattern->addSelectionCondition([ 'id' => 'entity_bundle:' . $entity_type, - 'bundles' => array($bundle => $bundle), + 'bundles' => [$bundle => $bundle], 'negate' => FALSE, - 'context_mapping' => [ $entity_type => $entity_type ], + 'context_mapping' => [$entity_type => $entity_type], ]); $pattern->save(); @@ -162,15 +160,16 @@ function pathauto_update_8100() { } // Validate bundle, langcode and language. if (!isset($bundle_info[$extracted_bundle]) || ($langcode == NULL) || ($language == NULL)) { - $messages[] = t('Unrecognized entity bundle @entity:@bundle was not processed. It defines the following patterns: @patterns', array( + $messages[] = t('Unrecognized entity bundle @entity:@bundle was not processed. It defines the following patterns: @patterns', [ '@entity' => $entity_type, '@bundle' => $bundle, '@patterns' => print_r($entity_patterns, TRUE), - )); + ]); continue; } - // This is a pattern for a bundle and a language, such as "node_article_es". + // This is a pattern for a bundle and a language, + // such as "node_article_es". $pattern = PathautoPattern::create([ 'id' => $entity_type . '_' . $extracted_bundle . '_' . str_replace('-', '_', $langcode), 'label' => $entity_label . ' ' . $bundle_info[$extracted_bundle]['label'] . ' ' . $language->getName(), @@ -182,20 +181,20 @@ function pathauto_update_8100() { // Add the bundle condition. $pattern->addSelectionCondition([ 'id' => 'entity_bundle:' . $entity_type, - 'bundles' => array($extracted_bundle => $extracted_bundle), + 'bundles' => [$extracted_bundle => $extracted_bundle], 'negate' => FALSE, - 'context_mapping' => [ $entity_type => $entity_type ], + 'context_mapping' => [$entity_type => $entity_type], ]); // Add the language condition. $language_mapping = $entity_type . ':' . $entity_type_manager->getDefinition($entity_type)->getKey('langcode') . ':language'; $pattern->addSelectionCondition([ 'id' => 'language', - 'langcodes' => [ $langcode => $langcode ], + 'langcodes' => [$langcode => $langcode], 'negate' => FALSE, 'context_mapping' => [ 'language' => $language_mapping, - ] + ], ]); // Add the context relationship for this language. diff --git a/pathauto.js b/pathauto.js index d4e068f..c63b8ed 100644 --- a/pathauto.js +++ b/pathauto.js @@ -1,3 +1,8 @@ +/** + * @file + * Name: pathauto.js. + */ + (function ($) { 'use strict'; Drupal.behaviors.pathFieldsetSummaries = { diff --git a/pathauto.links.action.yml b/pathauto.links.action.yml index d68b94a..0afa384 100644 --- a/pathauto.links.action.yml +++ b/pathauto.links.action.yml @@ -3,4 +3,3 @@ entity.pathauto_pattern.add_form: title: 'Add Pathauto pattern' appears_on: - entity.pathauto_pattern.collection - diff --git a/pathauto.module b/pathauto.module index d0763fa..d156d9d 100644 --- a/pathauto.module +++ b/pathauto.module @@ -13,7 +13,9 @@ /** * @file - * Main file for the Pathauto module, which automatically generates aliases for content. + * Main file for the Pathauto module. + * + * Which automatically generates aliases for content. * * @ingroup pathauto */ @@ -25,7 +27,6 @@ use Drupal\Core\Field\BaseFieldDefinition; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Url; -use Drupal\pathauto\PathautoState; /** * The default ignore word list. @@ -36,12 +37,12 @@ define('PATHAUTO_IGNORE_WORDS', 'a, an, as, at, before, but, by, for, from, is, * Implements hook_hook_info(). */ function pathauto_hook_info() { - $hooks = array( + $hooks = [ 'pathauto_pattern_alter', 'pathauto_alias_alter', 'pathauto_is_alias_reserved', - ); - return array_fill_keys($hooks, array('group' => 'pathauto')); + ]; + return array_fill_keys($hooks, ['group' => 'pathauto']); } /** @@ -59,7 +60,7 @@ function pathauto_help($route_name, RouteMatchInterface $route_match) { $output .= '
' . t('The "Patterns" page is used to configure automatic path aliasing. New patterns are created here using the Add Pathauto pattern button which presents a form to simplify pattern creation thru the use of available tokens. The patterns page provides a list of all patterns on the site and allows you to edit and reorder them. An alias is generated for the first pattern that applies.', [':pathauto_pattern' => Url::fromRoute('entity.pathauto_pattern.collection')->toString(), ':add_form' => Url::fromRoute('entity.pathauto_pattern.add_form')->toString()]) . '
'; $output .= '
' . t('Pathauto Settings') . '
'; $output .= '
' . t('The "Settings" page is used to customize global Pathauto settings for automated pattern creation.', [':settings' => Url::fromRoute('pathauto.settings.form')->toString()]) . '
'; - $output .= '
' . t('The maximum alias length and maximum component length values default to 100 and have a limit of @max from Pathauto. You should enter a value that is the length of the "alias" column of the url_alias database table minus the length of any strings that might get added to the end of the URL. The recommended and default value is 100.', array('@max' => \Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength())) . '
'; + $output .= '
' . t('The maximum alias length and maximum component length values default to 100 and have a limit of @max from Pathauto. You should enter a value that is the length of the "alias" column of the url_alias database table minus the length of any strings that might get added to the end of the URL. The recommended and default value is 100.', ['@max' => \Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength()]) . '
'; $output .= '
' . t('Bulk Generation') . '
'; $output .= '
' . t('The "Bulk Generate" page allows you to create URL aliases for items that currently have no aliases. This is typically used when installing Pathauto on a site that has existing un-aliased content that needs to be aliased in bulk.', [':pathauto_bulk' => Url::fromRoute('pathauto.bulk.update.form')->toString()]) . '
'; $output .= '
' . t('Delete Aliases') . '
'; @@ -135,10 +136,10 @@ function pathauto_entity_base_field_info(EntityTypeInterface $entity_type) { ->setLabel(t('URL alias')) ->setTranslatable(TRUE) ->setComputed(TRUE) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'path', 'weight' => 30, - )) + ]) ->setDisplayConfigurable('form', TRUE); return $fields; @@ -158,6 +159,8 @@ function pathauto_entity_base_field_info_alter(&$fields, EntityTypeInterface $en } /** + * Pattern validate. + * * Validate the pattern field, to ensure it doesn't contain any characters that * are invalid in URLs. */ @@ -175,11 +178,14 @@ function pathauto_pattern_validate($element, FormStateInterface $form_state) { } if (!empty($invalid_characters_used)) { - $form_state->setError($element, t('The %element-title is using the following invalid characters: @invalid-characters.', array('%element-title' => $title, '@invalid-characters' => implode(', ', $invalid_characters_used)))); + $form_state->setError($element, t('The %element-title is using the following invalid characters: @invalid-characters.', [ + '%element-title' => $title, + '@invalid-characters' => implode(', ', $invalid_characters_used), + ])); } if (preg_match('/(\s$)+/', $element['#value'])) { - $form_state->setError($element, t('The %element-title doesn\'t allow the patterns ending with whitespace.', array('%element-title' => $title))); + $form_state->setError($element, t('The %element-title doesn\'t allow the patterns ending with whitespace.', ['%element-title' => $title])); } } diff --git a/pathauto.tokens.inc b/pathauto.tokens.inc index 626ff09..4a4206e 100644 --- a/pathauto.tokens.inc +++ b/pathauto.tokens.inc @@ -11,12 +11,12 @@ use Drupal\Core\Render\BubbleableMetadata; * Implements hook_token_info(). */ function pathauto_token_info() { - $info = array(); + $info = []; - $info['tokens']['array']['join-path'] = array( + $info['tokens']['array']['join-path'] = [ 'name' => t('Joined path'), 'description' => t('The array values each cleaned by Pathauto and then joined with the slash into a string that resembles an URL.'), - ); + ]; return $info; } @@ -25,7 +25,7 @@ function pathauto_token_info() { * Implements hook_tokens(). */ function pathauto_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { - $replacements = array(); + $replacements = []; if ($type == 'array' && !empty($data['array'])) { $array = $data['array']; @@ -33,7 +33,7 @@ function pathauto_tokens($type, $tokens, array $data, array $options, Bubbleable foreach ($tokens as $name => $original) { switch ($name) { case 'join-path': - $values = array(); + $values = []; foreach (token_element_children($array) as $key) { $value = is_array($array[$key]) ? render($array[$key]) : (string) $array[$key]; $value = \Drupal::service('pathauto.alias_cleaner')->cleanString($value, $options); diff --git a/src/AliasCleaner.php b/src/AliasCleaner.php index 340a266..b5c3815 100644 --- a/src/AliasCleaner.php +++ b/src/AliasCleaner.php @@ -47,11 +47,10 @@ class AliasCleaner implements AliasCleanerInterface { /** * Calculated settings cache. * - * @todo Split this up into separate properties. - * * @var array + * @todo Split this up into separate properties. */ - protected $cleanStringCache = array(); + protected $cleanStringCache = []; /** * Transliteration service. @@ -155,20 +154,20 @@ class AliasCleaner implements AliasCleanerInterface { /** * {@inheritdoc} */ - public function cleanString($string, array $options = array()) { + public function cleanString($string, array $options = []) { if (empty($this->cleanStringCache)) { // Generate and cache variables used in this method. $config = $this->configFactory->get('pathauto.settings'); - $this->cleanStringCache = array( + $this->cleanStringCache = [ 'separator' => $config->get('separator'), - 'strings' => array(), + 'strings' => [], 'transliterate' => $config->get('transliterate'), - 'punctuation' => array(), + 'punctuation' => [], 'reduce_ascii' => (bool) $config->get('reduce_ascii'), 'ignore_words_regex' => FALSE, 'lowercase' => (bool) $config->get('case'), 'maxlength' => min($config->get('max_component_length'), $this->aliasStorageHelper->getAliasSchemaMaxLength()), - ); + ]; // Generate and cache the punctuation replacements for strtr(). $punctuation = $this->getPunctuationCharacters(); @@ -191,7 +190,11 @@ class AliasCleaner implements AliasCleanerInterface { // Generate and cache the ignored words regular expression. $ignore_words = $config->get('ignore_words'); - $ignore_words_regex = preg_replace(array('/^[,\s]+|[,\s]+$/', '/[,\s]+/'), array('', '\b|\b'), $ignore_words); + $ignore_words_regex = preg_replace( + ['/^[,\s]+|[,\s]+$/', '/[,\s]+/'], + ['', '\b|\b'], + $ignore_words + ); if ($ignore_words_regex) { $this->cleanStringCache['ignore_words_regex'] = '\b' . $ignore_words_regex . '\b'; if (function_exists('mb_eregi_replace')) { @@ -272,7 +275,6 @@ class AliasCleaner implements AliasCleanerInterface { return $output; } - /** * {@inheritdoc} */ @@ -285,39 +287,40 @@ class AliasCleaner implements AliasCleanerInterface { $this->punctuationCharacters = $cache->data; } else { - $punctuation = array(); - $punctuation['double_quotes'] = array('value' => '"', 'name' => t('Double quotation marks')); - $punctuation['quotes'] = array('value' => '\'', 'name' => t("Single quotation marks (apostrophe)")); - $punctuation['backtick'] = array('value' => '`', 'name' => t('Back tick')); - $punctuation['comma'] = array('value' => ',', 'name' => t('Comma')); - $punctuation['period'] = array('value' => '.', 'name' => t('Period')); - $punctuation['hyphen'] = array('value' => '-', 'name' => t('Hyphen')); - $punctuation['underscore'] = array('value' => '_', 'name' => t('Underscore')); - $punctuation['colon'] = array('value' => ':', 'name' => t('Colon')); - $punctuation['semicolon'] = array('value' => ';', 'name' => t('Semicolon')); - $punctuation['pipe'] = array('value' => '|', 'name' => t('Vertical bar (pipe)')); - $punctuation['left_curly'] = array('value' => '{', 'name' => t('Left curly bracket')); - $punctuation['left_square'] = array('value' => '[', 'name' => t('Left square bracket')); - $punctuation['right_curly'] = array('value' => '}', 'name' => t('Right curly bracket')); - $punctuation['right_square'] = array('value' => ']', 'name' => t('Right square bracket')); - $punctuation['plus'] = array('value' => '+', 'name' => t('Plus sign')); - $punctuation['equal'] = array('value' => '=', 'name' => t('Equal sign')); - $punctuation['asterisk'] = array('value' => '*', 'name' => t('Asterisk')); - $punctuation['ampersand'] = array('value' => '&', 'name' => t('Ampersand')); - $punctuation['percent'] = array('value' => '%', 'name' => t('Percent sign')); - $punctuation['caret'] = array('value' => '^', 'name' => t('Caret')); - $punctuation['dollar'] = array('value' => '$', 'name' => t('Dollar sign')); - $punctuation['hash'] = array('value' => '#', 'name' => t('Number sign (pound sign, hash)')); - $punctuation['at'] = array('value' => '@', 'name' => t('At sign')); - $punctuation['exclamation'] = array('value' => '!', 'name' => t('Exclamation mark')); - $punctuation['tilde'] = array('value' => '~', 'name' => t('Tilde')); - $punctuation['left_parenthesis'] = array('value' => '(', 'name' => t('Left parenthesis')); - $punctuation['right_parenthesis'] = array('value' => ')', 'name' => t('Right parenthesis')); - $punctuation['question_mark'] = array('value' => '?', 'name' => t('Question mark')); - $punctuation['less_than'] = array('value' => '<', 'name' => t('Less-than sign')); - $punctuation['greater_than'] = array('value' => '>', 'name' => t('Greater-than sign')); - $punctuation['slash'] = array('value' => '/', 'name' => t('Slash')); - $punctuation['back_slash'] = array('value' => '\\', 'name' => t('Backslash')); + $punctuation = []; + + $punctuation['double_quotes'] = ['value' => '"', 'name' => t('Double quotation marks')]; + $punctuation['quotes'] = ['value' => '\'', 'name' => t("Single quotation marks (apostrophe)")]; + $punctuation['backtick'] = ['value' => '`', 'name' => t('Back tick')]; + $punctuation['comma'] = ['value' => ',', 'name' => t('Comma')]; + $punctuation['period'] = ['value' => '.', 'name' => t('Period')]; + $punctuation['hyphen'] = ['value' => '-', 'name' => t('Hyphen')]; + $punctuation['underscore'] = ['value' => '_', 'name' => t('Underscore')]; + $punctuation['colon'] = ['value' => ':', 'name' => t('Colon')]; + $punctuation['semicolon'] = ['value' => ';', 'name' => t('Semicolon')]; + $punctuation['pipe'] = ['value' => '|', 'name' => t('Vertical bar (pipe)')]; + $punctuation['left_curly'] = ['value' => '{', 'name' => t('Left curly bracket')]; + $punctuation['left_square'] = ['value' => '[', 'name' => t('Left square bracket')]; + $punctuation['right_curly'] = ['value' => '}', 'name' => t('Right curly bracket')]; + $punctuation['right_square'] = ['value' => ']', 'name' => t('Right square bracket')]; + $punctuation['plus'] = ['value' => '+', 'name' => t('Plus sign')]; + $punctuation['equal'] = ['value' => '=', 'name' => t('Equal sign')]; + $punctuation['asterisk'] = ['value' => '*', 'name' => t('Asterisk')]; + $punctuation['ampersand'] = ['value' => '&', 'name' => t('Ampersand')]; + $punctuation['percent'] = ['value' => '%', 'name' => t('Percent sign')]; + $punctuation['caret'] = ['value' => '^', 'name' => t('Caret')]; + $punctuation['dollar'] = ['value' => '$', 'name' => t('Dollar sign')]; + $punctuation['hash'] = ['value' => '#', 'name' => t('Number sign (pound sign, hash)')]; + $punctuation['at'] = ['value' => '@', 'name' => t('At sign')]; + $punctuation['exclamation'] = ['value' => '!', 'name' => t('Exclamation mark')]; + $punctuation['tilde'] = ['value' => '~', 'name' => t('Tilde')]; + $punctuation['left_parenthesis'] = ['value' => '(', 'name' => t('Left parenthesis')]; + $punctuation['right_parenthesis'] = ['value' => ')', 'name' => t('Right parenthesis')]; + $punctuation['question_mark'] = ['value' => '?', 'name' => t('Question mark')]; + $punctuation['less_than'] = ['value' => '<', 'name' => t('Less-than sign')]; + $punctuation['greater_than'] = ['value' => '>', 'name' => t('Greater-than sign')]; + $punctuation['slash'] = ['value' => '/', 'name' => t('Slash')]; + $punctuation['back_slash'] = ['value' => '\\', 'name' => t('Backslash')]; // Allow modules to alter the punctuation list and cache the result. $this->moduleHandler->alter('pathauto_punctuation_chars', $punctuation); @@ -332,7 +335,7 @@ class AliasCleaner implements AliasCleanerInterface { /** * {@inheritdoc} */ - public function cleanTokenValues(&$replacements, $data = array(), $options = array()) { + public function cleanTokenValues(&$replacements, array $data = [], array $options = []) { foreach ($replacements as $token => $value) { // Only clean non-path tokens. if (!preg_match('/(path|alias|url|url-brief)\]$/', $token)) { @@ -345,7 +348,7 @@ class AliasCleaner implements AliasCleanerInterface { * {@inheritdoc} */ public function resetCaches() { - $this->cleanStringCache = array(); + $this->cleanStringCache = []; } } diff --git a/src/AliasCleanerInterface.php b/src/AliasCleanerInterface.php index 87cc27e..fca1579 100644 --- a/src/AliasCleanerInterface.php +++ b/src/AliasCleanerInterface.php @@ -3,6 +3,8 @@ namespace Drupal\pathauto; /** + * Alias Cleaner Interface. + * * @todo add class comment. */ interface AliasCleanerInterface { @@ -13,7 +15,8 @@ interface AliasCleanerInterface { * Performs the following alterations: * - Trim duplicate, leading, and trailing back-slashes. * - Trim duplicate, leading, and trailing separators. - * - Shorten to a desired length and logical position based on word boundaries. + * - Shorten to a desired length and logical position based on word + * boundaries. * * @param string $alias * A string with the URL alias to clean up. @@ -52,7 +55,8 @@ interface AliasCleanerInterface { * - Replace whitespace with the separator character. * - Trim duplicate, leading, and trailing separators. * - Convert to lower-case. - * - Shorten to a desired length and logical position based on word boundaries. + * - Shorten to a desired length and logical position based on word + * boundaries. * * This function should *not* be called on URL alias or path strings * because it is assumed that they are already clean. @@ -67,13 +71,13 @@ interface AliasCleanerInterface { * @return string * The cleaned string. */ - public function cleanString($string, array $options = array()); + public function cleanString($string, array $options = []); /** * Return an array of arrays for punctuation values. * - * Returns an array of arrays for punctuation values keyed by a name, including - * the value and a textual description. + * Returns an array of arrays for punctuation values keyed by a name, + * including the value and a textual description. * Can and should be expanded to include "all" non text punctuation values. * * @return array @@ -93,7 +97,7 @@ interface AliasCleanerInterface { * @param array $options * An array of options used to generate the replacements. */ - public function cleanTokenValues(&$replacements, $data = array(), $options = array()); + public function cleanTokenValues(array &$replacements, array $data = [], array $options = []); /** * Resets internal caches. diff --git a/src/AliasStorageHelper.php b/src/AliasStorageHelper.php index ac635c3..8b8f837 100644 --- a/src/AliasStorageHelper.php +++ b/src/AliasStorageHelper.php @@ -90,17 +90,17 @@ class AliasStorageHelper implements AliasStorageHelperInterface { // Alert users if they are trying to create an alias that is the same as the // internal path. if ($path['source'] == $path['alias']) { - $this->messenger->addMessage($this->t('Ignoring alias %alias because it is the same as the internal path.', array('%alias' => $path['alias']))); + $this->messenger->addMessage($this->t('Ignoring alias %alias because it is the same as the internal path.', ['%alias' => $path['alias']])); return NULL; } // Skip replacing the current alias with an identical alias. if (empty($existing_alias) || $existing_alias['alias'] != $path['alias']) { - $path += array( + $path += [ 'pathauto' => TRUE, 'original' => $existing_alias, 'pid' => NULL, - ); + ]; // If there is already an alias, respect some update actions. if (!empty($existing_alias)) { @@ -127,19 +127,19 @@ class AliasStorageHelper implements AliasStorageHelperInterface { if (!empty($existing_alias['pid'])) { $this->messenger->addMessage($this->t( 'Created new alias %alias for %source, replacing %old_alias.', - array( + [ '%alias' => $path['alias'], '%source' => $path['source'], '%old_alias' => $existing_alias['alias'], - ) + ] ) ); } else { - $this->messenger->addMessage($this->t('Created new alias %alias for %source.', array( + $this->messenger->addMessage($this->t('Created new alias %alias for %source.', [ '%alias' => $path['alias'], '%source' => $path['source'], - ))); + ])); } return $path; @@ -197,7 +197,7 @@ class AliasStorageHelper implements AliasStorageHelperInterface { */ public function loadBySourcePrefix($source) { $select = $this->database->select('url_alias', 'u') - ->fields('u', array('pid')); + ->fields('u', ['pid']); $or_group = $select->orConditionGroup() ->condition('source', $source) @@ -214,7 +214,7 @@ class AliasStorageHelper implements AliasStorageHelperInterface { */ public function countBySourcePrefix($source) { $select = $this->database->select('url_alias', 'u') - ->fields('u', array('pid')); + ->fields('u', ['pid']); $or_group = $select->orConditionGroup() ->condition('source', $source) @@ -246,9 +246,9 @@ class AliasStorageHelper implements AliasStorageHelperInterface { * @param int[] $pids * An array of path IDs to delete. */ - public function deleteMultiple($pids) { + public function deleteMultiple(array $pids) { foreach ($pids as $pid) { - $this->aliasStorage->delete(array('pid' => $pid)); + $this->aliasStorage->delete(['pid' => $pid]); } } diff --git a/src/AliasStorageHelperInterface.php b/src/AliasStorageHelperInterface.php index 4f17880..bf1c22b 100644 --- a/src/AliasStorageHelperInterface.php +++ b/src/AliasStorageHelperInterface.php @@ -1,6 +1,7 @@ configFactory = $config_factory; @@ -100,8 +102,8 @@ class AliasUniquifier implements AliasUniquifierInterface { // Check if this alias already exists. if ($existing_source = $this->aliasManager->getPathByAlias($alias, $langcode)) { if ($existing_source != $alias) { - // If it is an alias for the provided source, it is allowed to keep using - // it. If not, then it is reserved. + // If it is an alias for the provided source, it is allowed to keep + // using it. If not, then it is reserved. return $existing_source != $source; } @@ -112,11 +114,11 @@ class AliasUniquifier implements AliasUniquifierInterface { return TRUE; } // Finally check if any other modules have reserved the alias. - $args = array( + $args = [ $alias, $source, $langcode, - ); + ]; $implementations = $this->moduleHandler->getImplementations('pathauto_is_alias_reserved'); foreach ($implementations as $module) { diff --git a/src/AliasUniquifierInterface.php b/src/AliasUniquifierInterface.php index 2da4ba2..45547eb 100644 --- a/src/AliasUniquifierInterface.php +++ b/src/AliasUniquifierInterface.php @@ -1,6 +1,7 @@ deleteAll(); drupal_set_message($this->t('All of your path aliases have been deleted.')); } @@ -170,7 +170,7 @@ class PathautoAdminDelete extends FormBase { if ($results['delete_all']) { drupal_set_message(t('All of your automatically generated path aliases have been deleted.')); } - else if (isset($results['deletions'])) { + elseif (isset($results['deletions'])) { foreach (array_values($results['deletions']) as $label) { drupal_set_message(t('All of your automatically generated %label path aliases have been deleted.', ['%label' => $label])); } @@ -178,7 +178,10 @@ class PathautoAdminDelete extends FormBase { } else { $error_operation = reset($operations); - drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE)))); + drupal_set_message(t('An error occurred while processing @operation with arguments : @args', [ + '@operation' => $error_operation[0], + '@args' => print_r($error_operation[0], TRUE), + ])); } } diff --git a/src/Form/PathautoBulkUpdateForm.php b/src/Form/PathautoBulkUpdateForm.php index e66cd9d..a2b1025 100644 --- a/src/Form/PathautoBulkUpdateForm.php +++ b/src/Form/PathautoBulkUpdateForm.php @@ -53,16 +53,16 @@ class PathautoBulkUpdateForm extends FormBase { */ public function buildForm(array $form, FormStateInterface $form_state) { - $form = array(); + $form = []; - $form['#update_callbacks'] = array(); + $form['#update_callbacks'] = []; - $form['update'] = array( + $form['update'] = [ '#type' => 'checkboxes', '#title' => $this->t('Select the types of paths for which to generate URL aliases'), - '#options' => array(), - '#default_value' => array(), - ); + '#options' => [], + '#default_value' => [], + ]; $definitions = $this->aliasTypeManager->getVisibleDefinitions(); @@ -73,20 +73,20 @@ class PathautoBulkUpdateForm extends FormBase { } } - $form['action'] = array( + $form['action'] = [ '#type' => 'radios', '#title' => $this->t('Select which URL aliases to generate'), '#options' => ['create' => $this->t('Generate a URL alias for un-aliased paths only')], '#default_value' => 'create', - ); + ]; $config = $this->config('pathauto.settings'); if ($config->get('update_action') == PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW) { // Existing aliases should not be updated. - $form['warning'] = array( + $form['warning'] = [ '#markup' => $this->t('Pathauto settings are set to ignore paths which already have a URL alias. You can only create URL aliases for paths having none.', [':url' => Url::fromRoute('pathauto.settings.form')->toString()]), - ); + ]; } else { $form['action']['#options']['update'] = $this->t('Update the URL alias for paths having an old URL alias'); @@ -94,10 +94,10 @@ class PathautoBulkUpdateForm extends FormBase { } $form['actions']['#type'] = 'actions'; - $form['actions']['submit'] = array( + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Update'), - ); + ]; return $form; } @@ -106,19 +106,22 @@ class PathautoBulkUpdateForm extends FormBase { * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { - $batch = array( + $batch = [ 'title' => $this->t('Bulk updating URL aliases'), - 'operations' => array( - array('Drupal\pathauto\Form\PathautoBulkUpdateForm::batchStart', array()), - ), + 'operations' => [ + ['Drupal\pathauto\Form\PathautoBulkUpdateForm::batchStart', []], + ], 'finished' => 'Drupal\pathauto\Form\PathautoBulkUpdateForm::batchFinished', - ); + ]; $action = $form_state->getValue('action'); foreach ($form_state->getValue('update') as $id) { if (!empty($id)) { - $batch['operations'][] = array('Drupal\pathauto\Form\PathautoBulkUpdateForm::batchProcess', [$id, $action]); + $batch['operations'][] = [ + 'Drupal\pathauto\Form\PathautoBulkUpdateForm::batchProcess', + [$id, $action], + ]; } } @@ -157,7 +160,10 @@ class PathautoBulkUpdateForm extends FormBase { } else { $error_operation = reset($operations); - drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE)))); + drupal_set_message(t('An error occurred while processing @operation with arguments : @args', [ + '@operation' => $error_operation[0], + '@args' => print_r($error_operation[0], TRUE), + ])); } } diff --git a/src/Form/PathautoSettingsForm.php b/src/Form/PathautoSettingsForm.php index 281edb2..fa26c0d 100644 --- a/src/Form/PathautoSettingsForm.php +++ b/src/Form/PathautoSettingsForm.php @@ -20,22 +20,30 @@ use Symfony\Component\DependencyInjection\ContainerInterface; class PathautoSettingsForm extends ConfigFormBase { /** + * Entity Type Manager. + * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** + * Entity Field Manager. + * * @var \Drupal\Core\Entity\EntityFieldManagerInterface */ protected $entityFieldManager; /** + * Alias Type Manager. + * * @var \Drupal\pathauto\AliasTypeManager */ protected $aliasTypeManager; /** - * {@inheritDoc} + * Function to construct. + * + * {@inheritDoc}. */ public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AliasTypeManager $alias_type_manager) { parent::__construct($config_factory); @@ -45,7 +53,9 @@ class PathautoSettingsForm extends ConfigFormBase { } /** - * {@inheritDoc} + * Function to create. + * + * {@inheritDoc}. */ public static function create(ContainerInterface $container) { return new static( @@ -104,28 +114,28 @@ class PathautoSettingsForm extends ConfigFormBase { } } - $form['verbose'] = array( + $form['verbose'] = [ '#type' => 'checkbox', '#title' => $this->t('Verbose'), '#default_value' => $config->get('verbose'), '#description' => $this->t('Display alias changes (except during bulk updates).'), - ); + ]; - $form['separator'] = array( + $form['separator'] = [ '#type' => 'textfield', '#title' => $this->t('Separator'), '#size' => 1, '#maxlength' => 1, '#default_value' => $config->get('separator'), '#description' => $this->t('Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.'), - ); + ]; - $form['case'] = array( + $form['case'] = [ '#type' => 'checkbox', '#title' => $this->t('Character case'), '#default_value' => $config->get('case'), '#description' => $this->t('Convert token values to lowercase.'), - ); + ]; $max_length = \Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength(); @@ -134,7 +144,7 @@ class PathautoSettingsForm extends ConfigFormBase { $help_link = ' ' . $this->t('See Pathauto help for details.', [':pathauto-help' => Url::fromRoute('help.page', ['name' => 'pathauto'])->toString()]); } - $form['max_length'] = array( + $form['max_length'] = [ '#type' => 'number', '#title' => $this->t('Maximum alias length'), '#size' => 3, @@ -142,10 +152,10 @@ class PathautoSettingsForm extends ConfigFormBase { '#default_value' => $config->get('max_length'), '#min' => 1, '#max' => $max_length, - '#description' => $this->t('Maximum length of aliases to generate. 100 is the recommended length. @max is the maximum possible length.', array('@max' => $max_length)) . $help_link, - ); + '#description' => $this->t('Maximum length of aliases to generate. 100 is the recommended length. @max is the maximum possible length.', ['@max' => $max_length]) . $help_link, + ]; - $form['max_component_length'] = array( + $form['max_component_length'] = [ '#type' => 'number', '#title' => $this->t('Maximum component length'), '#size' => 3, @@ -154,57 +164,57 @@ class PathautoSettingsForm extends ConfigFormBase { '#min' => 1, '#max' => $max_length, '#description' => $this->t('Maximum text length of any component in the alias (e.g., [title]). 100 is the recommended length. @max is the maximum possible length.', ['@max' => $max_length]) . $help_link, - ); + ]; $description = $this->t('What should Pathauto do when updating an existing content item which already has an alias?'); if (\Drupal::moduleHandler()->moduleExists('redirect')) { - $description .= ' ' . $this->t('The Redirect module settings affect whether a redirect is created when an alias is deleted.', array(':url' => Url::fromRoute('redirect.settings')->toString())); + $description .= ' ' . $this->t('The Redirect module settings affect whether a redirect is created when an alias is deleted.', [':url' => Url::fromRoute('redirect.settings')->toString()]); } else { - $description .= ' ' . $this->t('Considering installing the Redirect module to get redirects when your aliases change.', array(':url' => 'http://drupal.org/project/redirect')); + $description .= ' ' . $this->t('Considering installing the Redirect module to get redirects when your aliases change.', [':url' => 'http://drupal.org/project/redirect']); } - $form['update_action'] = array( + $form['update_action'] = [ '#type' => 'radios', '#title' => $this->t('Update action'), '#default_value' => $config->get('update_action'), - '#options' => array( + '#options' => [ PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW => $this->t('Do nothing. Leave the old alias intact.'), PathautoGeneratorInterface::UPDATE_ACTION_LEAVE => $this->t('Create a new alias. Leave the existing alias functioning.'), PathautoGeneratorInterface::UPDATE_ACTION_DELETE => $this->t('Create a new alias. Delete the old alias.'), - ), + ], '#description' => $description, - ); + ]; - $form['transliterate'] = array( + $form['transliterate'] = [ '#type' => 'checkbox', '#title' => $this->t('Transliterate prior to creating alias'), '#default_value' => $config->get('transliterate'), '#description' => $this->t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the US-ASCII alphabet?'), - ); + ]; - $form['reduce_ascii'] = array( + $form['reduce_ascii'] = [ '#type' => 'checkbox', '#title' => $this->t('Reduce strings to letters and numbers'), '#default_value' => $config->get('reduce_ascii'), '#description' => $this->t('Filters the new alias to only letters and numbers found in the ASCII-96 set.'), - ); + ]; - $form['ignore_words'] = array( + $form['ignore_words'] = [ '#type' => 'textarea', '#title' => $this->t('Strings to Remove'), '#default_value' => $config->get('ignore_words'), '#description' => $this->t('Words to strip out of the URL alias, separated by commas. Do not use this to remove punctuation.'), '#wysiwyg' => FALSE, - ); + ]; - $form['punctuation'] = array( + $form['punctuation'] = [ '#type' => 'fieldset', '#title' => $this->t('Punctuation'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#tree' => TRUE, - ); + ]; $punctuation = \Drupal::service('pathauto.alias_cleaner')->getPunctuationCharacters(); @@ -217,16 +227,16 @@ class PathautoSettingsForm extends ConfigFormBase { // Otherwise use the correct default. $details['default'] = $details['value'] == $config->get('separator') ? PathautoGeneratorInterface::PUNCTUATION_REPLACE : PathautoGeneratorInterface::PUNCTUATION_REMOVE; } - $form['punctuation'][$name] = array( + $form['punctuation'][$name] = [ '#type' => 'select', '#title' => $details['name'] . ' (' . Html::escape($details['value']) . ')', '#default_value' => $details['default'], - '#options' => array( + '#options' => [ PathautoGeneratorInterface::PUNCTUATION_REMOVE => $this->t('Remove'), PathautoGeneratorInterface::PUNCTUATION_REPLACE => $this->t('Replace by separator'), PathautoGeneratorInterface::PUNCTUATION_DO_NOTHING => $this->t('No action (do not replace)'), - ), - ); + ], + ]; } return parent::buildForm($form, $form_state); diff --git a/src/Form/PatternDisableForm.php b/src/Form/PatternDisableForm.php index c87b88b..ec00fac 100644 --- a/src/Form/PatternDisableForm.php +++ b/src/Form/PatternDisableForm.php @@ -15,7 +15,7 @@ class PatternDisableForm extends EntityConfirmFormBase { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to disable the pattern %label?', array('%label' => $this->entity->label())); + return $this->t('Are you sure you want to disable the pattern %label?', ['%label' => $this->entity->label()]); } /** @@ -44,7 +44,7 @@ class PatternDisableForm extends EntityConfirmFormBase { */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->entity->disable()->save(); - drupal_set_message($this->t('Disabled pattern %label.', array('%label' => $this->entity->label()))); + drupal_set_message($this->t('Disabled pattern %label.', ['%label' => $this->entity->label()])); $form_state->setRedirectUrl($this->getCancelUrl()); } diff --git a/src/Form/PatternEditForm.php b/src/Form/PatternEditForm.php index 49efc7e..3db413c 100644 --- a/src/Form/PatternEditForm.php +++ b/src/Form/PatternEditForm.php @@ -16,11 +16,15 @@ use Symfony\Component\DependencyInjection\ContainerInterface; class PatternEditForm extends EntityForm { /** + * Manager. + * * @var \Drupal\pathauto\AliasTypeManager */ protected $manager; /** + * Entity. + * * @var \Drupal\pathauto\PathautoPatternInterface */ protected $entity; @@ -33,11 +37,15 @@ class PatternEditForm extends EntityForm { protected $entityTypeBundleInfo; /** + * Entity Type Manager. + * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** + * Language Manager. + * * @var \Drupal\Core\Language\LanguageManagerInterface */ protected $languageManager; @@ -58,11 +66,15 @@ class PatternEditForm extends EntityForm { * PatternEditForm constructor. * * @param \Drupal\pathauto\AliasTypeManager $manager + * Manager. * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info + * Entity type bundle info. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager + * Entity type manager. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager + * Language manager. */ - function __construct(AliasTypeManager $manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager) { + public function __construct(AliasTypeManager $manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager) { $this->manager = $manager; $this->entityTypeBundleInfo = $entity_type_bundle_info; $this->entityTypeManager = $entity_type_manager; @@ -70,7 +82,9 @@ class PatternEditForm extends EntityForm { } /** - * {@inheritDoc} + * Build Form. + * + * {@inheritDoc}. */ public function buildForm(array $form, FormStateInterface $form_state) { @@ -84,14 +98,14 @@ class PatternEditForm extends EntityForm { '#default_value' => $this->entity->getType(), '#options' => $options, '#required' => TRUE, - '#limit_validation_errors' => array(array('type')), - '#submit' => array('::submitSelectType'), + '#limit_validation_errors' => [['type']], + '#submit' => ['::submitSelectType'], '#executes_submit_callback' => TRUE, - '#ajax' => array( + '#ajax' => [ 'callback' => '::ajaxReplacePatternForm', 'wrapper' => 'pathauto-pattern', 'method' => 'replace', - ), + ], ]; $form['pattern_container'] = [ @@ -100,36 +114,36 @@ class PatternEditForm extends EntityForm { '#suffix' => '', ]; - // if there is no type yet, stop here. + // If there is no type yet, stop here. if ($this->entity->getType()) { $alias_type = $this->entity->getAliasType(); - $form['pattern_container']['pattern'] = array( + $form['pattern_container']['pattern'] = [ '#type' => 'textfield', '#title' => 'Path pattern', '#default_value' => $this->entity->getPattern(), '#size' => 65, '#maxlength' => 1280, - '#element_validate' => array('token_element_validate', 'pathauto_pattern_validate'), - '#after_build' => array('token_element_validate'), + '#element_validate' => ['token_element_validate', 'pathauto_pattern_validate'], + '#after_build' => ['token_element_validate'], '#token_types' => $alias_type->getTokenTypes(), '#min_tokens' => 1, '#required' => TRUE, - ); + ]; // Show the token help relevant to this pattern type. - $form['pattern_container']['token_help'] = array( + $form['pattern_container']['token_help'] = [ '#theme' => 'token_tree_link', '#token_types' => $alias_type->getTokenTypes(), - ); + ]; // Expose bundle and language conditions. if ($alias_type->getDerivativeId() && $entity_type = $this->entityTypeManager->getDefinition($alias_type->getDerivativeId())) { $default_bundles = []; $default_languages = []; - foreach ($this->entity->getSelectionConditions() as $condition_id => $condition) { + foreach ($this->entity->getSelectionConditions() as $condition) { if (in_array($condition->getPluginId(), ['entity_bundle:' . $entity_type->id(), 'node_type'])) { $default_bundles = $condition->getConfiguration()['bundles']; } @@ -143,13 +157,13 @@ class PatternEditForm extends EntityForm { foreach ($bundles as $id => $info) { $bundle_options[$id] = $info['label']; } - $form['pattern_container']['bundles'] = array( + $form['pattern_container']['bundles'] = [ '#title' => $entity_type->getBundleLabel(), '#type' => 'checkboxes', '#options' => $bundle_options, '#default_value' => $default_bundles, '#description' => $this->t('Check to which types this pattern should be applied. Leave empty to allow any.'), - ); + ]; } if ($this->languageManager->isMultilingual() && $entity_type->isTranslatable()) { @@ -157,37 +171,37 @@ class PatternEditForm extends EntityForm { foreach ($this->languageManager->getLanguages() as $id => $language) { $language_options[$id] = $language->getName(); } - $form['pattern_container']['languages'] = array( + $form['pattern_container']['languages'] = [ '#title' => $this->t('Languages'), '#type' => 'checkboxes', '#options' => $language_options, '#default_value' => $default_languages, '#description' => $this->t('Check to which languages this pattern should be applied. Leave empty to allow any.'), - ); + ]; } } } - $form['label'] = array( + $form['label'] = [ '#type' => 'textfield', '#title' => $this->t('Label'), '#maxlength' => 255, '#default_value' => $this->entity->label(), '#required' => TRUE, '#description' => $this->t('A short name to help you identify this pattern in the patterns list.'), - ); + ]; - $form['id'] = array( + $form['id'] = [ '#type' => 'machine_name', '#title' => $this->t('ID'), '#maxlength' => 255, '#default_value' => $this->entity->id(), '#required' => TRUE, '#disabled' => !$this->entity->isNew(), - '#machine_name' => array( + '#machine_name' => [ 'exists' => 'Drupal\pathauto\Entity\PathautoPattern::load', - ), - ); + ], + ]; $form['status'] = [ '#title' => $this->t('Enabled'), @@ -199,7 +213,9 @@ class PatternEditForm extends EntityForm { } /** - * {@inheritDoc} + * Build Entity. + * + * {@inheritDoc}. */ public function buildEntity(array $form, FormStateInterface $form_state) { /** @var \Drupal\pathauto\PathautoPatternInterface $entity */ @@ -213,7 +229,9 @@ class PatternEditForm extends EntityForm { $entity_type = $alias_type->getDerivativeId(); // First, remove bundle and language conditions. foreach ($entity->getSelectionConditions() as $condition_id => $condition) { - if (in_array($condition->getPluginId(), ['entity_bundle:' . $entity_type, 'node_type', 'language'])) { + if (in_array($condition->getPluginId(), [ + 'entity_bundle:' . $entity_type, 'node_type', 'language', + ])) { $entity->removeSelectionCondition($condition_id); } } @@ -228,7 +246,7 @@ class PatternEditForm extends EntityForm { 'negate' => FALSE, 'context_mapping' => [ $entity_type => $entity_type, - ] + ], ] ); } @@ -243,7 +261,7 @@ class PatternEditForm extends EntityForm { 'negate' => FALSE, 'context_mapping' => [ 'language' => $language_mapping, - ] + ], ] ); $entity->addRelationship($language_mapping, t('Language')); @@ -259,7 +277,9 @@ class PatternEditForm extends EntityForm { } /** - * {@inheritDoc} + * Function to save. + * + * {@inheritDoc}. */ public function save(array $form, FormStateInterface $form_state) { parent::save($form, $form_state); diff --git a/src/Form/PatternEnableForm.php b/src/Form/PatternEnableForm.php index 253ca31..df78f27 100644 --- a/src/Form/PatternEnableForm.php +++ b/src/Form/PatternEnableForm.php @@ -15,7 +15,7 @@ class PatternEnableForm extends EntityConfirmFormBase { * {@inheritdoc} */ public function getQuestion() { - return $this->t('Are you sure you want to enable the pattern %label?', array('%label' => $this->entity->label())); + return $this->t('Are you sure you want to enable the pattern %label?', ['%label' => $this->entity->label()]); } /** @@ -44,7 +44,7 @@ class PatternEnableForm extends EntityConfirmFormBase { */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->entity->enable()->save(); - drupal_set_message($this->t('Enabled pattern %label.', array('%label' => $this->entity->label()))); + drupal_set_message($this->t('Enabled pattern %label.', ['%label' => $this->entity->label()])); $form_state->setRedirectUrl($this->getCancelUrl()); } diff --git a/src/PathautoGenerator.php b/src/PathautoGenerator.php index 6c56a5c..58ec5ec 100644 --- a/src/PathautoGenerator.php +++ b/src/PathautoGenerator.php @@ -49,14 +49,14 @@ class PathautoGenerator implements PathautoGeneratorInterface { * * @var array */ - protected $patterns = array(); + protected $patterns = []; /** * Available patterns per entity type ID. * * @var array */ - protected $patternsByEntityType = array(); + protected $patternsByEntityType = []; /** * The alias cleaner. @@ -87,11 +87,15 @@ class PathautoGenerator implements PathautoGeneratorInterface { protected $messenger; /** + * Token Entity Mapper. + * * @var \Drupal\token\TokenEntityMapperInterface */ protected $tokenEntityMapper; /** + * Entity Type Manager. + * * @var Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; @@ -115,8 +119,10 @@ class PathautoGenerator implements PathautoGeneratorInterface { * The messenger service. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation * The string translation service. + * @param \Drupal\token\TokenEntityMapperInterface $token_entity_mappper + * The Token Entity Mapper. * @param Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager - * The entity type manager + * The entity type manager. */ public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, Token $token, AliasCleanerInterface $alias_cleaner, AliasStorageHelperInterface $alias_storage_helper, AliasUniquifierInterface $alias_uniquifier, MessengerInterface $messenger, TranslationInterface $string_translation, TokenEntityMapperInterface $token_entity_mappper, EntityTypeManagerInterface $entity_type_manager) { $this->configFactory = $config_factory; @@ -157,14 +163,14 @@ class PathautoGenerator implements PathautoGeneratorInterface { ]; // Allow other modules to alter the pattern. - $context = array( + $context = [ 'module' => $entity->getEntityType()->getProvider(), 'op' => $op, 'source' => $source, 'data' => $data, 'bundle' => $entity->bundle(), 'language' => &$langcode, - ); + ]; // @todo Is still hook still useful? $this->moduleHandler->alter('pathauto_pattern', $pattern, $context); @@ -186,12 +192,12 @@ class PathautoGenerator implements PathautoGeneratorInterface { // Uses callback option to clean replacements. No sanitization. // Pass empty BubbleableMetadata object to explicitly ignore cacheablity, // as the result is never rendered. - $alias = $this->token->replace($pattern->getPattern(), $data, array( + $alias = $this->token->replace($pattern->getPattern(), $data, [ 'clear' => TRUE, - 'callback' => array($this->aliasCleaner, 'cleanTokenValues'), + 'callback' => [$this->aliasCleaner, 'cleanTokenValues'], 'langcode' => $langcode, 'pathauto' => TRUE, - ), new BubbleableMetadata()); + ], new BubbleableMetadata()); // Check if the token replacement has not actually replaced any values. If // that is the case, then stop because we should not generate an alias. @@ -218,10 +224,10 @@ class PathautoGenerator implements PathautoGeneratorInterface { $this->aliasUniquifier->uniquify($alias, $source, $langcode); if ($original_alias != $alias) { // Alert the user why this happened. - $this->messenger->addMessage($this->t('The automatically generated alias %original_alias conflicted with an existing alias. Alias changed to %alias.', array( + $this->messenger->addMessage($this->t('The automatically generated alias %original_alias conflicted with an existing alias. Alias changed to %alias.', [ '%original_alias' => $original_alias, '%alias' => $alias, - )), $op); + ]), $op); } // Return the generated alias if requested. @@ -230,17 +236,17 @@ class PathautoGenerator implements PathautoGeneratorInterface { } // Build the new path alias array and send it off to be created. - $path = array( + $path = [ 'source' => $source, 'alias' => $alias, 'language' => $langcode, - ); + ]; return $this->aliasStorageHelper->save($path, $existing_alias, $op); } /** - * Loads pathauto patterns for a given entity type ID + * Loads pathauto patterns for a given entity type ID. * * @param string $entity_type_id * An entity type ID. @@ -297,7 +303,7 @@ class PathautoGenerator implements PathautoGeneratorInterface { /** * {@inheritdoc} */ - public function updateEntityAlias(EntityInterface $entity, $op, array $options = array()) { + public function updateEntityAlias(EntityInterface $entity, $op, array $options = []) { // Skip if the entity does not have the path field. if (!($entity instanceof ContentEntityInterface) || !$entity->hasField('path')) { return NULL; @@ -313,7 +319,7 @@ class PathautoGenerator implements PathautoGeneratorInterface { return NULL; } - $options += array('language' => $entity->language()->getId()); + $options += ['language' => $entity->language()->getId()]; $type = $entity->getEntityTypeId(); // Skip processing if the entity has no pattern. diff --git a/src/PathautoGeneratorInterface.php b/src/PathautoGeneratorInterface.php index 5880adb..c4c6ae1 100644 --- a/src/PathautoGeneratorInterface.php +++ b/src/PathautoGeneratorInterface.php @@ -10,17 +10,17 @@ use Drupal\Core\Entity\EntityInterface; interface PathautoGeneratorInterface { /** - * "Do nothing. Leave the old alias intact." + * Do nothing. Leave the old alias intact. */ const UPDATE_ACTION_NO_NEW = 0; /** - * "Create a new alias. Leave the existing alias functioning." + * Create a new alias. Leave the existing alias functioning. */ const UPDATE_ACTION_LEAVE = 1; /** - * "Create a new alias. Delete the old alias." + * Create a new alias. Delete the old alias. */ const UPDATE_ACTION_DELETE = 2; @@ -49,7 +49,9 @@ interface PathautoGeneratorInterface { * * @param \Drupal\Core\Entity\EntityInterface $entity * An entity. + * * @return \Drupal\pathauto\PathautoPatternInterface|null + * Return Pattern. */ public function getPatternByEntity(EntityInterface $entity); @@ -72,18 +74,18 @@ interface PathautoGeneratorInterface { /** * Creates or updates an alias for the given entity. * - * @param EntityInterface $entity + * @param \Drupal\Core\Entity\EntityInterface $entity * Entity for which to update the alias. * @param string $op * The operation performed (insert, update) * @param array $options - * - force: will force updating the path - * - language: the language for which to create the alias + * - Force: will force updating the path + * - language: the language for which to create the alias. * * @return array|null * - An array with alias data in case the alias has been created or updated. * - NULL if no operation performed. */ - public function updateEntityAlias(EntityInterface $entity, $op, array $options = array()); + public function updateEntityAlias(EntityInterface $entity, $op, array $options = []); } diff --git a/src/PathautoItem.php b/src/PathautoItem.php index cababe6..3967a8a 100644 --- a/src/PathautoItem.php +++ b/src/PathautoItem.php @@ -51,7 +51,7 @@ class PathautoItem extends PathItem { public function applyDefaultValue($notify = TRUE) { parent::applyDefaultValue($notify); // Created fields default creating a new alias. - $this->setValue(array('pathauto' => PathautoState::CREATE), $notify); + $this->setValue(['pathauto' => PathautoState::CREATE], $notify); return $this; } diff --git a/src/PathautoPatternInterface.php b/src/PathautoPatternInterface.php index 9782f2e..e884ed4 100644 --- a/src/PathautoPatternInterface.php +++ b/src/PathautoPatternInterface.php @@ -13,6 +13,7 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * Get the tokenized pattern used during alias generation. * * @return string + * Return string with pattern. */ public function getPattern(); @@ -20,8 +21,10 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * Set the tokenized pattern to use during alias generation. * * @param string $pattern + * String with pattern. * * @return $this + * Return pattern. */ public function setPattern($pattern); @@ -29,11 +32,15 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * Gets the type of this pattern. * * @return string + * Return string with Type. */ public function getType(); /** + * Get Alias Type. + * * @return \Drupal\pathauto\AliasTypeInterface + * Return Alias Type. */ public function getAliasType(); @@ -41,6 +48,7 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * Gets the weight of this pattern (compared to other patterns of this type). * * @return int + * Return weight. */ public function getWeight(); @@ -58,6 +66,7 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * Returns the contexts of this pattern. * * @return \Drupal\Core\Plugin\Context\ContextInterface[] + * Return contexts. */ public function getContexts(); @@ -126,6 +135,7 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * Gets the selection condition collection. * * @return \Drupal\Core\Condition\ConditionInterface[]|\Drupal\Core\Condition\ConditionPluginCollection + * Return Selection Conditions. */ public function getSelectionConditions(); @@ -147,6 +157,7 @@ interface PathautoPatternInterface extends ConfigEntityInterface { * The id of the condition. * * @return \Drupal\Core\Condition\ConditionInterface + * Return Selection Condition. */ public function getSelectionCondition($condition_id); @@ -171,10 +182,11 @@ interface PathautoPatternInterface extends ConfigEntityInterface { /** * Determines if this pattern can apply a given object. * - * @param $object + * @param object $object * The object used to determine if this plugin can apply. * * @return bool + * Return flag with type boolean. */ public function applies($object); diff --git a/src/PathautoState.php b/src/PathautoState.php index 6415252..805567b 100644 --- a/src/PathautoState.php +++ b/src/PathautoState.php @@ -1,4 +1,5 @@ parent->getEntity()->getEntityTypeId(); diff --git a/src/PathautoWidget.php b/src/PathautoWidget.php index 3ca0490..c015205 100644 --- a/src/PathautoWidget.php +++ b/src/PathautoWidget.php @@ -24,18 +24,19 @@ class PathautoWidget extends PathWidget { // @todo Impossible to do this in widget, use another solution /* $form['path'] += array( - '#type' => 'fieldset', - '#title' => $this->t('URL path settings'), - '#collapsible' => TRUE, - '#collapsed' => empty($form['path']['alias']), - '#group' => 'additional_settings', - '#attributes' => array( - 'class' => array('path-form'), - ), - '#access' => \Drupal::currentUser()->hasPermission('create url aliases') || \Drupal::currentUser()->hasPermission('administer url aliases'), - '#weight' => 30, - '#tree' => TRUE, - '#element_validate' => array('path_form_element_validate'), + '#type' => 'fieldset', + '#title' => $this->t('URL path settings'), + '#collapsible' => TRUE, + '#collapsed' => empty($form['path']['alias']), + '#group' => 'additional_settings', + '#attributes' => array( + 'class' => array('path-form'), + ), + // @codingStandardsIgnoreLine + '#access' => \Drupal::currentUser()->hasPermission('create url aliases') || \Drupal::currentUser()->hasPermission('administer url aliases'), + '#weight' => 30, + '#tree' => TRUE, + '#element_validate' => array('path_form_element_validate'), );*/ $pattern = \Drupal::service('pathauto.generator')->getPatternByEntity($entity); @@ -50,17 +51,17 @@ class PathautoWidget extends PathWidget { $description = $this->t('Uncheck this to create a custom alias below.'); } - $element['pathauto'] = array( + $element['pathauto'] = [ '#type' => 'checkbox', '#title' => $this->t('Generate automatic URL alias'), '#default_value' => $entity->path->pathauto, '#description' => $description, '#weight' => -1, - ); + ]; // Add JavaScript that will disable the path textfield when the automatic // alias checkbox is checked. - $element['alias']['#states']['disabled']['input[name="path[' . $delta . '][pathauto]"]'] = array('checked' => TRUE); + $element['alias']['#states']['disabled']['input[name="path[' . $delta . '][pathauto]"]'] = ['checked' => TRUE]; // Override path.module's vertical tabs summary. $element['alias']['#attached']['library'] = ['pathauto/widget']; diff --git a/src/Plugin/Action/UpdateAction.php b/src/Plugin/Action/UpdateAction.php index bfe0f48..3ec0a5d 100644 --- a/src/Plugin/Action/UpdateAction.php +++ b/src/Plugin/Action/UpdateAction.php @@ -22,7 +22,7 @@ class UpdateAction extends ActionBase { */ public function execute($entity = NULL) { $entity->path->pathauto = PathautoState::CREATE; - \Drupal::service('pathauto.generator')->updateEntityAlias($entity, 'bulkupdate', array('message' => TRUE)); + \Drupal::service('pathauto.generator')->updateEntityAlias($entity, 'bulkupdate', ['message' => TRUE]); } /** diff --git a/src/Plugin/Deriver/EntityAliasTypeDeriver.php b/src/Plugin/Deriver/EntityAliasTypeDeriver.php index cf7b4a2..0e08839 100644 --- a/src/Plugin/Deriver/EntityAliasTypeDeriver.php +++ b/src/Plugin/Deriver/EntityAliasTypeDeriver.php @@ -21,16 +21,22 @@ class EntityAliasTypeDeriver extends DeriverBase implements ContainerDeriverInte use StringTranslationTrait; /** + * Entity Type Manager. + * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** + * Entity Field Manager. + * * @var \Drupal\Core\Entity\EntityFieldManagerInterface */ protected $entityFieldManager; /** + * Token Entity Mapper. + * * @var \Drupal\token\TokenEntityMapperInterface */ protected $tokenEntityMapper; @@ -44,7 +50,7 @@ class EntityAliasTypeDeriver extends DeriverBase implements ContainerDeriverInte * The entity field manager. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation * The string translation service. - * @apram \Drupal\Token\TokenEntityMapperInterface $token_entity_mapper + * @param \Drupal\Token\TokenEntityMapperInterface $token_entity_mapper * The token entity mapper. */ public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, TranslationInterface $string_translation, TokenEntityMapperInterface $token_entity_mapper) { @@ -84,7 +90,7 @@ class EntityAliasTypeDeriver extends DeriverBase implements ContainerDeriverInte $this->derivatives[$entity_type_id]['types'] = [$this->tokenEntityMapper->getTokenTypeForEntityType($entity_type_id)]; $this->derivatives[$entity_type_id]['provider'] = $entity_type->getProvider(); $this->derivatives[$entity_type_id]['context'] = [ - $entity_type_id => new ContextDefinition("entity:$entity_type_id", $this->t('@label being aliased', ['@label' => $entity_type->getLabel()])) + $entity_type_id => new ContextDefinition("entity:$entity_type_id", $this->t('@label being aliased', ['@label' => $entity_type->getLabel()])), ]; } } diff --git a/src/Plugin/pathauto/AliasType/EntityAliasTypeBase.php b/src/Plugin/pathauto/AliasType/EntityAliasTypeBase.php index 121f04b..043a753 100644 --- a/src/Plugin/pathauto/AliasType/EntityAliasTypeBase.php +++ b/src/Plugin/pathauto/AliasType/EntityAliasTypeBase.php @@ -151,12 +151,15 @@ class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInt case 'create': $query->isNull('ua.source'); break; + case 'update': $query->isNotNull('ua.source'); break; + case 'all': // Nothing to do. We want all paths. break; + default: // Unknown action. Abort! return; @@ -184,7 +187,10 @@ class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInt $context['sandbox']['count'] += count($ids); $context['sandbox']['current'] = max($ids); $context['results']['updates'] += $updates; - $context['message'] = $this->t('Updated alias for %label @id.', array('%label' => $entity_type->getLabel(), '@id' => end($ids))); + $context['message'] = $this->t('Updated alias for %label @id.', [ + '%label' => $entity_type->getLabel(), + '@id' => end($ids), + ]); if ($context['sandbox']['count'] != $context['sandbox']['total']) { $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total']; @@ -255,10 +261,10 @@ class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInt * An optional array of additional options. * * @return int - * The number of updated URL aliases. + * The number of updated URL aliases. */ - protected function bulkUpdate(array $ids, array $options = array()) { - $options += array('message' => FALSE); + protected function bulkUpdate(array $ids, array $options = []) { + $options += ['message' => FALSE]; $updates = 0; $entities = $this->entityTypeManager->getStorage($this->getEntityTypeId())->loadMultiple($ids); @@ -274,7 +280,7 @@ class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInt } if (!empty($options['message'])) { - drupal_set_message(\Drupal::translation()->formatPlural(count($ids), 'Updated 1 %label URL alias.', 'Updated @count %label URL aliases.'), array('%label' => $this->getLabel())); + drupal_set_message(\Drupal::translation()->formatPlural(count($ids), 'Updated 1 %label URL alias.', 'Updated @count %label URL aliases.'), ['%label' => $this->getLabel()]); } return $updates; @@ -338,5 +344,4 @@ class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInt return $this; } - } diff --git a/src/Tests/PathautoBulkUpdateTest.php b/src/Tests/PathautoBulkUpdateTest.php index 2fa2194..91f2992 100644 --- a/src/Tests/PathautoBulkUpdateTest.php +++ b/src/Tests/PathautoBulkUpdateTest.php @@ -20,7 +20,7 @@ class PathautoBulkUpdateTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'pathauto', 'forum'); + public static $modules = ['node', 'pathauto', 'forum']; /** * Admin user. @@ -44,30 +44,35 @@ class PathautoBulkUpdateTest extends WebTestBase { protected $patterns; /** - * {inheritdoc} + * Function to set up. + * + * {inheritdoc}. */ - function setUp() { + public function setUp() { parent::setUp(); // Allow other modules to add additional permissions for the admin user. - $permissions = array( + $permissions = [ 'administer pathauto', 'administer url aliases', 'create url aliases', 'administer forums', - ); + ]; $this->adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); - $this->patterns = array(); + $this->patterns = []; $this->patterns['node'] = $this->createPattern('node', '/content/[node:title]'); $this->patterns['user'] = $this->createPattern('user', '/users/[user:name]'); $this->patterns['forum'] = $this->createPattern('forum', '/forums/[term:name]'); } - function testBulkUpdate() { + /** + * Function testBulkUpdate(). + */ + public function testBulkUpdate() { // Create some nodes. - $this->nodes = array(); + $this->nodes = []; for ($i = 1; $i <= 5; $i++) { $node = $this->drupalCreateNode(); $this->nodes[$node->id()] = $node; @@ -77,11 +82,11 @@ class PathautoBulkUpdateTest extends WebTestBase { $this->deleteAllAliases(); // Bulk create aliases. - $edit = array( + $edit = [ 'update[canonical_entities:node]' => TRUE, 'update[canonical_entities:user]' => TRUE, 'update[forum]' => TRUE, - ); + ]; $this->drupalPostForm('admin/config/search/path/update_bulk', $edit, t('Update')); // This has generated 8 aliases: 5 nodes, 2 users and 1 forum. @@ -96,7 +101,7 @@ class PathautoBulkUpdateTest extends WebTestBase { $this->assertAliasExists(['source' => '/taxonomy/term/1']); // Add a new node. - $new_node = $this->drupalCreateNode(array('path' => array('alias' => '', 'pathauto' => PathautoState::SKIP))); + $new_node = $this->drupalCreateNode(['path' => ['alias' => '', 'pathauto' => PathautoState::SKIP]]); // Run the update again which should not run against any nodes. $this->drupalPostForm('admin/config/search/path/update_bulk', $edit, t('Update')); @@ -111,15 +116,18 @@ class PathautoBulkUpdateTest extends WebTestBase { $this->drupalPostForm('admin/config/search/path/update_bulk', $edit, t('Update')); $this->assertText('No new URL aliases to generate.'); - // Update the node pattern, and leave other patterns alone. Existing nodes should get a new alias, - // except the node above whose alias is manually set. Other aliases must be left alone. + // Update the node pattern, and leave other patterns alone. Existing nodes + // should get a new alias, + // except the node above whose alias is manually set. Other aliases must be + // left alone. $this->patterns['node']->delete(); $this->patterns['node'] = $this->createPattern('node', '/archive/node-[node:nid]'); $this->drupalPostForm('admin/config/search/path/update_bulk', $edit, t('Update')); $this->assertText('Generated 5 URL aliases.'); - // Prevent existing aliases to be overriden. The bulk generate page should only offer + // Prevent existing aliases to be overriden. The bulk generate page should + // only offer // to create an alias for paths which have none. $this->drupalPostForm('admin/config/search/path/settings', ['update_action' => PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW], t('Save configuration')); @@ -133,20 +141,20 @@ class PathautoBulkUpdateTest extends WebTestBase { /** * Tests alias generation for nodes that existed before installing Pathauto. */ - function testBulkUpdateExistingContent() { + public function testBulkUpdateExistingContent() { // Create a node. $node = $this->drupalCreateNode(); // Delete its alias and Pathauto metadata. \Drupal::service('pathauto.alias_storage_helper')->deleteEntityPathAll($node); $node->path->first()->get('pathauto')->purge(); - \Drupal::entityTypeManager()->getStorage('node')->resetCache(array($node->id())); + \Drupal::entityTypeManager()->getStorage('node')->resetCache([$node->id()]); // Execute bulk generation. // Bulk create aliases. - $edit = array( + $edit = [ 'update[canonical_entities:node]' => TRUE, - ); + ]; $this->drupalPostForm('admin/config/search/path/update_bulk', $edit, t('Update')); // Verify that the alias was created for the node. diff --git a/src/Tests/PathautoEnablingEntityTypesTest.php b/src/Tests/PathautoEnablingEntityTypesTest.php index c8cc1ff..0287230 100644 --- a/src/Tests/PathautoEnablingEntityTypesTest.php +++ b/src/Tests/PathautoEnablingEntityTypesTest.php @@ -20,7 +20,7 @@ class PathautoEnablingEntityTypesTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'pathauto', 'comment'); + public static $modules = ['node', 'pathauto', 'comment']; /** * Admin user. @@ -30,31 +30,35 @@ class PathautoEnablingEntityTypesTest extends WebTestBase { protected $adminUser; /** - * {inheritdoc} + * Function to set up. + * + * {inheritdoc}. */ - function setUp() { + public function setUp() { parent::setUp(); - $this->drupalCreateContentType(array('type' => 'article')); + $this->drupalCreateContentType(['type' => 'article']); $this->addDefaultCommentField('node', 'article'); - $permissions = array( + $permissions = [ 'administer pathauto', 'administer url aliases', 'create url aliases', 'administer nodes', 'post comments', - ); + ]; $this->adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); } /** + * Function testEnablingEntityTypes(). + * * A suite of tests to verify if the feature to enable and disable the * ability to define alias patterns for a given entity type works. Test with * the comment module, as it is not enabled by default. */ - function testEnablingEntityTypes() { + public function testEnablingEntityTypes() { // Verify that the comment entity type is not available when trying to add // a new pattern, nor "broken". $this->drupalGet('/admin/config/search/path/patterns/add'); diff --git a/src/Tests/PathautoLocaleTest.php b/src/Tests/PathautoLocaleTest.php index dd271ef..db66a56 100644 --- a/src/Tests/PathautoLocaleTest.php +++ b/src/Tests/PathautoLocaleTest.php @@ -22,7 +22,12 @@ class PathautoLocaleTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'pathauto', 'locale', 'content_translation'); + public static $modules = [ + 'node', + 'pathauto', + 'locale', + 'content_translation', + ]; /** * {@inheritdoc} @@ -31,30 +36,31 @@ class PathautoLocaleTest extends WebTestBase { parent::setUp(); // Create Article node type. - $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); + $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']); } /** + * Function testLanguageAliases(). + * * Test that when an English node is updated, its old English alias is * updated and its newer French alias is left intact. */ - function testLanguageAliases() { + public function testLanguageAliases() { $this->createPattern('node', '/content/[node:title]'); // Add predefined French language. ConfigurableLanguage::createFromLangcode('fr')->save(); - $node = array( + $node = [ 'title' => 'English node', 'langcode' => 'en', - 'path' => array(array( - 'alias' => '/english-node', - 'pathauto' => FALSE, - )), - ); + 'path' => [ + ['alias' => '/english-node', 'pathauto' => FALSE], + ], + ]; $node = $this->drupalCreateNode($node); - $english_alias = \Drupal::service('path.alias_storage')->load(array('alias' => '/english-node', 'langcode' => 'en')); + $english_alias = \Drupal::service('path.alias_storage')->load(['alias' => '/english-node', 'langcode' => 'en']); $this->assertTrue($english_alias, 'Alias created with proper language.'); // Also save a French alias that should not be left alone, even though @@ -72,11 +78,11 @@ class PathautoLocaleTest extends WebTestBase { // Check that the new English alias replaced the old one. $this->assertEntityAlias($node, '/content/english-node-0', 'en'); $this->assertEntityAlias($node, '/french-node', 'fr'); - $this->assertAliasExists(array('pid' => $english_alias['pid'], 'alias' => '/content/english-node-0')); + $this->assertAliasExists(['pid' => $english_alias['pid'], 'alias' => '/content/english-node-0']); // Create a new node with the same title as before but without // specifying a language. - $node = $this->drupalCreateNode(array('title' => 'English node', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); + $node = $this->drupalCreateNode(['title' => 'English node', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); // Check that the new node had a unique alias generated with the '-0' // suffix. @@ -86,63 +92,63 @@ class PathautoLocaleTest extends WebTestBase { /** * Test that patterns work on multilingual content. */ - function testLanguagePatterns() { + public function testLanguagePatterns() { $this->drupalLogin($this->rootUser); // Add French language. - $edit = array( + $edit = [ 'predefined_langcode' => 'fr', - ); + ]; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); $this->enableArticleTranslation(); // Create a pattern for English articles. $this->drupalGet('admin/config/search/path/patterns/add'); - $edit = array( + $edit = [ 'type' => 'canonical_entities:node', - ); + ]; $this->drupalPostAjaxForm(NULL, $edit, 'type'); - $edit += array( + $edit += [ 'pattern' => '/the-articles/[node:title]', 'label' => 'English articles', 'id' => 'english_articles', 'bundles[article]' => TRUE, 'languages[en]' => TRUE, - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertText('Pattern English articles saved.'); // Create a pattern for French articles. $this->drupalGet('admin/config/search/path/patterns/add'); - $edit = array( + $edit = [ 'type' => 'canonical_entities:node', - ); + ]; $this->drupalPostAjaxForm(NULL, $edit, 'type'); - $edit += array( + $edit += [ 'pattern' => '/les-articles/[node:title]', 'label' => 'French articles', 'id' => 'french_articles', 'bundles[article]' => TRUE, 'languages[fr]' => TRUE, - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertText('Pattern French articles saved.'); // Create a node and its translation. Assert aliases. - $edit = array( + $edit = [ 'title[0][value]' => 'English node', 'langcode[0][value]' => 'en', - ); + ]; $this->drupalPostForm('node/add/article', $edit, t('Save and publish')); $english_node = $this->drupalGetNodeByTitle('English node'); $this->assertAlias('/node/' . $english_node->id(), '/the-articles/english-node', 'en'); $this->drupalGet('node/' . $english_node->id() . '/translations'); $this->clickLink(t('Add')); - $edit = array( + $edit = [ 'title[0][value]' => 'French node', - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save and keep published (this translation)')); $this->rebuildContainer(); $english_node = $this->drupalGetNodeByTitle('English node'); @@ -152,9 +158,9 @@ class PathautoLocaleTest extends WebTestBase { // Bulk delete and Bulk generate patterns. Assert aliases. $this->deleteAllAliases(); // Bulk create aliases. - $edit = array( + $edit = [ 'update[canonical_entities:node]' => TRUE, - ); + ]; $this->drupalPostForm('admin/config/search/path/update_bulk', $edit, t('Update')); $this->assertText(t('Generated 2 URL aliases.')); $this->assertAlias('/node/' . $english_node->id(), '/the-articles/english-node', 'en'); @@ -173,7 +179,11 @@ class PathautoLocaleTest extends WebTestBase { $pattern->save(); // Create a node with language Not Applicable. - $node = $this->createNode(['type' => 'article', 'title' => 'Test node', 'langcode' => LanguageInterface::LANGCODE_NOT_APPLICABLE]); + $node = $this->createNode([ + 'type' => 'article', + 'title' => 'Test node', + 'langcode' => LanguageInterface::LANGCODE_NOT_APPLICABLE, + ]); // Check that the generated alias has language Not Specified. $alias = \Drupal::service('pathauto.alias_storage_helper')->loadBySource('/node/' . $node->id()); @@ -190,11 +200,11 @@ class PathautoLocaleTest extends WebTestBase { protected function enableArticleTranslation() { // Enable content translation on articles. $this->drupalGet('admin/config/regional/content-language'); - $edit = array( + $edit = [ 'entity_types[node]' => TRUE, 'settings[node][article][translatable]' => TRUE, 'settings[node][article][settings][language][language_alterable]' => TRUE, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save configuration')); } diff --git a/src/Tests/PathautoMassDeleteTest.php b/src/Tests/PathautoMassDeleteTest.php index 93f4ca3..1a3e58c 100644 --- a/src/Tests/PathautoMassDeleteTest.php +++ b/src/Tests/PathautoMassDeleteTest.php @@ -19,7 +19,7 @@ class PathautoMassDeleteTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'taxonomy', 'pathauto'); + public static $modules = ['node', 'taxonomy', 'pathauto']; /** * Admin user. @@ -49,18 +49,19 @@ class PathautoMassDeleteTest extends WebTestBase { */ protected $terms; - /** - * {inheritdoc} + * Function to set up. + * + * {inheritdoc}. */ - function setUp() { + public function setUp() { parent::setUp(); - $permissions = array( + $permissions = [ 'administer pathauto', 'administer url aliases', 'create url aliases', - ); + ]; $this->adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); @@ -72,33 +73,37 @@ class PathautoMassDeleteTest extends WebTestBase { /** * Tests the deletion of all the aliases. */ - function testDeleteAll() { + public function testDeleteAll() { // 1. Test that deleting all the aliases, of any type, works. $this->generateAliases(); - $edit = array( + $edit = [ 'delete[all_aliases]' => TRUE, 'options[keep_custom_aliases]' => FALSE, - ); + ]; $this->drupalPostForm('admin/config/search/path/delete_bulk', $edit, t('Delete aliases now!')); $this->assertText(t('All of your path aliases have been deleted.')); $this->assertUrl('admin/config/search/path/delete_bulk'); // Make sure that all of them are actually deleted. - $aliases = \Drupal::database()->select('url_alias', 'ua')->fields('ua', array())->execute()->fetchAll(); - $this->assertEqual($aliases, array(), "All the aliases have been deleted."); + $aliases = \Drupal::database()->select('url_alias', 'ua')->fields('ua', [])->execute()->fetchAll(); + $this->assertEqual($aliases, [], "All the aliases have been deleted."); // 2. Test deleting only specific (entity type) aliases. $manager = $this->container->get('plugin.manager.alias_type'); - $pathauto_plugins = array('canonical_entities:node' => 'nodes', 'canonical_entities:taxonomy_term' => 'terms', 'canonical_entities:user' => 'accounts'); + $pathauto_plugins = [ + 'canonical_entities:node' => 'nodes', + 'canonical_entities:taxonomy_term' => 'terms', + 'canonical_entities:user' => 'accounts', + ]; foreach ($pathauto_plugins as $pathauto_plugin => $attribute) { $this->generateAliases(); - $edit = array( + $edit = [ 'delete[plugins][' . $pathauto_plugin . ']' => TRUE, 'options[keep_custom_aliases]' => FALSE, - ); + ]; $this->drupalPostForm('admin/config/search/path/delete_bulk', $edit, t('Delete aliases now!')); $alias_type = $manager->createInstance($pathauto_plugin); - $this->assertRaw(t('All of your %label path aliases have been deleted.', array('%label' => $alias_type->getLabel()))); + $this->assertRaw(t('All of your %label path aliases have been deleted.', ['%label' => $alias_type->getLabel()])); // Check that the aliases were actually deleted. foreach ($this->{$attribute} as $entity) { $this->assertNoEntityAlias($entity); @@ -118,10 +123,10 @@ class PathautoMassDeleteTest extends WebTestBase { // 3. Test deleting automatically generated aliases only. $this->generateAliases(); - $edit = array( + $edit = [ 'delete[all_aliases]' => TRUE, 'options[keep_custom_aliases]' => TRUE, - ); + ]; $this->drupalPostForm('admin/config/search/path/delete_bulk', $edit, t('Delete aliases now!')); $this->assertText(t('All of your automatically generated path aliases have been deleted.')); $this->assertUrl('admin/config/search/path/delete_bulk'); @@ -135,15 +140,17 @@ class PathautoMassDeleteTest extends WebTestBase { /** * Helper function to generate aliases. */ - function generateAliases() { - // Delete all aliases to avoid duplicated aliases. They will be recreated below. + public function generateAliases() { + // Delete all aliases to avoid duplicated aliases. They will be recreated + // below. $this->deleteAllAliases(); // We generate a bunch of aliases for nodes, users and taxonomy terms. If // the entities are already created we just update them, otherwise we create // them. if (empty($this->nodes)) { - // Create a large number of nodes (100+) to make sure that the batch code works. + // Create a large number of nodes (100+) to make sure that the batch code + // works. for ($i = 1; $i <= 105; $i++) { // Set the alias of two nodes manually. $settings = ($i > 103) ? ['path' => ['alias' => "/custom_alias_$i", 'pathauto' => PathautoState::SKIP]] : []; @@ -171,13 +178,13 @@ class PathautoMassDeleteTest extends WebTestBase { } } else { - foreach ($this->accounts as $id => $account) { + foreach ($this->accounts as $account) { $account->save(); } } if (empty($this->terms)) { - $vocabulary = $this->addVocabulary(array('name' => 'test vocabulary', 'vid' => 'test_vocabulary')); + $vocabulary = $this->addVocabulary(['name' => 'test vocabulary', 'vid' => 'test_vocabulary']); for ($i = 1; $i <= 5; $i++) { $term = $this->addTerm($vocabulary); $this->terms[$term->id()] = $term; @@ -190,7 +197,7 @@ class PathautoMassDeleteTest extends WebTestBase { } // Check that we have aliases for the entities. - foreach (array('nodes', 'accounts', 'terms') as $attribute) { + foreach (['nodes', 'accounts', 'terms'] as $attribute) { foreach ($this->{$attribute} as $entity) { $this->assertEntityAliasExists($entity); } diff --git a/src/Tests/PathautoNodeWebTest.php b/src/Tests/PathautoNodeWebTest.php index 95f5eb5..02be828 100644 --- a/src/Tests/PathautoNodeWebTest.php +++ b/src/Tests/PathautoNodeWebTest.php @@ -1,6 +1,7 @@ drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); - $this->drupalCreateContentType(array('type' => 'article')); + $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']); + $this->drupalCreateContentType(['type' => 'article']); // Allow other modules to add additional permissions for the admin user. - $permissions = array( + $permissions = [ 'administer pathauto', 'administer url aliases', 'create url aliases', 'administer nodes', 'bypass node access', 'access content overview', - ); + ]; $this->adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); @@ -56,15 +65,16 @@ class PathautoNodeWebTest extends WebTestBase { /** * Tests editing nodes with different settings. */ - function testNodeEditing() { - // Ensure that the Pathauto checkbox is checked by default on the node add form. + public function testNodeEditing() { + // Ensure that the Pathauto checkbox is checked by default on the node add + // form. $this->drupalGet('node/add/page'); $this->assertFieldChecked('edit-path-0-pathauto'); // Create a node by saving the node form. $title = ' Testing: node title ['; $automatic_alias = '/content/testing-node-title'; - $this->drupalPostForm(NULL, array('title[0][value]' => $title), t('Save and publish')); + $this->drupalPostForm(NULL, ['title[0][value]' => $title], t('Save and publish')); $node = $this->drupalGetNodeByTitle($title); // Look for alias generated in the form. @@ -78,12 +88,12 @@ class PathautoNodeWebTest extends WebTestBase { // Manually set the node's alias. $manual_alias = '/content/' . $node->id(); - $edit = array( + $edit = [ 'path[0][pathauto]' => FALSE, 'path[0][alias]' => $manual_alias, - ); + ]; $this->drupalPostForm($node->toUrl('edit-form'), $edit, t('Save and keep published')); - $this->assertText(t('@type @title has been updated.', array('@type' => 'page', '@title' => $title))); + $this->assertText(t('@type @title has been updated.', ['@type' => 'page', '@title' => $title])); // Check that the automatic alias checkbox is now unchecked by default. $this->drupalGet("node/{$node->id()}/edit"); @@ -91,8 +101,8 @@ class PathautoNodeWebTest extends WebTestBase { $this->assertFieldByName('path[0][alias]', $manual_alias); // Submit the node form with the default values. - $this->drupalPostForm(NULL, array('path[0][pathauto]' => FALSE), t('Save and keep published')); - $this->assertText(t('@type @title has been updated.', array('@type' => 'page', '@title' => $title))); + $this->drupalPostForm(NULL, ['path[0][pathauto]' => FALSE], t('Save and keep published')); + $this->assertText(t('@type @title has been updated.', ['@type' => 'page', '@title' => $title])); // Test that the old (automatic) alias has been deleted and only accessible // through the new (manual) alias. @@ -104,13 +114,13 @@ class PathautoNodeWebTest extends WebTestBase { // Test that the manual alias is not kept for new nodes when the pathauto // checkbox is ticked. $title = 'Automatic Title'; - $edit = array( + $edit = [ 'title[0][value]' => $title, 'path[0][pathauto]' => TRUE, 'path[0][alias]' => '/should-not-get-created', - ); + ]; $this->drupalPostForm('node/add/page', $edit, t('Save and publish')); - $this->assertNoAliasExists(array('alias' => 'should-not-get-created')); + $this->assertNoAliasExists(['alias' => 'should-not-get-created']); $node = $this->drupalGetNodeByTitle($title); $this->assertEntityAlias($node, '/content/automatic-title'); @@ -127,10 +137,10 @@ class PathautoNodeWebTest extends WebTestBase { $this->assertNoFieldById('edit-path-0-pathauto'); $this->assertFieldByName('path[0][alias]', ''); - $edit = array(); + $edit = []; $edit['title'] = 'My test article'; $this->drupalCreateNode($edit); - //$this->drupalPostForm(NULL, $edit, t('Save and keep published')); + // $this->drupalPostForm(NULL, $edit, t('Save and keep published'));. $node = $this->drupalGetNodeByTitle($edit['title']); // Pathauto checkbox should still not exist. @@ -143,9 +153,9 @@ class PathautoNodeWebTest extends WebTestBase { /** * Test node operations. */ - function testNodeOperations() { - $node1 = $this->drupalCreateNode(array('title' => 'node1')); - $node2 = $this->drupalCreateNode(array('title' => 'node2')); + public function testNodeOperations() { + $node1 = $this->drupalCreateNode(['title' => 'node1']); + $node2 = $this->drupalCreateNode(['title' => 'node2']); // Delete all current URL aliases. $this->deleteAllAliases(); @@ -160,10 +170,10 @@ class PathautoNodeWebTest extends WebTestBase { $index = 1; } - $edit = array( + $edit = [ 'action' => 'pathauto_update_alias_node', 'node_bulk_form[' . $index . ']' => TRUE, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Apply to selected items')); $this->assertText('Update URL alias was applied to 1 item.'); @@ -172,19 +182,21 @@ class PathautoNodeWebTest extends WebTestBase { } /** + * Function testNodeState(). + * * @todo Merge this with existing node test methods? */ public function testNodeState() { - $nodeNoAliasUser = $this->drupalCreateUser(array('bypass node access')); - $nodeAliasUser = $this->drupalCreateUser(array('bypass node access', 'create url aliases')); + $nodeNoAliasUser = $this->drupalCreateUser(['bypass node access']); + $nodeAliasUser = $this->drupalCreateUser(['bypass node access', 'create url aliases']); - $node = $this->drupalCreateNode(array( + $node = $this->drupalCreateNode([ 'title' => 'Node version one', 'type' => 'page', - 'path' => array( + 'path' => [ 'pathauto' => PathautoState::SKIP, - ), - )); + ], + ]); $this->assertNoEntityAlias($node); @@ -197,7 +209,8 @@ class PathautoNodeWebTest extends WebTestBase { $node = Node::load($node->id()); $this->assertIdentical($node->path->pathauto, PathautoState::SKIP); - // Ensure that the manual path alias was saved and an automatic alias was not generated. + // Ensure that the manual path alias was saved and an automatic alias was + // not generated. $this->assertEntityAlias($node, '/test-alias'); $this->assertNoEntityAliasExists($node, '/content/node-version-one'); @@ -206,7 +219,7 @@ class PathautoNodeWebTest extends WebTestBase { $this->drupalGet('node/' . $node->id() . '/edit'); $this->assertNoFieldByName('path[0][pathauto]'); - $edit = array('title[0][value]' => 'Node version two'); + $edit = ['title[0][value]' => 'Node version two']; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertText('Basic page Node version two has been updated.'); @@ -214,16 +227,17 @@ class PathautoNodeWebTest extends WebTestBase { $this->assertNoEntityAliasExists($node, '/content/node-version-one'); $this->assertNoEntityAliasExists($node, '/content/node-version-two'); - // Load the edit node page and check that the Pathauto checkbox is unchecked. + // Load the edit node page and check that the Pathauto checkbox is + // unchecked. $this->drupalLogin($nodeAliasUser); $this->drupalGet('node/' . $node->id() . '/edit'); $this->assertNoFieldChecked('edit-path-0-pathauto'); // Edit the manual alias and save the node. - $edit = array( + $edit = [ 'title[0][value]' => 'Node version three', 'path[0][alias]' => '/manually-edited-alias', - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertText('Basic page Node version three has been updated.'); @@ -254,7 +268,6 @@ class PathautoNodeWebTest extends WebTestBase { $this->assertNull(\Drupal::keyValue('pathauto_state.node')->get($node->id()), 'Pathauto state was deleted'); } - /** * Tests that nodes without a Pathauto pattern can set custom aliases. */ @@ -275,12 +288,16 @@ class PathautoNodeWebTest extends WebTestBase { $this->assertText(t('article Sample article has been created.')); // Test the alias. - $this->assertAliasExists(array('alias' => '/sample-article')); + $this->assertAliasExists(['alias' => '/sample-article']); $this->drupalGet('sample-article'); $this->assertResponse(200, 'A node without a pattern can have a custom alias.'); // Now create a node through the API. - $node = Node::create(['type' => 'article', 'title' => 'Sample article API', 'path' => ['alias' => '/sample-article-api']]); + $node = Node::create([ + 'type' => 'article', + 'title' => 'Sample article API', + 'path' => ['alias' => '/sample-article-api'], + ]); $node->save(); // Test the alias. diff --git a/src/Tests/PathautoSettingsFormWebTest.php b/src/Tests/PathautoSettingsFormWebTest.php index 9a4a690..1e3af86 100644 --- a/src/Tests/PathautoSettingsFormWebTest.php +++ b/src/Tests/PathautoSettingsFormWebTest.php @@ -19,7 +19,7 @@ class PathautoSettingsFormWebTest extends WebTestBase { * * @var array */ - public static $modules = array('node', 'pathauto'); + public static $modules = ['node', 'pathauto']; /** * Admin user. @@ -33,7 +33,7 @@ class PathautoSettingsFormWebTest extends WebTestBase { * * @var array */ - protected $defaultFormValues = array( + protected $defaultFormValues = [ 'verbose' => FALSE, 'separator' => '-', 'case' => '1', @@ -43,14 +43,14 @@ class PathautoSettingsFormWebTest extends WebTestBase { 'transliterate' => '1', 'reduce_ascii' => FALSE, 'ignore_words' => 'a, an, as, at, before, but, by, for, from, is, in, into, like, of, off, on, onto, per, since, than, the, this, that, to, up, via, with', - ); + ]; /** * Punctuation form items with default values. * * @var array */ - protected $defaultPunctuations = array( + protected $defaultPunctuations = [ 'punctuation[double_quotes]' => '0', 'punctuation[quotes]' => '0', 'punctuation[backtick]' => '0', @@ -82,24 +82,26 @@ class PathautoSettingsFormWebTest extends WebTestBase { 'punctuation[greater_than]' => '0', 'punctuation[slash]' => '0', 'punctuation[back_slash]' => '0', - ); + ]; /** - * {inheritdoc} + * Function to set up. + * + * {inheritdoc}. */ - function setUp() { + public function setUp() { parent::setUp(); - $this->drupalCreateContentType(array('type' => 'article')); + $this->drupalCreateContentType(['type' => 'article']); - $permissions = array( + $permissions = [ 'administer pathauto', 'notify of path changes', 'administer url aliases', 'create url aliases', 'administer nodes', 'bypass node access', - ); + ]; $this->adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); $this->createPattern('node', '/content/[node:title]'); @@ -108,7 +110,7 @@ class PathautoSettingsFormWebTest extends WebTestBase { /** * Test if the default values are shown correctly in the form. */ - function testDefaultFormValues() { + public function testDefaultFormValues() { $this->drupalGet('/admin/config/search/path/settings'); $this->assertNoFieldChecked('edit-verbose'); $this->assertField('edit-separator', $this->defaultFormValues['separator']); @@ -124,8 +126,8 @@ class PathautoSettingsFormWebTest extends WebTestBase { /** * Test the verbose option. */ - function testVerboseOption() { - $edit = array('verbose' => '1'); + public function testVerboseOption() { + $edit = ['verbose' => '1']; $this->drupalPostForm('/admin/config/search/path/settings', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); $this->assertFieldChecked('edit-verbose'); @@ -133,11 +135,11 @@ class PathautoSettingsFormWebTest extends WebTestBase { $title = 'Verbose settings test'; $this->drupalGet('/node/add/article'); $this->assertFieldChecked('edit-path-0-pathauto'); - $this->drupalPostForm(NULL, array('title[0][value]' => $title), t('Save and publish')); + $this->drupalPostForm(NULL, ['title[0][value]' => $title], t('Save and publish')); $this->assertText('Created new alias /content/verbose-settings-test for'); $node = $this->drupalGetNodeByTitle($title); - $this->drupalPostForm('/node/' . $node->id() . '/edit', array('title[0][value]' => 'Updated title'), t('Save and keep published')); + $this->drupalPostForm('/node/' . $node->id() . '/edit', ['title[0][value]' => 'Updated title'], t('Save and keep published')); $this->assertText('Created new alias /content/updated-title for'); $this->assertText('replacing /content/verbose-settings-test.'); } @@ -145,33 +147,33 @@ class PathautoSettingsFormWebTest extends WebTestBase { /** * Tests generating aliases with different settings. */ - function testSettingsForm() { + public function testSettingsForm() { // Ensure the separator settings apply correctly. - $this->checkAlias('My awesome content', '/content/my.awesome.content', array('separator' => '.')); + $this->checkAlias('My awesome content', '/content/my.awesome.content', ['separator' => '.']); // Ensure the character case setting works correctly. // Leave case the same as source token values. - $this->checkAlias('My awesome Content', '/content/My-awesome-Content', array('case' => FALSE)); - $this->checkAlias('Change Lower', '/content/change-lower', array('case' => '1')); + $this->checkAlias('My awesome Content', '/content/My-awesome-Content', ['case' => FALSE]); + $this->checkAlias('Change Lower', '/content/change-lower', ['case' => '1']); // Ensure the maximum alias length is working. - $this->checkAlias('My awesome Content', '/content/my-awesome', array('max_length' => '23')); + $this->checkAlias('My awesome Content', '/content/my-awesome', ['max_length' => '23']); // Ensure the maximum component length is working. - $this->checkAlias('My awesome Content', '/content/my', array('max_component_length' => '2')); + $this->checkAlias('My awesome Content', '/content/my', ['max_component_length' => '2']); // Ensure transliteration option is working. - $this->checkAlias('è é àl ö äl ü', '/content/e-e-al-o-al-u', array('transliterate' => '1')); - $this->checkAlias('è é àl äl ö ü', '/content/è-é-àl-äl-ö-ü', array('transliterate' => FALSE)); + $this->checkAlias('è é àl ö äl ü', '/content/e-e-al-o-al-u', ['transliterate' => '1']); + $this->checkAlias('è é àl äl ö ü', '/content/è-é-àl-äl-ö-ü', ['transliterate' => FALSE]); $ignore_words = 'a, new, very, should'; - $this->checkAlias('a very new alias to test', '/content/alias-to-test', array('ignore_words' => $ignore_words)); + $this->checkAlias('a very new alias to test', '/content/alias-to-test', ['ignore_words' => $ignore_words]); } /** * Test the punctuation setting form items. */ - function testPunctuationSettings() { + public function testPunctuationSettings() { // Test the replacement of punctuations. $settings = []; foreach ($this->defaultPunctuations as $key => $punctuation) { @@ -213,7 +215,7 @@ class PathautoSettingsFormWebTest extends WebTestBase { * @param array $settings * The form values the alias should be generated with. */ - protected function checkAlias($title, $alias, $settings = array()) { + protected function checkAlias($title, $alias, array $settings = []) { // Submit the settings form. $edit = array_merge($this->defaultFormValues + $this->defaultPunctuations, $settings); $this->drupalPostForm('/admin/config/search/path/settings', $edit, t('Save configuration')); @@ -225,12 +227,10 @@ class PathautoSettingsFormWebTest extends WebTestBase { \Drupal::service('pathauto.generator')->resetCaches(); // Create a node and check if the settings applied. - $node = $this->createNode( - array( - 'title' => $title, - 'type' => 'article', - ) - ); + $node = $this->createNode([ + 'title' => $title, + 'type' => 'article', + ]); $this->drupalGet($alias); $this->assertResponse(200); diff --git a/src/Tests/PathautoTaxonomyWebTest.php b/src/Tests/PathautoTaxonomyWebTest.php index e1a7e88..1a9d5ab 100644 --- a/src/Tests/PathautoTaxonomyWebTest.php +++ b/src/Tests/PathautoTaxonomyWebTest.php @@ -1,6 +1,7 @@ adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); $this->createPattern('taxonomy_term', '/[term:vocabulary]/[term:name]'); } - /** * Basic functional testing of Pathauto with taxonomy terms. */ - function testTermEditing() { + public function testTermEditing() { $this->drupalGet('admin/structure'); $this->drupalGet('admin/structure/taxonomy'); // Add vocabulary "tags". - $vocabulary = $this->addVocabulary(array('name' => 'tags', 'vid' => 'tags')); + $vocabulary = $this->addVocabulary(['name' => 'tags', 'vid' => 'tags']); // Create term for testing. $name = 'Testing: term name ['; $automatic_alias = '/tags/testing-term-name'; - $this->drupalPostForm('admin/structure/taxonomy/manage/tags/add', array('name[0][value]' => $name), 'Save'); + $this->drupalPostForm('admin/structure/taxonomy/manage/tags/add', ['name[0][value]' => $name], 'Save'); $name = trim($name); $this->assertText("Created new term $name."); $term = $this->drupalGetTermByName($name); @@ -75,10 +77,10 @@ class PathautoTaxonomyWebTest extends WebTestBase { // Manually set the term's alias. $manual_alias = '/tags/' . $term->id(); - $edit = array( + $edit = [ 'path[0][pathauto]' => FALSE, 'path[0][alias]' => $manual_alias, - ); + ]; $this->drupalPostForm("taxonomy/term/{$term->id()}/edit", $edit, t('Save')); $this->assertText("Updated term $name."); @@ -88,7 +90,7 @@ class PathautoTaxonomyWebTest extends WebTestBase { $this->assertFieldByName('path[0][alias]', $manual_alias); // Submit the term form with the default values. - $this->drupalPostForm(NULL, array('path[0][pathauto]' => FALSE), t('Save')); + $this->drupalPostForm(NULL, ['path[0][pathauto]' => FALSE], t('Save')); $this->assertText("Updated term $name."); // Test that the old (automatic) alias has been deleted and only accessible diff --git a/src/Tests/PathautoTestHelperTrait.php b/src/Tests/PathautoTestHelperTrait.php index 5fc6b40..8c70674 100644 --- a/src/Tests/PathautoTestHelperTrait.php +++ b/src/Tests/PathautoTestHelperTrait.php @@ -51,7 +51,7 @@ trait PathautoTestHelperTrait { * @param string $entity_type * The entity type ID. * @param string $bundle - * The bundle + * The bundle. */ protected function addBundleCondition(PathautoPatternInterface $pattern, $entity_type, $bundle) { $plugin_id = $entity_type == 'node' ? 'node_type' : 'entity_bundle:' . $entity_type; @@ -65,23 +65,42 @@ trait PathautoTestHelperTrait { 'negate' => FALSE, 'context_mapping' => [ $entity_type => $entity_type, - ] + ], ] ); } + /** + * Function to assert token. + */ public function assertToken($type, $object, $token, $expected) { $bubbleable_metadata = new BubbleableMetadata(); - $tokens = \Drupal::token()->generate($type, array($token => $token), array($type => $object), [], $bubbleable_metadata); - $tokens += array($token => ''); - $this->assertIdentical($tokens[$token], $expected, t("Token value for [@type:@token] was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $tokens[$token], '@expected' => $expected))); + $tokens = \Drupal::token()->generate($type, [$token => $token], [$type => $object], [], $bubbleable_metadata); + $tokens += [$token => '']; + $this->assertIdentical($tokens[$token], $expected, t("Token value for [@type:@token] was '@actual', expected value '@expected'.", [ + '@type' => $type, + '@token' => $token, + '@actual' => $tokens[$token], + '@expected' => $expected, + ])); } + /** + * Function to save alias. + */ public function saveAlias($source, $alias, $langcode = Language::LANGCODE_NOT_SPECIFIED) { - \Drupal::service('path.alias_storage')->delete(array('source' => $source, 'language', 'langcode' => $langcode)); + \Drupal::service('path.alias_storage')->delete([ + 'source' => $source, + // @codingStandardsIgnoreLine + 'language', + 'langcode' => $langcode, + ]); return \Drupal::service('path.alias_storage')->save($source, $alias, $langcode); } + /** + * Function to save entity alias. + */ public function saveEntityAlias(EntityInterface $entity, $alias, $langcode = NULL) { // By default, use the entity language. if (!$langcode) { @@ -90,18 +109,29 @@ trait PathautoTestHelperTrait { return $this->saveAlias('/' . $entity->toUrl()->getInternalPath(), $alias, $langcode); } + /** + * Function assertEntityAlias(). + */ public function assertEntityAlias(EntityInterface $entity, $expected_alias, $langcode = NULL) { // By default, use the entity language. if (!$langcode) { $langcode = $entity->language()->getId(); } - $this->assertAlias('/' . $entity->toUrl()->getInternalPath(), $expected_alias, $langcode); + $this >assertAlias('/' . $entity->toUrl()->getInternalPath(), $expected_alias, $langcode); } + /** + * Function assertEntityAliasExists(). + */ public function assertEntityAliasExists(EntityInterface $entity) { - return $this->assertAliasExists(array('source' => '/' . $entity->toUrl()->getInternalPath())); + return $this->assertAliasExists([ + 'source' => '/' . $entity->toUrl()->getInternalPath(), + ]); } + /** + * Function assertNoEntityAlias(). + */ public function assertNoEntityAlias(EntityInterface $entity, $langcode = NULL) { // By default, use the entity language. if (!$langcode) { @@ -110,31 +140,46 @@ trait PathautoTestHelperTrait { $this->assertEntityAlias($entity, '/' . $entity->toUrl()->getInternalPath(), $langcode); } + /** + * Function assertNoEntityAliasExists(). + */ public function assertNoEntityAliasExists(EntityInterface $entity, $alias = NULL) { - $path = array('source' => '/' . $entity->toUrl()->getInternalPath()); + $path = ['source' => '/' . $entity->toUrl()->getInternalPath()]; if (!empty($alias)) { $path['alias'] = $alias; } $this->assertNoAliasExists($path); } + /** + * + */ public function assertAlias($source, $expected_alias, $langcode = Language::LANGCODE_NOT_SPECIFIED) { \Drupal::service('path.alias_manager')->cacheClear($source); $this->assertEqual($expected_alias, \Drupal::service('path.alias_manager')->getAliasByPath($source, $langcode), t("Alias for %source with language '@language' is correct.", - array('%source' => $source, '@language' => $langcode))); + ['%source' => $source, '@language' => $langcode)]); } + /** + * + */ public function assertAliasExists($conditions) { $path = \Drupal::service('path.alias_storage')->load($conditions); - $this->assertTrue($path, t('Alias with conditions @conditions found.', array('@conditions' => var_export($conditions, TRUE)))); + $this->assertTrue($path, t('Alias with conditions @conditions found.', ['@conditions' => var_export($conditions, TRUE)])); return $path; } + /** + * + */ public function assertNoAliasExists($conditions) { $alias = \Drupal::service('path.alias_storage')->load($conditions); - $this->assertFalse($alias, t('Alias with conditions @conditions not found.', array('@conditions' => var_export($conditions, TRUE)))); + $this->assertFalse($alias, t('Alias with conditions @conditions not found.', ['@conditions' => var_export($conditions, TRUE)])); } + /** + * + */ public function deleteAllAliases() { \Drupal::database()->delete('url_alias')->execute(); \Drupal::service('path.alias_manager')->cacheClear(); @@ -144,31 +189,40 @@ trait PathautoTestHelperTrait { * @param array $values * @return \Drupal\taxonomy\VocabularyInterface */ - public function addVocabulary(array $values = array()) { + public function addVocabulary(array $values = []) { $name = Unicode::strtolower($this->randomMachineName(5)); - $values += array( + $values += [ 'name' => $name, 'vid' => $name, - ); + ]; $vocabulary = Vocabulary::create($values); $vocabulary->save(); return $vocabulary; } - public function addTerm(VocabularyInterface $vocabulary, array $values = array()) { - $values += array( + /** + * Add Term. + */ + public function addTerm(VocabularyInterface $vocabulary, array $values = []) { + $values += [ 'name' => Unicode::strtolower($this->randomMachineName(5)), 'vid' => $vocabulary->id(), - ); + ]; $term = Term::create($values); $term->save(); return $term; } + /** + * Function assertEntityPattern(). + * + * @codingStandardsIgnoreStart + */ public function assertEntityPattern($entity_type, $bundle, $langcode = Language::LANGCODE_NOT_SPECIFIED, $expected) { + // @codingStandardsIgnoreEnd $values = [ 'langcode' => $langcode, \Drupal::entityTypeManager()->getDefinition($entity_type)->getKey('bundle') => $bundle, @@ -179,11 +233,14 @@ trait PathautoTestHelperTrait { $this->assertIdentical($expected, $pattern->getPattern()); } + /** + * Function to Get Term. + */ public function drupalGetTermByName($name, $reset = FALSE) { if ($reset) { // @todo - implement cache reset. } - $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(array('name' => $name)); + $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['name' => $name]); return !empty($terms) ? reset($terms) : FALSE; } diff --git a/src/Tests/PathautoUiTest.php b/src/Tests/PathautoUiTest.php index a0bb436..7f78abc 100644 --- a/src/Tests/PathautoUiTest.php +++ b/src/Tests/PathautoUiTest.php @@ -19,7 +19,7 @@ class PathautoUiTest extends WebTestBase { * * @var array */ - public static $modules = array('pathauto', 'node'); + public static $modules = ['pathauto', 'node']; /** * Admin user. @@ -29,48 +29,72 @@ class PathautoUiTest extends WebTestBase { protected $adminUser; /** - * {inheritdoc} + * Function to set up. + * + * {inheritdoc}. */ - function setUp() { + public function setUp() { parent::setUp(); - $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); - $this->drupalCreateContentType(array('type' => 'article')); + $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']); + $this->drupalCreateContentType(['type' => 'article']); // Allow other modules to add additional permissions for the admin user. - $permissions = array( + $permissions = [ 'administer pathauto', 'administer url aliases', 'create url aliases', 'administer nodes', 'bypass node access', 'access content overview', - ); + ]; $this->adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); } - function testSettingsValidation() { - $edit = array(); + /** + * TestSettingsValidation. + */ + public function testSettingsValidation() { + $edit = []; $edit['max_length'] = 'abc'; $edit['max_component_length'] = 'abc'; $this->drupalPostForm('admin/config/search/path/settings', $edit, 'Save configuration'); - /*$this->assertText('The field Maximum alias length is not a valid number.'); - $this->assertText('The field Maximum component length is not a valid number.');*/ + /* + * @codingStandardsIgnoreStart + * @code + * $this->assertText('The field Maximum alias length is not a valid number.'); + * $this->assertText('The field Maximum component length is not a valid number.'); + * @endcode + * @codingStandardsIgnoreEnd + */ $this->assertNoText('The configuration options have been saved.'); $edit['max_length'] = '0'; $edit['max_component_length'] = '0'; $this->drupalPostForm('admin/config/search/path/settings', $edit, 'Save configuration'); - /*$this->assertText('The field Maximum alias length cannot be less than 1.'); - $this->assertText('The field Maximum component length cannot be less than 1.');*/ + /* + * @codingStandardsIgnoreStart + * @code + * $this->assertText('The field Maximum alias length cannot be less than 1.'); + * $this->assertText('The field Maximum component length cannot be less than 1.'); + * @endcode + * @codingStandardsIgnoreEnd + */ $this->assertNoText('The configuration options have been saved.'); $edit['max_length'] = '999'; $edit['max_component_length'] = '999'; $this->drupalPostForm('admin/config/search/path/settings', $edit, 'Save configuration'); - /*$this->assertText('The field Maximum alias length cannot be greater than 255.'); - $this->assertText('The field Maximum component length cannot be greater than 255.');*/ + /* + * @codingStandardsIgnoreStart + * @code + * $this->assertText('The field Maximum alias length cannot be greater than 255.'); + * $this->assertText('The field Maximum component length cannot be greater than 255.'); + * @endcode + * @codingStandardsIgnoreEnd + */ + $this->assertNoText('The configuration options have been saved.'); $edit['max_length'] = '50'; @@ -79,26 +103,29 @@ class PathautoUiTest extends WebTestBase { $this->assertText('The configuration options have been saved.'); } - function testPatternsWorkflow() { + /** + * Function testPatternsWorkflow(). + */ + public function testPatternsWorkflow() { // Try to save an empty pattern, should not be allowed. $this->drupalGet('admin/config/search/path/patterns/add'); - $edit = array( + $edit = [ 'type' => 'canonical_entities:node', - ); + ]; $this->drupalPostAjaxForm(NULL, $edit, 'type'); - $edit += array( + $edit += [ 'bundles[page]' => TRUE, 'label' => 'Page pattern', 'id' => 'page_pattern', - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertText('Path pattern field is required.'); $this->assertNoText('The configuration options have been saved.'); // Try to save an invalid pattern. - $edit += array( + $edit += [ 'pattern' => '[node:title]/[user:name]/[term:name]', - ); + ]; $this->drupalPostForm(NULL, $edit, 'Save'); $this->assertText('Path pattern is using the following invalid tokens: [user:name], [term:name].'); $this->assertNoText('The configuration options have been saved.'); @@ -138,7 +165,7 @@ class PathautoUiTest extends WebTestBase { $this->assertFieldChecked('edit-status'); $this->assertLink(t('Delete')); - $edit = array('label' => 'Test'); + $edit = ['label' => 'Test']; $this->drupalPostForm('/admin/config/search/path/patterns/page_pattern', $edit, t('Save')); $this->assertText('Pattern Test saved.'); // Check that the pattern weight did not change. diff --git a/src/Tests/PathautoUserWebTest.php b/src/Tests/PathautoUserWebTest.php index 54832df..095f255 100644 --- a/src/Tests/PathautoUserWebTest.php +++ b/src/Tests/PathautoUserWebTest.php @@ -1,6 +1,7 @@ adminUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->adminUser); $this->createPattern('user', '/users/[user:name]'); } - /** * Basic functional testing of Pathauto with users. */ - function testUserEditing() { + public function testUserEditing() { // There should be no Pathauto checkbox on user forms. $this->drupalGet('user/' . $this->adminUser->id() . '/edit'); $this->assertNoFieldById('path[0][pathauto]'); @@ -60,7 +62,7 @@ class PathautoUserWebTest extends WebTestBase { /** * Test user operations. */ - function testUserOperations() { + public function testUserOperations() { $account = $this->drupalCreateUser(); // Delete all current URL aliases. @@ -71,17 +73,16 @@ class PathautoUserWebTest extends WebTestBase { $view->initDisplay(); $view->preview('page_1'); - foreach ($view->result as $key => $row) { if ($view->field['name']->getValue($row) == $account->getUsername()) { break; } } - $edit = array( + $edit = [ 'action' => 'pathauto_update_alias_user', "user_bulk_form[$key]" => TRUE, - ); + ]; $this->drupalPostForm('admin/people', $edit, t('Apply to selected items')); $this->assertText('Update URL alias was applied to 1 item.'); diff --git a/src/VerboseMessenger.php b/src/VerboseMessenger.php index bc60b5c..08f8c01 100644 --- a/src/VerboseMessenger.php +++ b/src/VerboseMessenger.php @@ -49,7 +49,7 @@ class VerboseMessenger implements MessengerInterface { $this->isVerbose = $config->get('verbose') && $this->account->hasPermission('notify of path changes'); } - if (!$this->isVerbose || (isset($op) && in_array($op, array('bulkupdate', 'return')))) { + if (!$this->isVerbose || (isset($op) && in_array($op, ['bulkupdate', 'return']))) { return FALSE; } diff --git a/tests/modules/pathauto_views_test/pathauto_views_test.info.yml b/tests/modules/pathauto_views_test/pathauto_views_test.info.yml index 3392573..728f7e2 100644 --- a/tests/modules/pathauto_views_test/pathauto_views_test.info.yml +++ b/tests/modules/pathauto_views_test/pathauto_views_test.info.yml @@ -2,7 +2,6 @@ name: 'Views Test Config' type: module description: 'Provides default views for tests.' package: Testing -version: VERSION core: 8.x dependencies: - views diff --git a/tests/src/Kernel/PathautoKernelTest.php b/tests/src/Kernel/PathautoKernelTest.php index b69d437..cafd95c 100644 --- a/tests/src/Kernel/PathautoKernelTest.php +++ b/tests/src/Kernel/PathautoKernelTest.php @@ -28,24 +28,44 @@ class PathautoKernelTest extends KernelTestBase { use PathautoTestHelperTrait; - public static $modules = array('system', 'field', 'text', 'user', 'node', 'path', 'pathauto', 'taxonomy', 'token', 'filter', 'ctools', 'language'); + public static $modules = [ + 'system', + 'field', + 'text', + 'user', + 'node', + 'path', + 'pathauto', + 'taxonomy', + 'token', + 'filter', + 'ctools', + 'language', + ]; protected $currentUser; /** + * Node Pattern. + * * @var \Drupal\pathauto\PathautoPatternInterface */ protected $nodePattern; /** + * User Pattern. + * * @var \Drupal\pathauto\PathautoPatternInterface */ protected $userPattern; + /** + * Function to set up. + */ public function setUp() { parent::setup(); - $this->installConfig(array('pathauto', 'taxonomy', 'system', 'node')); + $this->installConfig(['pathauto', 'taxonomy', 'system', 'node']); $this->installEntitySchema('user'); $this->installEntitySchema('node'); @@ -53,8 +73,8 @@ class PathautoKernelTest extends KernelTestBase { ConfigurableLanguage::createFromLangcode('fr')->save(); - $this->installSchema('node', array('node_access')); - $this->installSchema('system', array('url_alias', 'sequences', 'router')); + $this->installSchema('node', ['node_access']); + $this->installSchema('system', ['url_alias', 'sequences', 'router']); $type = NodeType::create(['type' => 'page']); $type->save(); @@ -65,7 +85,7 @@ class PathautoKernelTest extends KernelTestBase { \Drupal::service('router.builder')->rebuild(); - $this->currentUser = User::create(array('name' => $this->randomMachineName())); + $this->currentUser = User::create(['name' => $this->randomMachineName()]); $this->currentUser->save(); } @@ -95,7 +115,7 @@ class PathautoKernelTest extends KernelTestBase { 'negate' => FALSE, 'context_mapping' => [ 'language' => 'node:langcode:language', - ] + ], ] ); @@ -106,8 +126,8 @@ class PathautoKernelTest extends KernelTestBase { $this->addBundleCondition($pattern, 'node', 'page'); $pattern->save(); - $tests = array( - array( + $tests = [ + [ 'entity' => 'node', 'values' => [ 'title' => 'Article fr', @@ -115,8 +135,8 @@ class PathautoKernelTest extends KernelTestBase { 'langcode' => 'fr', ], 'expected' => '/article/[node:title]', - ), - array( + ], + [ 'entity' => 'node', 'values' => [ 'title' => 'Article en', @@ -124,8 +144,8 @@ class PathautoKernelTest extends KernelTestBase { 'langcode' => 'en', ], 'expected' => '/article/en/[node:title]', - ), - array( + ], + [ 'entity' => 'node', 'values' => [ 'title' => 'Article und', @@ -133,31 +153,31 @@ class PathautoKernelTest extends KernelTestBase { 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, ], 'expected' => '/article/[node:title]', - ), - array( + ], + [ 'entity' => 'node', 'values' => [ 'title' => 'Page', 'type' => 'page', ], 'expected' => '/[node:title]', - ), - array( + ], + [ 'entity' => 'user', 'values' => [ 'name' => 'User', ], 'expected' => '/users/[user:name]', - ), - ); + ], + ]; foreach ($tests as $test) { $entity = \Drupal::entityTypeManager()->getStorage($test['entity'])->create($test['values']); $entity->save(); $actual = \Drupal::service('pathauto.generator')->getPatternByEntity($entity); - $this->assertIdentical($actual->getPattern(), $test['expected'], t("Correct pattern returned for @entity_type with @values", array( + $this->assertIdentical($actual->getPattern(), $test['expected'], t("Correct pattern returned for @entity_type with @values", [ '@entity' => $test['entity'], '@values' => print_r($test['values'], TRUE), - ))); + ])); } } @@ -190,10 +210,10 @@ class PathautoKernelTest extends KernelTestBase { public function testCleanString() { // Test with default settings defined in pathauto.settings.yml. - $this->installConfig(array('pathauto')); + $this->installConfig(['pathauto']); \Drupal::service('pathauto.generator')->resetCaches(); - $tests = array(); + $tests = []; // Test the 'ignored words' removal. $tests['this'] = 'this'; @@ -216,11 +236,11 @@ class PathautoKernelTest extends KernelTestBase { foreach ($tests as $input => $expected) { $output = \Drupal::service('pathauto.alias_cleaner')->cleanString($input); - $this->assertEqual($output, $expected, t("Drupal::service('pathauto.alias_cleaner')->cleanString('@input') expected '@expected', actual '@output'", array( + $this->assertEqual($output, $expected, t("Drupal::service('pathauto.alias_cleaner')->cleanString('@input') expected '@expected', actual '@output'", [ '@input' => $input, '@expected' => $expected, '@output' => $output, - ))); + ])); } } @@ -228,7 +248,7 @@ class PathautoKernelTest extends KernelTestBase { * Test pathauto_clean_alias(). */ public function testCleanAlias() { - $tests = array(); + $tests = []; $tests['one/two/three'] = '/one/two/three'; $tests['/one/two/three/'] = '/one/two/three'; $tests['one//two///three'] = '/one/two/three'; @@ -237,11 +257,11 @@ class PathautoKernelTest extends KernelTestBase { foreach ($tests as $input => $expected) { $output = \Drupal::service('pathauto.alias_cleaner')->cleanAlias($input); - $this->assertEqual($output, $expected, t("Drupal::service('pathauto.generator')->cleanAlias('@input') expected '@expected', actual '@output'", array( + $this->assertEqual($output, $expected, t("Drupal::service('pathauto.generator')->cleanAlias('@input') expected '@expected', actual '@output'", [ '@input' => $input, '@expected' => $expected, '@output' => $output, - ))); + ])); } } @@ -257,14 +277,17 @@ class PathautoKernelTest extends KernelTestBase { $this->saveAlias('/node/10', '/node-10-alias'); \Drupal::service('pathauto.alias_storage_helper')->deleteBySourcePrefix('/node/1'); - $this->assertNoAliasExists(array('source' => "/node/1")); - $this->assertNoAliasExists(array('source' => "/node/1/view")); - $this->assertAliasExists(array('source' => "/node/2")); - $this->assertAliasExists(array('source' => "/node/10")); + $this->assertNoAliasExists(['source' => "/node/1"]); + $this->assertNoAliasExists(['source' => "/node/1/view"]); + $this->assertAliasExists(['source' => "/node/2"]); + $this->assertAliasExists(['source' => "/node/10"]); } /** - * Test the different update actions in \Drupal::service('pathauto.generator')->createEntityAlias(). + * Test Update Actions. + * + * Test the different update actions in + * \Drupal::service('pathauto.generator')->createEntityAlias(). */ public function testUpdateActions() { $config = $this->config('pathauto.settings'); @@ -272,7 +295,7 @@ class PathautoKernelTest extends KernelTestBase { // Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'insert'. $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW); $config->save(); - $node = $this->drupalCreateNode(array('title' => 'First title')); + $node = $this->drupalCreateNode(['title' => 'First title']); $this->assertEntityAlias($node, '/content/first-title'); $node->path->pathauto = PathautoState::CREATE; @@ -283,24 +306,24 @@ class PathautoKernelTest extends KernelTestBase { $node->setTitle('Second title'); $node->save(); $this->assertEntityAlias($node, '/content/second-title'); - $this->assertNoAliasExists(array('alias' => '/content/first-title')); + $this->assertNoAliasExists(['alias' => '/content/first-title']); - // Test PATHAUTO_UPDATE_ACTION_LEAVE + // Test PATHAUTO_UPDATE_ACTION_LEAVE. $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_LEAVE); $config->save(); $node->setTitle('Third title'); $node->save(); $this->assertEntityAlias($node, '/content/third-title'); - $this->assertAliasExists(array('source' => '/' . $node->toUrl()->getInternalPath(), 'alias' => '/content/second-title')); + $this->assertAliasExists(['source' => '/' . $node->toUrl()->getInternalPath(), 'alias' => '/content/second-title']); $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_DELETE); $config->save(); $node->setTitle('Fourth title'); $node->save(); $this->assertEntityAlias($node, '/content/fourth-title'); - $this->assertNoAliasExists(array('alias' => '/content/third-title')); + $this->assertNoAliasExists(['alias' => '/content/third-title']); // The older second alias is not deleted yet. - $older_path = $this->assertAliasExists(array('source' => '/' . $node->toUrl()->getInternalPath(), 'alias' => '/content/second-title')); + $older_path = $this->assertAliasExists(['source' => '/' . $node->toUrl()->getInternalPath(), 'alias' => '/content/second-title']); \Drupal::service('path.alias_storage')->delete($older_path); $config->set('update_action', PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW); @@ -308,7 +331,7 @@ class PathautoKernelTest extends KernelTestBase { $node->setTitle('Fifth title'); $node->save(); $this->assertEntityAlias($node, '/content/fourth-title'); - $this->assertNoAliasExists(array('alias' => '/content/fifth-title')); + $this->assertNoAliasExists(['alias' => '/content/fifth-title']); // Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'update'. $this->deleteAllAliases(); @@ -323,8 +346,10 @@ class PathautoKernelTest extends KernelTestBase { } /** - * Test that \Drupal::service('pathauto.generator')->createEntityAlias() will not create an alias for a pattern - * that does not get any tokens replaced. + * Test no Tokens no Alias. + * + * Test that \Drupal::service('pathauto.generator')->createEntityAlias() will + * not create an alias for a pattern that does not get any tokens replaced. */ public function testNoTokensNoAlias() { $this->installConfig(['filter']); @@ -341,17 +366,20 @@ class PathautoKernelTest extends KernelTestBase { } /** - * Test the handling of path vs non-path tokens in pathauto_clean_token_values(). + * Test Path Tokens. + * + * Test the handling of path vs non-path tokens in + * pathauto_clean_token_values(). */ public function testPathTokens() { $this->createPattern('taxonomy_term', '/[term:parent:url:path]/[term:name]'); $vocab = $this->addVocabulary(); - $term1 = $this->addTerm($vocab, array('name' => 'Parent term')); + $term1 = $this->addTerm($vocab, ['name' => 'Parent term']); $this->assertEntityAlias($term1, '/parent-term'); - $term2 = $this->addTerm($vocab, array('name' => 'Child term', 'parent' => $term1->id())); + $term2 = $this->addTerm($vocab, ['name' => 'Child term', 'parent' => $term1->id()]); $this->assertEntityAlias($term2, '/parent-term/child-term'); $this->saveEntityAlias($term1, '/My Crazy/Alias/'); @@ -362,16 +390,19 @@ class PathautoKernelTest extends KernelTestBase { /** * Test using fields for path structures. */ - function testParentChildPathTokens() { + public function testParentChildPathTokens() { // First create a field which will be used to create the path. It must // begin with a letter. - $this->installEntitySchema('taxonomy_term'); Vocabulary::create(['vid' => 'tags'])->save(); $fieldname = 'a' . Unicode::strtolower($this->randomMachineName()); - $field_storage = FieldStorageConfig::create(['entity_type' => 'taxonomy_term', 'field_name' => $fieldname, 'type' => 'string']); + $field_storage = FieldStorageConfig::create([ + 'entity_type' => 'taxonomy_term', + 'field_name' => $fieldname, + 'type' => 'string', + ]); $field_storage->save(); $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'tags']); $field->save(); @@ -385,11 +416,20 @@ class PathautoKernelTest extends KernelTestBase { $this->createPattern('taxonomy_term', '/[term:parents:join-path]/[term:' . $fieldname . ']'); // Start by creating a parent term. - $parent = Term::create(['vid' => 'tags', $fieldname => $this->randomMachineName(), 'name' => $this->randomMachineName()]); + $parent = Term::create([ + 'vid' => 'tags', + $fieldname => $this->randomMachineName(), + 'name' => $this->randomMachineName(), + ]); $parent->save(); // Create the child term. - $child = Term::create(['vid' => 'tags', $fieldname => $this->randomMachineName(), 'parent' => $parent, 'name' => $this->randomMachineName()]); + $child = Term::create([ + 'vid' => 'tags', + $fieldname => $this->randomMachineName(), + 'parent' => $parent, + 'name' => $this->randomMachineName(), + ]); $child->save(); $this->assertEntityAlias($child, '/' . Unicode::strtolower($parent->getName() . '/' . $child->$fieldname->value)); @@ -402,8 +442,6 @@ class PathautoKernelTest extends KernelTestBase { * Tests aliases on taxonomy terms. */ public function testTaxonomyPattern() { - // Create a vocabulary and test that it's pattern variable works. - $vocab = $this->addVocabulary(array('vid' => 'name')); $this->createPattern('taxonomy_term', 'base'); $pattern = $this->createPattern('taxonomy_term', 'bundle', -1); $this->addBundleCondition($pattern, 'taxonomy_term', 'name'); @@ -411,7 +449,10 @@ class PathautoKernelTest extends KernelTestBase { $this->assertEntityPattern('taxonomy_term', 'name', Language::LANGCODE_NOT_SPECIFIED, 'bundle'); } - function testNoExistingPathAliases() { + /** + * Function test existing Path Aliases. + */ + public function testNoExistingPathAliases() { $this->config('pathauto.settings') ->set('punctuation.period', PathautoGeneratorInterface::PUNCTUATION_DO_NOTHING) ->save(); @@ -421,7 +462,7 @@ class PathautoKernelTest extends KernelTestBase { ->save(); // Check that Pathauto does not create an alias of '/admin'. - $node = $this->drupalCreateNode(array('title' => 'Admin', 'type' => 'page')); + $node = $this->drupalCreateNode(['title' => 'Admin', 'type' => 'page']); $this->assertEntityAlias($node, '/admin-0'); // Check that Pathauto does not create an alias of '/modules'. @@ -444,21 +485,21 @@ class PathautoKernelTest extends KernelTestBase { /** * Test programmatic entity creation for aliases. */ - function testProgrammaticEntityCreation() { + public function testProgrammaticEntityCreation() { $this->createPattern('taxonomy_term', '/[term:vocabulary]/[term:name]'); - $node = $this->drupalCreateNode(array('title' => 'Test node', 'path' => array('pathauto' => TRUE))); + $node = $this->drupalCreateNode(['title' => 'Test node', 'path' => ['pathauto' => TRUE]]); $this->assertEntityAlias($node, '/content/test-node'); - $vocabulary = $this->addVocabulary(array('name' => 'Tags')); - $term = $this->addTerm($vocabulary, array('name' => 'Test term', 'path' => array('pathauto' => TRUE))); + $vocabulary = $this->addVocabulary(['name' => 'Tags']); + $term = $this->addTerm($vocabulary, ['name' => 'Test term', 'path' => ['pathauto' => TRUE]]); $this->assertEntityAlias($term, '/tags/test-term'); - $edit['name'] = 'Test user'; - $edit['mail'] = 'test-user@example.com'; + $edit['name'] = 'Test user'; + $edit['mail'] = 'test-user@example.com'; $edit['pass'] = user_password(); - $edit['path'] = array('pathauto' => TRUE); + $edit['path'] = ['pathauto' => TRUE]; $edit['status'] = 1; - $account = User::create($edit); + $account = User::create($edit); $account->save(); $this->assertEntityAlias($account, '/users/test-user'); } @@ -466,17 +507,17 @@ class PathautoKernelTest extends KernelTestBase { /** * Tests word safe alias truncating. */ - function testPathAliasUniquifyWordsafe() { + public function testPathAliasUniquifyWordsafe() { $this->config('pathauto.settings') ->set('max_length', 26) ->save(); - $node_1 = $this->drupalCreateNode(array('title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page')); - $node_2 = $this->drupalCreateNode(array('title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page')); + $node_1 = $this->drupalCreateNode(['title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page']); + $node_2 = $this->drupalCreateNode(['title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page']); // Check that alias uniquifying is truncating with $wordsafe param set to // TRUE. - // If it doesn't path alias result would be content/thequick-brownf-0 + // If it doesn't path alias result would be content/thequick-brownf-0. $this->assertEntityAlias($node_1, '/content/thequick-brownfox'); $this->assertEntityAlias($node_2, '/content/thequick-0'); } @@ -484,7 +525,7 @@ class PathautoKernelTest extends KernelTestBase { /** * Test if aliases are (not) generated with enabled/disabled patterns. */ - function testPatternStatus() { + public function testPatternStatus() { // Create a node to get an alias for. $title = 'Pattern enabled'; $alias = '/content/pattern-enabled'; @@ -556,12 +597,12 @@ class PathautoKernelTest extends KernelTestBase { * @return \Drupal\node\Entity\Node * The created node. */ - protected function drupalCreateNode(array $settings = array()) { + protected function drupalCreateNode(array $settings = []) { // Populate defaults array. - $settings += array( + $settings += [ 'title' => $this->randomMachineName(8), 'type' => 'page', - ); + ]; $node = Node::create($settings); $node->save(); diff --git a/tests/src/Kernel/PathautoTokenTest.php b/tests/src/Kernel/PathautoTokenTest.php index 30c5ad1..49cde09 100644 --- a/tests/src/Kernel/PathautoTokenTest.php +++ b/tests/src/Kernel/PathautoTokenTest.php @@ -17,58 +17,75 @@ class PathautoTokenTest extends KernelTestBase { * * @var array */ - public static $modules = array('system', 'token', 'pathauto'); + public static $modules = ['system', 'token', 'pathauto']; + /** + * Function to test Pathauto Tokens. + */ public function testPathautoTokens() { - $this->installConfig(array('pathauto')); + $this->installConfig(['pathauto']); - $array = array( + $array = [ 'test first arg', 'The Array / value', - ); + ]; - $tokens = array( + $tokens = [ 'join-path' => 'test-first-arg/array-value', - ); + ]; $data['array'] = $array; $replacements = $this->assertTokens('array', $data, $tokens); - // Ensure that the cleanTokenValues() method does not alter this token value. + // Ensure that the cleanTokenValues() method does not alter this token + // value. /* @var \Drupal\pathauto\AliasCleanerInterface $alias_cleaner */ $alias_cleaner = \Drupal::service('pathauto.alias_cleaner'); - $alias_cleaner->cleanTokenValues($replacements, $data, array()); + $alias_cleaner->cleanTokenValues($replacements, $data, []); $this->assertEqual($replacements['[array:join-path]'], 'test-first-arg/array-value'); } /** * Function copied from TokenTestHelper::assertTokens(). */ - public function assertTokens($type, array $data, array $tokens, array $options = array()) { + public function assertTokens($type, array $data, array $tokens, array $options = []) { $input = $this->mapTokenNames($type, array_keys($tokens)); $bubbleable_metadata = new BubbleableMetadata(); $replacements = \Drupal::token()->generate($type, $input, $data, $options, $bubbleable_metadata); foreach ($tokens as $name => $expected) { $token = $input[$name]; if (!isset($expected)) { - $this->assertTrue(!isset($values[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token))); + $this->assertTrue(t("Token value for @token was not generated.", ['@type' => $type, '@token' => $token])); } elseif (!isset($replacements[$token])) { - $this->fail(t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token))); + $this->fail(t("Token value for @token was not generated.", ['@type' => $type, '@token' => $token])); } elseif (!empty($options['regex'])) { - $this->assertTrue(preg_match('/^' . $expected . '$/', $replacements[$token]), t("Token value for @token was '@actual', matching regular expression pattern '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected))); + $this->assertTrue(preg_match('/^' . $expected . '$/', $replacements[$token]), t("Token value for @token was '@actual', matching regular expression pattern '@expected'.", [ + '@type' => $type, + '@token' => $token, + '@actual' => $replacements[$token], + '@expected' => $expected, + ])); } else { - $this->assertIdentical($replacements[$token], $expected, t("Token value for @token was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected))); + $this->assertIdentical($replacements[$token], $expected, t("Token value for @token was '@actual', expected value '@expected'.", [ + '@type' => $type, + '@token' => $token, + '@actual' => $replacements[$token], + '@expected' => $expected, + ])); } } return $replacements; } - public function mapTokenNames($type, array $tokens = array()) { - $return = array(); + /** + * Function to Map token names. + */ + public function mapTokenNames($type, array $tokens = []) { + $return = []; foreach ($tokens as $token) { $return[$token] = "[$type:$token]"; } diff --git a/tests/src/Unit/VerboseMessengerTest.php b/tests/src/Unit/VerboseMessengerTest.php index 9567dd5..751bd2e 100644 --- a/tests/src/Unit/VerboseMessengerTest.php +++ b/tests/src/Unit/VerboseMessengerTest.php @@ -22,7 +22,7 @@ namespace Drupal\Tests\pathauto\Unit { * {@inheritdoc} */ protected function setUp() { - $config_factory = $this->getConfigFactoryStub(array('pathauto.settings' => array('verbose' => TRUE))); + $config_factory = $this->getConfigFactoryStub(['pathauto.settings' => ['verbose' => TRUE]]); $account = $this->getMock('\Drupal\Core\Session\AccountInterface'); $account->expects($this->once()) ->method('hasPermission') @@ -34,6 +34,7 @@ namespace Drupal\Tests\pathauto\Unit { /** * Tests add messages. + * * @covers ::addMessage */ public function testAddMessage() { @@ -41,19 +42,27 @@ namespace Drupal\Tests\pathauto\Unit { } /** + * Function for test do not add Message while bulkupdate. + * * @covers ::addMessage */ public function testDoNotAddMessageWhileBulkupdate() { $this->assertFalse($this->messenger->addMessage("Test message", "bulkupdate"), "The message was NOT added"); } -} + } } namespace { + // @todo Delete after https://drupal.org/node/1858196 is in. if (!function_exists('drupal_set_message')) { + + /** + * Function for set message in Drupal. + */ function drupal_set_message() { } + } }