Completed
Push — master ( 3bf76e...9f9c26 )
by Joschi
04:22
created

Relations   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 224
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 98.9%

Importance

Changes 11
Bugs 0 Features 2
Metric Value
c 11
b 0
f 2
dl 0
loc 224
ccs 90
cts 91
cp 0.989
rs 9.8
wmc 31
lcom 1
cbo 6

8 Methods

Rating   Name   Duplication   Size   Complexity  
A addRelationInstance() 0 4 1
B __construct() 0 26 5
A addRelation() 0 13 2
B getRelationInstance() 0 25 3
A deleteRelation() 0 12 2
C findRelations() 0 44 13
A toArray() 0 15 3
A getRelations() 0 11 2
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 8
    public function __construct(array $data, ObjectInterface $object)
72
    {
73 8
        parent::__construct($data, $object);
74
75
        // Run through all registered relation type collections
76
        /**
77
         * @var string $relationType
78
         * @var RelationInterface[] $relations
79
         */
80 8
        foreach ($this->data as $relationType => $relations) {
81
            // If the relation type collection is invalid or empty
82 8
            if (!is_array($relations) || !count($relations)) {
83
                // TODO Trigger warning
84 2
                continue;
85
            }
86
87
            // Run through all (serialized) relations
88 6
            foreach ($relations as $serializedRelation) {
89 6
                $this->addRelationInstance(RelationFactory::createFromString(
90 6
                    $relationType,
91 6
                    $serializedRelation,
92 6
                    $this->object->getRepositoryPath()->getRepository()
93 6
                ));
94 6
            }
95 8
        }
96 8
    }
97
98
    /**
99
     * Add a relation
100
     *
101
     * @param RelationInterface $relation Relation
102
     */
103 10
    protected function addRelationInstance(RelationInterface $relation)
104
    {
105 10
        $this->relations[$relation->getSignature()] = $relation;
106 10
    }
107
108
    /**
109
     * Unserialize and add a relation
110
     *
111
     * @param string|RelationInterface $relation Serialized or instantiated object relation
112
     * @param string|null $relationType Relation type
113
     * @return Relations Self reference
114
     * @throws InvalidArgumentException If the relation is not a valid relation instance
115
     */
116 4
    public function addRelation($relation, $relationType = null)
117
    {
118
        // If a new relation is to be added
119 4
        $relation = $this->getRelationInstance($relation, $relationType);
120 4
        if (!array_key_exists($relation->getSignature(), $this->relations)) {
121 4
            $relations = clone $this;
122 4
            $relations->addRelationInstance($relation);
123 4
            return $relations;
124
        }
125
126
        // Else: Return this
127 1
        return $this;
128
    }
129
130
    /**
131
     * Instantiate a relation
132
     *
133
     * @param string|RelationInterface $relation Serialized or instantiated object relation
134
     * @param string|null $relationType Relation type
135
     * @return RelationInterface Relation instance
136
     * @throws InvalidArgumentException If the relation is not a valid relation instance
137
     */
138 4
    protected function getRelationInstance($relation, $relationType = null)
139
    {
140
        // Unserialize and instantiate the relation if it's given in serialized form
141 4
        if (is_string($relation)) {
142
            // Validate the relation type
143 4
            RelationFactory::validateRelationType($relationType);
144
145
            // Create the relation instance
146 4
            $relation = RelationFactory::createFromString(
147 4
                $relationType,
148 4
                $relation,
149 4
                $this->object->getRepositoryPath()->getRepository()
150 4
            );
151 4
        }
152
153
        // If the relation is not a valid relation instance
154 4
        if (!($relation instanceof RelationInterface)) {
155 1
            throw new InvalidArgumentException(
156 1
                'Invalid object relation',
157
                InvalidArgumentException::INVALID_OBJECT_RELATION
158 1
            );
159
        }
160
161 4
        return $relation;
162
    }
163
164
    /**
165
     * Delete an object relation
166
     *
167
     * @param RelationInterface $relation Object relation
168
     * @return Relations Self reference
169
     */
170 1
    public function deleteRelation(RelationInterface $relation)
171
    {
172
        // If a new relation is to be added
173 1
        if (array_key_exists($relation->getSignature(), $this->relations)) {
174 1
            $relations = clone $this;
175 1
            unset($relations->relations[$relation->getSignature()]);
176 1
            return $relations;
177
        }
178
179
        // Else: Return this
180 1
        return $this;
181
    }
182
183
    /**
184
     * Get all relations (optional: Of a particular type)
185
     *
186
     * @param string|null $relationType Optional: Relation type
187
     * @return RelationInterface[] Relations
188
     */
189 1
    public function getRelations($relationType = null)
190
    {
191
192
        // Return all relations in case no particular type was requested
193 1
        if ($relationType === null) {
194
            return array_values($this->relations);
195
        }
196
197
        // Return all relations matching the requested type
198 1
        return $this->findRelations([RelationInterface::FILTER_TYPE => $relationType]);
199
    }
200
201
    /**
202
     * Find and return particular relations
203
     *
204
     * @param array $criteria Relation criteria
205
     * @return RelationInterface[] Relations
206
     */
207 5
    public function findRelations(array $criteria)
208
    {
209
        // Validate the relation type (if given as a criteria)
210 4
        if (array_key_exists(RelationInterface::FILTER_TYPE, $criteria)) {
211 3
            RelationFactory::validateRelationType($criteria[RelationInterface::FILTER_TYPE]);
212 3
        }
213
214
        // Find and return the relations matching the criteria
215 5
        return array_values(array_filter($this->relations, function (RelationInterface $relation) use ($criteria) {
216 4
            foreach ($criteria as $property => $value) {
217
                switch ($property) {
218 4
                    case RelationInterface::FILTER_TYPE:
219 3
                        if ($relation->getType() != $value) {
220 5
                            return false;
221
                        }
222 3
                        break;
223 2
                    case RelationInterface::FILTER_URL:
224
//                        print_r($relation->getUrl());
225 2
                        if (strpos($relation->getUrl(), $value) === false) {
226 2
                            return false;
227
                        }
228 2
                        break;
229 1
                    case RelationInterface::FILTER_LABEL:
230 1
                        if (strpos($relation->getLabel(), $value) === false) {
231 1
                            return false;
232
                        }
233 1
                        break;
234 1
                    case RelationInterface::FILTER_EMAIL:
235 1
                        if (strpos($relation->getEmail(), $value) === false) {
236 1
                            return false;
237
                        }
238 1
                        break;
239 1
                    case RelationInterface::FILTER_COUPLING:
240 1
                        if ($relation->getCoupling() !== intval(!!$value)) {
241 1
                            return false;
242
                        }
243 1
                        break;
244 1
                    default:
245 1
                        return false;
246 1
                }
247 4
            }
248 4
            return true;
249 4
        }));
250
    }
251
252
    /**
253
     * Return the property values as array
254
     *
255
     * @return array Property values
256
     */
257 5
    public function toArray()
258
    {
259 5
        $relations = [];
260
        /** @var RelationInterface $relation */
261 5
        foreach ($this->relations as $relation) {
262 5
            $relationType = $relation->getType();
263 5
            if (!array_key_exists($relationType, $relations)) {
264 5
                $relations[$relationType] = [strval($relation)];
265 5
                continue;
266
            }
267 5
            $relations[$relationType][] = strval($relation);
268 5
        }
269 5
        ksort($relations);
270 5
        return $relations;
271
    }
272
}
273