Syntax.php 1.4 KB

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