Passed
Branch 3.0.0 (dcfee6)
by Pieter
02:48
created

ClassResourceConverter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 21
c 0
b 0
f 0
dl 0
loc 68
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A denormalize() 0 18 5
A normalize() 0 5 1
A __construct() 0 5 1
1
<?php
2
namespace W2w\Lib\Apie\Core;
3
4
use ReflectionClass;
5
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
6
use W2w\Lib\Apie\Core\Resources\ApiResourcesInterface;
7
use W2w\Lib\Apie\Exceptions\ResourceNameNotFoundException;
8
9
/**
10
 * Converts between the api resource name in the url and the class name used in the code.
11
 */
12
class ClassResourceConverter implements NameConverterInterface
13
{
14
    /**
15
     * @var NameConverterInterface
16
     */
17
    private $nameConverter;
18
19
    /**
20
     * @var ApiResourcesInterface
21
     */
22
    private $resources;
23
24
    /**
25
     * @var bool
26
     */
27
    private $showResources;
28
29
    /**
30
     * @param NameConverterInterface $nameConverter
31
     * @param ApiResourcesInterface $resources
32
     * @param bool $showResources
33
     */
34
    public function __construct(NameConverterInterface $nameConverter, ApiResourcesInterface $resources, bool $showResources = true)
35
    {
36
        $this->nameConverter = $nameConverter;
37
        $this->resources = $resources;
38
        $this->showResources = $showResources;
39
    }
40
41
    /**
42
     * Converts a property name to its normalized value.
43
     *
44
     * @param string $propertyName
45
     *
46
     * @return string
47
     */
48
    public function normalize($propertyName)
49
    {
50
        $class = new ReflectionClass($propertyName);
51
52
        return $this->nameConverter->normalize($class->getShortName());
53
    }
54
55
    /**
56
     * Converts a property name to its denormalized value.
57
     *
58
     * @param string $propertyName
59
     *
60
     * @return string
61
     */
62
    public function denormalize($propertyName)
63
    {
64
        $available = [];
65
        $search = ucfirst($this->nameConverter->denormalize($propertyName));
66
        foreach ($this->resources->getApiResources() as $className) {
67
            $class = new ReflectionClass($className);
68
            if ($class->getShortName() === $search) {
69
                return $className;
70
            }
71
            if ($this->showResources) {
72
                $available[] = $this->nameConverter->normalize($class->getShortName());
73
            }
74
        }
75
        $availableMsg = '';
76
        if ($this->showResources) {
77
            $availableMsg = 'Possible resources: ' . implode(', ', $available);
78
        }
79
        throw new ResourceNameNotFoundException($propertyName, $availableMsg);
80
    }
81
}
82