JmsYamlNormalizer   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 15
lcom 0
cbo 2
dl 0
loc 66
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C __invoke() 0 56 14
1
<?php
2
namespace Thunder\Serializard\Normalizer;
3
4
use Symfony\Component\Yaml\Yaml;
5
use Thunder\Serializard\Exception\SerializationFailureException;
6
7
/**
8
 * @author Tomasz Kowalczyk <[email protected]>
9
 * @codeCoverageIgnore
10
 */
11
final class JmsYamlNormalizer
12
{
13
    private $path;
14
15
    public function __construct($path)
16
    {
17
        $this->path = $path;
18
    }
19
20
    public function __invoke($var)
21
    {
22
        $data = file_get_contents($this->path);
23
        if(!$data) {
24
            throw new SerializationFailureException(sprintf('Failed to read file at path %s!', $this->path));
25
        }
26
27
        // FIXME: Cache parsed config within normalizer instance
28
        $yaml = Yaml::parse($data);
29
        $keys = array_keys($yaml);
30
        $yaml = $yaml[$keys[0]];
31
        if(!$yaml) {
32
            throw new SerializationFailureException('No config at '.$this->path);
33
        }
34
35
        $hasPolicy = array_key_exists('exclusion_policy', $yaml);
36
        if(!$hasPolicy || ($hasPolicy && 'ALL' !== $yaml['exclusion_policy'])) {
37
            throw new SerializationFailureException(sprintf('This serializer supports only ALL, %s given!', $yaml['exclusion_policy']));
38
        }
39
40
        $ref = new \ReflectionObject($var);
41
        $result = [];
42
        $properties = array_key_exists('properties', $yaml) ? $yaml['properties'] : [];
43
        foreach($properties as $key => $config) {
44
            if($config['expose'] !== true) {
45
                continue;
46
            }
47
48
            $name = array_key_exists('serialized_name', $config) ? $config['serialized_name'] : $key;
49
50
            if($ref->hasProperty($key)) {
51
                $prop = $ref->getProperty($key);
52
                $prop->setAccessible(true);
53
54
                $result[$name] = $prop->getValue($var);
55
56
                continue;
57
            }
58
59
            $method = 'get'.ucfirst($key);
60
            if(method_exists($var, $method)) {
61
                $result[$name] = $var->{$method}();
62
63
                continue;
64
            }
65
66
            // no method or property found, skip current key
67
        }
68
69
        $virtual = array_key_exists('virtual_properties', $yaml) ? $yaml['virtual_properties'] : [];
70
        foreach($virtual as $method => $config) {
71
            $result[$config['serialized_name']] = $var->{$method}();
72
        }
73
74
        return $result;
75
    }
76
}
77