Cache::setLogger()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 4
nop 1
crap 12
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipbox/craft-psr6/blob/master/LICENSE
6
 * @link       https://github.com/flipbox/craft-psr6
7
 */
8
9
namespace flipbox\craft\psr6;
10
11
use Craft;
12
use Flipbox\Stash\Pool;
13
use flipbox\craft\psr6\events\RegisterCachePools;
14
use Psr\Log\LoggerInterface;
15
use Stash\Driver\BlackHole;
16
use Stash\Driver\FileSystem;
17
use Stash\Interfaces\DriverInterface;
18
use Stash\Interfaces\PoolInterface;
19
use yii\base\Component;
20
use yii\caching\FileCache;
21
use yii\log\Logger;
22
23
/**
24
 * @author Flipbox Factory <[email protected]>
25
 * @since 1.0.0
26
 */
27
class Cache extends Component
28
{
29
    /**
30
     * @var LoggerInterface
31
     */
32
    public $logger;
33
34
    /**
35
     * The event name
36
     */
37
    const EVENT_REGISTER_CACHE_POOLS = 'registerCachePools';
38
39
    /**
40
     * @var DriverInterface
41
     */
42
    public $applicationDriver;
43
44
    /**
45
     * @return PoolInterface[]
46
     */
47
    public function findAll()
48
    {
49
        $cacheDrivers = [
50
            'default' => $this->getApplicationPool(),
51
            'dummy' => $this->createDummyPool(),
52
        ];
53
54
        $event = new RegisterCachePools([
55
            'pools' => $cacheDrivers
56
        ]);
57
58
        Craft::$app->trigger(
59
            self::EVENT_REGISTER_CACHE_POOLS,
60
            $event
61
        );
62
63
        return $event->getPools();
64
    }
65
66
    /**
67
     * @param string $handle
68
     * @return PoolInterface
69
     */
70
    public function get(string $handle = 'default')
71
    {
72
        // Get all
73
        $pools = $this->findAll();
74
75
        if (!array_key_exists($handle, $pools)) {
76
            Craft::error(
77
                sprintf(
78
                    "Cache pool does not exist: '%s'.",
79
                    $handle
80
                ),
81
                'PSR-6'
82
            );
83
            return $this->createDummyPool();
84
        }
85
86
        return $pools[$handle];
87
    }
88
89
    /**
90
     * @return Pool
91
     */
92
    protected function getApplicationPool()
93
    {
94
        // New cache pool
95
        $pool = new Pool(
96
            $this->getApplicationDriver()
97
        );
98
99
        // Set default duration
100
        $pool->setItemDuration(
101
            Craft::$app->getConfig()->getGeneral()->cacheDuration
102
        );
103
104
        // Add logging
105
        $this->setLogger($pool);
106
107
        return $pool;
108
    }
109
110
    /**
111
     * @return DriverInterface
112
     */
113
    protected function getApplicationDriver()
114
    {
115
        if ($this->applicationDriver instanceof DriverInterface) {
116
            return $this->applicationDriver;
117
        }
118
119
        // Nothing set
120
        if ($this->applicationDriver === null) {
121
            $this->applicationDriver = $this->resolveApplicationDriver();
122
        }
123
124
        // Config
125
        if (is_array($this->applicationDriver)) {
126
            $this->applicationDriver = $this->createDriver(
127
                $this->applicationDriver
128
            );
129
        }
130
131
        return $this->applicationDriver;
132
    }
133
134
    /**
135
     * @return BlackHole|FileSystem
136
     */
137
    private function resolveApplicationDriver()
138
    {
139
        $cacheInterface = Craft::$app->getCache();
140
141
        // Todo - support other drivers
142
        if ($cacheInterface instanceof FileCache) {
143
            return new FileSystem([
144
                'path' => Craft::getAlias($cacheInterface->cachePath)
145
            ]);
146
        }
147
148
        Craft::getLogger()->log(
149
            sprintf(
150
                "Cache method '{cacheMethod}' is not supported.",
151
                get_class($cacheInterface)
152
            ),
153
            Logger::LEVEL_WARNING
154
        );
155
156
        return new BlackHole();
157
    }
158
159
    /**
160
     * @param array $config
161
     * @return object|DriverInterface
162
     * @throws \yii\base\InvalidConfigException
163
     */
164
    private function createDriver(array $config): DriverInterface
165
    {
166
        return Craft::createObject(
167
            $config
168
        );
169
    }
170
171
    /**
172
     * @return Pool
173
     */
174
    protected function createDummyPool()
175
    {
176
        // New cache pool
177
        $pool = new Pool(
178
            new BlackHole()
179
        );
180
181
        $this->setLogger($pool);
182
183
        return new Pool();
184
    }
185
186
    /**
187
     * @param \Stash\Pool $pool
188
     */
189
    protected function setLogger(\Stash\Pool $pool)
190
    {
191
        if (null === $this->logger) {
192
            $this->logger = $this->applicationLogger(false);
193
        }
194
195
        if ($this->isLoggerValid($this->logger)) {
196
            $pool->setLogger($this->logger);
0 ignored issues
show
Documentation introduced by
$this->logger is of type null|object, but the function expects a object<Psr\Log\LoggerInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
197
        }
198
    }
199
200
    /**
201
     * @param $logger
202
     * @return bool
203
     */
204
    private function isLoggerValid($logger)
205
    {
206
        return $logger && $logger instanceof LoggerInterface;
207
    }
208
209
    /**
210
     * @param null $default
211
     * @return null|object
212
     */
213
    private function applicationLogger($default = null)
214
    {
215
        if (!Craft::$app->has('psr3-logger')) {
216
            return $default;
217
        }
218
        return Craft::$app->get('psr3-logger');
219
    }
220
}
221