These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more
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\Metadata\Property\Factory; |
||
15 | |||
16 | use ApiPlatform\Core\Metadata\Property\PropertyNameCollection; |
||
17 | use Psr\Cache\CacheException; |
||
18 | use Psr\Cache\CacheItemPoolInterface; |
||
19 | |||
20 | /** |
||
21 | * Caches property name collection. |
||
22 | * |
||
23 | * @author Teoh Han Hui <[email protected]> |
||
24 | */ |
||
25 | View Code Duplication | final class CachedPropertyNameCollectionFactory implements PropertyNameCollectionFactoryInterface |
|
0 ignored issues
–
show
|
|||
26 | { |
||
27 | const CACHE_KEY_PREFIX = 'property_name_collection_'; |
||
28 | |||
29 | private $cacheItemPool; |
||
30 | private $decorated; |
||
31 | private $memoryCache = []; |
||
32 | |||
33 | public function __construct(CacheItemPoolInterface $cacheItemPool, PropertyNameCollectionFactoryInterface $decorated) |
||
34 | { |
||
35 | $this->cacheItemPool = $cacheItemPool; |
||
36 | $this->decorated = $decorated; |
||
37 | } |
||
38 | |||
39 | /** |
||
40 | * {@inheritdoc} |
||
41 | */ |
||
42 | public function create(string $resourceClass, array $options = []): PropertyNameCollection |
||
43 | { |
||
44 | $localKey = serialize([$resourceClass, $options]); |
||
45 | if (isset($this->memoryCache[$localKey])) { |
||
46 | return $this->memoryCache[$localKey]; |
||
47 | } |
||
48 | |||
49 | $cacheKey = self::CACHE_KEY_PREFIX.md5($localKey); |
||
50 | |||
51 | try { |
||
52 | $cacheItem = $this->cacheItemPool->getItem($cacheKey); |
||
53 | |||
54 | if ($cacheItem->isHit()) { |
||
55 | return $this->memoryCache[$localKey] = $cacheItem->get(); |
||
56 | } |
||
57 | } catch (CacheException $e) { |
||
58 | // do nothing |
||
59 | } |
||
60 | |||
61 | $propertyNameCollection = $this->decorated->create($resourceClass, $options); |
||
62 | |||
63 | if (!isset($cacheItem)) { |
||
64 | return $this->memoryCache[$localKey] = $propertyNameCollection; |
||
65 | } |
||
66 | |||
67 | $cacheItem->set($propertyNameCollection); |
||
68 | $this->cacheItemPool->save($cacheItem); |
||
69 | |||
70 | return $this->memoryCache[$localKey] = $propertyNameCollection; |
||
71 | } |
||
72 | } |
||
73 |
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.