Completed
Pull Request — master (#997)
by Antoine
03:12
created

CachedIriConverter::getItemFromIri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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 ApiPlatform\Core\Api\IriConverterInterface;
15
use ApiPlatform\Core\Api\UrlGeneratorInterface;
16
use ApiPlatform\Core\Exception\CacheException;
17
use ApiPlatform\Core\Util\ClassInfoTrait;
18
use Psr\Cache\CacheException as CacheExceptionInterface;
19
use Psr\Cache\CacheItemPoolInterface;
20
21
/**
22
 * {@inheritdoc}
23
 *
24
 * @author Antoine Bluchet <[email protected]>
25
 */
26
final class CachedIriConverter implements IriConverterInterface
27
{
28
    use ClassInfoTrait;
29
30
    const CACHE_KEY_PREFIX = 'iri_converter';
31
32
    private $cacheItemPool;
33
34
    public function __construct(CacheItemPoolInterface $cacheItemPool, IriConverterInterface $decorated)
0 ignored issues
show
Unused Code introduced by
The parameter $decorated is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
35
    {
36
        $this->cacheItemPool = $cacheItemPool;
37
    }
38
39
    public function getItemFromIri(string $iri, array $context = [])
40
    {
41
        return $this->decorated->getItemFromIri($iri, $context);
0 ignored issues
show
Bug introduced by
The property decorated does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
42
    }
43
44
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
45
    {
46
        $resourceClass = $this->getObjectClass($item);
47
        $cacheKey = self::CACHE_KEY_PREFIX.md5($resourceClass);
48
49
        try {
50
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
51
52
            if ($cacheItem->isHit()) {
53
                foreach ($cacheItem->get() as $propertyName) {
54
                    $identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);
0 ignored issues
show
Bug introduced by
The property propertyAccessor does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Coding Style Comprehensibility introduced by
$identifiers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $identifiers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
55
56
                    if (is_object($identifiers[$propertyName])) {
57
                        $relatedCacheKey = self::CACHE_KEY_PREFIX.md5(serialize($this->getObjectClass($identifiers[$propertyName])));
0 ignored issues
show
Bug introduced by
The variable $identifiers does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
58
59
                        $cacheItem = $this->cacheItemPool->getItem($relatedCacheKey);
60
61
                        if (!$cacheItem->isHit()) {
62
                            throw new CacheException("Can't find related identifiers");
63
                        }
64
65
                        $identifiers[$propertyName] = $cacheItem->get()[0];
66
                    }
67
                }
68
69
                return $identifiers;
70
            }
71
        } catch (CacheExceptionInterface $e) {
72
            // do nothing
73
        }
74
75
        $identifiers = $this->decorated->getIriFromItem();
76
77
        if (isset($cacheItem)) {
78
            try {
79
                $cacheItem->set(array_keys($identifiers));
80
                $this->cacheItemPool->save($cacheItem);
81
            } catch (CacheExceptionInterface $e) {
82
                // do nothing
83
            }
84
        }
85
86
        return $identifiers;
87
    }
88
89
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
90
    {
91
        return $this->decorated->getIriFromResourceClass($resourceClass, $referenceType);
92
    }
93
}
94