1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 * (c) Armin Ronacher
8 *
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
11 */
12
13namespace Twig\Error;
14
15/**
16 * \Exception thrown when a syntax error occurs during lexing or parsing of a template.
17 *
18 * @author Fabien Potencier <fabien@symfony.com>
19 */
20class SyntaxError extends Error
21{
22    /**
23     * Tweaks the error message to include suggestions.
24     *
25     * @param string $name  The original name of the item that does not exist
26     * @param array  $items An array of possible items
27     */
28    public function addSuggestions($name, array $items)
29    {
30        if (!$alternatives = self::computeAlternatives($name, $items)) {
31            return;
32        }
33
34        $this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', $alternatives)));
35    }
36
37    /**
38     * @internal
39     *
40     * To be merged with the addSuggestions() method in 2.0.
41     */
42    public static function computeAlternatives($name, $items)
43    {
44        $alternatives = [];
45        foreach ($items as $item) {
46            $lev = levenshtein($name, $item);
47            if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
48                $alternatives[$item] = $lev;
49            }
50        }
51        asort($alternatives);
52
53        return array_keys($alternatives);
54    }
55}
56
57class_alias('Twig\Error\SyntaxError', 'Twig_Error_Syntax');
58