CacheReturner   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 15
dl 0
loc 40
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A return() 0 16 4
1
<?php
2
3
namespace Dpeuscher\Util\Cache;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\SimpleCache\CacheInterface;
7
use Psr\SimpleCache\InvalidArgumentException;
8
9
/**
10
 * @category  util
11
 * @copyright Copyright (c) 2018 Dominik Peuscher
12
 */
13
class CacheReturner
14
{
15
    /**
16
     * @var CacheInterface
17
     */
18
    private $cache;
19
20
    /**
21
     * @var LoggerInterface
22
     */
23
    private $logger;
24
25
    /**
26
     * CacheReturner constructor.
27
     *
28
     * @param CacheInterface $cache
29
     * @param LoggerInterface $logger
30
     */
31
    public function __construct(CacheInterface $cache, LoggerInterface $logger)
32
    {
33
        $this->cache = $cache;
34
        $this->logger = $logger;
35
    }
36
37
    public function return(string $key, callable $callback)
38
    {
39
        try {
40
            if ($this->cache->has(hash('sha256', $key))) {
41
                return $this->cache->get(hash('sha256', $key));
42
            }
43
        } catch (InvalidArgumentException $e) {
44
            $this->logger->warning('Used invalid key as cache key "' . $key . '" - handled as miss');
45
        }
46
        $result = $callback($key);
47
        /** @noinspection UnSafeIsSetOverArrayInspection */
48
        if (!isset($e)) {
49
            /** @noinspection PhpUnhandledExceptionInspection */
50
            $this->cache->set(hash('sha256', $key), $result);
51
        }
52
        return $result;
53
    }
54
}
55