CachedProvider::provideDefinition()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Mapper\Definition;
5
6
use Psr\Cache\CacheItemPoolInterface;
7
8
/**
9
 * Caching decorator for a definition provider using PSR-6 cache.
10
 *
11
 * @see http://www.php-fig.org/psr/psr-6/
12
 *
13
 * @package Mikemirten\Component\JsonApi\Mapper\Definition
14
 */
15
class CachedProvider implements DefinitionProviderInterface
16
{
17
    const PREFIX = 'json_api_mapper.';
18
19
    /**
20
     * Delegated provider
21
     *
22
     * @var DefinitionProviderInterface
23
     */
24
    protected $provider;
25
26
    /**
27
     * PSR-6 Compatible cache
28
     *
29
     * @var CacheItemPoolInterface
30
     */
31
    protected $cache;
32
33
    /**
34
     * Locally cached definitions
35
     *
36
     * @var Definition[]
37
     */
38
    protected $definitions = [];
39
40
    /**
41
     * CachedProvider constructor.
42
     *
43
     * @param DefinitionProviderInterface $provider
44
     * @param CacheItemPoolInterface      $cache
45
     */
46 3
    public function __construct(DefinitionProviderInterface $provider, CacheItemPoolInterface $cache)
47
    {
48 3
        $this->provider = $provider;
49 3
        $this->cache    = $cache;
50 3
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 3 View Code Duplication
    public function getDefinition(string $class): Definition
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
    {
57 3
        if (! isset($this->definitions[$class])) {
58 3
            $this->definitions[$class] = $this->provideDefinition($class);
59
        }
60
61 3
        return $this->definitions[$class];
62
    }
63
64
    /**
65
     * Provide definition: try cache or get from provider
66
     *
67
     * @param  string $class
68
     * @return Definition
69
     */
70 3
    public function provideDefinition(string $class): Definition
71
    {
72 3
        $key  = self::PREFIX . md5($class);
73 3
        $item = $this->cache->getItem($key);
74
75 3
        if ($item->isHit()) {
76 1
            return $item->get();
77
        }
78
79 2
        $definition = $this->provider->getDefinition($class);
80
81 2
        $item->set($definition);
82 2
        $this->cache->save($item);
83
84 2
        return $definition;
85
    }
86
}