Passed
Pull Request — 2.1 (#1729)
by Antoine
04:12 queued 01:10
created

CachedRouteNameResolver::getRouteName()   C

Complexity

Conditions 7
Paths 66

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 19
nc 66
nop 2
dl 0
loc 35
rs 6.7272
c 0
b 0
f 0
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\Bridge\Symfony\Routing;
15
16
use Psr\Cache\CacheException;
17
use Psr\Cache\CacheItemPoolInterface;
18
19
/**
20
 * {@inheritdoc}
21
 *
22
 * @author Teoh Han Hui <[email protected]>
23
 */
24
final class CachedRouteNameResolver implements RouteNameResolverInterface
25
{
26
    const CACHE_KEY_PREFIX = 'route_name_';
27
28
    private $cacheItemPool;
29
    private $decorated;
30
31
    public function __construct(CacheItemPoolInterface $cacheItemPool, RouteNameResolverInterface $decorated)
32
    {
33
        $this->cacheItemPool = $cacheItemPool;
34
        $this->decorated = $decorated;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function getRouteName(string $resourceClass, $operationType /**, array $context = []**/): string
41
    {
42
        $context = \func_num_args() > 2 ? func_get_arg(2) : [];
43
        $cacheKey = self::CACHE_KEY_PREFIX.md5(serialize([$resourceClass, $operationType, $context['subresource_resources'] ?? null]));
44
45
        try {
46
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
47
48
            if ($cacheItem->isHit()) {
49
                return $cacheItem->get();
50
            }
51
        } catch (CacheException $e) {
52
            // do nothing
53
        }
54
55
        if (\func_num_args() > 2) {
56
            $context = func_get_arg(2);
57
        } else {
58
            $context = [];
59
        }
60
61
        $routeName = $this->decorated->getRouteName($resourceClass, $operationType, $context);
62
63
        if (!isset($cacheItem)) {
64
            return $routeName;
65
        }
66
67
        try {
68
            $cacheItem->set($routeName);
69
            $this->cacheItemPool->save($cacheItem);
70
        } catch (CacheException $e) {
71
            // do nothing
72
        }
73
74
        return $routeName;
75
    }
76
}
77