Completed
Push — master ( 4f8937...8be83a )
by Tobias
71:36 queued 46:35
created

CacheDataCollector::reset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of php-cache\cache-bundle package.
5
 *
6
 * (c) 2015 Aaron Scherer <[email protected]>, Tobias Nyholm <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Cache\CacheBundle\DataCollector;
13
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
17
use Symfony\Component\VarDumper\Caster\CutStub;
18
use Symfony\Component\VarDumper\Cloner\Stub;
19
use Symfony\Component\VarDumper\Cloner\VarCloner;
20
21
/**
22
 * @author Aaron Scherer <[email protected]>
23
 * @author Tobias Nyholm <[email protected]>
24
 *
25
 * @internal
26
 */
27
class CacheDataCollector extends DataCollector
28
{
29
    /**
30
     * @type CacheProxyInterface[]
31
     */
32
    private $instances = [];
33
34
    /**
35
     * @type VarCloner
36
     */
37
    private $cloner = null;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
38
39
    /**
40
     * @param string              $name
41
     * @param CacheProxyInterface $instance
42
     */
43
    public function addInstance($name, CacheProxyInterface $instance)
44
    {
45
        $this->instances[$name] = $instance;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function collect(Request $request, Response $response, \Exception $exception = null)
52
    {
53
        $empty      = ['calls' => [], 'config' => [], 'options' => [], 'statistics' => []];
54
        $this->data = ['instances' => $empty, 'total' => $empty];
55
        foreach ($this->instances as $name => $instance) {
56
            $calls = $instance->__getCalls();
57
            foreach ($calls as $call) {
58
                if (isset($call->result)) {
59
                    $call->result = $this->cloneData($call->result);
60
                }
61
                if (isset($call->argument)) {
62
                    $call->argument = $this->cloneData($call->argument);
63
                }
64
            }
65
            $this->data['instances']['calls'][$name] = $calls;
66
        }
67
68
        $this->data['instances']['statistics'] = $this->calculateStatistics();
69
        $this->data['total']['statistics']     = $this->calculateTotalStatistics();
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function reset()
76
    {
77
        $empty      = ['calls' => [], 'config' => [], 'options' => [], 'statistics' => []];
78
        $this->data = ['instances' => $empty, 'total' => $empty];
79
    }
80
81
    /**
82
     * To be compatible with many versions of Symfony.
83
     *
84
     * @param $var
85
     */
86
    private function cloneData($var)
87
    {
88
        if (method_exists($this, 'cloneVar')) {
89
            // Symfony 3.2 or higher
90
            return $this->cloneVar($var);
91
        }
92
93
        if (null === $this->cloner) {
94
            $this->cloner = new VarCloner();
95
            $this->cloner->setMaxItems(-1);
96
            $this->cloner->addCasters($this->getCloneCasters());
97
        }
98
99
        return $this->cloner->cloneVar($var);
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function getName()
106
    {
107
        return 'php-cache';
108
    }
109
110
    /**
111
     * Method returns amount of logged Cache reads: "get" calls.
112
     *
113
     * @return array
114
     */
115
    public function getStatistics()
116
    {
117
        return $this->data['instances']['statistics'];
118
    }
119
120
    /**
121
     * Method returns the statistic totals.
122
     *
123
     * @return array
124
     */
125
    public function getTotals()
126
    {
127
        return $this->data['total']['statistics'];
128
    }
129
130
    /**
131
     * Method returns all logged Cache call objects.
132
     *
133
     * @return mixed
134
     */
135
    public function getCalls()
136
    {
137
        return $this->data['instances']['calls'];
138
    }
139
140
    /**
141
     * @return array
142
     */
143
    private function calculateStatistics()
144
    {
145
        $statistics = [];
146
        foreach ($this->data['instances']['calls'] as $name => $calls) {
147
            $statistics[$name] = [
148
                'calls'   => 0,
149
                'time'    => 0,
150
                'reads'   => 0,
151
                'writes'  => 0,
152
                'deletes' => 0,
153
                'hits'    => 0,
154
                'misses'  => 0,
155
            ];
156
            /** @type TraceableAdapterEvent $call */
157
            foreach ($calls as $call) {
158
                $statistics[$name]['calls'] += 1;
159
                $statistics[$name]['time'] += $call->end - $call->start;
160
                if ('getItem' === $call->name) {
161
                    $statistics[$name]['reads'] += 1;
162 View Code Duplication
                    if ($call->hits) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
                        $statistics[$name]['hits'] += 1;
164
                    } else {
165
                        $statistics[$name]['misses'] += 1;
166
                    }
167
                } elseif ('getItems' === $call->name) {
168
                    $count = $call->hits + $call->misses;
169
                    $statistics[$name]['reads'] += $count;
170
                    $statistics[$name]['hits'] += $call->hits;
171
                    $statistics[$name]['misses'] += $count - $call->misses;
172
                } elseif ('hasItem' === $call->name) {
173
                    $statistics[$name]['reads'] += 1;
174 View Code Duplication
                    if (false === $call->result) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
175
                        $statistics[$name]['misses'] += 1;
176
                    } else {
177
                        $statistics[$name]['hits'] += 1;
178
                    }
179
                } elseif ('save' === $call->name) {
180
                    $statistics[$name]['writes'] += 1;
181
                } elseif ('deleteItem' === $call->name) {
182
                    $statistics[$name]['deletes'] += 1;
183
                }
184
            }
185
            if ($statistics[$name]['reads']) {
186
                $statistics[$name]['hit_read_ratio'] = round(100 * $statistics[$name]['hits'] / $statistics[$name]['reads'], 2);
187
            } else {
188
                $statistics[$name]['hit_read_ratio'] = null;
189
            }
190
        }
191
192
        return $statistics;
193
    }
194
195
    /**
196
     * @return array
197
     */
198
    private function calculateTotalStatistics()
199
    {
200
        $statistics = $this->getStatistics();
201
        $totals     = [
202
            'calls'   => 0,
203
            'time'    => 0,
204
            'reads'   => 0,
205
            'writes'  => 0,
206
            'deletes' => 0,
207
            'hits'    => 0,
208
            'misses'  => 0,
209
        ];
210
        foreach ($statistics as $name => $values) {
211
            foreach ($totals as $key => $value) {
212
                $totals[$key] += $statistics[$name][$key];
213
            }
214
        }
215
        if ($totals['reads']) {
216
            $totals['hit_read_ratio'] = round(100 * $totals['hits'] / $totals['reads'], 2);
217
        } else {
218
            $totals['hit_read_ratio'] = null;
219
        }
220
221
        return $totals;
222
    }
223
224
    /**
225
     * @return callable[] The casters to add to the cloner
226
     */
227
    private function getCloneCasters()
228
    {
229
        return [
230
            '*' => function ($v, array $a, Stub $s, $isNested) {
0 ignored issues
show
Unused Code introduced by
The parameter $s is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $isNested is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
231
                if (!$v instanceof Stub) {
232
                    foreach ($a as $k => $v) {
233
                        if (is_object($v) && !$v instanceof \DateTimeInterface && !$v instanceof Stub) {
234
                            $a[$k] = new CutStub($v);
235
                        }
236
                    }
237
                }
238
239
                return $a;
240
            },
241
        ];
242
    }
243
}
244