1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ps2alerts\Api\Loader\Metrics; |
4
|
|
|
|
5
|
|
|
use Ps2alerts\Api\Loader\AbstractLoader; |
6
|
|
|
use Ps2alerts\Api\QueryObjects\QueryObject; |
7
|
|
|
|
8
|
|
|
abstract class AbstractMetricsLoader extends AbstractLoader |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Allows injection of where statements |
12
|
|
|
* |
13
|
|
|
* @var array |
14
|
|
|
*/ |
15
|
|
|
protected $metrics = []; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Returns metrics for a particular result |
19
|
|
|
* |
20
|
|
|
* @param string $id |
21
|
|
|
* |
22
|
|
|
* @return array |
23
|
|
|
*/ |
24
|
|
|
public function readSingle($id) |
25
|
|
|
{ |
26
|
|
|
$redisKey = "{$this->getCacheNamespace()}{$id}:{$this->getType()}"; |
27
|
|
|
|
28
|
|
|
if (! empty($this->getMetrics())) { |
29
|
|
|
foreach ($this->getMetrics() as $metric) { |
30
|
|
|
$redisKey .= ":{$metric['col']}{$op}{$metric['value']}"; |
|
|
|
|
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if ($this->checkRedis($redisKey)) { |
35
|
|
|
return $this->getFromRedis($redisKey); |
|
|
|
|
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$queryObject = new QueryObject; |
39
|
|
|
$queryObject->addWhere([ |
40
|
|
|
'col' => 'result', |
41
|
|
|
'value' => $id |
42
|
|
|
]); |
43
|
|
|
|
44
|
|
|
if (! empty($this->getMetrics())) { |
45
|
|
|
foreach ($this->getMetrics() as $metric) { |
46
|
|
|
$op = (isset($metric['op']) ? $metric['op'] : '='); |
47
|
|
|
$queryObject->addWhere([ |
48
|
|
|
'col' => $metric['col'], |
49
|
|
|
'op' => $op, |
50
|
|
|
'value' => $metric['value'] |
51
|
|
|
]); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $this->cacheAndReturn( |
56
|
|
|
$this->repository->read($queryObject), |
|
|
|
|
57
|
|
|
$redisKey |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Allows setting of metrics to filter |
63
|
|
|
* |
64
|
|
|
* @param array |
65
|
|
|
*/ |
66
|
|
|
public function setMetrics($metric) |
67
|
|
|
{ |
68
|
|
|
if (! empty($metric)) { |
69
|
|
|
// Don't allow setting if the proper data isn't there. |
70
|
|
|
// Prevents and kind of errors later on. |
71
|
|
|
if (! empty($metric['col']) && ! empty($metric['value'])) { |
72
|
|
|
$this->metrics[] = $metric; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Pulls in metrics |
79
|
|
|
* |
80
|
|
|
* @return array |
81
|
|
|
*/ |
82
|
|
|
public function getMetrics() |
83
|
|
|
{ |
84
|
|
|
return $this->metrics; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
This error can happen if you refactor code and forget to move the variable initialization.
Let’s take a look at a simple example:
The above code is perfectly fine. Now imagine that we re-order the statements:
In that case,
$x
would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.