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\Profiler\Dumper;
13
14use Twig\Profiler\Profile;
15
16/**
17 * @author Fabien Potencier <fabien@symfony.com>
18 *
19 * @final
20 */
21class BlackfireDumper
22{
23    public function dump(Profile $profile)
24    {
25        $data = [];
26        $this->dumpProfile('main()', $profile, $data);
27        $this->dumpChildren('main()', $profile, $data);
28
29        $start = sprintf('%f', microtime(true));
30        $str = <<<EOF
31file-format: BlackfireProbe
32cost-dimensions: wt mu pmu
33request-start: {$start}
34
35
36EOF;
37
38        foreach ($data as $name => $values) {
39            $str .= "{$name}//{$values['ct']} {$values['wt']} {$values['mu']} {$values['pmu']}\n";
40        }
41
42        return $str;
43    }
44
45    private function dumpChildren($parent, Profile $profile, &$data)
46    {
47        foreach ($profile as $p) {
48            if ($p->isTemplate()) {
49                $name = $p->getTemplate();
50            } else {
51                $name = sprintf('%s::%s(%s)', $p->getTemplate(), $p->getType(), $p->getName());
52            }
53            $this->dumpProfile(sprintf('%s==>%s', $parent, $name), $p, $data);
54            $this->dumpChildren($name, $p, $data);
55        }
56    }
57
58    private function dumpProfile($edge, Profile $profile, &$data)
59    {
60        if (isset($data[$edge])) {
61            ++$data[$edge]['ct'];
62            $data[$edge]['wt'] += floor($profile->getDuration() * 1000000);
63            $data[$edge]['mu'] += $profile->getMemoryUsage();
64            $data[$edge]['pmu'] += $profile->getPeakMemoryUsage();
65        } else {
66            $data[$edge] = [
67                'ct' => 1,
68                'wt' => floor($profile->getDuration() * 1000000),
69                'mu' => $profile->getMemoryUsage(),
70                'pmu' => $profile->getPeakMemoryUsage(),
71            ];
72        }
73    }
74}
75
76class_alias('Twig\Profiler\Dumper\BlackfireDumper', 'Twig_Profiler_Dumper_Blackfire');
77