Completed
Push — master ( 131c91...75b368 )
by Kévin
03:30
created

CachedSubresourceOperationFactory::create()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 12
nc 5
nop 1
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Operation\Factory;
15
16
use Psr\Cache\CacheException;
17
use Psr\Cache\CacheItemPoolInterface;
18
19
/**
20
 * @internal
21
 */
22
final class CachedSubresourceOperationFactory implements SubresourceOperationFactoryInterface
23
{
24
    const CACHE_KEY_PREFIX = 'subresource_operations_';
25
26
    private $cacheItemPool;
27
    private $decorated;
28
29
    public function __construct(CacheItemPoolInterface $cacheItemPool, SubresourceOperationFactoryInterface $decorated)
30
    {
31
        $this->cacheItemPool = $cacheItemPool;
32
        $this->decorated = $decorated;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function create(string $resourceClass): array
39
    {
40
        $cacheKey = self::CACHE_KEY_PREFIX.str_replace('\\', '', $resourceClass);
41
42
        try {
43
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
44
45
            if ($cacheItem->isHit()) {
46
                return $cacheItem->get();
47
            }
48
        } catch (CacheException $e) {
49
            return $this->decorated->create($resourceClass);
50
        }
51
52
        $subresourceOperations = $this->decorated->create($resourceClass);
53
54
        $cacheItem->set($subresourceOperations);
55
        $this->cacheItemPool->save($cacheItem);
56
57
        return $subresourceOperations;
58
    }
59
}
60