DeprecationCollector.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * @author Fabien Potencier <fabien@symfony.com>
  12. */
  13. class Twig_Util_DeprecationCollector
  14. {
  15. private $twig;
  16. private $deprecations;
  17. public function __construct(Twig_Environment $twig)
  18. {
  19. $this->twig = $twig;
  20. }
  21. /**
  22. * Returns deprecations for templates contained in a directory.
  23. *
  24. * @param string $dir A directory where templates are stored
  25. * @param string $ext Limit the loaded templates by extension
  26. *
  27. * @return array() An array of deprecations
  28. */
  29. public function collectDir($dir, $ext = '.twig')
  30. {
  31. $iterator = new RegexIterator(
  32. new RecursiveIteratorIterator(
  33. new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY
  34. ), '{'.preg_quote($ext).'$}'
  35. );
  36. return $this->collect(new Twig_Util_TemplateDirIterator($iterator));
  37. }
  38. /**
  39. * Returns deprecations for passed templates.
  40. *
  41. * @param Iterator $iterator An iterator of templates (where keys are template names and values the contents of the template)
  42. *
  43. * @return array() An array of deprecations
  44. */
  45. public function collect(Iterator $iterator)
  46. {
  47. $this->deprecations = array();
  48. set_error_handler(array($this, 'errorHandler'));
  49. foreach ($iterator as $name => $contents) {
  50. try {
  51. $this->twig->parse($this->twig->tokenize($contents, $name));
  52. } catch (Twig_Error_Syntax $e) {
  53. // ignore templates containing syntax errors
  54. }
  55. }
  56. restore_error_handler();
  57. $deprecations = $this->deprecations;
  58. $this->deprecations = array();
  59. return $deprecations;
  60. }
  61. /**
  62. * @internal
  63. */
  64. public function errorHandler($type, $msg)
  65. {
  66. if (E_USER_DEPRECATED === $type) {
  67. $this->deprecations[] = $msg;
  68. }
  69. }
  70. }