diff --git a/css/jquery.treetable.css b/css/jquery.treetable.css index 4e95bfd..5485c58 100644 --- a/css/jquery.treetable.css +++ b/css/jquery.treetable.css @@ -3,19 +3,16 @@ table.treetable span.indenter { margin: 0; padding: 0; text-align: right; - /* Disable text selection of nodes (for better D&D UX) */ user-select: none; -khtml-user-select: none; -moz-user-select: none; -o-user-select: none; -webkit-user-select: none; - /* Force content-box box model for indenter (Bootstrap compatibility) */ -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; - width: 19px; } diff --git a/css/token.css b/css/token.css index ca201b8..069e207 100644 --- a/css/token.css +++ b/css/token.css @@ -13,7 +13,8 @@ margin-left: 0; } -.token-tree td, .token-tree th { +.token-tree td, +.token-tree th { padding-top: 0; padding-bottom: 0; } diff --git a/src/Controller/TokenAutocompleteController.php b/src/Controller/TokenAutocompleteController.php index a50da70..4a177a9 100644 --- a/src/Controller/TokenAutocompleteController.php +++ b/src/Controller/TokenAutocompleteController.php @@ -19,6 +19,9 @@ class TokenAutocompleteController extends ControllerBase { */ protected $treeBuilder; + /** + * + */ public function __construct(TreeBuilderInterface $tree_builder) { $this->treeBuilder = $tree_builder; } @@ -48,7 +51,7 @@ class TokenAutocompleteController extends ControllerBase { public function autocomplete($token_type, $filter, Request $request) { $filter = substr($filter, strrpos($filter, '[')); - $matches = array(); + $matches = []; if (!Unicode::strlen($filter)) { $matches["[{$token_type}:"] = 0; diff --git a/src/Controller/TokenCacheController.php b/src/Controller/TokenCacheController.php index 39dc5b0..36cdefd 100644 --- a/src/Controller/TokenCacheController.php +++ b/src/Controller/TokenCacheController.php @@ -7,7 +7,7 @@ use Drupal\Core\Controller\ControllerBase; /** * Clears cache for tokens. */ -class TokenCacheController extends ControllerBase { +class TokenCacheController extends ControllerBase { /** * Clear caches and redirect back to the frontpage. diff --git a/src/Controller/TokenDevelController.php b/src/Controller/TokenDevelController.php index 332bad2..ba3511c 100644 --- a/src/Controller/TokenDevelController.php +++ b/src/Controller/TokenDevelController.php @@ -24,6 +24,9 @@ class TokenDevelController extends ControllerBase { */ protected $entityMapper; + /** + * + */ public function __construct(TreeBuilderInterface $tree_builder, TokenEntityMapperInterface $entity_mapper) { $this->treeBuilder = $tree_builder; $this->entityMapper = $entity_mapper; @@ -43,10 +46,10 @@ class TokenDevelController extends ControllerBase { * Prints the loaded structure of the current entity. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match - * A RouteMatch object. + * A RouteMatch object. * * @return array - * Array of page elements to render. + * Array of page elements to render. */ public function entityTokens(RouteMatchInterface $route_match) { $output = []; @@ -88,12 +91,11 @@ class TokenDevelController extends ControllerBase { 'tokens' => $this->treeBuilder->buildTree($token_type, $options), ], ]; -// foreach ($tree as $token => $token_info) { -// if (!isset($token_info['value']) && !empty($token_info['parent']) && !isset($tree[$token_info['parent']]['value'])) { -// continue; -// } -// } - + // Foreach ($tree as $token => $token_info) { + // if (!isset($token_info['value']) && !empty($token_info['parent']) && !isset($tree[$token_info['parent']]['value'])) { + // continue; + // } + // }. $build['tokens'] = [ '#type' => 'token_tree_table', '#show_restricted' => FALSE, @@ -106,4 +108,5 @@ class TokenDevelController extends ControllerBase { return $build; } + } diff --git a/src/Controller/TokenTreeController.php b/src/Controller/TokenTreeController.php index f233ab2..36e5c47 100644 --- a/src/Controller/TokenTreeController.php +++ b/src/Controller/TokenTreeController.php @@ -18,6 +18,9 @@ class TokenTreeController extends ControllerBase { */ protected $treeBuilder; + /** + * + */ public function __construct(TreeBuilderInterface $tree_builder) { $this->treeBuilder = $tree_builder; } @@ -34,7 +37,7 @@ class TokenTreeController extends ControllerBase { /** * Page callback to output a token tree as an empty page. */ - function outputTree(Request $request) { + public function outputTree(Request $request) { $options = $request->query->has('options') ? Json::decode($request->query->get('options')) : []; // The option token_types may only be an array OR 'all'. If it is not set, diff --git a/src/Element/TokenTreeTable.php b/src/Element/TokenTreeTable.php index 6de9c95..8dc22e2 100644 --- a/src/Element/TokenTreeTable.php +++ b/src/Element/TokenTreeTable.php @@ -108,10 +108,16 @@ class TokenTreeTable extends Table { return $element; } + /** + * + */ protected static function cleanCssIdentifier($id) { return 'token-' . Html::cleanCssIdentifier(trim($id, '[]'), static::$cssFilter); } + /** + * + */ protected static function formatRow($token, $token_info, $columns, $is_group = FALSE) { $row = [ 'id' => static::cleanCssIdentifier($token), @@ -152,4 +158,5 @@ class TokenTreeTable extends Table { return $row; } + } diff --git a/src/Plugin/Derivative/DevelLocalTask.php b/src/Plugin/Derivative/DevelLocalTask.php index 5b22e84..85aa69c 100644 --- a/src/Plugin/Derivative/DevelLocalTask.php +++ b/src/Plugin/Derivative/DevelLocalTask.php @@ -9,12 +9,18 @@ use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\Core\StringTranslation\TranslationInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +/** + * + */ class DevelLocalTask extends DeriverBase implements ContainerDeriverInterface { use StringTranslationTrait; protected $entityTypeManager; + /** + * + */ public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation) { $this->entityTypeManager = $entity_type_manager; $this->stringTranslation = $string_translation; @@ -53,4 +59,5 @@ class DevelLocalTask extends DeriverBase implements ContainerDeriverInterface { return $this->derivatives; } + } diff --git a/src/Routing/RouteSubscriber.php b/src/Routing/RouteSubscriber.php index ae6815a..23806bd 100644 --- a/src/Routing/RouteSubscriber.php +++ b/src/Routing/RouteSubscriber.php @@ -24,6 +24,9 @@ class RouteSubscriber extends RouteSubscriberBase { */ protected $moduleHandler; + /** + * + */ public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler) { $this->entityTypeManager = $entity_type_manager; $this->moduleHandler = $module_handler; @@ -68,7 +71,8 @@ class RouteSubscriber extends RouteSubscriberBase { */ public static function getSubscribedEvents() { $events = parent::getSubscribedEvents(); - $events[RoutingEvents::ALTER] = array('onAlterRoutes', 100); + $events[RoutingEvents::ALTER] = ['onAlterRoutes', 100]; return $events; } + } diff --git a/src/Tests/TokenBlockTest.php b/src/Tests/TokenBlockTest.php index 66e3025..63b15ea 100644 --- a/src/Tests/TokenBlockTest.php +++ b/src/Tests/TokenBlockTest.php @@ -1,6 +1,7 @@ admin_user = $this->drupalCreateUser(array('access content', 'administer blocks')); + $this->admin_user = $this->drupalCreateUser(['access content', 'administer blocks']); $this->drupalLogin($this->admin_user); } + /** + * + */ public function testBlockTitleTokens() { $label = 'tokenblock'; - $bundle = BlockContentType::create(array( + $bundle = BlockContentType::create([ 'id' => $label, 'label' => $label, - 'revision' => FALSE - )); + 'revision' => FALSE, + ]); $bundle->save(); - $block_content = BlockContent::create(array( + $block_content = BlockContent::create([ 'type' => $label, 'label' => '[current-page:title] block title', 'info' => 'Test token title block', 'body[value]' => 'This is the test token title block.', - )); + ]); $block_content->save(); - $block = $this->drupalPlaceBlock('block_content:' . $block_content->uuid(), array( + $block = $this->drupalPlaceBlock('block_content:' . $block_content->uuid(), [ 'label' => '[user:name]', - )); + ]); $this->drupalGet($block->urlInfo()); // Ensure that the link to available tokens is present and correctly // positioned. $this->assertLink('Browse available tokens.'); $this->assertText('This field supports tokens. Browse available tokens.'); - $this->drupalPostForm(NULL, array(), t('Save block')); + $this->drupalPostForm(NULL, [], t('Save block')); // Ensure token validation is working on the block. $this->assertText('Title is using the following invalid tokens: [user:name].'); @@ -63,10 +67,11 @@ class TokenBlockTest extends TokenTestBase { $block->save(); // Ensure that tokens are not double-escaped when output as a block title. - $this->drupalCreateContentType(array('type' => 'page')); - $node = $this->drupalCreateNode(array('title' => "Site's first node")); + $this->drupalCreateContentType(['type' => 'page']); + $node = $this->drupalCreateNode(['title' => "Site's first node"]); $this->drupalGet('node/' . $node->id()); // The apostraphe should only be escaped once. $this->assertRaw("Site's first node block title"); } + } diff --git a/src/Tests/TokenCurrentPageTest.php b/src/Tests/TokenCurrentPageTest.php index cd8ac37..b2d8954 100644 --- a/src/Tests/TokenCurrentPageTest.php +++ b/src/Tests/TokenCurrentPageTest.php @@ -16,51 +16,55 @@ class TokenCurrentPageTest extends TokenTestBase { * * @var array */ - public static $modules = array('node'); + public static $modules = ['node']; - function testCurrentPageTokens() { - $tokens = array( + /** + * + */ + public function testCurrentPageTokens() { + $tokens = [ '[current-page:title]' => t('Log in'), - '[current-page:url]' => Url::fromRoute('user.login', [], array('absolute' => TRUE))->toString(), - '[current-page:url:absolute]' => Url::fromRoute('user.login', [], array('absolute' => TRUE))->toString(), + '[current-page:url]' => Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString(), + '[current-page:url:absolute]' => Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString(), '[current-page:url:relative]' => Url::fromRoute('user.login')->toString(), '[current-page:url:path]' => '/user/login', '[current-page:url:args:value:0]' => 'user', '[current-page:url:args:value:1]' => 'login', '[current-page:url:args:value:2]' => NULL, - '[current-page:url:unaliased]' => Url::fromRoute('user.login', [], array('absolute' => TRUE, 'alias' => TRUE))->toString(), + '[current-page:url:unaliased]' => Url::fromRoute('user.login', [], ['absolute' => TRUE, 'alias' => TRUE])->toString(), '[current-page:page-number]' => 1, '[current-page:query:foo]' => NULL, '[current-page:query:bar]' => NULL, - // Deprecated tokens + // Deprecated tokens. '[current-page:arg:0]' => 'user', '[current-page:arg:1]' => 'login', '[current-page:arg:2]' => NULL, - ); + ]; $this->assertPageTokens('user/login', $tokens); - $this->drupalCreateContentType(array('type' => 'page')); - $node = $this->drupalCreateNode(array('title' => 'Node title', 'path' => array('alias' => '/node-alias'))); - $tokens = array( + $this->drupalCreateContentType(['type' => 'page']); + $node = $this->drupalCreateNode(['title' => 'Node title', 'path' => ['alias' => '/node-alias']]); + $tokens = [ '[current-page:title]' => 'Node title', - '[current-page:url]' => $node->url('canonical', array('absolute' => TRUE)), - '[current-page:url:absolute]' => $node->url('canonical', array('absolute' => TRUE)), + '[current-page:url]' => $node->url('canonical', ['absolute' => TRUE]), + '[current-page:url:absolute]' => $node->url('canonical', ['absolute' => TRUE]), '[current-page:url:relative]' => $node->url(), '[current-page:url:alias]' => '/node-alias', '[current-page:url:args:value:0]' => 'node-alias', '[current-page:url:args:value:1]' => NULL, - '[current-page:url:unaliased]' => $node->url('canonical', array('absolute' => TRUE, 'alias' => TRUE)), + '[current-page:url:unaliased]' => $node->url('canonical', ['absolute' => TRUE, 'alias' => TRUE]), '[current-page:url:unaliased:args:value:0]' => 'node', '[current-page:url:unaliased:args:value:1]' => $node->id(), '[current-page:url:unaliased:args:value:2]' => NULL, '[current-page:page-number]' => 1, '[current-page:query:foo]' => 'bar', '[current-page:query:bar]' => NULL, - // Deprecated tokens + // Deprecated tokens. '[current-page:arg:0]' => 'node', '[current-page:arg:1]' => 1, '[current-page:arg:2]' => NULL, - ); - $this->assertPageTokens("/node/{$node->id()}", $tokens, array(), array('url_options' => array('query' => array('foo' => 'bar')))); + ]; + $this->assertPageTokens("/node/{$node->id()}", $tokens, [], ['url_options' => ['query' => ['foo' => 'bar']]]); } + } diff --git a/src/Tests/TokenFieldUiTest.php b/src/Tests/TokenFieldUiTest.php index f7983e7..f8aeb73 100644 --- a/src/Tests/TokenFieldUiTest.php +++ b/src/Tests/TokenFieldUiTest.php @@ -41,50 +41,50 @@ class TokenFieldUiTest extends TokenTestBase { ]); $node_type->save(); - entity_create('field_storage_config', array( + entity_create('field_storage_config', [ 'field_name' => 'field_body', 'entity_type' => 'node', 'type' => 'text_with_summary', - ))->save(); - entity_create('field_config', array( + ])->save(); + entity_create('field_config', [ 'field_name' => 'field_body', 'label' => 'Body', 'entity_type' => 'node', 'bundle' => 'article', - ))->save(); - entity_create('field_storage_config', array( + ])->save(); + entity_create('field_storage_config', [ 'field_name' => 'field_image', 'entity_type' => 'node', 'type' => 'image', - ))->save(); - entity_create('field_config', array( + ])->save(); + entity_create('field_config', [ 'field_name' => 'field_image', 'label' => 'Image', 'entity_type' => 'node', 'bundle' => 'article', - ))->save(); - entity_create('field_storage_config', array( + ])->save(); + entity_create('field_storage_config', [ 'field_name' => 'field_image_2', 'entity_type' => 'node', 'type' => 'image', - ))->save(); - entity_create('field_config', array( + ])->save(); + entity_create('field_config', [ 'field_name' => 'field_image_2', 'label' => 'Image 2', 'entity_type' => 'node', 'bundle' => 'article', - ))->save(); - entity_create('field_storage_config', array( + ])->save(); + entity_create('field_storage_config', [ 'field_name' => 'multivalued_field_image', 'entity_type' => 'node', 'type' => 'image', - ))->save(); - entity_create('field_config', array( + ])->save(); + entity_create('field_config', [ 'field_name' => 'multivalued_field_image', 'label' => 'Multivalued field image', 'entity_type' => 'node', 'bundle' => 'article', - ))->save(); + ])->save(); entity_get_form_display('node', 'article', 'default') ->setComponent('field_body', [ @@ -98,6 +98,9 @@ class TokenFieldUiTest extends TokenTestBase { ->save(); } + /** + * + */ public function testFileFieldUi() { $this->drupalGet('admin/structure/types/manage/article/fields/node.article.field_image'); @@ -110,6 +113,9 @@ class TokenFieldUiTest extends TokenTestBase { $this->assertText(t('Saved Image configuration.')); } + /** + * + */ public function testFieldDescriptionTokens() { $edit = [ 'description' => 'The site is called [site:name].', @@ -191,7 +197,7 @@ class TokenFieldUiTest extends TokenTestBase { unlink('public://styles/large/public/example2-test.gif'); $tokens = [ - // field_image + // field_image. 'field_image:thumbnail:mimetype' => 'image/png', 'field_image:medium:mimetype' => 'image/png', 'field_image:large:mimetype' => 'image/png', @@ -213,7 +219,7 @@ class TokenFieldUiTest extends TokenTestBase { 'field_image:thumbnail' => $style_thumbnail->buildUrl('public://example1.png'), 'field_image:medium' => $style_medium->buildUrl('public://example1.png'), 'field_image:large' => $style_large->buildUrl('public://example1.png'), - // field_image_2 + // field_image_2. 'field_image_2:thumbnail:mimetype' => 'image/gif', 'field_image_2:medium:mimetype' => 'image/gif', 'field_image_2:large:mimetype' => 'image/gif', diff --git a/src/Tests/TokenMenuTest.php b/src/Tests/TokenMenuTest.php index b9eb920..1b76bba 100644 --- a/src/Tests/TokenMenuTest.php +++ b/src/Tests/TokenMenuTest.php @@ -6,7 +6,6 @@ use Drupal\node\Entity\Node; use Drupal\Core\Url; use Drupal\node\Entity\NodeType; use Drupal\language\Entity\ConfigurableLanguage; -use Drupal\Core\Language\LanguageInterface; use Drupal\system\Entity\Menu; use Drupal\menu_link_content\Entity\MenuLinkContent; @@ -31,15 +30,18 @@ class TokenMenuTest extends TokenTestBase { 'content_translation', ]; - function testMenuTokens() { + /** + * + */ + public function testMenuTokens() { // Make sure we have a body field on the node type. $this->drupalCreateContentType(['type' => 'page']); // Add a menu. - $menu = entity_create('menu', array( + $menu = entity_create('menu', [ 'id' => 'main-menu', 'label' => 'Main menu', 'description' => 'The Main menu is used on many sites to show the major sections of the site, often in a top navigation bar.', - )); + ]); $menu->save(); // Place the menu block. @@ -47,25 +49,25 @@ class TokenMenuTest extends TokenTestBase { // Add a root link. /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $root_link */ - $root_link = entity_create('menu_link_content', array( + $root_link = entity_create('menu_link_content', [ 'link' => ['uri' => 'internal:/admin'], 'title' => 'Administration', 'menu_name' => 'main-menu', - )); + ]); $root_link->save(); // Add another link with the root link as the parent. /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $parent_link */ - $parent_link = entity_create('menu_link_content', array( + $parent_link = entity_create('menu_link_content', [ 'link' => ['uri' => 'internal:/admin/config'], 'title' => 'Configuration', 'menu_name' => 'main-menu', 'parent' => $root_link->getPluginId(), - )); + ]); $parent_link->save(); // Test menu link tokens. - $tokens = array( + $tokens = [ 'id' => $parent_link->getPluginId(), 'title' => 'Configuration', 'menu' => 'Main menu', @@ -73,13 +75,13 @@ class TokenMenuTest extends TokenTestBase { 'menu:machine-name' => $menu->id(), 'menu:description' => 'The Main menu is used on many sites to show the major sections of the site, often in a top navigation bar.', 'menu:menu-link-count' => '2', - 'menu:edit-url' => Url::fromRoute('entity.menu.edit_form', ['menu' => 'main-menu'], array('absolute' => TRUE))->toString(), - 'url' => Url::fromRoute('system.admin_config', [], array('absolute' => TRUE))->toString(), - 'url:absolute' => Url::fromRoute('system.admin_config', [], array('absolute' => TRUE))->toString(), - 'url:relative' => Url::fromRoute('system.admin_config', [], array('absolute' => FALSE))->toString(), + 'menu:edit-url' => Url::fromRoute('entity.menu.edit_form', ['menu' => 'main-menu'], ['absolute' => TRUE])->toString(), + 'url' => Url::fromRoute('system.admin_config', [], ['absolute' => TRUE])->toString(), + 'url:absolute' => Url::fromRoute('system.admin_config', [], ['absolute' => TRUE])->toString(), + 'url:relative' => Url::fromRoute('system.admin_config', [], ['absolute' => FALSE])->toString(), 'url:path' => '/admin/config', 'url:alias' => '/admin/config', - 'edit-url' => Url::fromRoute('entity.menu_link_content.canonical', ['menu_link_content' => $parent_link->id()], array('absolute' => TRUE))->toString(), + 'edit-url' => Url::fromRoute('entity.menu_link_content.canonical', ['menu_link_content' => $parent_link->id()], ['absolute' => TRUE])->toString(), 'parent' => 'Administration', 'parent:id' => $root_link->getPluginId(), 'parent:title' => 'Administration', @@ -92,27 +94,26 @@ class TokenMenuTest extends TokenTestBase { 'root:id' => $root_link->getPluginId(), 'root:parent' => NULL, 'root:root' => NULL, - ); - $this->assertTokens('menu-link', array('menu-link' => $parent_link), $tokens); + ]; + $this->assertTokens('menu-link', ['menu-link' => $parent_link], $tokens); // Add a node. $node = $this->drupalCreateNode(); // Allow main menu for this node type. - //$this->config('menu.entity.node.' . $node->getType())->set('available_menus', array('main-menu'))->save(); - + // $this->config('menu.entity.node.' . $node->getType())->set('available_menus', array('main-menu'))->save(); // Add a node menu link. /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $node_link */ - $node_link = entity_create('menu_link_content', array( - 'link' => ['uri' =>'entity:node/' . $node->id()], + $node_link = entity_create('menu_link_content', [ + 'link' => ['uri' => 'entity:node/' . $node->id()], 'title' => 'Node link', 'parent' => $parent_link->getPluginId(), 'menu_name' => 'main-menu', - )); + ]); $node_link->save(); // Test [node:menu] tokens. - $tokens = array( + $tokens = [ 'menu-link' => 'Node link', 'menu-link:id' => $node_link->getPluginId(), 'menu-link:title' => 'Node link', @@ -127,12 +128,12 @@ class TokenMenuTest extends TokenTestBase { 'menu-link:parents:keys' => $root_link->getPluginId() . ', ' . $parent_link->getPluginId(), 'menu-link:root' => 'Administration', 'menu-link:root:id' => $root_link->getPluginId(), - ); - $this->assertTokens('node', array('node' => $node), $tokens); + ]; + $this->assertTokens('node', ['node' => $node], $tokens); // Reload the node which will not have $node->menu defined and re-test. $loaded_node = Node::load($node->id()); - $this->assertTokens('node', array('node' => $loaded_node), $tokens); + $this->assertTokens('node', ['node' => $loaded_node], $tokens); // Regression test for http://drupal.org/node/1317926 to ensure the // original node object is not changed when calling menu_node_prepare(). @@ -148,11 +149,11 @@ class TokenMenuTest extends TokenTestBase { 'access administration pages', ])); // Setup node type menu options. - $edit = array( + $edit = [ 'menu_options[main-menu]' => 1, 'menu_options[main]' => 1, 'menu_parent' => 'main-menu:', - ); + ]; $this->drupalPostForm('admin/structure/types/manage/page', $edit, t('Save content type')); // Use a menu-link token in the body. @@ -186,7 +187,7 @@ class TokenMenuTest extends TokenTestBase { $select = reset($selects); $options = $this->getAllOptions($select); // Filter to items with title containing 'Test preview'. - $options = array_filter($options, function(\SimpleXMLElement $item) { + $options = array_filter($options, function (\SimpleXMLElement $item) { return strpos((string) $item[0], 'Test preview') !== FALSE; }); $this->assertEqual(1, count($options)); @@ -195,14 +196,14 @@ class TokenMenuTest extends TokenTestBase { 'body[0][value]' => 'This is a [node:menu-link:parent:url:path] token to the menu link parent', 'menu[enabled]' => 1, 'menu[title]' => 'Child link', - 'menu[menu_parent]' => 'main-menu:' . $parent_link->getPluginId(), + 'menu[menu_parent]' => 'main-menu:' . $parent_link->getPluginId(), ], t('Save and publish')); $node = $this->drupalGetNodeByTitle('Node menu title parent path test'); $this->assertEqual('This is a /admin/config token to the menu link parent', $node->body->value); // Now edit the node and update the parent and title. $this->drupalPostForm('node/' . $node->id() . '/edit', [ - 'menu[menu_parent]' => 'main-menu:' . $node_link->getPluginId(), + 'menu[menu_parent]' => 'main-menu:' . $node_link->getPluginId(), 'title[0][value]' => 'Node menu title edit parent path test', 'body[0][value]' => 'This is a [node:menu-link:parent:url:path] token to the menu link parent', ], t('Save and keep published')); @@ -218,7 +219,7 @@ class TokenMenuTest extends TokenTestBase { $select = reset($selects); $options = $this->getAllOptions($select); // Filter to items with title containing 'Test preview'. - $options = array_filter($options, function(\SimpleXMLElement $item) { + $options = array_filter($options, function (\SimpleXMLElement $item) { return strpos((string) $item[0], 'Child link') !== FALSE; }); $this->assertEqual(1, count($options)); @@ -238,7 +239,7 @@ class TokenMenuTest extends TokenTestBase { 'body[0][value]' => 'This is a [node:menu-link:parent:url:path] token to the menu link parent', 'menu[enabled]' => 1, 'menu[title]' => 'Child link', - 'menu[menu_parent]' => 'main-menu:' . $parent_link->getPluginId(), + 'menu[menu_parent]' => 'main-menu:' . $parent_link->getPluginId(), ], t('Save and keep published')); $node = $this->drupalGetNodeByTitle('Node menu adding menu later test', TRUE); $this->assertEqual('This is a /admin/config token to the menu link parent', $node->body->value); @@ -289,7 +290,7 @@ class TokenMenuTest extends TokenTestBase { * Tests that the module doesn't affect integrity of the menu, when * translating them and that menu links tokens are correct. */ - function testMultilingualMenu() { + public function testMultilingualMenu() { // Place the menu block. $this->drupalPlaceBlock('system_menu_block:main'); @@ -306,7 +307,7 @@ class TokenMenuTest extends TokenTestBase { ]); $node_type->save(); - $permissions = array( + $permissions = [ 'access administration pages', 'administer content translation', 'administer content types', @@ -316,18 +317,18 @@ class TokenMenuTest extends TokenTestBase { 'edit any article content', 'translate any entity', 'administer menu', - ); + ]; $this->drupalLogin($this->drupalCreateUser($permissions)); // Enable translation for articles and menu links. $this->drupalGet('admin/config/regional/content-language'); - $edit = array( + $edit = [ 'entity_types[node]' => TRUE, 'entity_types[menu_link_content]' => TRUE, 'settings[node][article][translatable]' => TRUE, 'settings[node][article][fields][title]' => TRUE, 'settings[menu_link_content][menu_link_content][translatable]' => TRUE, - ); + ]; $this->drupalPostForm(NULL, $edit, t('Save configuration')); $this->assertText('Settings successfully updated.'); @@ -379,11 +380,11 @@ class TokenMenuTest extends TokenTestBase { 'menu_name' => 'menu_test', ]; $child_1 = $base_options + [ - 'title' => 'child_1 title EN', - 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent/child_1'], - 'parent' => $link->getPluginId(), - 'langcode' => 'en', - ]; + 'title' => 'child_1 title EN', + 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent/child_1'], + 'parent' => $link->getPluginId(), + 'langcode' => 'en', + ]; $child_1 = MenuLinkContent::create($child_1); $child_1->save(); @@ -410,32 +411,32 @@ class TokenMenuTest extends TokenTestBase { // Create a menu with a simple link hierarchy : // - parent // - child-1 - // - child-1-1 - Menu::create(array( + // - child-1-1. + Menu::create([ 'id' => 'menu_test', 'label' => 'Test menu', - ))->save(); + ])->save(); $base_options = [ 'provider' => 'menu_test', 'menu_name' => 'menu_test', ]; $parent = $base_options + [ - 'title' => 'parent title', - 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent'], + 'title' => 'parent title', + 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent'], ]; $parent = MenuLinkContent::create($parent); $parent->save(); $child_1 = $base_options + [ - 'title' => 'child_1 title', - 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent/child_1'], - 'parent' => $parent->getPluginId(), + 'title' => 'child_1 title', + 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent/child_1'], + 'parent' => $parent->getPluginId(), ]; $child_1 = MenuLinkContent::create($child_1); $child_1->save(); $child_1_1 = $base_options + [ - 'title' => 'child_1_1 title', - 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent/child_1/child_1_1'], - 'parent' => $child_1->getPluginId(), + 'title' => 'child_1_1 title', + 'link' => ['uri' => 'internal:/menu-test/hierarchy/parent/child_1/child_1_1'], + 'parent' => $child_1->getPluginId(), ]; $child_1_1 = MenuLinkContent::create($child_1_1); $child_1_1->save(); diff --git a/src/Tests/TokenTestBase.php b/src/Tests/TokenTestBase.php index 29c1ac3..814ba77 100644 --- a/src/Tests/TokenTestBase.php +++ b/src/Tests/TokenTestBase.php @@ -16,6 +16,6 @@ abstract class TokenTestBase extends WebTestBase { * * @var array */ - public static $modules = array('path', 'token', 'token_module_test'); + public static $modules = ['path', 'token', 'token_module_test']; } diff --git a/src/Tests/TokenTestTrait.php b/src/Tests/TokenTestTrait.php index b37cae9..7177b13 100644 --- a/src/Tests/TokenTestTrait.php +++ b/src/Tests/TokenTestTrait.php @@ -11,62 +11,80 @@ use Drupal\Core\Render\BubbleableMetadata; */ trait TokenTestTrait { - function assertToken($type, array $data, $token, $expected, array $options = array()) { - return $this->assertTokens($type, $data, array($token => $expected), $options); + /** + * + */ + public function assertToken($type, array $data, $token, $expected, array $options = []) { + return $this->assertTokens($type, $data, [$token => $expected], $options); } - 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($replacements[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token))); + $this->assertTrue(!isset($replacements[$token]), 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->assertEqual($replacements[$token], $expected, t("Token value for @token was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected))); + $this->assertEqual($replacements[$token], $expected, t("Token value for @token was '@actual', expected value '@expected'.", ['@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected])); } } return $replacements; } - function mapTokenNames($type, array $tokens = array()) { - $return = array(); + /** + * + */ + public function mapTokenNames($type, array $tokens = []) { + $return = []; foreach ($tokens as $token) { $return[$token] = "[$type:$token]"; } return $return; } - function assertNoTokens($type, array $data, array $tokens, array $options = array()) { + /** + * + */ + public function assertNoTokens($type, array $data, array $tokens, array $options = []) { $input = $this->mapTokenNames($type, $tokens); $bubbleable_metadata = new BubbleableMetadata(); $replacements = \Drupal::token()->generate($type, $input, $data, $options, $bubbleable_metadata); foreach ($tokens as $name) { $token = $input[$name]; - $this->assertTrue(!isset($replacements[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token))); + $this->assertTrue(!isset($replacements[$token]), t("Token value for @token was not generated.", ['@type' => $type, '@token' => $token])); } } - function saveAlias($source, $alias, $language = Language::LANGCODE_NOT_SPECIFIED) { - $alias = array( + /** + * + */ + public function saveAlias($source, $alias, $language = Language::LANGCODE_NOT_SPECIFIED) { + $alias = [ 'source' => $source, 'alias' => $alias, 'language' => $language, - ); + ]; \Drupal::service('path.alias_storage')->save($alias['source'], $alias['alias']); return $alias; } - function saveEntityAlias($entity_type, EntityInterface $entity, $alias, $language = Language::LANGCODE_NOT_SPECIFIED) { + /** + * + */ + public function saveEntityAlias($entity_type, EntityInterface $entity, $alias, $language = Language::LANGCODE_NOT_SPECIFIED) { $uri = $entity->toUrl()->toArray(); return $this->saveAlias($uri['path'], $alias, $language); } @@ -74,22 +92,22 @@ trait TokenTestTrait { /** * Make a page request and test for token generation. */ - function assertPageTokens($url, array $tokens, array $data = array(), array $options = array()) { + public function assertPageTokens($url, array $tokens, array $data = [], array $options = []) { if (empty($tokens)) { return TRUE; } - $token_page_tokens = array( + $token_page_tokens = [ 'tokens' => $tokens, 'data' => $data, 'options' => $options, - ); + ]; \Drupal::state()->set('token_page_tokens', $token_page_tokens); - $options += array('url_options' => array()); + $options += ['url_options' => []]; $this->drupalGet($url, $options['url_options']); $this->refreshVariables(); - $result = \Drupal::state()->get('token_page_tokens', array()); + $result = \Drupal::state()->get('token_page_tokens', []); if (!isset($result['values']) || !is_array($result['values'])) { return $this->fail('Failed to generate tokens.'); @@ -97,13 +115,13 @@ trait TokenTestTrait { foreach ($tokens as $token => $expected) { if (!isset($expected)) { - $this->assertTrue(!isset($result['values'][$token]) || $result['values'][$token] === $token, t("Token value for @token was not generated.", array('@token' => $token))); + $this->assertTrue(!isset($result['values'][$token]) || $result['values'][$token] === $token, t("Token value for @token was not generated.", ['@token' => $token])); } elseif (!isset($result['values'][$token])) { - $this->fail(t('Failed to generate token @token.', array('@token' => $token))); + $this->fail(t('Failed to generate token @token.', ['@token' => $token])); } else { - $this->assertIdentical($result['values'][$token], (string) $expected, t("Token value for @token was '@actual', expected value '@expected'.", array('@token' => $token, '@actual' => $result['values'][$token], '@expected' => $expected))); + $this->assertIdentical($result['values'][$token], (string) $expected, t("Token value for @token was '@actual', expected value '@expected'.", ['@token' => $token, '@actual' => $result['values'][$token], '@expected' => $expected])); } } } diff --git a/src/Tests/TokenURLTest.php b/src/Tests/TokenURLTest.php index 6241f3b..9152f8a 100644 --- a/src/Tests/TokenURLTest.php +++ b/src/Tests/TokenURLTest.php @@ -16,7 +16,7 @@ class TokenURLTest extends TokenTestBase { * * @var array */ - public static $modules = array('node'); + public static $modules = ['node']; /** * {@inheritdoc} @@ -26,26 +26,30 @@ class TokenURLTest extends TokenTestBase { $this->saveAlias('/node/1', '/first-node'); } - function testURLTokens() { - $url = new Url('entity.node.canonical', array('node' => 1)); - $tokens = array( + /** + * + */ + public function testURLTokens() { + $url = new Url('entity.node.canonical', ['node' => 1]); + $tokens = [ 'absolute' => $url->setAbsolute()->toString(), 'relative' => $url->setAbsolute(FALSE)->toString(), 'path' => '/first-node', - 'brief' => preg_replace(array('!^https?://!', '!/$!'), '', $url->setAbsolute()->toString()), + 'brief' => preg_replace(['!^https?://!', '!/$!'], '', $url->setAbsolute()->toString()), 'args:value:0' => 'first-node', 'args:value:1' => NULL, 'args:value:N' => NULL, 'unaliased' => $url->setAbsolute()->setOption('alias', TRUE)->toString(), 'unaliased:relative' => $url->setAbsolute(FALSE)->setOption('alias', TRUE)->toString(), 'unaliased:path' => '/node/1', - 'unaliased:brief' => preg_replace(array('!^https?://!', '!/$!'), '', $url->setAbsolute()->setOption('alias', TRUE)->toString()), + 'unaliased:brief' => preg_replace(['!^https?://!', '!/$!'], '', $url->setAbsolute()->setOption('alias', TRUE)->toString()), 'unaliased:args:value:0' => 'node', 'unaliased:args:value:1' => '1', 'unaliased:args:value:2' => NULL, // Deprecated tokens. 'alias' => '/first-node', - ); - $this->assertTokens('url', array('url' => new Url('entity.node.canonical', array('node' => 1))), $tokens); + ]; + $this->assertTokens('url', ['url' => new Url('entity.node.canonical', ['node' => 1])], $tokens); } + } diff --git a/src/Tests/TokenUserTest.php b/src/Tests/TokenUserTest.php index 2178c7e..f5502db 100644 --- a/src/Tests/TokenUserTest.php +++ b/src/Tests/TokenUserTest.php @@ -24,7 +24,7 @@ class TokenUserTest extends TokenTestBase { * * @var array */ - public static $modules = array('token_user_picture'); + public static $modules = ['token_user_picture']; /** * {@inheritdoc} @@ -36,6 +36,9 @@ class TokenUserTest extends TokenTestBase { $this->drupalLogin($this->account); } + /** + * + */ public function testUserTokens() { // Enable user pictures. \Drupal::state()->set('user_pictures', 1); @@ -49,7 +52,7 @@ class TokenUserTest extends TokenTestBase { // Add a user picture to the account. $image = current($this->drupalGetTestFiles('image')); - $edit = array('files[user_picture_0]' => drupal_realpath($image->uri)); + $edit = ['files[user_picture_0]' => drupal_realpath($image->uri)]; $this->drupalPostForm('user/' . $this->account->id() . '/edit', $edit, t('Save')); $storage = \Drupal::entityTypeManager()->getStorage('user'); @@ -65,14 +68,14 @@ class TokenUserTest extends TokenTestBase { ]; /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); - $user_tokens = array( + $user_tokens = [ 'picture' => $renderer->renderPlain($picture), 'picture:fid' => $this->account->user_picture->target_id, 'picture:size-raw' => 125, 'ip-address' => NULL, 'roles' => implode(', ', $this->account->getRoles()), - ); - $this->assertTokens('user', array('user' => $this->account), $user_tokens); + ]; + $this->assertTokens('user', ['user' => $this->account], $user_tokens); // Remove the simpletest-created user role. $roles = $this->account->getRoles(); @@ -84,33 +87,37 @@ class TokenUserTest extends TokenTestBase { $storage->resetCache(); $this->account = $storage->load($this->account->id()); - $user_tokens = array( + $user_tokens = [ 'picture' => NULL, 'picture:fid' => NULL, 'ip-address' => NULL, 'roles' => 'authenticated', 'roles:keys' => (string) DRUPAL_AUTHENTICATED_RID, - ); - $this->assertTokens('user', array('user' => $this->account), $user_tokens); + ]; + $this->assertTokens('user', ['user' => $this->account], $user_tokens); // The ip address token should work for the current user token type. - $tokens = array( + $tokens = [ 'ip-address' => \Drupal::request()->getClientIp(), - ); - $this->assertTokens('current-user', array(), $tokens); + ]; + $this->assertTokens('current-user', [], $tokens); $anonymous = new AnonymousUserSession(); - $tokens = array( + $tokens = [ 'roles' => 'anonymous', 'roles:keys' => (string) DRUPAL_ANONYMOUS_RID, - ); - $this->assertTokens('user', array('user' => $anonymous), $tokens); + ]; + $this->assertTokens('user', ['user' => $anonymous], $tokens); } + /** + * + */ public function testUserAccountSettings() { $this->drupalGet('admin/config/people/accounts'); $this->assertText('The list of available tokens that can be used in e-mails is provided below.'); $this->assertLink('Browse available tokens.'); $this->assertLinkByHref('token/tree'); } -} \ No newline at end of file + +} diff --git a/src/Tests/Tree/AutocompleteTest.php b/src/Tests/Tree/AutocompleteTest.php index 30b3ea4..f217a67 100644 --- a/src/Tests/Tree/AutocompleteTest.php +++ b/src/Tests/Tree/AutocompleteTest.php @@ -58,4 +58,5 @@ class AutocompleteTest extends TokenTestBase { $this->assertTrue(isset($response['[user:original:uid]'])); } + } diff --git a/src/Tests/Tree/HelpPageTest.php b/src/Tests/Tree/HelpPageTest.php index a957e32..e912a41 100644 --- a/src/Tests/Tree/HelpPageTest.php +++ b/src/Tests/Tree/HelpPageTest.php @@ -25,6 +25,9 @@ class HelpPageTest extends TokenTestBase { */ public static $modules = ['help']; + /** + * + */ public function setUp() { parent::setUp(); diff --git a/src/Tests/Tree/TokenTreeTestTrait.php b/src/Tests/Tree/TokenTreeTestTrait.php index dc70a23..cf2215b 100644 --- a/src/Tests/Tree/TokenTreeTestTrait.php +++ b/src/Tests/Tree/TokenTreeTestTrait.php @@ -128,4 +128,5 @@ trait TokenTreeTestTrait { $xpath .= '/td[contains(@class, "token-key") and text() = "' . $token . '"]'; return $xpath; } + } diff --git a/src/Tests/Tree/TreeTest.php b/src/Tests/Tree/TreeTest.php index ed1dd3c..dba8796 100644 --- a/src/Tests/Tree/TreeTest.php +++ b/src/Tests/Tree/TreeTest.php @@ -26,6 +26,9 @@ class TreeTest extends TokenTestBase { */ public static $modules = ['node']; + /** + * + */ public function setUp() { parent::setUp(); @@ -137,7 +140,7 @@ class TreeTest extends TokenTestBase { protected function getTokenTreeUrl($options = []) { $this->drupalGet('token_module_test/browse'); $this->assertTitle('Available Tokens | Drupal'); - $links = $this->xpath('//a[contains(@href, :href)]/@href', array(':href' => 'token/tree')); + $links = $this->xpath('//a[contains(@href, :href)]/@href', [':href' => 'token/tree']); $link = $this->getAbsoluteUrl((string) current($links)); if (!empty($options)) { $options = Json::encode($options); @@ -145,4 +148,5 @@ class TreeTest extends TokenTestBase { } return $link; } + } diff --git a/src/Token.php b/src/Token.php index 360ae35..70099da 100644 --- a/src/Token.php +++ b/src/Token.php @@ -65,9 +65,9 @@ class Token extends TokenBase implements TokenInterface { } $this->tokenInfo = $token_info; - $this->cache->set($cache_id, $this->tokenInfo, CacheBackendInterface::CACHE_PERMANENT, array( + $this->cache->set($cache_id, $this->tokenInfo, CacheBackendInterface::CACHE_PERMANENT, [ static::TOKEN_INFO_CACHE_TAG, - )); + ]); } } @@ -83,7 +83,7 @@ class Token extends TokenBase implements TokenInterface { * @return string[] * List of the names keyed by the token key. */ - protected function prepareMultisort($token_info) { + protected function prepareMultisort(array $token_info) { $by_name = []; foreach ($token_info as $key => $token_info_element) { $by_name[$key] = $token_info_element['name']; @@ -134,9 +134,9 @@ class Token extends TokenBase implements TokenInterface { /** * {@inheritdoc} */ - function getInvalidTokens($type, $tokens) { + public function getInvalidTokens($type, $tokens) { $token_info = $this->getInfo(); - $invalid_tokens = array(); + $invalid_tokens = []; foreach ($tokens as $token => $full_token) { if (isset($token_info['tokens'][$type][$token])) { @@ -162,7 +162,7 @@ class Token extends TokenBase implements TokenInterface { } else { // Recursively check the chained tokens. - $sub_tokens = $this->findWithPrefix(array($token => $full_token), $parts[0]); + $sub_tokens = $this->findWithPrefix([$token => $full_token], $parts[0]); $invalid_tokens = array_merge($invalid_tokens, $this->getInvalidTokens($sub_token_info['type'], $sub_tokens)); } } @@ -184,7 +184,7 @@ class Token extends TokenBase implements TokenInterface { $valid_types = array_merge($valid_types, $this->getGlobalTokenTypes()); } - $invalid_tokens = array(); + $invalid_tokens = []; $value_tokens = is_string($value) ? $this->scan($value) : $value; foreach ($value_tokens as $type => $tokens) { diff --git a/src/TokenEntityMapper.php b/src/TokenEntityMapper.php index 051df8f..09c718b 100644 --- a/src/TokenEntityMapper.php +++ b/src/TokenEntityMapper.php @@ -29,6 +29,9 @@ class TokenEntityMapper implements TokenEntityMapperInterface { */ protected $entityMappings; + /** + * + */ public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler) { $this->entityTypeManager = $entity_type_manager; $this->moduleHandler = $module_handler; @@ -52,7 +55,7 @@ class TokenEntityMapper implements TokenEntityMapperInterface { /** * {@inheritdoc} */ - function getEntityTypeForTokenType($token_type, $fallback = FALSE) { + public function getEntityTypeForTokenType($token_type, $fallback = FALSE) { if (empty($this->entityMappings)) { $this->getEntityTypeMappings(); } @@ -64,7 +67,7 @@ class TokenEntityMapper implements TokenEntityMapperInterface { /** * {@inheritdoc} */ - function getTokenTypeForEntityType($entity_type, $fallback = FALSE) { + public function getTokenTypeForEntityType($entity_type, $fallback = FALSE) { if (empty($this->entityMappings)) { $this->getEntityTypeMappings(); } diff --git a/src/TokenEntityMapperInterface.php b/src/TokenEntityMapperInterface.php index 5eb038e..510956a 100644 --- a/src/TokenEntityMapperInterface.php +++ b/src/TokenEntityMapperInterface.php @@ -2,6 +2,9 @@ namespace Drupal\token; +/** + * + */ interface TokenEntityMapperInterface { /** @@ -27,7 +30,7 @@ interface TokenEntityMapperInterface { * @see token_entity_info_alter() * @see http://drupal.org/node/737726 */ - function getEntityTypeForTokenType($token_type, $fallback = FALSE); + public function getEntityTypeForTokenType($token_type, $fallback = FALSE); /** * Return the token type of a particular entity type. @@ -44,10 +47,11 @@ interface TokenEntityMapperInterface { * @see token_entity_info_alter() * @see http://drupal.org/node/737726 */ - function getTokenTypeForEntityType($entity_type, $fallback = FALSE); + public function getTokenTypeForEntityType($entity_type, $fallback = FALSE); /** * Resets metadata describing token and entity mappings. */ public function resetInfo(); + } diff --git a/src/TokenInterface.php b/src/TokenInterface.php index a66f137..9a3ae8d 100644 --- a/src/TokenInterface.php +++ b/src/TokenInterface.php @@ -2,6 +2,9 @@ namespace Drupal\token; +/** + * + */ interface TokenInterface { /** @@ -56,7 +59,7 @@ interface TokenInterface { * @return string[] * An array with the invalid tokens in their original raw forms. */ - function getInvalidTokens($type, $tokens); + public function getInvalidTokens($type, array $tokens); /** * Validate tokens in raw text based on possible contexts. @@ -72,4 +75,5 @@ interface TokenInterface { * An array with the invalid tokens in their original raw forms. */ public function getInvalidTokensByContext($value, array $valid_types = []); + } diff --git a/src/TokenServiceProvider.php b/src/TokenServiceProvider.php index c855195..da2325a 100644 --- a/src/TokenServiceProvider.php +++ b/src/TokenServiceProvider.php @@ -17,4 +17,5 @@ class TokenServiceProvider extends ServiceProviderBase { $definition = $container->getDefinition('token'); $definition->setClass('\Drupal\token\Token'); } + } diff --git a/src/TreeBuilder.php b/src/TreeBuilder.php index 80ebca2..4edf1ac 100644 --- a/src/TreeBuilder.php +++ b/src/TreeBuilder.php @@ -7,6 +7,9 @@ use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Language\LanguageManagerInterface; use Drupal\Core\Render\BubbleableMetadata; +/** + * + */ class TreeBuilder implements TreeBuilderInterface { /** @@ -36,6 +39,9 @@ class TreeBuilder implements TreeBuilderInterface { */ protected $builtTrees; + /** + * + */ public function __construct(TokenInterface $token_service, TokenEntityMapperInterface $entity_mapper, CacheBackendInterface $cache_backend, LanguageManagerInterface $language_manager) { $this->tokenService = $token_service; $this->entityMapper = $entity_mapper; @@ -61,16 +67,16 @@ class TreeBuilder implements TreeBuilderInterface { $token_types = array_merge($token_types, $this->tokenService->getGlobalTokenTypes()); } - $element = array( + $element = [ /*'#cache' => array( 'cid' => 'tree-rendered:' . hash('sha256', serialize(array('token_types' => $token_types, 'global_types' => NULL) + $variables)), 'tags' => array(Token::TOKEN_INFO_CACHE_TAG), ),*/ - ); + ]; // @todo Find a way to use the render cache for this. /*if ($cached_output = token_render_cache_get($element)) { - return $cached_output; + return $cached_output; }*/ $tree_options = [ @@ -233,7 +239,7 @@ class TreeBuilder implements TreeBuilderInterface { // Prevent duplicate recursive tokens. For example, this will prevent // the tree from generating the following tokens or deeper: // [comment:parent:parent] - // [comment:parent:root:parent] + // [comment:parent:root:parent]. continue; } @@ -264,4 +270,5 @@ class TreeBuilder implements TreeBuilderInterface { return $tree; } + } diff --git a/src/TreeBuilderInterface.php b/src/TreeBuilderInterface.php index c4212c2..5c7316d 100644 --- a/src/TreeBuilderInterface.php +++ b/src/TreeBuilderInterface.php @@ -2,6 +2,9 @@ namespace Drupal\token; +/** + * + */ interface TreeBuilderInterface { /** @@ -76,4 +79,5 @@ interface TreeBuilderInterface { * Render array for the token tree. */ public function buildAllRenderable(array $options = []); + } diff --git a/tests/modules/token_module_test/src/Controller/TokenTreeBrowseController.php b/tests/modules/token_module_test/src/Controller/TokenTreeBrowseController.php index 9b2ba08..1f391bf 100644 --- a/tests/modules/token_module_test/src/Controller/TokenTreeBrowseController.php +++ b/tests/modules/token_module_test/src/Controller/TokenTreeBrowseController.php @@ -5,12 +5,15 @@ namespace Drupal\token_module_test\Controller; use Drupal\Core\Controller\ControllerBase; use Symfony\Component\HttpFoundation\Request; +/** + * + */ class TokenTreeBrowseController extends ControllerBase { /** * Page callback to output a link. */ - function outputLink(Request $request) { + public function outputLink(Request $request) { $build['tree']['#theme'] = 'token_tree_link'; $build['tokenarea'] = [ '#markup' => \Drupal::token()->replace('[current-page:title]'), diff --git a/tests/modules/token_module_test/token_module_test.module b/tests/modules/token_module_test/token_module_test.module index c263320..c022b65 100644 --- a/tests/modules/token_module_test/token_module_test.module +++ b/tests/modules/token_module_test/token_module_test.module @@ -4,14 +4,15 @@ * @file * Helper module for token tests. */ + use Drupal\node\NodeInterface; /** * Implements hook_page_attachments(). */ function token_module_test_page_attachments() { - if ($debug = \Drupal::state()->get('token_page_tokens', array())) { - $debug += array('tokens' => array(), 'data' => array(), 'options' => array()); + if ($debug = \Drupal::state()->get('token_page_tokens', [])) { + $debug += ['tokens' => [], 'data' => [], 'options' => []]; foreach (array_keys($debug['tokens']) as $token) { $debug['values'][$token] = \Drupal::token()->replace($token, $debug['data'], $debug['options']); } diff --git a/tests/modules/token_module_test/token_module_test.tokens.inc b/tests/modules/token_module_test/token_module_test.tokens.inc index ba8da53..a2158e9 100644 --- a/tests/modules/token_module_test/token_module_test.tokens.inc +++ b/tests/modules/token_module_test/token_module_test.tokens.inc @@ -1,13 +1,17 @@ t('A test token with colons in the name'), 'description' => NULL, - ); + ]; return $info; } diff --git a/tests/src/Kernel/ArrayTest.php b/tests/src/Kernel/ArrayTest.php index a7f83ae..4957d27 100644 --- a/tests/src/Kernel/ArrayTest.php +++ b/tests/src/Kernel/ArrayTest.php @@ -9,10 +9,13 @@ namespace Drupal\Tests\token\Kernel; */ class ArrayTest extends KernelTestBase { - function testArrayTokens() { + /** + * + */ + public function testArrayTokens() { // Test a simple array. - $array = array(0 => 'a', 1 => 'b', 2 => 'c', 4 => 'd'); - $tokens = array( + $array = [0 => 'a', 1 => 'b', 2 => 'c', 4 => 'd']; + $tokens = [ 'first' => 'a', 'last' => 'd', 'value:0' => 'a', @@ -27,19 +30,19 @@ class ArrayTest extends KernelTestBase { 'join' => 'abcd', 'join:, ' => 'a, b, c, d', 'join: ' => 'a b c d', - ); - $this->assertTokens('array', array('array' => $array), $tokens); + ]; + $this->assertTokens('array', ['array' => $array], $tokens); // Test a mixed simple and render array. - // 2 => c, 0 => a, 4 => d, 1 => b - $array = array( + // 2 => c, 0 => a, 4 => d, 1 => b. + $array = [ '#property' => 'value', 0 => 'a', - 1 => array('#markup' => 'b', '#weight' => 0.01), - 2 => array('#markup' => 'c', '#weight' => -10), - 4 => array('#markup' => 'd', '#weight' => 0), - ); - $tokens = array( + 1 => ['#markup' => 'b', '#weight' => 0.01], + 2 => ['#markup' => 'c', '#weight' => -10], + 4 => ['#markup' => 'd', '#weight' => 0], + ]; + $tokens = [ 'first' => 'c', 'last' => 'b', 'value:0' => 'a', @@ -54,7 +57,8 @@ class ArrayTest extends KernelTestBase { 'join' => 'cadb', 'join:, ' => 'c, a, d, b', 'join: ' => 'c a d b', - ); - $this->assertTokens('array', array('array' => $array), $tokens); + ]; + $this->assertTokens('array', ['array' => $array], $tokens); } + } diff --git a/tests/src/Kernel/BookTest.php b/tests/src/Kernel/BookTest.php index 67a13ee..4f77a7a 100644 --- a/tests/src/Kernel/BookTest.php +++ b/tests/src/Kernel/BookTest.php @@ -27,12 +27,15 @@ class BookTest extends KernelTestBase { $this->installEntitySchema('user'); $this->installEntitySchema('node'); - $this->installSchema('book', array('book')); - $this->installSchema('node', array('node_access')); - $this->installConfig(array('node', 'book', 'field')); + $this->installSchema('book', ['book']); + $this->installSchema('node', ['node_access']); + $this->installConfig(['node', 'book', 'field']); } - function testBookTokens() { + /** + * + */ + public function testBookTokens() { $book = Node::create([ 'type' => 'book', 'title' => 'Book Main Page', @@ -63,12 +66,12 @@ class BookTest extends KernelTestBase { 'book:root' => $book_title, 'book:root:nid' => $book->id(), 'book:root:title' => $book_title, - 'book:root:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], array('absolute' => TRUE))->toString(), + 'book:root:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], ['absolute' => TRUE])->toString(), 'book:root:content-type' => 'Book page', - 'book:parent' => null, - 'book:parents' => null, + 'book:parent' => NULL, + 'book:parents' => NULL, ]; - $this->assertTokens('node', array('node' => $book), $tokens); + $this->assertTokens('node', ['node' => $book], $tokens); $tokens = [ 'nid' => $page1->id(), @@ -77,15 +80,15 @@ class BookTest extends KernelTestBase { 'book:root' => $book_title, 'book:root:nid' => $book->id(), 'book:root:title' => $book_title, - 'book:root:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], array('absolute' => TRUE))->toString(), + 'book:root:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], ['absolute' => TRUE])->toString(), 'book:root:content-type' => 'Book page', 'book:parent:nid' => $book->id(), 'book:parent:title' => $book_title, - 'book:parent:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], array('absolute' => TRUE))->toString(), + 'book:parent:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], ['absolute' => TRUE])->toString(), 'book:parents:count' => 1, 'book:parents:join:/' => $book_title, ]; - $this->assertTokens('node', array('node' => $page1), $tokens); + $this->assertTokens('node', ['node' => $page1], $tokens); $tokens = [ 'nid' => $page2->id(), @@ -94,14 +97,15 @@ class BookTest extends KernelTestBase { 'book:root' => $book_title, 'book:root:nid' => $book->id(), 'book:root:title' => $book_title, - 'book:root:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], array('absolute' => TRUE))->toString(), + 'book:root:url' => Url::fromRoute('entity.node.canonical', ['node' => $book->id()], ['absolute' => TRUE])->toString(), 'book:root:content-type' => 'Book page', 'book:parent:nid' => $page1->id(), 'book:parent:title' => $page1->getTitle(), - 'book:parent:url' => Url::fromRoute('entity.node.canonical', ['node' => $page1->id()], array('absolute' => TRUE))->toString(), + 'book:parent:url' => Url::fromRoute('entity.node.canonical', ['node' => $page1->id()], ['absolute' => TRUE])->toString(), 'book:parents:count' => 2, 'book:parents:join:/' => $book_title . '/' . $page1->getTitle(), ]; - $this->assertTokens('node', array('node' => $page2), $tokens); + $this->assertTokens('node', ['node' => $page2], $tokens); } + } diff --git a/tests/src/Kernel/CommentTest.php b/tests/src/Kernel/CommentTest.php index 499f087..e808483 100644 --- a/tests/src/Kernel/CommentTest.php +++ b/tests/src/Kernel/CommentTest.php @@ -43,10 +43,13 @@ class CommentTest extends KernelTestBase { $this->addDefaultCommentField('node', 'page'); } - function testCommentTokens() { + /** + * + */ + public function testCommentTokens() { $node = Node::create([ 'type' => 'page', - 'title' => $this->randomMachineName() + 'title' => $this->randomMachineName(), ]); $node->save(); @@ -64,14 +67,14 @@ class CommentTest extends KernelTestBase { // Fix http://example.com/index.php/comment/1 fails 'url:path' test. $parent_comment_path = $parent_comment->url(); - $tokens = array( + $tokens = [ 'url' => $parent_comment->urlInfo('canonical', ['fragment' => "comment-{$parent_comment->id()}"])->setAbsolute()->toString(), 'url:absolute' => $parent_comment->urlInfo('canonical', ['fragment' => "comment-{$parent_comment->id()}"])->setAbsolute()->toString(), 'url:relative' => $parent_comment->urlInfo('canonical', ['fragment' => "comment-{$parent_comment->id()}"])->toString(), 'url:path' => $parent_comment_path, 'parent:url:absolute' => NULL, - ); - $this->assertTokens('comment', array('comment' => $parent_comment), $tokens); + ]; + $this->assertTokens('comment', ['comment' => $parent_comment], $tokens); $comment = Comment::create([ 'entity_id' => $node->id(), @@ -87,16 +90,16 @@ class CommentTest extends KernelTestBase { $comment->save(); // Fix http://example.com/index.php/comment/1 fails 'url:path' test. - $comment_path = Url::fromRoute('entity.comment.canonical', array('comment' => $comment->id()))->toString(); + $comment_path = Url::fromRoute('entity.comment.canonical', ['comment' => $comment->id()])->toString(); - $tokens = array( + $tokens = [ 'url' => $comment->urlInfo('canonical', ['fragment' => "comment-{$comment->id()}"])->setAbsolute()->toString(), 'url:absolute' => $comment->urlInfo('canonical', ['fragment' => "comment-{$comment->id()}"])->setAbsolute()->toString(), 'url:relative' => $comment->urlInfo('canonical', ['fragment' => "comment-{$comment->id()}"])->toString(), 'url:path' => $comment_path, 'parent:url:absolute' => $parent_comment->urlInfo('canonical', ['fragment' => "comment-{$parent_comment->id()}"])->setAbsolute()->toString(), - ); - $this->assertTokens('comment', array('comment' => $comment), $tokens); + ]; + $this->assertTokens('comment', ['comment' => $comment], $tokens); } } diff --git a/tests/src/Kernel/DateTest.php b/tests/src/Kernel/DateTest.php index c25bf03..dca2509 100644 --- a/tests/src/Kernel/DateTest.php +++ b/tests/src/Kernel/DateTest.php @@ -24,12 +24,16 @@ class DateTest extends KernelTestBase { $this->installConfig(['system', 'token_module_test']); } - function testDateTokens() { - $tokens = array( + /** + * + */ + public function testDateTokens() { + $tokens = [ 'token_module_test' => '1984', 'invalid_format' => NULL, - ); + ]; - $this->assertTokens('date', array('date' => 453859200), $tokens); + $this->assertTokens('date', ['date' => 453859200], $tokens); } + } diff --git a/tests/src/Kernel/EntityTest.php b/tests/src/Kernel/EntityTest.php index 7ff471d..5f35d4e 100644 --- a/tests/src/Kernel/EntityTest.php +++ b/tests/src/Kernel/EntityTest.php @@ -41,7 +41,10 @@ class EntityTest extends KernelTestBase { $this->vocab = $vocabulary; } - function testEntityMapping() { + /** + * + */ + public function testEntityMapping() { /** @var \Drupal\token\TokenEntityMapperInterface $mapper */ $mapper = \Drupal::service('token.entity_mapper'); $this->assertIdentical($mapper->getEntityTypeForTokenType('node'), 'node'); @@ -59,15 +62,18 @@ class EntityTest extends KernelTestBase { // that we still get the tokens replaced. $vocabulary = entity_load('taxonomy_vocabulary', 'tags'); $term = $this->addTerm($vocabulary); - $this->assertIdentical(\Drupal::token()->replace('[vocabulary:name]', array('taxonomy_vocabulary' => $vocabulary)), $vocabulary->label()); - $this->assertIdentical(\Drupal::token()->replace('[term:name][term:vocabulary:name]', array('taxonomy_term' => $term)), $term->label() . $vocabulary->label()); + $this->assertIdentical(\Drupal::token()->replace('[vocabulary:name]', ['taxonomy_vocabulary' => $vocabulary]), $vocabulary->label()); + $this->assertIdentical(\Drupal::token()->replace('[term:name][term:vocabulary:name]', ['taxonomy_term' => $term]), $term->label() . $vocabulary->label()); } - function addTerm(VocabularyInterface $vocabulary, array $term = array()) { - $term += array( + /** + * + */ + public function addTerm(VocabularyInterface $vocabulary, array $term = []) { + $term += [ 'name' => Unicode::strtolower($this->randomMachineName(5)), 'vid' => $vocabulary->id(), - ); + ]; $term = entity_create('taxonomy_term', $term); $term->save(); return $term; @@ -76,29 +82,30 @@ class EntityTest extends KernelTestBase { /** * Test the [entity:original:*] tokens. */ - function testEntityOriginal() { + public function testEntityOriginal() { $node = Node::create(['type' => 'page', 'title' => 'Original title']); $node->save(); - $tokens = array( + $tokens = [ 'nid' => $node->id(), 'title' => 'Original title', 'original' => NULL, 'original:nid' => NULL, - ); - $this->assertTokens('node', array('node' => $node), $tokens); + ]; + $this->assertTokens('node', ['node' => $node], $tokens); // Emulate the original entity property that would be available from // node_save() and change the title for the node. $node->original = entity_load_unchanged('node', $node->id()); $node->title = 'New title'; - $tokens = array( + $tokens = [ 'nid' => $node->id(), 'title' => 'New title', 'original' => 'Original title', 'original:nid' => $node->id(), - ); - $this->assertTokens('node', array('node' => $node), $tokens); + ]; + $this->assertTokens('node', ['node' => $node], $tokens); } + } diff --git a/tests/src/Kernel/FieldTest.php b/tests/src/Kernel/FieldTest.php index de94699..d36f264 100644 --- a/tests/src/Kernel/FieldTest.php +++ b/tests/src/Kernel/FieldTest.php @@ -114,7 +114,7 @@ class FieldTest extends KernelTestBase { 'allowed_values' => [ 'key1' => 'value1', 'key2' => 'value2', - ] + ], ], ]); $field_storage->save(); @@ -191,30 +191,30 @@ class FieldTest extends KernelTestBase { $language->save(); // Add a datetime field. - $field_datetime_storage = FieldStorageConfig::create(array( - 'field_name' => 'field_datetime', - 'type' => 'datetime', - 'entity_type' => 'node', - 'settings' => array('datetime_type' => DateTimeItem::DATETIME_TYPE_DATETIME), - )); + $field_datetime_storage = FieldStorageConfig::create([ + 'field_name' => 'field_datetime', + 'type' => 'datetime', + 'entity_type' => 'node', + 'settings' => ['datetime_type' => DateTimeItem::DATETIME_TYPE_DATETIME], + ]); $field_datetime_storage->save(); $field_datetime = FieldConfig::create([ - 'field_storage' => $field_datetime_storage, - 'bundle' => 'article', + 'field_storage' => $field_datetime_storage, + 'bundle' => 'article', ]); $field_datetime->save(); // Add a daterange field. - $field_daterange_storage = FieldStorageConfig::create(array( - 'field_name' => 'field_daterange', - 'type' => 'daterange', - 'entity_type' => 'node', - 'settings' => array('datetime_type' => DateRangeItem::DATETIME_TYPE_DATETIME), - )); + $field_daterange_storage = FieldStorageConfig::create([ + 'field_name' => 'field_daterange', + 'type' => 'daterange', + 'entity_type' => 'node', + 'settings' => ['datetime_type' => DateRangeItem::DATETIME_TYPE_DATETIME], + ]); $field_daterange_storage->save(); $field_daterange = FieldConfig::create([ - 'field_storage' => $field_daterange_storage, - 'bundle' => 'article', + 'field_storage' => $field_daterange_storage, + 'bundle' => 'article', ]); $field_daterange->save(); } @@ -390,7 +390,7 @@ class FieldTest extends KernelTestBase { 'type' => 'text_trimmed', 'settings' => [ 'trim_length' => 50, - ] + ], ]); $entity_display->save(); @@ -443,7 +443,7 @@ class FieldTest extends KernelTestBase { $this->assertNull($tokenService->getTokenInfo('node', 'uid')); } - /* + /** * Tests chaining entity reference tokens. */ public function testEntityReferenceTokens() { @@ -453,7 +453,7 @@ class FieldTest extends KernelTestBase { 'test_field' => [ 'value' => 'foo', 'format' => $this->testFormat->id(), - ] + ], ]); $reference->save(); $term_reference_field_value = $this->randomString(); @@ -690,8 +690,8 @@ class FieldTest extends KernelTestBase { public function testDatetimeRangeFieldTokens() { $node = Node::create([ - 'title' => 'Node for daterange field', - 'type' => 'article', + 'title' => 'Node for daterange field', + 'type' => 'article', ]); $node->field_daterange->value = '2013-12-22T00:00:00'; diff --git a/tests/src/Kernel/FileTest.php b/tests/src/Kernel/FileTest.php index 3a6a7fd..404c480 100644 --- a/tests/src/Kernel/FileTest.php +++ b/tests/src/Kernel/FileTest.php @@ -14,7 +14,7 @@ class FileTest extends KernelTestBase { * * @var array */ - public static $modules = array('file'); + public static $modules = ['file']; /** * {@inheritdoc} @@ -24,32 +24,36 @@ class FileTest extends KernelTestBase { $this->installEntitySchema('file'); } - function testFileTokens() { + /** + * + */ + public function testFileTokens() { // Create a test file object. - $file = entity_create('file', array( + $file = entity_create('file', [ 'fid' => 1, 'filename' => 'test.png', 'filesize' => 100, 'uri' => 'public://images/test.png', 'filemime' => 'image/png', - )); + ]); - $tokens = array( + $tokens = [ 'basename' => 'test.png', 'extension' => 'png', 'size-raw' => 100, - ); - $this->assertTokens('file', array('file' => $file), $tokens); + ]; + $this->assertTokens('file', ['file' => $file], $tokens); // Test a file with no extension and a fake name. $file->filename = 'Test PNG image'; $file->uri = 'public://images/test'; - $tokens = array( + $tokens = [ 'basename' => 'test', 'extension' => '', 'size-raw' => 100, - ); - $this->assertTokens('file', array('file' => $file), $tokens); + ]; + $this->assertTokens('file', ['file' => $file], $tokens); } + } diff --git a/tests/src/Kernel/KernelTestBase.php b/tests/src/Kernel/KernelTestBase.php index a9657f6..dbf9d6d 100644 --- a/tests/src/Kernel/KernelTestBase.php +++ b/tests/src/Kernel/KernelTestBase.php @@ -17,7 +17,13 @@ abstract class KernelTestBase extends BaseKernelTestBase { * * @var array */ - public static $modules = ['path', 'token', 'token_module_test', 'system', 'user']; + public static $modules = [ + 'path', + 'token', + 'token_module_test', + 'system', + 'user', + ]; /** * {@inheritdoc} diff --git a/tests/src/Kernel/NodeTest.php b/tests/src/Kernel/NodeTest.php index e44b9ab..e1a73c2 100644 --- a/tests/src/Kernel/NodeTest.php +++ b/tests/src/Kernel/NodeTest.php @@ -43,57 +43,61 @@ class NodeTest extends KernelTestBase { $node_type->save(); } - function testNodeTokens() { + /** + * + */ + public function testNodeTokens() { $page = Node::create([ 'type' => 'page', 'title' => 'Source Title', 'revision_log' => $this->randomMachineName(), - 'path' => array('alias' => '/content/source-node') + 'path' => ['alias' => '/content/source-node'], ]); $page->save(); - $tokens = array( + $tokens = [ 'log' => $page->revision_log->value, 'url:path' => '/content/source-node', - 'url:absolute' => Url::fromRoute('entity.node.canonical', ['node' => $page->id()], array('absolute' => TRUE))->toString(), - 'url:relative' => Url::fromRoute('entity.node.canonical', ['node' => $page->id()], array('absolute' => FALSE))->toString(), + 'url:absolute' => Url::fromRoute('entity.node.canonical', ['node' => $page->id()], ['absolute' => TRUE])->toString(), + 'url:relative' => Url::fromRoute('entity.node.canonical', ['node' => $page->id()], ['absolute' => FALSE])->toString(), 'url:unaliased:path' => "/node/{$page->id()}", 'content-type' => 'Basic page', 'content-type:name' => 'Basic page', 'content-type:machine-name' => 'page', 'content-type:description' => "Use basic pages for your static content, such as an 'About us' page.", 'content-type:node-count' => 1, - 'content-type:edit-url' => Url::fromRoute('entity.node_type.edit_form', ['node_type' => 'page'], array('absolute' => TRUE))->toString(), + 'content-type:edit-url' => Url::fromRoute('entity.node_type.edit_form', ['node_type' => 'page'], ['absolute' => TRUE])->toString(), 'source:title' => 'Source Title', // Deprecated tokens. 'type' => 'page', 'type-name' => 'Basic page', 'url:alias' => '/content/source-node', - ); - $this->assertTokens('node', array('node' => $page), $tokens); + ]; + $this->assertTokens('node', ['node' => $page], $tokens); $article = Node::create([ 'type' => 'article', 'title' => 'Source Title', ]); $article->save(); - $tokens = array( + $tokens = [ 'log' => '', 'url:path' => "/node/{$article->id()}", - 'url:absolute' => Url::fromRoute('entity.node.canonical', ['node' => $article->id()], array('absolute' => TRUE))->toString(), - 'url:relative' => Url::fromRoute('entity.node.canonical', ['node' => $article->id()], array('absolute' => FALSE))->toString(), + 'url:absolute' => Url::fromRoute('entity.node.canonical', ['node' => $article->id()], ['absolute' => TRUE])->toString(), + 'url:relative' => Url::fromRoute('entity.node.canonical', ['node' => $article->id()], ['absolute' => FALSE])->toString(), 'url:unaliased:path' => "/node/{$article->id()}", 'content-type' => 'Article', 'content-type:name' => 'Article', 'content-type:machine-name' => 'article', 'content-type:description' => "Use articles for time-sensitive content like news, press releases or blog posts.", 'content-type:node-count' => 1, - 'content-type:edit-url' => Url::fromRoute('entity.node_type.edit_form', ['node_type' => 'article'], array('absolute' => TRUE))->toString(), + 'content-type:edit-url' => Url::fromRoute('entity.node_type.edit_form', ['node_type' => 'article'], ['absolute' => TRUE])->toString(), 'source:title' => 'Source Title', // Deprecated tokens. 'type' => 'article', 'type-name' => 'Article', 'url:alias' => "/node/{$article->id()}", - ); - $this->assertTokens('node', array('node' => $article), $tokens); + ]; + $this->assertTokens('node', ['node' => $article], $tokens); } + } diff --git a/tests/src/Kernel/RandomTest.php b/tests/src/Kernel/RandomTest.php index a4b0930..f487f75 100644 --- a/tests/src/Kernel/RandomTest.php +++ b/tests/src/Kernel/RandomTest.php @@ -9,19 +9,23 @@ namespace Drupal\Tests\token\Kernel; */ class RandomTest extends KernelTestBase { - function testRandomTokens() { - $tokens = array( + /** + * + */ + public function testRandomTokens() { + $tokens = [ 'number' => '[0-9]{1,}', 'hash:md5' => '[0-9a-f]{32}', 'hash:sha1' => '[0-9a-f]{40}', 'hash:sha256' => '[0-9a-f]{64}', 'hash:invalid-algo' => NULL, - ); + ]; - $first_set = $this->assertTokens('random', array(), $tokens, array('regex' => TRUE)); - $second_set = $this->assertTokens('random', array(), $tokens, array('regex' => TRUE)); + $first_set = $this->assertTokens('random', [], $tokens, ['regex' => TRUE]); + $second_set = $this->assertTokens('random', [], $tokens, ['regex' => TRUE]); foreach ($first_set as $token => $value) { $this->assertNotIdentical($first_set[$token], $second_set[$token]); } } + } diff --git a/tests/src/Kernel/TaxonomyTest.php b/tests/src/Kernel/TaxonomyTest.php index 73274df..47b5ce5 100644 --- a/tests/src/Kernel/TaxonomyTest.php +++ b/tests/src/Kernel/TaxonomyTest.php @@ -20,7 +20,7 @@ class TaxonomyTest extends KernelTestBase { * * @var array */ - public static $modules = array('taxonomy', 'text', 'language'); + public static $modules = ['taxonomy', 'text', 'language']; /** * {@inheritdoc} @@ -42,77 +42,83 @@ class TaxonomyTest extends KernelTestBase { /** * Test the additional taxonomy term tokens. */ - function testTaxonomyTokens() { - $root_term = $this->addTerm($this->vocab, array('name' => 'Root term', 'path' => array('alias' => '/root-term'))); - $tokens = array( - 'url' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $root_term->id()], array('absolute' => TRUE))->toString(), - 'url:absolute' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $root_term->id()], array('absolute' => TRUE))->toString(), - 'url:relative' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $root_term->id()], array('absolute' => FALSE))->toString(), + public function testTaxonomyTokens() { + $root_term = $this->addTerm($this->vocab, ['name' => 'Root term', 'path' => ['alias' => '/root-term']]); + $tokens = [ + 'url' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $root_term->id()], ['absolute' => TRUE])->toString(), + 'url:absolute' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $root_term->id()], ['absolute' => TRUE])->toString(), + 'url:relative' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $root_term->id()], ['absolute' => FALSE])->toString(), 'url:path' => '/root-term', 'url:unaliased:path' => "/taxonomy/term/{$root_term->id()}", - 'edit-url' => Url::fromRoute('entity.taxonomy_term.edit_form', ['taxonomy_term' => $root_term->id()], array('absolute' => TRUE))->toString(), + 'edit-url' => Url::fromRoute('entity.taxonomy_term.edit_form', ['taxonomy_term' => $root_term->id()], ['absolute' => TRUE])->toString(), 'parents' => NULL, 'parents:count' => NULL, 'parents:keys' => NULL, 'root' => NULL, - // Deprecated tokens + // Deprecated tokens. 'url:alias' => '/root-term', - ); - $this->assertTokens('term', array('term' => $root_term), $tokens); - - $parent_term = $this->addTerm($this->vocab, array('name' => 'Parent term', 'parent' => $root_term->id())); - $tokens = array( - 'url' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $parent_term->id()], array('absolute' => TRUE))->toString(), - 'url:absolute' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $parent_term->id()], array('absolute' => TRUE))->toString(), - 'url:relative' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $parent_term->id()], array('absolute' => FALSE))->toString(), + ]; + $this->assertTokens('term', ['term' => $root_term], $tokens); + + $parent_term = $this->addTerm($this->vocab, ['name' => 'Parent term', 'parent' => $root_term->id()]); + $tokens = [ + 'url' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $parent_term->id()], ['absolute' => TRUE])->toString(), + 'url:absolute' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $parent_term->id()], ['absolute' => TRUE])->toString(), + 'url:relative' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $parent_term->id()], ['absolute' => FALSE])->toString(), 'url:path' => "/taxonomy/term/{$parent_term->id()}", 'url:unaliased:path' => "/taxonomy/term/{$parent_term->id()}", - 'edit-url' => Url::fromRoute('entity.taxonomy_term.edit_form', ['taxonomy_term' => $parent_term->id()], array('absolute' => TRUE))->toString(), + 'edit-url' => Url::fromRoute('entity.taxonomy_term.edit_form', ['taxonomy_term' => $parent_term->id()], ['absolute' => TRUE])->toString(), 'parents' => 'Root term', 'parents:count' => 1, 'parents:keys' => $root_term->id(), 'root' => $root_term->label(), 'root:tid' => $root_term->id(), - // Deprecated tokens + // Deprecated tokens. 'url:alias' => "/taxonomy/term/{$parent_term->id()}", - ); - $this->assertTokens('term', array('term' => $parent_term), $tokens); + ]; + $this->assertTokens('term', ['term' => $parent_term], $tokens); - $term = $this->addTerm($this->vocab, array('name' => 'Test term', 'parent' => $parent_term->id())); - $tokens = array( + $term = $this->addTerm($this->vocab, ['name' => 'Test term', 'parent' => $parent_term->id()]); + $tokens = [ 'parents' => 'Root term, Parent term', 'parents:count' => 2, - 'parents:keys' => implode(', ', array($root_term->id(), $parent_term->id())), - ); - $this->assertTokens('term', array('term' => $term), $tokens); + 'parents:keys' => implode(', ', [$root_term->id(), $parent_term->id()]), + ]; + $this->assertTokens('term', ['term' => $term], $tokens); } /** * Test the additional vocabulary tokens. */ - function testVocabularyTokens() { + public function testVocabularyTokens() { $vocabulary = $this->vocab; - $tokens = array( + $tokens = [ 'machine-name' => 'tags', - 'edit-url' => Url::fromRoute('entity.taxonomy_vocabulary.edit_form', ['taxonomy_vocabulary' => $vocabulary->id()], array('absolute' => TRUE))->toString(), - ); - $this->assertTokens('vocabulary', array('vocabulary' => $vocabulary), $tokens); + 'edit-url' => Url::fromRoute('entity.taxonomy_vocabulary.edit_form', ['taxonomy_vocabulary' => $vocabulary->id()], ['absolute' => TRUE])->toString(), + ]; + $this->assertTokens('vocabulary', ['vocabulary' => $vocabulary], $tokens); } - function addVocabulary(array $vocabulary = array()) { - $vocabulary += array( + /** + * + */ + public function addVocabulary(array $vocabulary = []) { + $vocabulary += [ 'name' => Unicode::strtolower($this->randomMachineName(5)), - 'nodes' => array('article' => 'article'), - ); + 'nodes' => ['article' => 'article'], + ]; $vocabulary = entity_create('taxonomy_vocabulary', $vocabulary)->save(); return $vocabulary; } - function addTerm($vocabulary, array $term = array()) { - $term += array( + /** + * + */ + public function addTerm($vocabulary, array $term = []) { + $term += [ 'name' => Unicode::strtolower($this->randomMachineName(5)), 'vid' => $vocabulary->id(), - ); + ]; $term = entity_create('taxonomy_term', $term); $term->save(); return $term; @@ -121,7 +127,7 @@ class TaxonomyTest extends KernelTestBase { /** * Test the multilingual terms. */ - function testMultilingualTerms() { + public function testMultilingualTerms() { // Add a second language. $language = ConfigurableLanguage::createFromLangcode('de'); $language->save(); @@ -146,6 +152,7 @@ class TaxonomyTest extends KernelTestBase { ])->save(); // Expect the parent term to be in the specified language. - $this->assertTokens('term', array('term' => $child_term), ['parents' => 'german-parent-term'], ['langcode' => 'de']); + $this->assertTokens('term', ['term' => $child_term], ['parents' => 'german-parent-term'], ['langcode' => 'de']); } + } diff --git a/tests/src/Kernel/UnitTest.php b/tests/src/Kernel/UnitTest.php index c91f194..482a8b4 100644 --- a/tests/src/Kernel/UnitTest.php +++ b/tests/src/Kernel/UnitTest.php @@ -33,9 +33,9 @@ class UnitTest extends KernelTestBase { * Test invalid tokens. */ public function testGetInvalidTokens() { - $tests = array(); - $tests[] = array( - 'valid tokens' => array( + $tests = []; + $tests[] = [ + 'valid tokens' => [ '[node:title]', '[node:created:short]', '[node:created:custom:invalid]', @@ -46,8 +46,8 @@ class UnitTest extends KernelTestBase { '[current-date:short]', '[current-user:uid]', '[current-user:ip-address]', - ), - 'invalid tokens' => array( + ], + 'invalid tokens' => [ '[node:title:invalid]', '[node:created:invalid]', '[node:created:short:invalid]', @@ -57,16 +57,16 @@ class UnitTest extends KernelTestBase { '[user:ip-address]', '[user:uid]', '[comment:cid]', - // Deprecated tokens + // Deprecated tokens. '[node:tnid]', '[node:type]', '[node:type-name]', '[date:short]', - ), - 'types' => array('node'), - ); - $tests[] = array( - 'valid tokens' => array( + ], + 'types' => ['node'], + ]; + $tests[] = [ + 'valid tokens' => [ '[node:title]', '[node:created:short]', '[node:created:custom:invalid]', @@ -77,8 +77,8 @@ class UnitTest extends KernelTestBase { '[user:uid]', '[current-date:short]', '[current-user:uid]', - ), - 'invalid tokens' => array( + ], + 'invalid tokens' => [ '[node:title:invalid]', '[node:created:invalid]', '[node:created:short:invalid]', @@ -87,13 +87,13 @@ class UnitTest extends KernelTestBase { '[site:invalid]', '[user:ip-address]', '[comment:cid]', - // Deprecated tokens + // Deprecated tokens. '[node:tnid]', '[node:type]', '[node:type-name]', - ), - 'types' => array('all'), - ); + ], + 'types' => ['all'], + ]; foreach ($tests as $test) { $tokens = array_merge($test['valid tokens'], $test['invalid tokens']); @@ -116,4 +116,5 @@ class UnitTest extends KernelTestBase { $this->assertNull($this->tokenService->getTokenInfo('user_role', 'url')); $this->assertNull($this->tokenService->getTypeInfo('user_role')); } + } diff --git a/token.install b/token.install index 664b1af..4fb6714 100644 --- a/token.install +++ b/token.install @@ -9,7 +9,7 @@ * Implements hook_requirements(). */ function token_requirements($phase = 'runtime') { - $requirements = array(); + $requirements = []; if ($phase == 'runtime') { // Check for various token definition problems. @@ -24,11 +24,11 @@ function token_requirements($phase = 'runtime') { '#items' => $problems, ]; - $requirements['token-' . $problem_key] = array( + $requirements['token-' . $problem_key] = [ 'title' => $problem['label'], 'value' => \Drupal::service('renderer')->renderPlain($build), 'severity' => $problem['severity'], - ); + ]; } } } @@ -51,12 +51,12 @@ function token_install() { $storage = \Drupal::entityTypeManager()->getStorage('entity_view_mode'); // Add a token view mode if it does not already exist. if (!$storage->load("$entity_type.token")) { - $storage->create(array( + $storage->create([ 'targetEntityType' => $entity_type, 'id' => "$entity_type.token", 'status' => TRUE, 'label' => t('Token'), - ))->save(); + ])->save(); } } } @@ -65,8 +65,8 @@ function token_install() { * Build a list of Drupal 6 tokens and their Drupal 7 token names. */ function _token_upgrade_token_list() { - $tokens = array( - // Global tokens + $tokens = [ + // Global tokens. 'user-name' => 'current-user:name', 'user-id' => 'current-user:id', 'user-mail' => 'current-user:mail', @@ -76,23 +76,23 @@ function _token_upgrade_token_list() { 'site-mission' => 'site:mission', 'site-mail' => 'site:mail', 'site-date' => 'date:short', - //'site-date-' => '', // Date tokens expanded below + // 'site-date-' => '', // Date tokens expanded below. 'current-page-path' => 'current-page:path', 'current-page-url' => 'current-page:url', 'page-number' => 'current-page:page-number', - // Comment tokens + // Comment tokens. 'comment-cid' => 'comment:cid', 'comment-nid' => 'comment:node:nid', 'comment-title' => 'comment:title', 'comment-body' => 'comment:body', 'comment-author-name' => 'comment:author:name', 'comment-author-mail' => 'comment:author:mail', - //'comment-body-format' => '', - //'comment-' => '', // Date tokens expanded below + // 'comment-body-format' => '', + // 'comment-' => '', // Date tokens expanded below. 'comment-node-title' => 'comment:node', - // Node tokens + // Node tokens. 'nid' => 'node:nid', 'type' => 'node:type', 'type-name' => 'node:type-name', @@ -104,24 +104,22 @@ function _token_upgrade_token_list() { 'node_comment_count' => 'node:comment-count', 'unread_comment_count' => 'node:comment-count-new', 'log' => 'node:log', - //'' => '', // Date tokens expanded below - //'mod-' => '', // Date tokens expanded below + // '' => '', // Date tokens expanded below + // 'mod-' => '', // Date tokens expanded below. 'menupath' => 'node:menu-link:parent:path][node:menu-link', 'menu' => 'node:menu-link:menu-name', 'menu-link-title' => 'node:menu-link', 'menu-link-mlid' => 'node:menu-link:mlid', 'menu-link-plid' => 'node:menu-link:parent:mlid', - //'term' => 'node:term', - //'term-id' => 'node:term:tid', - //'vocab' => 'node:term:vocabulary', - //'vocab-id' => 'node:term:vocabulary:vid', - + // 'term' => 'node:term', + // 'term-id' => 'node:term:tid', + // 'vocab' => 'node:term:vocabulary', + // 'vocab-id' => 'node:term:vocabulary:vid', // Book tokens - //'book' => 'node:book', - //'book_id' => 'node:book:bid', - //'bookpath' => 'node:book:path', - - // Taxonomy tokens + // 'book' => 'node:book', + // 'book_id' => 'node:book:bid', + // 'bookpath' => 'node:book:path', + // Taxonomy tokens. 'tid' => 'term:tid', 'cat' => 'term:name', 'cat-description' => 'term:description', @@ -129,26 +127,26 @@ function _token_upgrade_token_list() { 'vocab' => 'term:vocabulary', 'vocab-description' => 'term:vocabulary:description', - // User tokens + // User tokens. 'user' => 'user:name', 'uid' => 'user:uid', 'mail' => 'user:mail', 'reg-date' => 'user:created', 'reg-since' => 'user:created:since', - //'user-created' => '', // Date tokens expanded below + // 'user-created' => '', // Date tokens expanded below. 'log-date' => 'user:last-login', 'log-since' => 'user:last-login:since', - //'user-last-login' => '', // Date tokens expanded below - //'date-in-tz' => '', + // 'user-last-login' => '', // Date tokens expanded below + // 'date-in-tz' => '',. 'account-url' => 'user:url', 'account-edit' => 'user:edit-url', - ); + ]; // Account for date tokens which need to be expanded. $tokens += _token_upgrade_token_date_list('site-', 'site:date'); $tokens += _token_upgrade_token_date_list('', 'node:created'); $tokens += _token_upgrade_token_date_list('mod-', 'node:changed'); - //$tokens += _token_upgrade_token_date_list('node-revision-', 'node:changed'); + // $tokens += _token_upgrade_token_date_list('node-revision-', 'node:changed');. $tokens += _token_upgrade_token_date_list('comment-', 'comment:created'); $tokens += _token_upgrade_token_date_list('user-register-', 'user:created'); $tokens += _token_upgrade_token_date_list('user-last-login-', 'user:last-login'); @@ -160,8 +158,8 @@ function _token_upgrade_token_list() { * Build a list of Drupal 6 date tokens and their Drupal 7 token names. */ function _token_upgrade_token_date_list($old_token, $new_token) { - $tokens = array(); - $formats = array( + $tokens = []; + $formats = [ 'yyyy' => 'Y', 'yy' => 'y', 'month' => 'F', @@ -174,7 +172,7 @@ function _token_upgrade_token_date_list($old_token, $new_token) { 'ddd' => 'D', 'dd' => 'd', 'd' => 'j', - ); + ]; foreach ($formats as $token_format => $date_format) { $tokens[$old_token . $token_format] = "$new_token:custom:$date_format"; } @@ -193,12 +191,13 @@ function _token_upgrade_token_date_list($old_token, $new_token) { * The default tokens will be merged into this array. Note neither the old * or new token names should include the surrounding bracket ([ and ]) * characters. + * * @return * A string with the tokens upgraded * * @see _token_upgrade_token_list() */ -function token_update_token_text($text, $updates = array(), $leading = '[', $trailing = ']') { +function token_update_token_text($text, $updates = [], $leading = '[', $trailing = ']') { $updates += _token_upgrade_token_list(); $regex = '/' . preg_quote($leading, '/') . '([^\s]*)' . preg_quote($trailing, '/') . '/'; preg_match_all($regex, $text, $matches); @@ -220,8 +219,8 @@ function token_update_token_text($text, $updates = array(), $leading = '[', $tra */ function token_get_token_problems() { // @todo Improve the duplicate checking to report which modules are the offenders. - //$token_info = array(); - //foreach (module_implements('token_info') as $module) { + // $token_info = array(); + // foreach (module_implements('token_info') as $module) { // $module_token_info = module_invoke($module, 'token_info'); // if (in_array($module, _token_core_supported_modules())) { // $module .= '/token'; @@ -243,31 +242,30 @@ function token_get_token_problems() { // if (is_array($module_token_info)) { // $token_info = array_merge_recursive($token_info, $module_token_info); // } - //} - + // } $token_info = \Drupal::token()->getInfo(); - $token_problems = array( - 'not-array' => array( + $token_problems = [ + 'not-array' => [ 'label' => t('Tokens or token types not defined as arrays'), 'severity' => REQUIREMENT_ERROR, - ), - 'missing-info' => array( + ], + 'missing-info' => [ 'label' => t('Tokens or token types missing name property'), 'severity' => REQUIREMENT_WARNING, - ), - 'type-no-tokens' => array( + ], + 'type-no-tokens' => [ 'label' => t('Token types do not have any tokens defined'), 'severity' => REQUIREMENT_INFO, - ), - 'tokens-no-type' => array( + ], + 'tokens-no-type' => [ 'label' => t('Token types are not defined but have tokens'), 'severity' => REQUIREMENT_INFO, - ), - 'duplicate' => array( + ], + 'duplicate' => [ 'label' => t('Token or token types are defined by multiple modules'), 'severity' => REQUIREMENT_ERROR, - ), - ); + ], + ]; // Check token types for problems. foreach ($token_info['types'] as $type => $type_info) { @@ -313,4 +311,4 @@ function token_get_token_problems() { } return $token_problems; -} \ No newline at end of file +} diff --git a/token.module b/token.module index 32a38da..e35a13d 100644 --- a/token.module +++ b/token.module @@ -15,7 +15,6 @@ use Drupal\Core\Render\Element; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Entity\EntityTypeInterface; use Drupal\Core\Field\BaseFieldDefinition; -use Drupal\Core\TypedData\TranslatableInterface; use Drupal\menu_link_content\Entity\MenuLinkContent; use Drupal\menu_link_content\MenuLinkContentInterface; use Drupal\node\Entity\Node; @@ -47,7 +46,7 @@ function token_help($route_name, RouteMatchInterface $route_match) { * Return an array of the core modules supported by token.module. */ function _token_core_supported_modules() { - return array('book', 'field', 'menu_ui'); + return ['book', 'field', 'menu_ui']; } /** @@ -96,8 +95,7 @@ function token_form_block_form_alter(&$form, FormStateInterface $form_state) { ]; $rendered_token_tree = \Drupal::service('renderer')->render($token_tree); $form['settings']['label']['#description'] = - t('This field supports tokens. @browse_tokens_link', ['@browse_tokens_link' => $rendered_token_tree]) - ; + t('This field supports tokens. @browse_tokens_link', ['@browse_tokens_link' => $rendered_token_tree]); $form['settings']['label']['#element_validate'][] = 'token_element_validate'; $form['settings']['label'] += ['#token_types' => []]; } @@ -106,7 +104,7 @@ function token_form_block_form_alter(&$form, FormStateInterface $form_state) { * Implements hook_field_info_alter(). */ function token_field_info_alter(&$info) { - $defaults = array( + $defaults = [ 'taxonomy_term_reference' => 'taxonomy_term_reference_plain', 'number_integer' => 'number_unformatted', 'number_decimal' => 'number_unformatted', @@ -120,10 +118,10 @@ function token_field_info_alter(&$info) { 'list_float' => 'list_default', 'list_string' => 'list_default', 'list_boolean' => 'list_default', - ); + ]; foreach ($defaults as $field_type => $default_token_formatter) { if (isset($info[$field_type])) { - $info[$field_type] += array('default_token_formatter' => $default_token_formatter); + $info[$field_type] += ['default_token_formatter' => $default_token_formatter]; } } } @@ -226,7 +224,7 @@ function token_module_implements_alter(&$implementations, $hook) { // other modules. if (isset($implementations['token'])) { unset($implementations['token']); - $implementations = array_merge(array('token' => 'tokens'), $implementations); + $implementations = array_merge(['token' => 'tokens'], $implementations); } } } @@ -281,13 +279,13 @@ function token_element_validate($element, FormStateInterface $form_state) { // Validate if an element must have a minimum number of tokens. if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) { - $error = \Drupal::translation()->formatPlural($element['#min_tokens'], '%name must contain at least one token.', '%name must contain at least @count tokens.', array('%name' => $title)); + $error = \Drupal::translation()->formatPlural($element['#min_tokens'], '%name must contain at least one token.', '%name must contain at least @count tokens.', ['%name' => $title]); $form_state->setError($element, $error); } // Validate if an element must have a maximum number of tokens. if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) { - $error = \Drupal::translation()->formatPlural($element['#max_tokens'], '%name must contain at most one token.', '%name must contain at most @count tokens.', array('%name' => $title)); + $error = \Drupal::translation()->formatPlural($element['#max_tokens'], '%name must contain at most one token.', '%name must contain at most @count tokens.', ['%name' => $title]); $form_state->setError($element, $error); } @@ -295,7 +293,7 @@ function token_element_validate($element, FormStateInterface $form_state) { if (isset($element['#token_types'])) { $invalid_tokens = \Drupal::token()->getInvalidTokensByContext($tokens, $element['#token_types']); if ($invalid_tokens) { - $form_state->setError($element, t('%name is using the following invalid tokens: @invalid-tokens.', array('%name' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens)))); + $form_state->setError($element, t('%name is using the following invalid tokens: @invalid-tokens.', ['%name' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens)])); } } @@ -318,19 +316,19 @@ function token_form_field_config_edit_form_alter(&$form, FormStateInterface $for // Date support needs to be implicitly added, as while technically it's not // a global token, it is a not only used but is the default value. // https://www.drupal.org/node/2642160 - $form['settings']['file_directory'] += array('#token_types' => array('date')); + $form['settings']['file_directory'] += ['#token_types' => ['date']]; $form['settings']['file_directory']['#description'] .= ' ' . t('This field supports tokens.'); } // Note that the description is tokenized via token_field_widget_form_alter(). $form['description']['#element_validate'][] = 'token_element_validate'; - $form['description'] += array('#token_types' => array()); + $form['description'] += ['#token_types' => []]; - $form['token_tree'] = array( + $form['token_tree'] = [ '#theme' => 'token_tree_link', - '#token_types' => array(), + '#token_types' => [], '#weight' => $form['description']['#weight'] + 0.5, - ); + ]; } /** @@ -380,6 +378,7 @@ function token_form_user_admin_settings_alter(&$form, FormStateInterface $form_s case 'email_cancel_confirm': // Do nothing, but allow execution to continue. break; + case 'email_activated': case 'email_blocked': case 'email_canceled': @@ -387,6 +386,7 @@ function token_form_user_admin_settings_alter(&$form, FormStateInterface $form_s // sub-element, so switch to that element instead. $element = &$form[$key]['settings']; break; + default: continue 2; } @@ -398,24 +398,24 @@ function token_form_user_admin_settings_alter(&$form, FormStateInterface $form_s elseif ($element[$sub_key]['#type'] == 'textfield' && substr($sub_key, -8) === '_subject') { // Add validation to subject textfields. $element[$sub_key]['#element_validate'][] = 'token_element_validate'; - $element[$sub_key] += array('#token_types' => array('user')); + $element[$sub_key] += ['#token_types' => ['user']]; } elseif ($element[$sub_key]['#type'] == 'textarea' && substr($sub_key, -5) === '_body') { // Add validation to body textareas. $element[$sub_key]['#element_validate'][] = 'token_element_validate'; - $element[$sub_key] += array('#token_types' => array('user')); + $element[$sub_key] += ['#token_types' => ['user']]; } } } // Add the token tree UI. - $form['email']['token_tree'] = array( + $form['email']['token_tree'] = [ '#theme' => 'token_tree_link', - '#token_types' => array('user'), + '#token_types' => ['user'], '#show_restricted' => TRUE, '#show_nested' => FALSE, '#weight' => 90, - ); + ]; } /** @@ -423,14 +423,15 @@ function token_form_user_admin_settings_alter(&$form, FormStateInterface $form_s * * @param $name * The token name to clean. + * * @return * The cleaned token name. */ function token_clean_token_name($name) { - static $names = array(); + static $names = []; if (!isset($names[$name])) { - $cleaned_name = strtr($name, array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')); + $cleaned_name = strtr($name, [' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '']); $cleaned_name = preg_replace('/[^\w\-]/i', '', $cleaned_name); $cleaned_name = trim($cleaned_name, '-'); $names[$name] = $cleaned_name; @@ -442,8 +443,8 @@ function token_clean_token_name($name) { /** * Do not use this function yet. Its API has not been finalized. */ -function token_render_array(array $array, array $options = array()) { - $rendered = array(); +function token_render_array(array $array, array $options = []) { + $rendered = []; /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); @@ -459,7 +460,7 @@ function token_render_array(array $array, array $options = array()) { /** * Do not use this function yet. Its API has not been finalized. */ -function token_render_array_value($value, array $options = array()) { +function token_render_array_value($value, array $options = []) { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); @@ -493,7 +494,7 @@ function token_render_cache_get($elements) { */ function token_render_cache_set(&$markup, $elements) { // This should only run of drupal_render_cache_set() did not. - if (in_array(\Drupal::request()->server->get('REQUEST_METHOD'), array('GET', 'HEAD'))) { + if (in_array(\Drupal::request()->server->get('REQUEST_METHOD'), ['GET', 'HEAD'])) { return FALSE; } @@ -515,10 +516,10 @@ function token_render_cache_set(&$markup, $elements) { * List of menu link parent titles. */ function token_menu_link_load_all_parents($plugin_id, $langcode) { - $cache = &drupal_static(__FUNCTION__, array()); + $cache = &drupal_static(__FUNCTION__, []); if (!isset($cache[$plugin_id][$langcode])) { - $cache[$plugin_id][$langcode] = array(); + $cache[$plugin_id][$langcode] = []; /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */ $menu_link_manager = \Drupal::service('plugin.manager.menu.link'); $parent_ids = $menu_link_manager->getParentIds($plugin_id); @@ -526,7 +527,7 @@ function token_menu_link_load_all_parents($plugin_id, $langcode) { unset($parent_ids[$plugin_id]); foreach ($parent_ids as $parent_id) { $parent = $menu_link_manager->createInstance($parent_id); - $cache[$plugin_id][$langcode] = array($parent_id => token_menu_link_translated_title($parent, $langcode)) + $cache[$plugin_id][$langcode]; + $cache[$plugin_id][$langcode] = [$parent_id => token_menu_link_translated_title($parent, $langcode)] + $cache[$plugin_id][$langcode]; } } @@ -573,14 +574,14 @@ function token_menu_link_translated_title(MenuLinkInterface $menu_link, $langcod * The term parents collection. */ function token_taxonomy_term_load_all_parents($tid, $langcode) { - $cache = &drupal_static(__FUNCTION__, array()); + $cache = &drupal_static(__FUNCTION__, []); if (!is_numeric($tid)) { - return array(); + return []; } if (!isset($cache[$langcode][$tid])) { - $cache[$langcode][$tid] = array(); + $cache[$langcode][$tid] = []; /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */ $term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); $parents = $term_storage->loadAllParents($tid); @@ -596,12 +597,15 @@ function token_taxonomy_term_load_all_parents($tid, $langcode) { return $cache[$langcode][$tid]; } +/** + * + */ function token_element_children(&$elements, $sort = FALSE) { // Do not attempt to sort elements which have already been sorted. $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort; // Filter out properties from the element, leaving only children. - $children = array(); + $children = []; $sortable = FALSE; foreach ($elements as $key => $value) { if ($key === '' || $key[0] !== '#') { @@ -639,15 +643,15 @@ function token_element_children(&$elements, $sort = FALSE) { * List of node titles of the book parents. */ function token_book_load_all_parents(array $book) { - $cache = &drupal_static(__FUNCTION__, array()); + $cache = &drupal_static(__FUNCTION__, []); if (empty($book['nid'])) { - return array(); + return []; } $nid = $book['nid']; if (!isset($cache[$nid])) { - $cache[$nid] = array(); + $cache[$nid] = []; $i = 1; while ($book["p$i"] != $nid) { $cache[$nid][] = Node::load($book["p$i"])->getTitle(); @@ -673,14 +677,14 @@ function token_entity_base_field_info(EntityTypeInterface $entity_type) { ->setRevisionable(TRUE) ->setSetting('target_type', 'menu_link_content') ->setTranslatable(TRUE) - ->setDisplayOptions('view', array( + ->setDisplayOptions('view', [ 'label' => 'hidden', 'type' => 'hidden', - )) + ]) ->setComputed(TRUE) - ->setDisplayOptions('form', array( + ->setDisplayOptions('form', [ 'type' => 'hidden', - )); + ]); return $fields; } @@ -740,19 +744,19 @@ function token_node_menu_link_submit($entity_type, NodeInterface $node, &$form, else { if ($node->isNew()) { // Create a new menu_link_content entity. - $entity = MenuLinkContent::create(array( + $entity = MenuLinkContent::create([ // Lets just reference the UUID for now, the link is not important for // token generation. 'link' => ['uri' => 'internal:/node/' . $node->uuid()], 'langcode' => $node->language()->getId(), - )); + ]); } else { // Create a new menu_link_content entity. - $entity = MenuLinkContent::create(array( + $entity = MenuLinkContent::create([ 'link' => ['uri' => 'entity:node/' . $node->id()], 'langcode' => $node->language()->getId(), - )); + ]); } } $entity->title->value = trim($values['title']); @@ -775,7 +779,7 @@ function token_node_menu_link_submit($entity_type, NodeInterface $node, &$form, function token_node_insert(NodeInterface $node) { if ($node->hasField('menu_link') && $menu_link = $node->menu_link->entity) { // Update the menu-link to point to the now saved node. - $menu_link->link = 'entity:node/' . $node->id(); + $menu_link->link = 'entity:node/' . $node->id(); $menu_link->save(); } } diff --git a/token.pages.inc b/token.pages.inc index 4b92df1..75960d7 100644 --- a/token.pages.inc +++ b/token.pages.inc @@ -4,6 +4,7 @@ * @file * User page callbacks for the token module. */ + use Drupal\Component\Serialization\Json; use Drupal\Component\Utility\DiffArray; use Drupal\Core\Link; @@ -53,7 +54,7 @@ function template_preprocess_token_tree_link(&$variables) { 'draggable' => TRUE, 'autoResize' => FALSE, ]), - ]; + ]; $variables['link'] = Link::createFromRoute($variables['text'], 'token.tree', [], $variables['options'])->toRenderable(); $variables['url'] = new Url('token.tree', [], $variables['options']); diff --git a/token.tokens.inc b/token.tokens.inc index f6ad619..9ee49a6 100644 --- a/token.tokens.inc +++ b/token.tokens.inc @@ -4,6 +4,7 @@ * @file * Token callbacks for the token module. */ + use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Core\Entity\FieldableEntityInterface; use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface; @@ -21,7 +22,6 @@ use Drupal\node\NodeInterface; use Drupal\system\Entity\Menu; use Drupal\user\UserInterface; use Symfony\Cmf\Component\Routing\RouteObjectInterface; -use Drupal\Core\TypedData\PrimitiveInterface; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\Entity\ContentEntityTypeInterface; use Drupal\image\Entity\ImageStyle; @@ -33,11 +33,11 @@ function token_token_info_alter(&$info) { // Force 'date' type tokens to require input and add a 'current-date' type. // @todo Remove when http://drupal.org/node/943028 is fixed. $info['types']['date']['needs-data'] = 'date'; - $info['types']['current-date'] = array( + $info['types']['current-date'] = [ 'name' => t('Current date'), 'description' => t('Tokens related to the current date and time.'), 'type' => 'date', - ); + ]; // Add a 'dynamic' key to any tokens that have chained but dynamic tokens. $info['tokens']['date']['custom']['dynamic'] = TRUE; @@ -87,22 +87,22 @@ function token_token_info_alter(&$info) { // Add [entity:url] tokens if they do not already exist. // @todo Support entity:label if (!isset($info['tokens'][$token_type]['url'])) { - $info['tokens'][$token_type]['url'] = array( + $info['tokens'][$token_type]['url'] = [ 'name' => t('URL'), - 'description' => t('The URL of the @entity.', array('@entity' => Unicode::strtolower($entity_info->getLabel()))), + 'description' => t('The URL of the @entity.', ['@entity' => Unicode::strtolower($entity_info->getLabel())]), 'module' => 'token', 'type' => 'url', - ); + ]; } // Add [entity:original] tokens if they do not already exist. if (!isset($info['tokens'][$token_type]['original'])) { - $info['tokens'][$token_type]['original'] = array( - 'name' => t('Original @entity', array('@entity' => Unicode::strtolower($entity_info->getLabel()))), - 'description' => t('The original @entity data if the @entity is being updated or saved.', array('@entity' => Unicode::strtolower($entity_info->getLabel()))), + $info['tokens'][$token_type]['original'] = [ + 'name' => t('Original @entity', ['@entity' => Unicode::strtolower($entity_info->getLabel())]), + 'description' => t('The original @entity data if the @entity is being updated or saved.', ['@entity' => Unicode::strtolower($entity_info->getLabel())]), 'module' => 'token', 'type' => $token_type, - ); + ]; } } @@ -112,11 +112,11 @@ function token_token_info_alter(&$info) { foreach ($date_format_types as $date_format_type => $date_format_type_info) { /* @var \Drupal\system\Entity\DateFormat $date_format_type_info */ if (!isset($info['tokens']['date'][$date_format_type])) { - $info['tokens']['date'][$date_format_type] = array( + $info['tokens']['date'][$date_format_type] = [ 'name' => Html::escape($date_format_type_info->label()), - 'description' => t("A date in '@type' format. (%date)", array('@type' => $date_format_type, '%date' => format_date(REQUEST_TIME, $date_format_type))), + 'description' => t("A date in '@type' format. (%date)", ['@type' => $date_format_type, '%date' => format_date(REQUEST_TIME, $date_format_type)]), 'module' => 'token', - ); + ]; } } } @@ -126,264 +126,264 @@ function token_token_info_alter(&$info) { */ function token_token_info() { // Node tokens. - $info['tokens']['node']['source'] = array( + $info['tokens']['node']['source'] = [ 'name' => t('Translation source node'), 'description' => t("The source node for this current node's translation set."), 'type' => 'node', - ); - $info['tokens']['node']['log'] = array( + ]; + $info['tokens']['node']['log'] = [ 'name' => t('Revision log message'), 'description' => t('The explanation of the most recent changes made to the node.'), - ); - $info['tokens']['node']['content-type'] = array( + ]; + $info['tokens']['node']['content-type'] = [ 'name' => t('Content type'), 'description' => t('The content type of the node.'), 'type' => 'content-type', - ); + ]; // Content type tokens. - $info['types']['content-type'] = array( + $info['types']['content-type'] = [ 'name' => t('Content types'), 'description' => t('Tokens related to content types.'), 'needs-data' => 'node_type', - ); - $info['tokens']['content-type']['name'] = array( + ]; + $info['tokens']['content-type']['name'] = [ 'name' => t('Name'), 'description' => t('The name of the content type.'), - ); - $info['tokens']['content-type']['machine-name'] = array( + ]; + $info['tokens']['content-type']['machine-name'] = [ 'name' => t('Machine-readable name'), 'description' => t('The unique machine-readable name of the content type.'), - ); - $info['tokens']['content-type']['description'] = array( + ]; + $info['tokens']['content-type']['description'] = [ 'name' => t('Description'), 'description' => t('The optional description of the content type.'), - ); - $info['tokens']['content-type']['node-count'] = array( + ]; + $info['tokens']['content-type']['node-count'] = [ 'name' => t('Node count'), 'description' => t('The number of nodes belonging to the content type.'), - ); - $info['tokens']['content-type']['edit-url'] = array( + ]; + $info['tokens']['content-type']['edit-url'] = [ 'name' => t('Edit URL'), 'description' => t("The URL of the content type's edit page."), - // 'type' => 'url', - ); + // 'type' => 'url',. + ]; // Taxonomy term and vocabulary tokens. if (\Drupal::moduleHandler()->moduleExists('taxonomy')) { - $info['tokens']['term']['edit-url'] = array( + $info['tokens']['term']['edit-url'] = [ 'name' => t('Edit URL'), 'description' => t("The URL of the taxonomy term's edit page."), - // 'type' => 'url', - ); - $info['tokens']['term']['parents'] = array( + // 'type' => 'url',. + ]; + $info['tokens']['term']['parents'] = [ 'name' => t('Parents'), 'description' => t("An array of all the term's parents, starting with the root."), 'type' => 'array', - ); - $info['tokens']['term']['root'] = array( + ]; + $info['tokens']['term']['root'] = [ 'name' => t('Root term'), 'description' => t("The root term of the taxonomy term."), 'type' => 'term', - ); + ]; - $info['tokens']['vocabulary']['machine-name'] = array( + $info['tokens']['vocabulary']['machine-name'] = [ 'name' => t('Machine-readable name'), 'description' => t('The unique machine-readable name of the vocabulary.'), - ); - $info['tokens']['vocabulary']['edit-url'] = array( + ]; + $info['tokens']['vocabulary']['edit-url'] = [ 'name' => t('Edit URL'), 'description' => t("The URL of the vocabulary's edit page."), - // 'type' => 'url', - ); + // 'type' => 'url',. + ]; } // File tokens. - $info['tokens']['file']['basename'] = array( + $info['tokens']['file']['basename'] = [ 'name' => t('Base name'), 'description' => t('The base name of the file.'), - ); - $info['tokens']['file']['extension'] = array( + ]; + $info['tokens']['file']['extension'] = [ 'name' => t('Extension'), 'description' => t('The extension of the file.'), - ); - $info['tokens']['file']['size-raw'] = array( + ]; + $info['tokens']['file']['size-raw'] = [ 'name' => t('File byte size'), 'description' => t('The size of the file, in bytes.'), - ); + ]; // User tokens. // Add information on the restricted user tokens. - $info['tokens']['user']['cancel-url'] = array( + $info['tokens']['user']['cancel-url'] = [ 'name' => t('Account cancellation URL'), 'description' => t('The URL of the confirm delete page for the user account.'), 'restricted' => TRUE, - // 'type' => 'url', - ); - $info['tokens']['user']['one-time-login-url'] = array( + // 'type' => 'url',. + ]; + $info['tokens']['user']['one-time-login-url'] = [ 'name' => t('One-time login URL'), 'description' => t('The URL of the one-time login page for the user account.'), 'restricted' => TRUE, - // 'type' => 'url', - ); - $info['tokens']['user']['roles'] = array( + // 'type' => 'url',. + ]; + $info['tokens']['user']['roles'] = [ 'name' => t('Roles'), 'description' => t('The user roles associated with the user account.'), 'type' => 'array', - ); + ]; // Current user tokens. - $info['tokens']['current-user']['ip-address'] = array( + $info['tokens']['current-user']['ip-address'] = [ 'name' => t('IP address'), 'description' => 'The IP address of the current user.', - ); + ]; // Menu link tokens (work regardless if menu module is enabled or not). - $info['types']['menu-link'] = array( + $info['types']['menu-link'] = [ 'name' => t('Menu links'), 'description' => t('Tokens related to menu links.'), 'needs-data' => 'menu-link', - ); - $info['tokens']['menu-link']['mlid'] = array( + ]; + $info['tokens']['menu-link']['mlid'] = [ 'name' => t('Link ID'), 'description' => t('The unique ID of the menu link.'), - ); - $info['tokens']['menu-link']['title'] = array( + ]; + $info['tokens']['menu-link']['title'] = [ 'name' => t('Title'), 'description' => t('The title of the menu link.'), - ); - $info['tokens']['menu-link']['url'] = array( + ]; + $info['tokens']['menu-link']['url'] = [ 'name' => t('URL'), 'description' => t('The URL of the menu link.'), 'type' => 'url', - ); - $info['tokens']['menu-link']['parent'] = array( + ]; + $info['tokens']['menu-link']['parent'] = [ 'name' => t('Parent'), 'description' => t("The menu link's parent."), 'type' => 'menu-link', - ); - $info['tokens']['menu-link']['parents'] = array( + ]; + $info['tokens']['menu-link']['parents'] = [ 'name' => t('Parents'), 'description' => t("An array of all the menu link's parents, starting with the root."), 'type' => 'array', - ); - $info['tokens']['menu-link']['root'] = array( + ]; + $info['tokens']['menu-link']['root'] = [ 'name' => t('Root'), 'description' => t("The menu link's root."), 'type' => 'menu-link', - ); + ]; // Current page tokens. - $info['types']['current-page'] = array( + $info['types']['current-page'] = [ 'name' => t('Current page'), 'description' => t('Tokens related to the current page request.'), - ); - $info['tokens']['current-page']['title'] = array( + ]; + $info['tokens']['current-page']['title'] = [ 'name' => t('Title'), 'description' => t('The title of the current page.'), - ); - $info['tokens']['current-page']['url'] = array( + ]; + $info['tokens']['current-page']['url'] = [ 'name' => t('URL'), 'description' => t('The URL of the current page.'), 'type' => 'url', - ); - $info['tokens']['current-page']['page-number'] = array( + ]; + $info['tokens']['current-page']['page-number'] = [ 'name' => t('Page number'), 'description' => t('The page number of the current page when viewing paged lists.'), - ); - $info['tokens']['current-page']['query'] = array( + ]; + $info['tokens']['current-page']['query'] = [ 'name' => t('Query string value'), 'description' => t('The value of a specific query string field of the current page.'), 'dynamic' => TRUE, - ); + ]; // URL tokens. - $info['types']['url'] = array( + $info['types']['url'] = [ 'name' => t('URL'), 'description' => t('Tokens related to URLs.'), 'needs-data' => 'path', - ); - $info['tokens']['url']['path'] = array( + ]; + $info['tokens']['url']['path'] = [ 'name' => t('Path'), 'description' => t('The path component of the URL.'), - ); - $info['tokens']['url']['relative'] = array( + ]; + $info['tokens']['url']['relative'] = [ 'name' => t('Relative URL'), 'description' => t('The relative URL.'), - ); - $info['tokens']['url']['absolute'] = array( + ]; + $info['tokens']['url']['absolute'] = [ 'name' => t('Absolute URL'), 'description' => t('The absolute URL.'), - ); - $info['tokens']['url']['brief'] = array( + ]; + $info['tokens']['url']['brief'] = [ 'name' => t('Brief URL'), 'description' => t('The URL without the protocol and trailing backslash.'), - ); - $info['tokens']['url']['unaliased'] = array( + ]; + $info['tokens']['url']['unaliased'] = [ 'name' => t('Unaliased URL'), 'description' => t('The unaliased URL.'), 'type' => 'url', - ); - $info['tokens']['url']['args'] = array( + ]; + $info['tokens']['url']['args'] = [ 'name' => t('Arguments'), 'description' => t("The specific argument of the current page (e.g. 'arg:1' on the page 'node/1' returns '1')."), 'type' => 'array', - ); + ]; // Array tokens. - $info['types']['array'] = array( + $info['types']['array'] = [ 'name' => t('Array'), 'description' => t('Tokens related to arrays of strings.'), 'needs-data' => 'array', 'nested' => TRUE, - ); - $info['tokens']['array']['first'] = array( + ]; + $info['tokens']['array']['first'] = [ 'name' => t('First'), 'description' => t('The first element of the array.'), - ); - $info['tokens']['array']['last'] = array( + ]; + $info['tokens']['array']['last'] = [ 'name' => t('Last'), 'description' => t('The last element of the array.'), - ); - $info['tokens']['array']['count'] = array( + ]; + $info['tokens']['array']['count'] = [ 'name' => t('Count'), 'description' => t('The number of elements in the array.'), - ); - $info['tokens']['array']['reversed'] = array( + ]; + $info['tokens']['array']['reversed'] = [ 'name' => t('Reversed'), 'description' => t('The array reversed.'), 'type' => 'array', - ); - $info['tokens']['array']['keys'] = array( + ]; + $info['tokens']['array']['keys'] = [ 'name' => t('Keys'), 'description' => t('The array of keys of the array.'), 'type' => 'array', - ); - $info['tokens']['array']['join'] = array( + ]; + $info['tokens']['array']['join'] = [ 'name' => t('Imploded'), 'description' => t('The values of the array joined together with a custom string in-between each value.'), 'dynamic' => TRUE, - ); - $info['tokens']['array']['value'] = array( + ]; + $info['tokens']['array']['value'] = [ 'name' => t('Value'), 'description' => t('The specific value of the array.'), 'dynamic' => TRUE, - ); + ]; // Random tokens. - $info['types']['random'] = array( + $info['types']['random'] = [ 'name' => t('Random'), 'description' => t('Tokens related to random data.'), - ); - $info['tokens']['random']['number'] = array( + ]; + $info['tokens']['random']['number'] = [ 'name' => t('Number'), - 'description' => t('A random number from 0 to @max.', array('@max' => mt_getrandmax())), - ); - $info['tokens']['random']['hash'] = array( + 'description' => t('A random number from 0 to @max.', ['@max' => mt_getrandmax()]), + ]; + $info['tokens']['random']['hash'] = [ 'name' => t('Hash'), - 'description' => t('A random hash. The possible hashing algorithms are: @hash-algos.', array('@hash-algos' => implode(', ', hash_algos()))), + 'description' => t('A random hash. The possible hashing algorithms are: @hash-algos.', ['@hash-algos' => implode(', ', hash_algos())]), 'dynamic' => TRUE, - ); + ]; // Define image_with_image_style token type. if (\Drupal::moduleHandler()->moduleExists('image')) { @@ -427,10 +427,10 @@ function token_token_info() { /** * Implements hook_tokens(). */ -function token_tokens($type, array $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) { - $replacements = array(); +function token_tokens($type, array $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) { + $replacements = []; $language_manager = \Drupal::languageManager(); - $url_options = array('absolute' => TRUE); + $url_options = ['absolute' => TRUE]; if (isset($options['langcode'])) { $url_options['language'] = $language_manager->getLanguage($options['langcode']); $langcode = $options['langcode']; @@ -455,7 +455,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Current date tokens. // @todo Remove when http://drupal.org/node/943028 is fixed. if ($type == 'current-date') { - $replacements += \Drupal::token()->generate('date', $tokens, array('date' => REQUEST_TIME), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('date', $tokens, ['date' => REQUEST_TIME], $options, $bubbleable_metadata); } // Comment tokens. @@ -466,7 +466,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Chained token relationships. if (($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url'))) { // Add fragment to url options. - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $comment->urlInfo('canonical', ['fragment' => "comment-{$comment->id()}"])), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $comment->urlInfo('canonical', ['fragment' => "comment-{$comment->id()}"])], $options, $bubbleable_metadata); } } @@ -480,6 +480,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option case 'log': $replacements[$original] = (string) $node->revision_log->value; break; + case 'content-type': $type_name = \Drupal::entityTypeManager()->getStorage('node_type')->load($node->getType())->label(); $replacements[$original] = $type_name; @@ -489,13 +490,13 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Chained token relationships. if (($parent_tokens = \Drupal::token()->findWithPrefix($tokens, 'source')) && $source_node = $node->getUntranslated()) { - $replacements += \Drupal::token()->generate('node', $parent_tokens, array('node' => $source_node), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('node', $parent_tokens, ['node' => $source_node], $options, $bubbleable_metadata); } if (($node_type_tokens = \Drupal::token()->findWithPrefix($tokens, 'content-type')) && $node_type = node_type_load($node->bundle())) { - $replacements += \Drupal::token()->generate('content-type', $node_type_tokens, array('node_type' => $node_type), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('content-type', $node_type_tokens, ['node_type' => $node_type], $options, $bubbleable_metadata); } if (($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url'))) { - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $node->urlInfo()), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $node->urlInfo()], $options, $bubbleable_metadata); } } @@ -509,12 +510,15 @@ function token_tokens($type, array $tokens, array $data = array(), array $option case 'name': $replacements[$original] = $node_type->label(); break; + case 'machine-name': $replacements[$original] = $node_type->id(); break; + case 'description': $replacements[$original] = $node_type->getDescription(); break; + case 'node-count': $count = \Drupal::entityQueryAggregate('node') ->aggregate('nid', 'COUNT') @@ -522,6 +526,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option ->execute(); $replacements[$original] = (int) $count; break; + case 'edit-url': $replacements[$original] = $node_type->url('edit-form', $url_options); break; @@ -561,19 +566,19 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Chained token relationships. if (($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url'))) { - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $term->urlInfo()), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $term->urlInfo()], $options, $bubbleable_metadata); } // [term:parents:*] chained tokens. if ($parents_tokens = \Drupal::token()->findWithPrefix($tokens, 'parents')) { if ($parents = token_taxonomy_term_load_all_parents($term->id(), $langcode)) { - $replacements += \Drupal::token()->generate('array', $parents_tokens, array('array' => $parents), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $parents_tokens, ['array' => $parents], $options, $bubbleable_metadata); } } if ($root_tokens = \Drupal::token()->findWithPrefix($tokens, 'root')) { $parents = $term_storage->loadAllParents($term->id()); $root_term = end($parents); if ($root_term->tid != $term->id()) { - $replacements += \Drupal::token()->generate('term', $root_tokens, array('term' => $root_term), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('term', $root_tokens, ['term' => $root_term], $options, $bubbleable_metadata); } } } @@ -587,6 +592,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option case 'machine-name': $replacements[$original] = $vocabulary->id(); break; + case 'edit-url': $replacements[$original] = Url::fromRoute('entity.taxonomy_vocabulary.edit_form', ['taxonomy_vocabulary' => $vocabulary->id()], $url_options)->toString(); break; @@ -604,10 +610,12 @@ function token_tokens($type, array $tokens, array $data = array(), array $option $basename = pathinfo($file->uri->value, PATHINFO_BASENAME); $replacements[$original] = $basename; break; + case 'extension': $extension = pathinfo($file->uri->value, PATHINFO_EXTENSION); $replacements[$original] = $extension; break; + case 'size-raw': $replacements[$original] = (int) $file->filesize->value; break; @@ -644,15 +652,15 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Chained token relationships. if ($account instanceof UserInterface && $account->hasField('user_picture') && ($picture_tokens = \Drupal::token()->findWithPrefix($tokens, 'picture'))) { - $replacements += \Drupal::token()->generate('file', $picture_tokens, array('file' => $account->user_picture->entity), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('file', $picture_tokens, ['file' => $account->user_picture->entity], $options, $bubbleable_metadata); } if ($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url')) { - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $account->urlInfo()), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $account->urlInfo()], $options, $bubbleable_metadata); } if ($role_tokens = \Drupal::token()->findWithPrefix($tokens, 'roles')) { $roles = $account->getRoles(); $roles_names = array_combine($roles, $roles); - $replacements += \Drupal::token()->generate('array', $role_tokens, array('array' => $roles_names), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $role_tokens, ['array' => $roles_names], $options, $bubbleable_metadata); } } @@ -684,12 +692,15 @@ function token_tokens($type, array $tokens, array $data = array(), array $option case 'id': $replacements[$original] = $link->getPluginId(); break; + case 'title': $replacements[$original] = token_menu_link_translated_title($link, $langcode); break; + case 'url': $replacements[$original] = $link->getUrlObject()->setAbsolute()->toString(); break; + case 'parent': /** @var \Drupal\Core\Menu\MenuLinkInterface $parent */ @@ -697,11 +708,13 @@ function token_tokens($type, array $tokens, array $data = array(), array $option $replacements[$original] = token_menu_link_translated_title($parent, $langcode); } break; + case 'parents': if ($parents = token_menu_link_load_all_parents($link->getPluginId(), $langcode)) { $replacements[$original] = token_render_array($parents, $options); } break; + case 'root'; if ($link->getParent() && $parent_ids = array_keys(token_menu_link_load_all_parents($link->getPluginId(), $langcode))) { $root = $menu_link_manager->createInstance(array_shift($parent_ids)); @@ -714,20 +727,20 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Chained token relationships. /** @var \Drupal\Core\Menu\MenuLinkInterface $parent */ if ($link->getParent() && ($parent_tokens = \Drupal::token()->findWithPrefix($tokens, 'parent')) && $parent = $menu_link_manager->createInstance($link->getParent())) { - $replacements += \Drupal::token()->generate('menu-link', $parent_tokens, array('menu-link' => $parent), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('menu-link', $parent_tokens, ['menu-link' => $parent], $options, $bubbleable_metadata); } // [menu-link:parents:*] chained tokens. if ($parents_tokens = \Drupal::token()->findWithPrefix($tokens, 'parents')) { if ($parents = token_menu_link_load_all_parents($link->getPluginId(), $langcode)) { - $replacements += \Drupal::token()->generate('array', $parents_tokens, array('array' => $parents), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $parents_tokens, ['array' => $parents], $options, $bubbleable_metadata); } } if (($root_tokens = \Drupal::token()->findWithPrefix($tokens, 'root')) && $link->getParent() && $parent_ids = array_keys(token_menu_link_load_all_parents($link->getPluginId(), $langcode))) { $root = $menu_link_manager->createInstance(array_shift($parent_ids)); - $replacements += \Drupal::token()->generate('menu-link', $root_tokens, array('menu-link' => $root), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('menu-link', $root_tokens, ['menu-link' => $root], $options, $bubbleable_metadata); } if ($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url')) { - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $link->getUrlObject()), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $link->getUrlObject()], $options, $bubbleable_metadata); } } @@ -744,9 +757,11 @@ function token_tokens($type, array $tokens, array $data = array(), array $option $replacements[$original] = token_render_array_value($title); } break; + case 'url': $replacements[$original] = Url::fromRoute('', [], $url_options)->toString(); break; + case 'page-number': if ($page = \Drupal::request()->query->get('page')) { // @see PagerDefault::execute() @@ -785,7 +800,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Chained token relationships. if ($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url')) { $url = Url::fromRoute(''); - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $url), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $url], $options, $bubbleable_metadata); } } @@ -803,24 +818,30 @@ function token_tokens($type, array $tokens, array $data = array(), array $option $value = !($url->getOption('alias')) ? \Drupal::service('path.alias_manager')->getAliasByPath($path, $langcode) : $path; $replacements[$original] = $value; break; + case 'alias': // @deprecated $alias = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langcode); $replacements[$original] = $alias; break; + case 'absolute': $replacements[$original] = $url->setAbsolute()->toString(); break; + case 'relative': $replacements[$original] = $url->setAbsolute(FALSE)->toString(); break; + case 'brief': - $replacements[$original] = preg_replace(array('!^https?://!', '!/$!'), '', $url->setAbsolute()->toString()); + $replacements[$original] = preg_replace(['!^https?://!', '!/$!'], '', $url->setAbsolute()->toString()); break; + case 'unaliased': $unaliased = clone $url; $replacements[$original] = $unaliased->setAbsolute()->setOption('alias', TRUE)->toString(); break; + case 'args': $value = !($url->getOption('alias')) ? \Drupal::service('path.alias_manager')->getAliasByPath($path, $langcode) : $path; $replacements[$original] = token_render_array(explode('/', $value), $options); @@ -832,13 +853,13 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // [url:args:*] chained tokens. if ($arg_tokens = \Drupal::token()->findWithPrefix($tokens, 'args')) { $value = !($url->getOption('alias')) ? \Drupal::service('path.alias_manager')->getAliasByPath($path, $langcode) : $path; - $replacements += \Drupal::token()->generate('array', $arg_tokens, array('array' => explode('/', ltrim($value, '/'))), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $arg_tokens, ['array' => explode('/', ltrim($value, '/'))], $options, $bubbleable_metadata); } // [url:unaliased:*] chained tokens. if ($unaliased_tokens = \Drupal::token()->findWithPrefix($tokens, 'unaliased')) { $url->setOption('alias', TRUE); - $replacements += \Drupal::token()->generate('url', $unaliased_tokens, array('url' => $url), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $unaliased_tokens, ['url' => $url], $options, $bubbleable_metadata); } } @@ -866,20 +887,20 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // [entity:url:*] chained tokens. if (($url_tokens = \Drupal::token()->findWithPrefix($tokens, 'url')) && _token_module($type, 'url') == 'token') { - $replacements += \Drupal::token()->generate('url', $url_tokens, array('url' => $entity->toUrl()), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('url', $url_tokens, ['url' => $entity->toUrl()], $options, $bubbleable_metadata); } // [entity:original:*] chained tokens. if (($original_tokens = \Drupal::token()->findWithPrefix($tokens, 'original')) && _token_module($type, 'original') == 'token' && !empty($entity->original)) { - $replacements += \Drupal::token()->generate($type, $original_tokens, array($type => $entity->original), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate($type, $original_tokens, [$type => $entity->original], $options, $bubbleable_metadata); } // Pass through to an generic 'entity' token type generation. - $entity_data = array( + $entity_data = [ 'entity_type' => $entity_type, 'entity' => $entity, 'token_type' => $type, - ); + ]; // @todo Investigate passing through more data like everything from entity_extract_ids(). $replacements += \Drupal::token()->generate('entity', $tokens, $entity_data, $options, $bubbleable_metadata); } @@ -901,23 +922,28 @@ function token_tokens($type, array $tokens, array $data = array(), array $option $value = is_array($value) ? $renderer->renderPlain($value) : (string) $value; $replacements[$original] = $value; break; + case 'last': $value = $array[$keys[count($keys) - 1]]; $value = is_array($value) ? $renderer->renderPlain($value) : (string) $value; - $replacements[$original] =$value; + $replacements[$original] = $value; break; + case 'count': $replacements[$original] = count($keys); break; + case 'keys': $replacements[$original] = token_render_array($keys, $options); break; + case 'reversed': $reversed = array_reverse($array, TRUE); $replacements[$original] = token_render_array($reversed, $options); break; + case 'join': - $replacements[$original] = token_render_array($array, array('join' => '') + $options); + $replacements[$original] = token_render_array($array, ['join' => ''] + $options); break; } } @@ -934,18 +960,18 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // [array:join:*] dynamic tokens. if ($join_tokens = \Drupal::token()->findWithPrefix($tokens, 'join')) { foreach ($join_tokens as $join => $original) { - $replacements[$original] = token_render_array($array, array('join' => $join) + $options); + $replacements[$original] = token_render_array($array, ['join' => $join] + $options); } } // [array:keys:*] chained tokens. if ($key_tokens = \Drupal::token()->findWithPrefix($tokens, 'keys')) { - $replacements += \Drupal::token()->generate('array', $key_tokens, array('array' => $keys), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $key_tokens, ['array' => $keys], $options, $bubbleable_metadata); } // [array:reversed:*] chained tokens. if ($reversed_tokens = \Drupal::token()->findWithPrefix($tokens, 'reversed')) { - $replacements += \Drupal::token()->generate('array', $reversed_tokens, array('array' => array_reverse($array, TRUE)), array('array sort' => FALSE) + $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $reversed_tokens, ['array' => array_reverse($array, TRUE)], ['array sort' => FALSE] + $options, $bubbleable_metadata); } // @todo Handle if the array values are not strings and could be chained. @@ -977,7 +1003,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option if (empty($data[$type]) && ($entity_type = \Drupal::service('token.entity_mapper')->getEntityTypeForTokenType($type)) && $entity_type != $type && !empty($data[$entity_type]) && empty($options['recursive'])) { $data[$type] = $data[$entity_type]; $options['recursive'] = TRUE; - $replacements += \Drupal::moduleHandler()->invokeAll('tokens', array($type, $tokens, $data, $options, $bubbleable_metadata)); + $replacements += \Drupal::moduleHandler()->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]); } // If the token type specifics a 'needs-data' value, and the value is not @@ -986,7 +1012,7 @@ function token_tokens($type, array $tokens, array $data = array(), array $option // Only check when tests are running. $type_info = \Drupal::token()->getTypeInfo($type); if (!empty($type_info['needs-data']) && !isset($data[$type_info['needs-data']])) { - trigger_error(t('Attempting to perform token replacement for token type %type without required data', array('%type' => $type)), E_USER_WARNING); + trigger_error(t('Attempting to perform token replacement for token type %type without required data', ['%type' => $type]), E_USER_WARNING); } } @@ -997,50 +1023,50 @@ function token_tokens($type, array $tokens, array $data = array(), array $option * Implements hook_token_info() on behalf of book.module. */ function book_token_info() { - $info['types']['book'] = array( + $info['types']['book'] = [ 'name' => t('Book'), 'description' => t('Tokens related to books.'), 'needs-data' => 'book', - ); + ]; - $info['tokens']['book']['title'] = array( + $info['tokens']['book']['title'] = [ 'name' => t('Title'), 'description' => t('Title of the book.'), - ); - $info['tokens']['book']['author'] = array( + ]; + $info['tokens']['book']['author'] = [ 'name' => t('Author'), 'description' => t('The author of the book.'), 'type' => 'user', - ); - $info['tokens']['book']['root'] = array( + ]; + $info['tokens']['book']['root'] = [ 'name' => t('Root'), 'description' => t('Top level of the book.'), 'type' => 'node', - ); - $info['tokens']['book']['parent'] = array( + ]; + $info['tokens']['book']['parent'] = [ 'name' => t('Parent'), 'description' => t('Parent of the current page.'), 'type' => 'node', - ); - $info['tokens']['book']['parents'] = array( + ]; + $info['tokens']['book']['parents'] = [ 'name' => t('Parents'), 'description' => t("An array of all the node's parents, starting with the root."), 'type' => 'array', - ); + ]; - $info['tokens']['node']['book'] = array( + $info['tokens']['node']['book'] = [ 'name' => t('Book'), 'description' => t('The book page associated with the node.'), 'type' => 'book', - ); + ]; return $info; } /** * Implements hook_tokens() on behalf of book.module. */ -function book_tokens($type, $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) { - $replacements = array(); +function book_tokens($type, $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) { + $replacements = []; // Node tokens. if ($type == 'node' && !empty($data['node'])) { @@ -1049,12 +1075,12 @@ function book_tokens($type, $tokens, array $data = array(), array $options = arr if (!empty($book['bid'])) { if ($book_tokens = \Drupal::token()->findWithPrefix($tokens, 'book')) { $child_node = Node::load($book['nid']); - $replacements += \Drupal::token()->generate('book', $book_tokens, array('book' => $child_node), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('book', $book_tokens, ['book' => $child_node], $options, $bubbleable_metadata); } } } // Book tokens. - else if ($type == 'book' && !empty($data['book'])) { + elseif ($type == 'book' && !empty($data['book'])) { $book = $data['book']->book; if (!empty($book['bid'])) { @@ -1066,12 +1092,14 @@ function book_tokens($type, $tokens, array $data = array(), array $options = arr case 'title': $replacements[$original] = $book_node->getTitle(); break; + case 'parent': if (!empty($book['pid'])) { $parent_node = Node::load($book['pid']); $replacements[$original] = $parent_node->getTitle(); } break; + case 'parents': if ($parents = token_book_load_all_parents($book)) { $replacements[$original] = token_render_array($parents, $options); @@ -1081,18 +1109,18 @@ function book_tokens($type, $tokens, array $data = array(), array $options = arr } if ($book_tokens = \Drupal::token()->findWithPrefix($tokens, 'author')) { - $replacements += \Drupal::token()->generate('user', $book_tokens, array('user' => $book_node->getOwner()), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('user', $book_tokens, ['user' => $book_node->getOwner()], $options, $bubbleable_metadata); } if ($book_tokens = \Drupal::token()->findWithPrefix($tokens, 'root')) { - $replacements += \Drupal::token()->generate('node', $book_tokens, array('node' => $book_node), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('node', $book_tokens, ['node' => $book_node], $options, $bubbleable_metadata); } if (!empty($book['pid']) && $book_tokens = \Drupal::token()->findWithPrefix($tokens, 'parent')) { $parent_node = Node::load($book['pid']); - $replacements += \Drupal::token()->generate('node', $book_tokens, array('node' => $parent_node), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('node', $book_tokens, ['node' => $parent_node], $options, $bubbleable_metadata); } if ($book_tokens = \Drupal::token()->findWithPrefix($tokens, 'parents')) { $parents = token_book_load_all_parents($book); - $replacements += \Drupal::token()->generate('array', $book_tokens, array('array' => $parents), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('array', $book_tokens, ['array' => $parents], $options, $bubbleable_metadata); } } } @@ -1105,46 +1133,46 @@ function book_tokens($type, $tokens, array $data = array(), array $options = arr */ function menu_ui_token_info() { // Menu tokens. - $info['types']['menu'] = array( + $info['types']['menu'] = [ 'name' => t('Menus'), 'description' => t('Tokens related to menus.'), 'needs-data' => 'menu', - ); - $info['tokens']['menu']['name'] = array( + ]; + $info['tokens']['menu']['name'] = [ 'name' => t('Name'), 'description' => t("The name of the menu."), - ); - $info['tokens']['menu']['machine-name'] = array( + ]; + $info['tokens']['menu']['machine-name'] = [ 'name' => t('Machine-readable name'), 'description' => t("The unique machine-readable name of the menu."), - ); - $info['tokens']['menu']['description'] = array( + ]; + $info['tokens']['menu']['description'] = [ 'name' => t('Description'), 'description' => t('The optional description of the menu.'), - ); - $info['tokens']['menu']['menu-link-count'] = array( + ]; + $info['tokens']['menu']['menu-link-count'] = [ 'name' => t('Menu link count'), 'description' => t('The number of menu links belonging to the menu.'), - ); - $info['tokens']['menu']['edit-url'] = array( + ]; + $info['tokens']['menu']['edit-url'] = [ 'name' => t('Edit URL'), 'description' => t("The URL of the menu's edit page."), - ); + ]; - $info['tokens']['menu-link']['menu'] = array( + $info['tokens']['menu-link']['menu'] = [ 'name' => t('Menu'), 'description' => t('The menu of the menu link.'), 'type' => 'menu', - ); - $info['tokens']['menu-link']['edit-url'] = array( + ]; + $info['tokens']['menu-link']['edit-url'] = [ 'name' => t('Edit URL'), 'description' => t("The URL of the menu link's edit page."), - ); - $info['tokens']['node']['menu-link'] = array( + ]; + $info['tokens']['node']['menu-link'] = [ 'name' => t('Menu link'), 'description' => t("The menu link for this node."), 'type' => 'menu-link', - ); + ]; return $info; } @@ -1152,13 +1180,13 @@ function menu_ui_token_info() { /** * Implements hook_tokens() on behalf of menu_ui.module. */ -function menu_ui_tokens($type, $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) { - $replacements = array(); +function menu_ui_tokens($type, $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) { + $replacements = []; /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */ $menu_link_manager = \Drupal::service('plugin.manager.menu.link'); - $url_options = array('absolute' => TRUE); + $url_options = ['absolute' => TRUE]; if (isset($options['langcode'])) { $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']); $langcode = $options['langcode']; @@ -1196,13 +1224,13 @@ function menu_ui_tokens($type, $tokens, array $data = array(), array $options = if ($menu_tokens = \Drupal::token()->findWithPrefix($tokens, 'menu-link')) { if ($node->getFieldDefinition('menu_link') && $menu_link = $node->menu_link->entity) { /** @var \Drupal\menu_link_content\MenuLinkContentInterface $menu_link */ - $replacements += \Drupal::token()->generate('menu-link', $menu_tokens, array('menu-link' => $menu_link), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('menu-link', $menu_tokens, ['menu-link' => $menu_link], $options, $bubbleable_metadata); } else { $url = $node->urlInfo(); if ($links = $menu_link_manager->loadLinksByRoute($url->getRouteName(), $url->getRouteParameters())) { $link = _token_menu_link_best_match($node, $links); - $replacements += \Drupal::token()->generate('menu-link', $menu_tokens, array('menu-link' => $link), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('menu-link', $menu_tokens, ['menu-link' => $link], $options, $bubbleable_metadata); } } } @@ -1234,7 +1262,7 @@ function menu_ui_tokens($type, $tokens, array $data = array(), array $options = // Chained token relationships. if (($menu_tokens = \Drupal::token()->findWithPrefix($tokens, 'menu')) && $menu = Menu::load($link->getMenuName())) { - $replacements += \Drupal::token()->generate('menu', $menu_tokens, array('menu' => $menu), $options, $bubbleable_metadata); + $replacements += \Drupal::token()->generate('menu', $menu_tokens, ['menu' => $menu], $options, $bubbleable_metadata); } } @@ -1370,13 +1398,13 @@ function field_token_info_alter(&$info) { $cardinality = $field->getCardinality(); $cardinality = ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED || $cardinality > 3) ? 3 : $cardinality; $field_token_name = $token_type . '-' . $field_name; - $info['tokens'][$token_type][$field_name] = array( + $info['tokens'][$token_type][$field_name] = [ 'name' => Html::escape($label), 'description' => $description, 'module' => 'token', // For multivalue fields the field token is a list type. 'type' => $cardinality > 1 ? "list<$field_token_name>" : $field_token_name, - ); + ]; // Field token type. $info['types'][$field_token_name] = [ @@ -1387,12 +1415,12 @@ function field_token_info_alter(&$info) { ]; // Field list token type. if ($cardinality > 1) { - $info['types']["list<$field_token_name>"] = array( - 'name' => t('List of @type values', array('@type' => Html::escape($label))), - 'description' => t('Tokens for lists of @type values.', array('@type' => Html::escape($label))), + $info['types']["list<$field_token_name>"] = [ + 'name' => t('List of @type values', ['@type' => Html::escape($label)]), + 'description' => t('Tokens for lists of @type values.', ['@type' => Html::escape($label)]), 'needs-data' => "list<$field_token_name>", 'nested' => TRUE, - ); + ]; } // Show a different token for each field delta. @@ -1488,8 +1516,8 @@ function _token_field_label($entity_type, $field_name) { /** * Implements hook_tokens() on behalf of field.module. */ -function field_tokens($type, $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) { - $replacements = array(); +function field_tokens($type, $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) { + $replacements = []; $langcode = isset($options['langcode']) ? $options['langcode'] : NULL; // Entity tokens. if ($type == 'entity' && !empty($data['entity_type']) && !empty($data['entity']) && !empty($data['token_type'])) { @@ -1573,7 +1601,7 @@ function field_tokens($type, $tokens, array $data = array(), array $options = ar } // Handle [entity:field_name:value] and [entity:field_name:0:value] // tokens. - else if ($field_tokens = \Drupal::token()->findWithPrefix($tokens, $field_name)) { + elseif ($field_tokens = \Drupal::token()->findWithPrefix($tokens, $field_name)) { $property_token_data = [ 'field_property' => TRUE, $data['entity_type'] . '-' . $field_name => $entity->$field_name, @@ -1670,7 +1698,8 @@ function field_tokens($type, $tokens, array $data = array(), array $options = ar case 'mimetype': $replacements[$original] = $image->getMimeType(); break; - case 'filesize' : + + case 'filesize': $replacements[$original] = $image->getFileSize(); break; } @@ -1679,7 +1708,7 @@ function field_tokens($type, $tokens, array $data = array(), array $options = ar } elseif (in_array($field_item->getFieldDefinition()->getType(), ['datetime', 'daterange']) && in_array($property_name, ['date', 'start_date', 'end_date'])) { $datetime = $field_item->$property_name->getTimestamp(); - if($property_name == $token) { + if ($property_name == $token) { $replacements[$original] = $datetime; } else { @@ -1713,7 +1742,7 @@ function token_pre_render_field_token($elements) { foreach ($deltas as $index => $delta) { // Do not add a suffix to the last item. if ($index < ($count - 1)) { - $elements[$delta] += array('#suffix' => $join); + $elements[$delta] += ['#suffix' => $join]; } } }