Completed
Push — master ( 90ccc1...22512f )
by Kamil
35:43
created

AbstractMetadata::merge()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
dl 0
loc 27
rs 8.439
c 2
b 1
f 0
cc 6
eloc 15
nc 5
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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 Sylius\Component\Metadata\Model;
13
14
/**
15
 * Base metadata class with reusable merging ability.
16
 *
17
 * @author Kamil Kokot <[email protected]>
18
 */
19
abstract class AbstractMetadata implements MetadataInterface
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function merge(MetadataInterface $metadata)
25
    {
26
        if (!$metadata instanceof $this || !$this instanceof $metadata) {
27
            throw new \InvalidArgumentException(
28
                sprintf(
29
                    'You can only merge instances of the same classes. Tried to merge "%s" with "%s".',
30
                    get_class($this),
31
                    get_class($metadata)
32
                )
33
            );
34
        }
35
36
        $inheritedVariables = get_object_vars($metadata);
37
        foreach ($inheritedVariables as $inheritedKey => $inheritedValue) {
38
            if ($this->{$inheritedKey} instanceof MetadataInterface) {
39
                $this->{$inheritedKey}->merge($inheritedValue);
40
41
                continue;
42
            }
43
44
            if (null !== $this->{$inheritedKey}) {
45
                continue;
46
            }
47
48
            $this->{$inheritedKey} = $inheritedValue;
49
        }
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function toArray()
56
    {
57
        return array_map(
58
            function ($value) {
59
                if ($value instanceof MetadataInterface) {
60
                    $value = $value->toArray();
61
                }
62
63
                return $value;
64
            },
65
            get_object_vars($this)
66
        );
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function forAll(callable $callable)
73
    {
74
        foreach (get_object_vars($this) as $key => $value) {
75
            $this->$key = $callable($value);
76
        }
77
    }
78
}
79