Completed
Push — master ( 09eb3c...091311 )
by Jan
03:00
created

StructuralDBElement::getChildren()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * Part-DB Version 0.4+ "nextgen"
6
 * Copyright (C) 2016 - 2019 Jan Böhmer
7
 * https://github.com/jbtronics.
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
22
 */
23
24
namespace App\Entity;
25
26
use Doctrine\ORM\Mapping as ORM;
27
use Doctrine\ORM\PersistentCollection;
28
use App\Validator\Constraints\NoneOfItsChildren;
29
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
30
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
31
use Symfony\Component\Serializer\Annotation\Groups;
32
33
/**
34
 * All elements with the fields "id", "name" and "parent_id" (at least).
35
 *
36
 * This class is for managing all database objects with a structural design.
37
 * All these sub-objects must have the table columns 'id', 'name' and 'parent_id' (at least)!
38
 * The root node has always the ID '0'.
39
 * It's allowed to have instances of root elements, but if you try to change
40
 * an attribute of a root element, you will get an exception!
41
 *
42
 * @ORM\MappedSuperclass(repositoryClass="App\Repository\StructuralDBElementRepository")
43
 *
44
 * @UniqueEntity(fields={"name", "parent"}, ignoreNull=false, message="structural.entity.unique_name")
45
 */
