Passed
Pull Request — master (#5)
by
unknown
31:12
created

CacheCollector::hasCacheLogger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license.
17
 *
18
 * CacheCollector.php
19
 * @data:       2017-02-08 21:58
20
 */
21
22
namespace DoctrineCacheToolbar\Collector;
23
24
use Doctrine\ORM\EntityManager;
25
use Zend\Mvc\MvcEvent;
26
use ZendDeveloperTools\Collector\AbstractCollector;
27
use ZendDeveloperTools\Collector\AutoHideInterface;
28
29
/**
30
 * Class CacheCollector
31
 * @package DoctrineCacheToolbar\Collector
32
 * @author: Szymon Michałowski <[email protected]>
33
 */
34
class CacheCollector extends AbstractCollector implements AutoHideInterface
35
{
36
    /**
37
     * @var string
38
     */
39
    protected $name = 'cache.toolbar';
40
41
    /**
42
     * @var int
43
     */
44
    protected $priority = 15;
45
46
    /**
47
     * @var EntityManager
48
     */
49
    protected $entityManager;
50
51
    /**
52
     * @param MvcEvent $mvcEvent
53
     * @return array
54
     */
55 1
    public function collect(MvcEvent $mvcEvent)
56
    {
57 1
        if (!isset($this->data)) {
58 1
            return $this->data = [];
59
        }
60 1
    }
61
62
    /**
63
     * {@inheritdoc}
64
     * @return bool
65
     */
66 1
    public function canHide()
67
    {
68 1
        if (!$this->getEntityManager()) {
69 1
            return true;
70
        }
71
72 1
        $isCacheEnabled = $this->getEntityManager()
73 1
            ->getConfiguration()
74 1
            ->isSecondLevelCacheEnabled();
75
76 1
        if (!$isCacheEnabled) {
77 1
            return true;
78
        }
79
80 1
        return false;
81
    }
82
83
    /**
84
     * Has cache logger
85
     *
86
     * @return bool
87
     */
88 1
    public function hasCacheLogger()
89
    {
90 1
        $config = $this->getEntityManager()->getConfiguration();
91
92 1
        if (! $config->isSecondLevelCacheEnabled()) {
93 1
            return false;
94
        }
95
96 1
        $logger = $config->getSecondLevelCacheConfiguration()
97 1
            ->getCacheLogger();
98
99 1
        return $logger !== null;
100
    }
101
102
    /**
103
     * Get cache stats
104
     *
105
     * @return array
106
     */
107 4
    public function getCacheStats()
108
    {
109 4
        if (!$this->getEntityManager()) {
110 1
            throw new \LogicException('Entity Manager must be set.');
111
        }
112
113 3
        $config = $this->getEntityManager()->getConfiguration();
114
115 3
        if (!$config->isSecondLevelCacheEnabled()) {
116 1
            return $this->data;
117
        }
118
119 2
        $logger = $config->getSecondLevelCacheConfiguration()
120 2
            ->getCacheLogger();
121
122 2
        if (null === $logger) {
123 1
            throw new \LogicException('Cache logger must be set.');
124
        }
125
126
        $info = [
127
            'info' => [
128 1
                'metadata_adapter'    => is_object($config->getMetadataCacheImpl())
129 1
                    ? get_class($config->getMetadataCacheImpl())
130 1
                    : 'NA',
131 1
                'query_adapter'       => is_object($config->getQueryCacheImpl())
132 1
                    ? get_class($config->getQueryCacheImpl())
133 1
                    : 'NA',
134 1
                'result_adapter'      => is_object($config->getResultCacheImpl())
135 1
                    ? get_class($config->getResultCacheImpl())
136 1
                    : 'NA',
137 1
                'hydration_adapter'   => is_object($config->getHydrationCacheImpl())
138 1
                    ? get_class($config->getHydrationCacheImpl())
139 1
                    : 'NA',
140
            ]
141
        ];
142
        $total = [
143
            'total' => [
144 1
                'put' => $logger->getPutCount(),
145 1
                'hit' => $logger->getHitCount(),
146 1
                'miss' => $logger->getMissCount(),
147
            ]
148
        ];
149
        $regions = [
150 1
            'regions' => [
151 1
                'put' => $logger->getRegionsPut() ?: ['None' => null],
152 1
                'hit' => $logger->getRegionsHit() ?: ['None' => null],
153 1
                'miss' => $logger->getRegionsMiss() ?: ['None' => null],
154
            ]
155
        ];
156
157 1
        $this->data = array_merge($info, $total, $regions);
158 1
        return $this->data;
159
    }
160
161
    /**
162
     * @return string
163
     */
164 1
    public function getName()
165
    {
166 1
        return $this->name;
167
    }
168
169
    /**
170
     * @return string
171
     */
172 1
    public function getPriority()
173
    {
174 1
        return $this->priority;
175
    }
176
177
    /**
178
     * @return EntityManager
179
     */
180 1
    public function getEntityManager()
181
    {
182 1
        return $this->entityManager;
183
    }
184
185
    /**
186
     * @param EntityManager $entityManager
187
     */
188 1
    public function setEntityManager(EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
189
    {
190 1
        $this->entityManager = $entityManager;
191 1
    }
192
}
193