Completed
Pull Request — master (#721)
by Han Hui
03:12
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
class CachedRouteNameResolver implements RouteNameResolverInterface
18
{
19
    const CACHE_KEY_PREFIX = 'route_name_';
20
21
    private $cacheItemPool;
22
    private $decorated;
23
24
    public function __construct(CacheItemPoolInterface $cacheItemPool, RouteNameResolverInterface $decorated)
25
    {
26
        $this->cacheItemPool = $cacheItemPool;
27
        $this->decorated = $decorated;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function getRouteName(string $resourceClass, bool $collection) : string
34
    {
35
        $cacheKey = self::CACHE_KEY_PREFIX.md5(serialize([$resourceClass, $collection]));
36
37
        try {
38
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
39
40
            if ($cacheItem->isHit()) {
41
                return $cacheItem->get();
42
            }
43
        } catch (CacheException $e) {
44
            // do nothing
45
        }
46
47
        $routeName = $this->decorated->getRouteName($resourceClass, $collection);
48
49
        if (isset($cacheItem)) {
50
            try {
51
                $cacheItem->set($routeName);
52
                $this->cacheItemPool->save($cacheItem);
53
            } catch (CacheException $e) {
54
                // do nothing
55
            }
56
        }
57
58
        return $routeName;
59
    }
60
}
61