1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\Mapper\Definition; |
5
|
|
|
|
6
|
|
|
use Psr\SimpleCache\CacheInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Caching decorator for a definition provider using PSR-16 compatible cache. |
10
|
|
|
* |
11
|
|
|
* @see http://www.php-fig.org/psr/psr-16/ |
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-16 Compatible cache |
28
|
|
|
* |
29
|
|
|
* @var CacheInterface |
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 CacheInterface $cache |
45
|
|
|
*/ |
46
|
3 |
|
public function __construct(DefinitionProviderInterface $provider, CacheInterface $cache) |
47
|
|
|
{ |
48
|
3 |
|
$this->provider = $provider; |
49
|
3 |
|
$this->cache = $cache; |
50
|
3 |
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* {@inheritdoc} |
54
|
|
|
*/ |
55
|
3 |
|
public function getDefinition(string $class): Definition |
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 |
|
$data = $this->cache->get($key); |
74
|
|
|
|
75
|
3 |
|
if ($data !== null) { |
76
|
1 |
|
return unserialize($data); |
77
|
|
|
} |
78
|
|
|
|
79
|
2 |
|
$definition = $this->provider->getDefinition($class); |
80
|
|
|
|
81
|
2 |
|
$this->cache->set($key, serialize($definition)); |
82
|
|
|
|
83
|
2 |
|
return $definition; |
84
|
|
|
} |
85
|
|
|
} |