Model::getCacheTag()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * File: Model.php
4
 *
5
 * @author      Maciej Sławik <[email protected]>
6
 * Github:      https://github.com/maciejslawik
7
 */
8
9
namespace MSlwk\Otomoto\Middleware\App\Model;
10
11
use MSlwk\Otomoto\App\Manufacturer\Data\ManufacturerDTOInterface;
12
use MSlwk\Otomoto\App\Model\Data\ModelDTOArray;
13
use MSlwk\Otomoto\App\Model\ModelProvider;
14
use MSlwk\Otomoto\Middleware\Cache\Adapter\CacheAdapterInterface;
15
16
/**
17
 * Class Model
18
 * @package MSlwk\Otomoto\Middleware\App\Model
19
 */
20
class Model
21
{
22
    const CACHE_TAG = 'models_%manufacturer%';
23
24
    /**
25
     * @var CacheAdapterInterface
26
     */
27
    private $cacheAdapter;
28
29
    /**
30
     * @var ModelProvider
31
     */
32
    private $modelProvider;
33
34
    /**
35
     * @var ModelSerializer
36
     */
37
    private $modelSerializer;
38
39
40
    /**
41
     * Model constructor.
42
     * @param CacheAdapterInterface $cacheAdapter
43
     * @param ModelProvider $modelProvider
44
     * @param ModelSerializer $modelSerializer
45
     */
46 3
    public function __construct(
47
        CacheAdapterInterface $cacheAdapter,
48
        ModelProvider $modelProvider,
49
        ModelSerializer $modelSerializer
50
    ) {
51 3
        $this->cacheAdapter = $cacheAdapter;
52 3
        $this->modelProvider = $modelProvider;
53 3
        $this->modelSerializer = $modelSerializer;
54 3
    }
55
56
    /**
57
     * @param ManufacturerDTOInterface $manufacturerDTO
58
     * @return ModelDTOArray
59
     */
60 2
    public function getModels(ManufacturerDTOInterface $manufacturerDTO): ModelDTOArray
61
    {
62 2
        $cacheItem = $this->cacheAdapter->retrieve($this->getCacheTag($manufacturerDTO));
63 2
        if (!$cacheItem->get()) {
64 1
            $models = $this->modelProvider->getModels($manufacturerDTO);
65 1
            $cacheItem->set($this->modelSerializer->serialize($models));
66 1
            $this->cacheAdapter->store($cacheItem);
67 1
            $cacheItem = $this->cacheAdapter->retrieve($this->getCacheTag($manufacturerDTO));
68
        }
69
70 2
        return $this->modelSerializer->unserialize($cacheItem->get());
71
    }
72
73
    /**
74
     * @param ManufacturerDTOInterface $manufacturerDTO
75
     * @return string
76
     */
77 2
    private function getCacheTag(ManufacturerDTOInterface $manufacturerDTO): string
78
    {
79 2
        return str_replace('%manufacturer%', $manufacturerDTO->getName(), self::CACHE_TAG);
80
    }
81
}
82