Passed
Push — master ( da72f5...6369ee )
by Jan
04:43
created

AbstractStructuralDBElement   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 293
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 293
rs 10
c 0
b 0
f 0
wmc 30

16 Methods

Rating   Name   Duplication   Size   Complexity  
A clearChildren() 0 5 1
A getSubelements() 0 3 1
A isNotSelectable() 0 3 1
A setParent() 0 10 1
A getComment() 0 3 1
A getPathArray() 0 11 3
A isChildOf() 0 17 5
A getFullPath() 0 20 4
A __construct() 0 4 1
A getParent() 0 3 1
A setComment() 0 5 1
A getChildren() 0 3 1
A isRoot() 0 3 1
A getLevel() 0 15 4
A setChildren() 0 9 3
A setNotSelectable() 0 5 1
1
<?php
2
/**
3
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4
 *
5
 * Copyright (C) 2019 Jan Böhmer (https://github.com/jbtronics)
6
 *
7
 * This program is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU General Public License
9
 * as published by the Free Software Foundation; either version 2
10
 * of the License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
20
 */
21
22
declare(strict_types=1);
23
24
namespace App\Entity\Base;
25
26
use App\Entity\Attachments\AttachmentContainingDBElement;
27
use App\Validator\Constraints\NoneOfItsChildren;
28
use function count;
29
use Doctrine\Common\Collections\ArrayCollection;
30
use Doctrine\Common\Collections\Collection;
31
use Doctrine\ORM\Mapping as ORM;
32
use function get_class;
33
use InvalidArgumentException;
34
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
35
use Symfony\Component\Serializer\Annotation\Groups;
36
37
/**
38
 * All elements with the fields "id", "name" and "parent_id" (at least).
39
 *
40
 * This class is for managing all database objects with a structural design.
41
 * All these sub-objects must have the table columns 'id', 'name' and 'parent_id' (at least)!
42
 * The root node has always the ID '0'.
43
 * It's allowed to have instances of root elements, but if you try to change
44
 * an attribute of a root element, you will get an exception!
45
 *
46
 * @ORM\MappedSuperclass(repositoryClass="App\Repository\StructuralDBElementRepository")
47
 *
48
 * @ORM\EntityListeners({"App\Security\EntityListeners\ElementPermissionListener", "App\EntityListeners\TreeCacheInvalidationListener"})
49
 *
50
 * @UniqueEntity(fields={"name", "parent"}, ignoreNull=false, message="structural.entity.unique_name")
51
 */
