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 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | */ |
| 11 | |
| 12 | namespace Twig\Util; |
| 13 | |
| 14 | use Twig\Environment; |
| 15 | use Twig\Error\SyntaxError; |
| 16 | use Twig\Source; |
| 17 | |
| 18 | /** |
| 19 | * @author Fabien Potencier <fabien@symfony.com> |
| 20 | */ |
| 21 | final class DeprecationCollector |
| 22 | { |
| 23 | private $twig; |
| 24 | |
| 25 | public function __construct(Environment $twig) |
| 26 | { |
| 27 | $this->twig = $twig; |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * Returns deprecations for templates contained in a directory. |
| 32 | * |
| 33 | * @param string $dir A directory where templates are stored |
| 34 | * @param string $ext Limit the loaded templates by extension |
| 35 | * |
| 36 | * @return array An array of deprecations |
| 37 | */ |
| 38 | public function collectDir(string $dir, string $ext = '.twig'): array |
| 39 | { |
| 40 | $iterator = new \RegexIterator( |
| 41 | new \RecursiveIteratorIterator( |
| 42 | new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY |
| 43 | ), '{'.preg_quote($ext).'$}' |
| 44 | ); |
| 45 | |
| 46 | return $this->collect(new TemplateDirIterator($iterator)); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Returns deprecations for passed templates. |
| 51 | * |
| 52 | * @param \Traversable $iterator An iterator of templates (where keys are template names and values the contents of the template) |
| 53 | * |
| 54 | * @return array An array of deprecations |
| 55 | */ |
| 56 | public function collect(\Traversable $iterator): array |
| 57 | { |
| 58 | $deprecations = []; |
| 59 | set_error_handler(function ($type, $msg) use (&$deprecations) { |
| 60 | if (\E_USER_DEPRECATED === $type) { |
| 61 | $deprecations[] = $msg; |
| 62 | } |
| 63 | }); |
| 64 | |
| 65 | foreach ($iterator as $name => $contents) { |
| 66 | try { |
| 67 | $this->twig->parse($this->twig->tokenize(new Source($contents, $name))); |
| 68 | } catch (SyntaxError $e) { |
| 69 | // ignore templates containing syntax errors |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | restore_error_handler(); |
| 74 | |
| 75 | return $deprecations; |
| 76 | } |
| 77 | } |