Completed
Pull Request — master (#721)
by Han Hui
03:47
created

CachedRouteNameResolver::getRouteName()   B

Complexity

Conditions 5
Paths 17

Size

Total Lines 29
Code Lines 15

Duplication

Lines 29
Ratio 100 %

Importance

Changes 0
Metric Value
dl 29
loc 29
c 0
b 0
f 0
rs 8.439
cc 5
eloc 15
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 View Code Duplication
final class CachedRouteNameResolver implements RouteNameResolverInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
            return $routeName;
56
        }
57
58
        try {
59
            $cacheItem->set($routeName);
60
            $this->cacheItemPool->save($cacheItem);
61
        } catch (CacheException $e) {
62
            // do nothing
63
        }
64
65
        return $routeName;
66
    }
67
}
68