46
abstract class StructuralDBElement extends AttachmentContainingDBElement
47
{
48
    public const ID_ROOT_ELEMENT = 0;
49
50
    //This is a not standard character, so build a const, so a dev can easily use it
51
    public const PATH_DELIMITER_ARROW = ' → ';
52
53
    // We can not define the mapping here or we will get an exception. Unfortunatly we have to do the mapping in the
54
    // subclasses
55
    /**
56
     * @var StructuralDBElement[]
57
     * @Groups({"include_children"})
58
     */
59
    protected $children;
60
    /**
61
     * @var StructuralDBElement
62
     * @NoneOfItsChildren()
63
     * @Groups({"include_parents"})
64
     */
65
    protected $parent;
66
67
    /**
68
     * @var string The comment info for this element
69
     * @ORM\Column(type="string", nullable=true)
70
     * @Groups({"simple", "extended", "full"})
71
     */
72
    protected $comment;
73
74
    /**
75
     * @var int
76
     * @ORM\Column(type="integer", nullable=true)
77
     */
78
    protected $parent_id;
79
80
    /**
81
     * @var int
82
     */
83
    protected $level = 0;
84
85
    /** @var string[] all names of all parent elements as a array of strings,
86
     *  the last array element is the name of the element itself
87
     *
88
     */
89
    private $full_path_strings;
90
91
    /******************************************************************************
92
     * StructuralDBElement constructor.
93
     *****************************************************************************/
94
95
    /**
96
     * Check if this element is a child of another element (recursive).
97
     *
98
     * @param StructuralDBElement $another_element the object to compare
99
     *     IMPORTANT: both objects to compare must be from the same class (for example two "Device" objects)!
100
     *
101
     * @return bool True, if this element is child of $another_element.
102
     *
103
     * @throws \InvalidArgumentException if there was an error
104
     */
105
    public function isChildOf(StructuralDBElement $another_element)
106
    {
107
        $class_name = \get_class($this);
108
109
        //Check if both elements compared, are from the same type:
110
        if ($class_name != \get_class($another_element)) {
111
            throw new \InvalidArgumentException('isChildOf() only works for objects of the same type!');
112
        }
113
114
        if (null == $this->getParent()) { // this is the root node
115
            return false;
116
        }
117
118
        //If this' parents element, is $another_element, then we are finished
119
        return ($this->parent->getID() == $another_element->getID())
120
            || $this->parent->isChildOf($another_element); //Otherwise, check recursivley
121
    }
122
123
    /******************************************************************************
124
     *
125
     * Getters
126
     *
127
     ******************************************************************************/
128
129
    /**
130
     * Get the parent-ID
131
     *
132
     * @return integer          * the ID of the parent element
133
     *                          * NULL means, the parent is the root node
134
     *                          * the parent ID of the root node is -1
135
     */
136
    protected function getParentID(): int
137
    {
138
        return $this->parent_id ?? self::ID_ROOT_ELEMENT; //Null means root element
139
    }
140
141
    /**
142
     * Get the parent of this element.
143
     *
144
     * @return StructuralDBElement|null The parent element. Null if this element, does not have a parent.
145
     */
146
    public function getParent(): ?self
147
    {
148
        return $this->parent;
149
    }
150
151
    /**
152
     *  Get the comment of the element.
153
154
     * @return string the comment
155
     */
156
    public function getComment(): ?string
157
    {
158
        return $this->comment;
159
    }
160
161
    /**
162
     * Get the level.
163
     *
164
     * The level of the root node is -1.
165
     *
166
     * @return int the level of this element (zero means a most top element
167
     *             [a subelement of the root node])
168
     *
169
     */
170
    public function getLevel(): int
171
    {
172
        /**
173
         * Only check for nodes that have a parent. In the other cases zero is correct.
174
         */
175
        if (0 === $this->level && $this->parent !== null) {
176
            $element = $this->parent;
177
            while ($element !== null) {
178
                /** @var StructuralDBElement $element */
179
                $element = $element->parent;
180
                ++$this->level;
181
            }
182
        }
183
        return $this->level;
184
    }
185
186
    /**
187
     * Get the full path.
188
     *
189
     * @param string $delimeter the delimeter of the returned string
190
     *
191
     * @return string the full path (incl. the name of this element), delimeted by $delimeter
192
     *
193
     */
194
    public function getFullPath(string $delimeter = self::PATH_DELIMITER_ARROW): string
195
    {
196
        if (!\is_array($this->full_path_strings)) {
0 ignored issues
show
introduced by
The condition is_array($this->full_path_strings) is always true.
Loading history...
197
            $this->full_path_strings = array();
198
            $this->full_path_strings[] = $this->getName();
199
            $element = $this;
200
201
            $overflow = 20; //We only allow 20 levels depth
202
203
            while (null != $element->parent && $overflow >= 0) {
204
                $element = $element->parent;
205
                $this->full_path_strings[] = $element->getName();
206
                //Decrement to prevent mem overflow.
207
                $overflow--;
208
            }
209
210
            $this->full_path_strings = array_reverse($this->full_path_strings);
211
        }
212
213
        return implode($delimeter, $this->full_path_strings);
214
    }
215
216
    /**
217
     * Get all subelements of this element.
218
     *
219
     * @param bool $recursive if true, the search is recursive
220
     *
221
     * @return static[] all subelements as an array of objects (sorted by their full path)
222
     */
223
    public function getSubelements(): PersistentCollection
224
    {
225
        return $this->children;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->children returns the type App\Entity\StructuralDBElement[] which is incompatible with the type-hinted return Doctrine\ORM\PersistentCollection.
Loading history...
226
    }
227
228
    public function getChildren(): PersistentCollection
229
    {
230
        return $this->children;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->children returns the type App\Entity\StructuralDBElement[] which is incompatible with the type-hinted return Doctrine\ORM\PersistentCollection.
Loading history...
231
    }
232
233
    /******************************************************************************
234
     *
235
     * Setters
236
     *
237
     ******************************************************************************/
238
239
    /**
240
     * Sets the new parent object
241
     * @param self $new_parent The new parent object
242
     * @return StructuralDBElement
243
     */
244
    public function setParent(?self $new_parent) : self
245
    {
246
        /*
247
        if ($new_parent->isChildOf($this)) {
248
            throw new \InvalidArgumentException('You can not use one of the element childs as parent!');
249
        } */
250
251
        $this->parent = $new_parent;
252
253
        return $this;
254
    }
255
256
    /**
257
     *  Set the comment.
258
     * @param string $new_comment the new comment
259
     * @return StructuralDBElement
260
     */
261
    public function setComment(?string $new_comment): self
262
    {
263
        $this->comment = $new_comment;
264
265
        return $this;
266
    }
267
}
268