Completed
Push — master ( ca81b9...863650 )
by Joschi
03:44
created

Relations::toArray()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 2
eloc 10
c 3
b 0
f 1
nc 1
nop 0
dl 0
loc 16
ccs 9
cts 9
cp 1
crap 2
rs 9.4285
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\Application
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Apparat\Object\Domain\Model\Properties;
38
39
use Apparat\Object\Domain\Factory\RelationFactory;
40
use Apparat\Object\Domain\Model\Object\ObjectInterface;
41
use Apparat\Object\Domain\Model\Relation\RelationInterface;
42
43
/**
44
 * Object resource relations
45
 *
46
 * @package Apparat\Object
47
 * @subpackage Apparat\Object\Application
48
 */
49
class Relations extends AbstractProperties
50
{
51
    /**
52
     * Collection name
53
     *
54
     * @var string
55
     */
56
    const COLLECTION = 'relations';
57
    /**
58
     * Relations
59
     *
60
     * @var array
61
     */
62
    protected $relations = [];
63
64
65
    /**
66
     * Relations constructor
67
     *
68
     * @param array $data Property data
69
     * @param ObjectInterface $object Owner object
70
     */
71 19
    public function __construct(array $data, ObjectInterface $object)
72
    {
73 19
        parent::__construct($data, $object);
74
75
        // Run through all registered relation type collections
76
        /**
77
         * @var string $relationType
78
         * @var RelationInterface[] $relations
79
         */
80 19
        foreach ($this->data as $relationType => $relations) {
81
            // If the relation type collection is invalid or empty
82 18
            if (!is_array($relations) || !count($relations)) {
83
                // TODO Trigger warning
84
                continue;
85
            }
86
87
            // Run through all (serialized) relations
88 18
            foreach ($relations as $serializedRelation) {
89 18
                $this->addRelationInstance(RelationFactory::createFromString(
90
                    $relationType,
91
                    $serializedRelation,
92 18
                    $this->object->getRepositoryPath()->getRepository()
93
                ));
94
            }
95
        }
96 19
    }
97
98
    /**
99
     * Add a relation
100
     *
101
     * @param RelationInterface $relation Relation
102
     */
103 18
    protected function addRelationInstance(RelationInterface $relation)
104
    {
105
        // Initialize the relation type
106 18
        if (!array_key_exists($relation->getType(), $this->relations)) {
107 18
            $this->relations[$relation->getType()] = [];
108
        }
109
110 18
        $this->relations[$relation->getType()][$relation->getSignature()] = $relation;
111 18
    }
112
113
    /**
114
     * Unserialize and add a relation
115
     *
116
     * @param string $relationType Relation type
117
     * @param string|RelationInterface $relation Serialized or instantiated object relation
118
     * @return Relations Self reference
119
     * @throws InvalidArgumentException If the relation is not a valid relation instance
120
     */
121 1
    public function addRelation($relationType, $relation)
122
    {
123
        // Unserialize and instantiate the relation if it's given in serialized form
124 1
        if (is_string($relation)) {
125 1
            $relation = RelationFactory::createFromString(
126
                $relationType,
127
                $relation,
128 1
                $this->object->getRepositoryPath()->getRepository()
129
            );
130
        }
131
132
        // If the relation is not a valid relation instance
133 1
        if (!($relation instanceof RelationInterface)) {
134
            throw new InvalidArgumentException(
135
                'Invalid object relation',
136
                InvalidArgumentException::INVALID_OBJECT_RELATION
137
            );
138
        }
139
140
        // If a new relation is to be added
141 1
        if (empty($this->relations[$relationType])
142 1
            || !array_key_exists($relation->getSignature(), $this->relations[$relationType])
143
        ) {
144 1
            $relations = clone $this;
145 1
            $relations->addRelationInstance($relation);
146 1
            return $relations;
147
        }
148
149
        // Else: Return this
150
        return $this;
151
    }
152
153
    /**
154
     * Get all relations (optional: Of a particular type)
155
     *
156
     * @param string|null $relationType Optional: Relation type
157
     * @return array Object relations
158
     */
159
    public function getRelations($relationType = null) {
160
161
        // Return all relations in case no particular type was requested
162
        if ($relationType === null) {
163
            return $this->relations;
164
        }
165
166
        // Validate the relation type
167
        RelationFactory::validateRelationType($relationType);
168
169
        return empty($this->relations[$relationType]) ? [] : $this->relations[$relationType];
170
    }
171
172
    /**
173
     * Return the property values as array
174
     *
175
     * @return array Property values
176
     */
177 5
    public function toArray()
178
    {
179 5
        $relations = array_filter(
180
            array_map(
181 5
                function(array $relationTypeCollection) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
182 4
                    if (!count($relationTypeCollection)) {
183
                        return false;
184
                    }
185 4
                    return array_values(array_map('strval', $relationTypeCollection));
186 5
                },
187 5
                $this->relations
188
            )
189
        );
190 5
        ksort($relations);
191 5
        return $relations;
192
    }
193
}
194