Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 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 | |
| 13 | namespace 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 | */ |
| 20 | class 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(string $name, array $items): void |
| 29 | { |
| 30 | $alternatives = []; |
| 31 | foreach ($items as $item) { |
| 32 | $lev = levenshtein($name, $item); |
| 33 | if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) { |
| 34 | $alternatives[$item] = $lev; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | if (!$alternatives) { |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | asort($alternatives); |
| 43 | |
| 44 | $this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', array_keys($alternatives)))); |
| 45 | } |
| 46 | } |