Completed
Push — 1.4 ( f2fa86...1c2218 )
by Paweł
08:49
created

CachedJMSSerializer   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 1
dl 0
loc 53
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 15 4
A deserialize() 0 15 4
A getCacheKey() 0 16 5
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2019 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2019 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Serializer;
18
19
use SWP\Bridge\JMSSerializerBundle\JMSSerializer;
20
use SWP\Component\Common\Model\TimestampableInterface;
21
use SWP\Component\Storage\Model\PersistableInterface;
22
23
final class CachedJMSSerializer extends JMSSerializer
24
{
25
    private $cachedData = [];
26
27
    public function serialize($data, $format)
28
    {
29
        $cacheKey = $this->getCacheKey($data, null, $format);
30
        if (null !== $cacheKey && \array_key_exists($cacheKey, $this->cachedData)) {
31
            return $this->cachedData[$cacheKey];
32
        }
33
34
        $result = parent::serialize($data, $format);
35
36
        if (null !== $cacheKey) {
37
            $this->cachedData[$cacheKey] = $result;
38
        }
39
40
        return $result;
41
    }
42
43
    public function deserialize($data, $type, $format)
44
    {
45
        $cacheKey = $this->getCacheKey($data, $type, $format);
46
        if (null !== $cacheKey && \array_key_exists($cacheKey, $this->cachedData)) {
47
            return $this->cachedData[$cacheKey];
48
        }
49
50
        $result = parent::deserialize($data, $type, $format);
51
52
        if (null !== $cacheKey) {
53
            $this->cachedData[$cacheKey] = $result;
54
        }
55
56
        return $result;
57
    }
58
59
    private function getCacheKey($data, string $type = null, string $format = null): ?string
60
    {
61
        if ($data instanceof TimestampableInterface && $data instanceof PersistableInterface) {
62
            $keyElements = [$data->getId(), $data->getCreatedAt()->getTimestamp()];
63
            $keyElements[] = $data->getUpdatedAt() ? $data->getUpdatedAt()->getTimestamp() : null;
64
            $keyElements[] = $format;
65
66
            return \implode('__', $keyElements);
67
        }
68
69
        if (\is_string($data)) {
70
            return md5($data.'__'.$type.'__'.$format);
71
        }
72
73
        return null;
74
    }
75
}
76