Psr16Storage::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\Storage\Drivers;
11
12
use Psr\SimpleCache\CacheInterface;
13
use Railt\Io\Readable;
14
use Railt\Storage\Storage;
15
16
/**
17
 * Class Psr16Storage
18
 */
19
class Psr16Storage implements Storage
20
{
21
    private const DEFAULT_REMEMBER_TIME = 60 * 5;
22
23
    /**
24
     * @var int
25
     */
26
    private $timeout;
27
28
    /**
29
     * @var CacheInterface
30
     */
31
    private $storage;
32
33
    /**
34
     * Psr16Storage constructor.
35
     * @param CacheInterface $storage
36
     * @param int $timeout
37
     */
38
    public function __construct(CacheInterface $storage, int $timeout = self::DEFAULT_REMEMBER_TIME)
39
    {
40
        $this->storage = $storage;
41
        $this->timeout = $timeout;
42
    }
43
44
    /**
45
     * @param Readable $readable
46
     * @param \Closure $then
47
     * @return mixed
48
     * @throws \Exception
49
     * @throws \Psr\SimpleCache\InvalidArgumentException
50
     */
51
    public function remember(Readable $readable, \Closure $then)
52
    {
53
        $data = $this->storage->get($readable->getHash());
54
55
        // If entity exists
56
        if (\is_object($data)) {
57
            return $data;
58
        }
59
60
        $result = $then($readable);
61
62
        $this->storage->set($readable->getHash(), $data, $this->timeout);
63
64
        return $result;
65
    }
66
}
67