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

CachedRouteNameResolver   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 100 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 46
loc 46
c 0
b 0
f 0
wmc 6
lcom 1
cbo 3
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 5 5 1
B getRouteName() 29 29 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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