XhprofCollector::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 6
Bugs 0 Features 2
Metric Value
c 6
b 0
f 2
dl 0
loc 15
ccs 10
cts 11
cp 0.9091
rs 9.2
cc 4
eloc 10
nc 2
nop 3
crap 4.0119
1
<?php
2
3
namespace Jns\Bundle\XhprofBundle\DataCollector;
4
5
// supports 2.0, 2.1 LoggerInterface
6
use Symfony\Component\HttpKernel\Log\LoggerInterface as HttpKernelLoggerInterface;
7
use Psr\Log\LoggerInterface as PsrLoggerInterface;
8
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
use Doctrine\Common\Persistence\ManagerRegistry;
14
use Jns\Bundle\XhprofBundle\Document\XhguiRuns as XhguiRuns_Document;
15
use Jns\Bundle\XhprofBundle\Entity\XhguiRuns as XhguiRuns_Entity;
16
use Doctrine\ODM\MongoDB\DocumentManager;
17
18
/**
19
 * XhprofDataCollector.
20
 *
21
 * @author Jonas Wouters <[email protected]>
22
 */
23
class XhprofCollector extends DataCollector
24
{
25
    protected $container;
26
    protected $logger;
27
    protected $runId;
28
    protected $doctrine;
29
    protected $collecting = false;
30
    protected $collectingRequest;
31
32 3
    public function __construct(ContainerInterface $container, $logger = null, ManagerRegistry $doctrine = null)
33
    {
34 3
        $this->container = $container;
35
36 3
        if ($logger !== null && !$logger instanceof HttpKernelLoggerInterface && !$logger instanceof PsrLoggerInterface) {
0 ignored issues
show
Bug introduced by
The class Symfony\Component\HttpKernel\Log\LoggerInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
37
            throw new \InvalidArgumentException('Logger must be an instance of Symfony\Component\HttpKernel\Log\LoggerInterface or Psr\Log\LoggerInterface');
38
        }
39
40 3
        $this->logger    = $logger;
41 3
        $this->doctrine  = $doctrine;
42 3
        $this->data['xhprof_extension_exists'] = function_exists('xhprof_enable');
43 3
        $this->data['xhprof'] = null;
44 3
        $this->data['source'] = null;
45 3
        $this->data['xhprof_url'] = null;
46 3
    }
47
48
    /**
49
     * {@inheritdoc}
50
     *
51
     * Prepare data for the debug toolbar.
52
     */
53
    public function collect(Request $request, Response $response, \Exception $exception = null)
54
    {
55
        if (!$this->runId && $request === $this->collectingRequest) {
56
            $this->stopProfiling($request->getHost(), $request->getUri());
57
        }
58
    }
59
60
    /**
61
     * Start profiling with probability according to sample size.
62
     *
63
     * @return boolean whether profiling was started or not.
64
     */
65
    public function startProfiling(Request $request = null)
66
    {
67
        if (!function_exists('xhprof_enable') || mt_rand(1, $this->container->getParameter('jns_xhprof.sample_size')) != 1) {
68
            return false;
69
        }
70
71
        $this->collecting = true;
72
        $this->collectingRequest = $request;
73
        xhprof_enable($this->getFlags());
74
75
        if ($this->logger) {
76
            $this->logger->debug('Enabled XHProf');
77
        }
78
79
        return true;
80
    }
81
82
    /**
83
     * Calculate the flags for xhprof_enable
84
     *
85
     * @return int
86
     */
87 1
    private function getFlags()
88
    {
89
        $flags = XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY;
90
        if ($this->container->getParameter('jns_xhprof.skip_builtin_functions') === true) {
91 1
            $flags |= XHPROF_FLAGS_NO_BUILTINS;
92
        }
93
94
        return $flags;
95
    }
96
97
    /**
98
     * Stop profiling if we where profiling.
99
     *
100
     * @param string $serverName The server name the request is running on, or cli for command line.
101
     * @param string $uri        The requested uri / command name.
102
     *
103
     * @return bool
104
     */
105
    public function stopProfiling($serverName, $uri)
106
    {
107
        if (isset($this->data['xhprof'])) {
108
            return $this->data['xhprof'];
109
        }
110
111
        if (!$this->collecting) {
112
            return $this->data['xhprof'] ? $this->data['xhprof'] : false;
113
        }
114
115
        $this->collecting = false;
116
117
        $xhprof_data = xhprof_disable();
118
119
        if ($this->logger) {
120
            $this->logger->debug('Disabled XHProf');
121
        }
122
123
        $xhprof_runs = $this->createRun($serverName, $uri);
124
        $source = null;
125
126
        if ($xhprof_runs instanceof \XHProfRuns_Default) {
127
            $source = $this->sanitizeUriForSource($uri);
128
        }
129
130
        $this->runId = $xhprof_runs->save_run($xhprof_data, $source);
131
132
        $this->data = array(
133
            'xhprof' => $this->runId,
134
            'source' => $source,
135
        );
136
137
        if ($xhprof_runs instanceof XhguiRuns_Document) {
138
            $this->data['xhprof_url'] = $this->container->getParameter('jns_xhprof.location_web') . '/run/view?id=' . $this->data['xhprof'];
139
        } else {
140
            $this->data['xhprof_url'] = $this->container->getParameter('jns_xhprof.location_web') . '?run=' . $this->data['xhprof'] . '&source='.$this->data['source'];
141
        }
142
143
        return $this->data['xhprof'];
144
    }
145
146
    /**
147
     * @return \iXHProfRuns
148
     */
149 3
    protected function createRun($serverName, $uri) {
150 3
        $enableXhgui = $this->container->getParameter('jns_xhprof.enable_xhgui');
151 3
        if ($enableXhgui) {
152 2
            $managerRegistry = $this->container->get($this->container->getParameter('jns_xhprof.manager_registry'));
153 2
            $objectManager = $managerRegistry->getManager($this->container->getParameter('jns_xhprof.entity_manager'));
154 2
            if ($objectManager instanceof DocumentManager) {
0 ignored issues
show
Bug introduced by
The class Doctrine\ODM\MongoDB\DocumentManager does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
155 1
                $xhprof_runs = new XhguiRuns_Document($objectManager);
156 1
            } else {
157 1
                $xhprof_runs = new XhguiRuns_Entity($serverName, $uri);
158 1
                $xhprof_runs->setContainer($this->container);
159
            }
160 2
        } else {
161 1
            $xhprof_runs = new \XHProfRuns_Default();
162
        }
163 3
        return $xhprof_runs;
164
    }
165
166
    /**
167
     * Sanitize an uri to use it as source
168
     *
169
     * @param  string $uri
170
     * @return string
171
     */
172
    private function sanitizeUriForSource($uri)
173
    {
174
        $uri = preg_replace('/[\/]+/', '~', $uri);
175
176
        return preg_replace('/[^\w~\-_]+/', '-', $uri);
177
    }
178
179
    /**
180
     * {@inheritdoc}
181
     */
182
    public function getName()
183
    {
184
        return 'xhprof';
185
    }
186
187
    /**
188
     * Gets the XHProf extension exists or not.
189
     *
190
     * @return boolean Extension exists or not
191
     */
192
    public function getXhprofExtensionExists()
193
    {
194
        return $this->data['xhprof_extension_exists'];
195
    }
196
197
    /**
198
     * Gets the run id.
199
     *
200
     * @return integer The run id
201
     */
202
    public function getXhprof()
203
    {
204
        return $this->data['xhprof'];
205
    }
206
207
    /**
208
     * Gets the XHProf url.
209
     *
210
     * @return string The XHProf url
211
     */
212
    public function getXhprofUrl()
213
    {
214
        return $this->data['xhprof_url'];
215
    }
216
217
    /**
218
     * Check whether this request was profiled. Used for the debug toolbar.
219
     *
220
     * @return boolean
221
     */
222
    public function isProfiling()
223
    {
224
        return $this->data['xhprof']  ? true : false;
225
    }
226
}
227