Version 1
[yaffs-website] / vendor / symfony / http-kernel / DataCollector / DumpDataCollector.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
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 Symfony\Component\HttpKernel\DataCollector;
13
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\RequestStack;
16 use Symfony\Component\HttpFoundation\Response;
17 use Symfony\Component\Stopwatch\Stopwatch;
18 use Symfony\Component\VarDumper\Cloner\Data;
19 use Symfony\Component\VarDumper\Cloner\VarCloner;
20 use Symfony\Component\VarDumper\Dumper\CliDumper;
21 use Symfony\Component\VarDumper\Dumper\HtmlDumper;
22 use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
23
24 /**
25  * @author Nicolas Grekas <p@tchwork.com>
26  */
27 class DumpDataCollector extends DataCollector implements DataDumperInterface
28 {
29     private $stopwatch;
30     private $fileLinkFormat;
31     private $dataCount = 0;
32     private $isCollected = true;
33     private $clonesCount = 0;
34     private $clonesIndex = 0;
35     private $rootRefs;
36     private $charset;
37     private $requestStack;
38     private $dumper;
39     private $dumperIsInjected;
40
41     public function __construct(Stopwatch $stopwatch = null, $fileLinkFormat = null, $charset = null, RequestStack $requestStack = null, DataDumperInterface $dumper = null)
42     {
43         $this->stopwatch = $stopwatch;
44         $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
45         $this->charset = $charset ?: ini_get('php.output_encoding') ?: ini_get('default_charset') ?: 'UTF-8';
46         $this->requestStack = $requestStack;
47         $this->dumper = $dumper;
48         $this->dumperIsInjected = null !== $dumper;
49
50         // All clones share these properties by reference:
51         $this->rootRefs = array(
52             &$this->data,
53             &$this->dataCount,
54             &$this->isCollected,
55             &$this->clonesCount,
56         );
57     }
58
59     public function __clone()
60     {
61         $this->clonesIndex = ++$this->clonesCount;
62     }
63
64     public function dump(Data $data)
65     {
66         if ($this->stopwatch) {
67             $this->stopwatch->start('dump');
68         }
69         if ($this->isCollected) {
70             $this->isCollected = false;
71         }
72
73         $trace = DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS;
74         if (PHP_VERSION_ID >= 50400) {
75             $trace = debug_backtrace($trace, 7);
76         } else {
77             $trace = debug_backtrace($trace);
78         }
79
80         $file = $trace[0]['file'];
81         $line = $trace[0]['line'];
82         $name = false;
83         $fileExcerpt = false;
84
85         for ($i = 1; $i < 7; ++$i) {
86             if (isset($trace[$i]['class'], $trace[$i]['function'])
87                 && 'dump' === $trace[$i]['function']
88                 && 'Symfony\Component\VarDumper\VarDumper' === $trace[$i]['class']
89             ) {
90                 $file = $trace[$i]['file'];
91                 $line = $trace[$i]['line'];
92
93                 while (++$i < 7) {
94                     if (isset($trace[$i]['function'], $trace[$i]['file']) && empty($trace[$i]['class']) && 0 !== strpos($trace[$i]['function'], 'call_user_func')) {
95                         $file = $trace[$i]['file'];
96                         $line = $trace[$i]['line'];
97
98                         break;
99                     } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof \Twig_Template) {
100                         $template = $trace[$i]['object'];
101                         $name = $template->getTemplateName();
102                         $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
103                         $info = $template->getDebugInfo();
104                         if (isset($info[$trace[$i - 1]['line']])) {
105                             $line = $info[$trace[$i - 1]['line']];
106                             $file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;
107
108                             if ($src) {
109                                 $src = explode("\n", $src);
110                                 $fileExcerpt = array();
111
112                                 for ($i = max($line - 3, 1), $max = min($line + 3, count($src)); $i <= $max; ++$i) {
113                                     $fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
114                                 }
115
116                                 $fileExcerpt = '<ol start="'.max($line - 3, 1).'">'.implode("\n", $fileExcerpt).'</ol>';
117                             }
118                         }
119                         break;
120                     }
121                 }
122                 break;
123             }
124         }
125
126         if (false === $name) {
127             $name = str_replace('\\', '/', $file);
128             $name = substr($name, strrpos($name, '/') + 1);
129         }
130
131         if ($this->dumper) {
132             $this->doDump($data, $name, $file, $line);
133         }
134
135         $this->data[] = compact('data', 'name', 'file', 'line', 'fileExcerpt');
136         ++$this->dataCount;
137
138         if ($this->stopwatch) {
139             $this->stopwatch->stop('dump');
140         }
141     }
142
143     public function collect(Request $request, Response $response, \Exception $exception = null)
144     {
145         // Sub-requests and programmatic calls stay in the collected profile.
146         if ($this->dumper || ($this->requestStack && $this->requestStack->getMasterRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
147             return;
148         }
149
150         // In all other conditions that remove the web debug toolbar, dumps are written on the output.
151         if (!$this->requestStack
152             || !$response->headers->has('X-Debug-Token')
153             || $response->isRedirection()
154             || ($response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html'))
155             || 'html' !== $request->getRequestFormat()
156             || false === strripos($response->getContent(), '</body>')
157         ) {
158             if ($response->headers->has('Content-Type') && false !== strpos($response->headers->get('Content-Type'), 'html')) {
159                 $this->dumper = new HtmlDumper('php://output', $this->charset);
160             } else {
161                 $this->dumper = new CliDumper('php://output', $this->charset);
162             }
163
164             foreach ($this->data as $dump) {
165                 $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
166             }
167         }
168     }
169
170     public function serialize()
171     {
172         if ($this->clonesCount !== $this->clonesIndex) {
173             return 'a:0:{}';
174         }
175
176         $this->data[] = $this->fileLinkFormat;
177         $this->data[] = $this->charset;
178         $ser = serialize($this->data);
179         $this->data = array();
180         $this->dataCount = 0;
181         $this->isCollected = true;
182         if (!$this->dumperIsInjected) {
183             $this->dumper = null;
184         }
185
186         return $ser;
187     }
188
189     public function unserialize($data)
190     {
191         parent::unserialize($data);
192         $charset = array_pop($this->data);
193         $fileLinkFormat = array_pop($this->data);
194         $this->dataCount = count($this->data);
195         self::__construct($this->stopwatch, $fileLinkFormat, $charset);
196     }
197
198     public function getDumpsCount()
199     {
200         return $this->dataCount;
201     }
202
203     public function getDumps($format, $maxDepthLimit = -1, $maxItemsPerDepth = -1)
204     {
205         $data = fopen('php://memory', 'r+b');
206
207         if ('html' === $format) {
208             $dumper = new HtmlDumper($data, $this->charset);
209         } else {
210             throw new \InvalidArgumentException(sprintf('Invalid dump format: %s', $format));
211         }
212         $dumps = array();
213
214         foreach ($this->data as $dump) {
215             if (method_exists($dump['data'], 'withMaxDepth')) {
216                 $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
217             } else {
218                 // getLimitedClone is @deprecated, to be removed in 3.0
219                 $dumper->dump($dump['data']->getLimitedClone($maxDepthLimit, $maxItemsPerDepth));
220             }
221             $dump['data'] = stream_get_contents($data, -1, 0);
222             ftruncate($data, 0);
223             rewind($data);
224             $dumps[] = $dump;
225         }
226
227         return $dumps;
228     }
229
230     public function getName()
231     {
232         return 'dump';
233     }
234
235     public function __destruct()
236     {
237         if (0 === $this->clonesCount-- && !$this->isCollected && $this->data) {
238             $this->clonesCount = 0;
239             $this->isCollected = true;
240
241             $h = headers_list();
242             $i = count($h);
243             array_unshift($h, 'Content-Type: '.ini_get('default_mimetype'));
244             while (0 !== stripos($h[$i], 'Content-Type:')) {
245                 --$i;
246             }
247
248             if ('cli' !== PHP_SAPI && stripos($h[$i], 'html')) {
249                 $this->dumper = new HtmlDumper('php://output', $this->charset);
250             } else {
251                 $this->dumper = new CliDumper('php://output', $this->charset);
252             }
253
254             foreach ($this->data as $i => $dump) {
255                 $this->data[$i] = null;
256                 $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
257             }
258
259             $this->data = array();
260             $this->dataCount = 0;
261         }
262     }
263
264     private function doDump($data, $name, $file, $line)
265     {
266         if (PHP_VERSION_ID >= 50400 && $this->dumper instanceof CliDumper) {
267             $contextDumper = function ($name, $file, $line, $fileLinkFormat) {
268                 if ($this instanceof HtmlDumper) {
269                     if ($file) {
270                         $s = $this->style('meta', '%s');
271                         $name = strip_tags($this->style('', $name));
272                         $file = strip_tags($this->style('', $file));
273                         if ($fileLinkFormat) {
274                             $link = strtr(strip_tags($this->style('', $fileLinkFormat)), array('%f' => $file, '%l' => (int) $line));
275                             $name = sprintf('<a href="%s" title="%s">'.$s.'</a>', $link, $file, $name);
276                         } else {
277                             $name = sprintf('<abbr title="%s">'.$s.'</abbr>', $file, $name);
278                         }
279                     } else {
280                         $name = $this->style('meta', $name);
281                     }
282                     $this->line = $name.' on line '.$this->style('meta', $line).':';
283                 } else {
284                     $this->line = $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
285                 }
286                 $this->dumpLine(0);
287             };
288             $contextDumper = $contextDumper->bindTo($this->dumper, $this->dumper);
289             $contextDumper($name, $file, $line, $this->fileLinkFormat);
290         } else {
291             $cloner = new VarCloner();
292             $this->dumper->dump($cloner->cloneVar($name.' on line '.$line.':'));
293         }
294         $this->dumper->dump($data);
295     }
296
297     private function htmlEncode($s)
298     {
299         $html = '';
300
301         $dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset);
302         $dumper->setDumpHeader('');
303         $dumper->setDumpBoundaries('', '');
304
305         $cloner = new VarCloner();
306         $dumper->dump($cloner->cloneVar($s));
307
308         return substr(strip_tags($html), 1, -1);
309     }
310 }