52
abstract class AbstractStructuralDBElement extends AttachmentContainingDBElement
53
{
54
    public const ID_ROOT_ELEMENT = 0;
55
56
    /**
57
     * This is a not standard character, so build a const, so a dev can easily use it.
58
     */
59
    public const PATH_DELIMITER_ARROW = ' → ';
60
61
    /**
62
     * @var string The comment info for this element
63
     * @ORM\Column(type="text")
64
     * @Groups({"simple", "extended", "full"})
65
     */
66
    protected $comment = '';
67
68
    /**
69
     * @var bool If this property is set, this element can not be selected for part properties.
70
     *           Useful if this element should be used only for grouping, sorting.
71
     * @ORM\Column(type="boolean")
72
     */
73
    protected $not_selectable = false;
74
75
    /**
76
     * @var int
77
     */
78
    protected $level = 0;
79
80
    /**
81
     * We can not define the mapping here or we will get an exception. Unfortunately we have to do the mapping in the
82
     * subclasses.
83
     *
84
     * @var AbstractStructuralDBElement[]|Collection
85
     * @Groups({"include_children"})
86
     */
87
    protected $children;
88
89
    /**
90
     * @var AbstractStructuralDBElement
91
     * @NoneOfItsChildren()
92
     * @Groups({"include_parents"})
93
     */
94
    protected $parent;
95
96
    /** @var string[] all names of all parent elements as a array of strings,
97
     *  the last array element is the name of the element itself
98
     */
99
    private $full_path_strings = [];
100
101
    public function __construct()
102
    {
103
        parent::__construct();
104
        $this->children = new ArrayCollection();
105
    }
106
107
    /******************************************************************************
108
     * StructuralDBElement constructor.
109
     *****************************************************************************/
110
111
    /**
112
     * Check if this element is a child of another element (recursive).
113
     *
114
     * @param AbstractStructuralDBElement $another_element the object to compare
115
     *                                             IMPORTANT: both objects to compare must be from the same class (for example two "Device" objects)!
116
     *
117
     * @return bool True, if this element is child of $another_element.
118
     *
119
     * @throws InvalidArgumentException if there was an error
120
     */
121
    public function isChildOf(self $another_element): bool
122
    {
123
        $class_name = static::class;
124
125
        //Check if both elements compared, are from the same type
126
        // (we have to check inheritance, or we get exceptions when using doctrine entities (they have a proxy type):
127
        if (! is_a($another_element, $class_name) && ! is_a($this, get_class($another_element))) {
128
            throw new InvalidArgumentException('isChildOf() only works for objects of the same type!');
129
        }
130
131
        if (null === $this->getParent()) { // this is the root node
132
            return false;
133
        }
134
135
        //If this' parents element, is $another_element, then we are finished
136
        return ($this->parent->getID() === $another_element->getID())
137
            || $this->parent->isChildOf($another_element); //Otherwise, check recursively
138
    }
139
140
    /**
141
     * Checks if this element is an root element (has no parent).
142
     *
143
     * @return bool True if the this element is an root element.
144
     */
145
    public function isRoot(): bool
146
    {
147
        return null === $this->parent;
148
    }
149
150
    /******************************************************************************
151
     *
152
     * Getters
153
     *
154
     ******************************************************************************/
155
156
    /**
157
     * Get the parent of this element.
158
     *
159
     * @return AbstractStructuralDBElement|null The parent element. Null if this element, does not have a parent.
160
     */
161
    public function getParent(): ?self
162
    {
163
        return $this->parent;
164
    }
165
166
    /**
167
     *  Get the comment of the element.
168
169
     *
170
     * @return string the comment
171
     */
172
    public function getComment(): ?string
173
    {
174
        return $this->comment;
175
    }
176
177
    /**
178
     * Get the level.
179
     *
180
     * The level of the root node is -1.
181
     *
182
     * @return int the level of this element (zero means a most top element
183
     *             [a sub element of the root node])
184
     */
185
    public function getLevel(): int
186
    {
187
        /*
188
         * Only check for nodes that have a parent. In the other cases zero is correct.
189
         */
190
        if (0 === $this->level && null !== $this->parent) {
191
            $element = $this->parent;
192
            while (null !== $element) {
193
                /** @var AbstractStructuralDBElement $element */
194
                $element = $element->parent;
195
                ++$this->level;
196
            }
197
        }
198
199
        return $this->level;
200
    }
201
202
    /**
203
     * Get the full path.
204
     *
205
     * @param string $delimiter the delimiter of the returned string
206
     *
207
     * @return string the full path (incl. the name of this element), delimited by $delimiter
208
     */
209
    public function getFullPath(string $delimiter = self::PATH_DELIMITER_ARROW): string
210
    {
211
        if (empty($this->full_path_strings)) {
212
            $this->full_path_strings = [];
213
            $this->full_path_strings[] = $this->getName();
214
            $element = $this;
215
216
            $overflow = 20; //We only allow 20 levels depth
217
218
            while (null !== $element->parent && $overflow >= 0) {
219
                $element = $element->parent;
220
                $this->full_path_strings[] = $element->getName();
221
                //Decrement to prevent mem overflow.
222
                --$overflow;
223
            }
224
225
            $this->full_path_strings = array_reverse($this->full_path_strings);
226
        }
227
228
        return implode($delimiter, $this->full_path_strings);
229
    }
230
231
    /**
232
     * Gets the path to this element (including the element itself).
233
     *
234
     * @return self[] An array with all (recursively) parent elements (including this one),
235
     *                ordered from the lowest levels (root node) first to the highest level (the element itself)
236
     */
237
    public function getPathArray(): array
238
    {
239
        $tmp = [];
240
        $tmp[] = $this;
241
242
        //We only allow 20 levels depth
243
        while (! end($tmp)->isRoot() && count($tmp) < 20) {
244
            $tmp[] = end($tmp)->parent;
245
        }
246
247
        return array_reverse($tmp);
248
    }
249
250
    /**
251
     * Get all sub elements of this element.
252
     *
253
     * @return Collection<static>|iterable all subelements as an array of objects (sorted by their full path)
254
     */
255
    public function getSubelements(): iterable
256
    {
257
        return $this->children;
258
    }
259
260
    /**
261
     * @return Collection<static>|iterable
262
     */
263
    public function getChildren(): iterable
264
    {
265
        return $this->children;
266
    }
267
268
    /**
269
     * @return bool
270
     */
271
    public function isNotSelectable(): bool
272
    {
273
        return $this->not_selectable;
274
    }
275
276
    /******************************************************************************
277
     *
278
     * Setters
279
     *
280
     ******************************************************************************/
281
282
    /**
283
     * Sets the new parent object.
284
     *
285
     * @param self $new_parent The new parent object
286
     *
287
     * @return AbstractStructuralDBElement
288
     */
289
    public function setParent(?self $new_parent): self
290
    {
291
        /*
292
        if ($new_parent->isChildOf($this)) {
293
            throw new \InvalidArgumentException('You can not use one of the element childs as parent!');
294
        } */
295
296
        $this->parent = $new_parent;
297
298
        return $this;
299
    }
300
301
    /**
302
     *  Set the comment.
303
     *
304
     * @param string $new_comment the new comment
305
     *
306
     * @return AbstractStructuralDBElement
307
     */
308
    public function setComment(?string $new_comment): self
309
    {
310
        $this->comment = $new_comment;
311
312
        return $this;
313
    }
314
315
    /**
316
     * @param  static[]|Collection  $elements
317
     * @return $this
318
     */
319
    public function setChildren($elements): self
320
    {
321
        if (!is_array($elements) && !$elements instanceof Collection) {
0 ignored issues
show
introduced by
$elements is always a sub-type of Doctrine\Common\Collections\Collection.
Loading history...
322
           throw new InvalidArgumentException('$elements must be an array or Collection!');
323
        }
324
325
        $this->children = $elements;
326
327
        return $this;
328
    }
329
330
    /**
331
     * @return AbstractStructuralDBElement
332
     */
333
    public function setNotSelectable(bool $not_selectable): self
334
    {
335
        $this->not_selectable = $not_selectable;
336
337
        return $this;
338
    }
339
340
    public function clearChildren(): self
341
    {
342
        $this->children = new ArrayCollection();
343
344
        return $this;
345
    }
346
}
347