1<?php
2
3declare(strict_types=1);
4
5namespace Metadata\Cache;
6
7use Metadata\ClassMetadata;
8use Psr\Cache\CacheItemPoolInterface;
9
10class PsrCacheAdapter implements CacheInterface
11{
12    /**
13     * @var string
14     */
15    private $prefix;
16
17    /**
18     * @var CacheItemPoolInterface
19     */
20    private $pool;
21
22    /**
23     * @var CacheItemPoolInterface
24     */
25    private $lastItem;
26
27    public function __construct(string $prefix, CacheItemPoolInterface $pool)
28    {
29        $this->prefix = $prefix;
30        $this->pool = $pool;
31    }
32
33    /**
34     * {@inheritDoc}
35     */
36    public function load(string $class): ?ClassMetadata
37    {
38        $this->lastItem = $this->pool->getItem(strtr($this->prefix . $class, '\\', '.'));
39
40        return $this->lastItem->get();
41    }
42
43    /**
44     * {@inheritDoc}
45     */
46    public function put(ClassMetadata $metadata): void
47    {
48        $key = strtr($this->prefix . $metadata->name, '\\', '.');
49
50        if (null === $this->lastItem || $this->lastItem->getKey() !== $key) {
51            $this->lastItem = $this->pool->getItem($key);
52        }
53
54        $this->pool->save($this->lastItem->set($metadata));
55    }
56
57    /**
58     * {@inheritDoc}
59     */
60    public function evict(string $class): void
61    {
62        $this->pool->deleteItem(strtr($this->prefix . $class, '\\', '.'));
63    }
64}
65