Updated all the contrib modules to their latest versions.
[yaffs-website] / web / modules / contrib / token / src / Controller / TokenAutocompleteController.php
1 <?php
2
3 namespace Drupal\token\Controller;
4
5 use Drupal\Core\Controller\ControllerBase;
6 use Drupal\token\TreeBuilderInterface;
7 use Symfony\Component\DependencyInjection\ContainerInterface;
8 use Symfony\Component\HttpFoundation\JsonResponse;
9 use Symfony\Component\HttpFoundation\Request;
10
11 /**
12  * Returns autocomplete responses for tokens.
13  */
14 class TokenAutocompleteController extends ControllerBase {
15
16   /**
17    * @var \Drupal\token\TreeBuilderInterface
18    */
19   protected $treeBuilder;
20
21   public function __construct(TreeBuilderInterface $tree_builder) {
22     $this->treeBuilder = $tree_builder;
23   }
24
25   /**
26    * {@inheritdoc}
27    */
28   public static function create(ContainerInterface $container) {
29     return new static(
30       $container->get('token.tree_builder')
31     );
32   }
33
34   /**
35    * Retrieves suggestions for block category autocompletion.
36    *
37    * @param \Symfony\Component\HttpFoundation\Request $request
38    *   The current request.
39    * @param string $token_type
40    *   The token type.
41    * @param string $filter
42    *   The autocomplete filter.
43    *
44    * @return \Symfony\Component\HttpFoundation\JsonResponse
45    *   A JSON response containing autocomplete suggestions.
46    */
47   public function autocomplete($token_type, $filter, Request $request) {
48     $filter = substr($filter, strrpos($filter, '['));
49
50     $matches = [];
51
52     if (!mb_strlen($filter)) {
53       $matches["[{$token_type}:"] = 0;
54     }
55     else {
56       $depth = max(1, substr_count($filter, ':'));
57       $tree = $this->treeBuilder->buildTree($token_type, ['flat' => TRUE, 'depth' => $depth]);
58       foreach (array_keys($tree) as $token) {
59         if (strpos($token, $filter) === 0) {
60           $matches[$token] = levenshtein($token, $filter);
61           if (isset($tree[$token]['children'])) {
62             $token = rtrim($token, ':]') . ':';
63             $matches[$token] = levenshtein($token, $filter);
64           }
65         }
66       }
67     }
68
69     asort($matches);
70
71     $keys = array_keys($matches);
72     $matches = array_combine($keys, $keys);
73
74     return new JsonResponse($matches);
75   }
76
77 }