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
12namespace Twig\Util;
13
14use Twig\Environment;
15use Twig\Error\SyntaxError;
16use Twig\Source;
17
18/**
19 * @author Fabien Potencier <fabien@symfony.com>
20 *
21 * @final
22 */
23class DeprecationCollector
24{
25    private $twig;
26    private $deprecations;
27
28    public function __construct(Environment $twig)
29    {
30        $this->twig = $twig;
31    }
32
33    /**
34     * Returns deprecations for templates contained in a directory.
35     *
36     * @param string $dir A directory where templates are stored
37     * @param string $ext Limit the loaded templates by extension
38     *
39     * @return array An array of deprecations
40     */
41    public function collectDir($dir, $ext = '.twig')
42    {
43        $iterator = new \RegexIterator(
44            new \RecursiveIteratorIterator(
45                new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY
46            ), '{'.preg_quote($ext).'$}'
47        );
48
49        return $this->collect(new TemplateDirIterator($iterator));
50    }
51
52    /**
53     * Returns deprecations for passed templates.
54     *
55     * @param \Traversable $iterator An iterator of templates (where keys are template names and values the contents of the template)
56     *
57     * @return array An array of deprecations
58     */
59    public function collect(\Traversable $iterator)
60    {
61        $this->deprecations = [];
62
63        set_error_handler([$this, 'errorHandler']);
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        $deprecations = $this->deprecations;
76        $this->deprecations = [];
77
78        return $deprecations;
79    }
80
81    /**
82     * @internal
83     */
84    public function errorHandler($type, $msg)
85    {
86        if (E_USER_DEPRECATED === $type) {
87            $this->deprecations[] = $msg;
88        }
89    }
90}
91
92class_alias('Twig\Util\DeprecationCollector', 'Twig_Util_DeprecationCollector');
93