Completed
Push — master ( 5ba1dc...b85ec4 )
by Tomasz
02:09
created

JmsYamlNormalizer   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 15
c 1
b 0
f 1
lcom 0
cbo 1
dl 0
loc 65
rs 10

2 Methods

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