Completed
Pull Request — master (#721)
by Han Hui
04:07
created

CachedRouteNameResolver::getRouteName()   B

Complexity

Conditions 5
Paths 17

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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