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
|
|
|
|