TokenAutocompleteController.php in Token 8
File
src/Controller/TokenAutocompleteController.php
View source
<?php
namespace Drupal\token\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\token\TreeBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class TokenAutocompleteController extends ControllerBase {
protected $treeBuilder;
public function __construct(TreeBuilderInterface $tree_builder) {
$this->treeBuilder = $tree_builder;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('token.tree_builder'));
}
public function autocomplete($token_type, $filter, Request $request) {
$filter = substr($filter, strrpos($filter, '['));
$matches = [];
if (!mb_strlen($filter)) {
$matches["[{$token_type}:"] = 0;
}
else {
$depth = max(1, substr_count($filter, ':'));
$tree = $this->treeBuilder
->buildTree($token_type, [
'flat' => TRUE,
'depth' => $depth,
]);
foreach (array_keys($tree) as $token) {
if (strpos($token, $filter) === 0) {
$matches[$token] = levenshtein($token, $filter);
if (isset($tree[$token]['children'])) {
$token = rtrim($token, ':]') . ':';
$matches[$token] = levenshtein($token, $filter);
}
}
}
}
asort($matches);
$keys = array_keys($matches);
$matches = array_combine($keys, $keys);
return new JsonResponse($matches);
}
}