Passed
Push — master ( 465233...3e7150 )
by Jan
03:11
created

StructuralDBElement::setParent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 10
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
30
/**
31
 * All elements with the fields "id", "name" and "parent_id" (at least).
32
 *
33
 * This class is for managing all database objects with a structural design.
34
 * All these sub-objects must have the table columns 'id', 'name' and 'parent_id' (at least)!
35
 * The root node has always the ID '0'.
36
 * It's allowed to have instances of root elements, but if you try to change
37
 * an attribute of a root element, you will get an exception!
38
 *
39
 * @ORM\MappedSuperclass(repositoryClass="App\Repository\StructuralDBElementRepository")
40
 */
41
abstract class StructuralDBElement extends AttachmentContainingDBElement
42
{
43
    public const ID_ROOT_ELEMENT = 0;
44
45
    //This is a not standard character, so build a const, so a dev can easily use it
46
    public const PATH_DELIMITER_ARROW = ' → ';
47
48
    // We can not define the mapping here or we will get an exception. Unfortunatly we have to do the mapping in the
49
    // subclasses
50
    /**
51
     * @var StructuralDBElement[]
52
     */
53
    protected $children;
54
    /**
55
     * @var StructuralDBElement
56
     * @NoneOfItsChildren()
57
     */
58
    protected $parent;
59
60
    /**
61
     * @var string The comment info for this element
62
     * @ORM\Column(type="string", nullable=true)
63
     */
64
    protected $comment;
65
66
    /**
67
     * @var int
68
     * @ORM\Column(type="integer", nullable=true)
69
     */
70
    protected $parent_id;
71
72
    /**
73
     * @var int
74
     */
75
    protected $level = 0;
76
77
    /** @var string[] all names of all parent elements as a array of strings,
78
     *  the last array element is the name of the element itself */
79
    private $full_path_strings;
80
81
    /******************************************************************************
82
     * StructuralDBElement constructor.
83
     *****************************************************************************/
84
85
    /**
86
     * Check if this element is a child of another element (recursive).
87
     *
88
     * @param StructuralDBElement $another_element the object to compare
89
     *     IMPORTANT: both objects to compare must be from the same class (for example two "Device" objects)!
90
     *
91
     * @return bool True, if this element is child of $another_element.
92
     *
93
     * @throws \InvalidArgumentException if there was an error
94
     */
95
    public function isChildOf(StructuralDBElement $another_element)
96
    {
97
        $class_name = \get_class($this);
98
99
        //Check if both elements compared, are from the same type:
100
        if ($class_name != \get_class($another_element)) {
101
            throw new \InvalidArgumentException('isChildOf() only works for objects of the same type!');
102
        }
103
104
        if (null == $this->getParent()) { // this is the root node
105
            return false;
106
        }
107
108
        //If this' parents element, is $another_element, then we are finished
109
        return ($this->parent->getID() == $another_element->getID())
110
            || $this->parent->isChildOf($another_element); //Otherwise, check recursivley
111
    }
112
113
    /******************************************************************************
114
     *
115
     * Getters
116
     *
117
     ******************************************************************************/
118
119
    /**
120
     * Get the parent-ID
121
     *
122
     * @return integer          * the ID of the parent element
123
     *                          * NULL means, the parent is the root node
124
     *                          * the parent ID of the root node is -1
125
     */
126
    protected function getParentID(): int
127
    {
128
        return $this->parent_id ?? self::ID_ROOT_ELEMENT; //Null means root element
129
    }
130
131
    /**
132
     * Get the parent of this element.
133
     *
134
     * @return StructuralDBElement|null The parent element. Null if this element, does not have a parent.
135
     */
136
    public function getParent(): ?self
137
    {
138
        return $this->parent;
139
    }
140
141
    /**
142
     *  Get the comment of the element.
143
144
     * @return string the comment
145
     */
146
    public function getComment(): ?string
147
    {
148
        return $this->comment;
149
    }
150
151
    /**
152
     * Get the level.
153
     *
154
     *     The level of the root node is -1.
155
     *
156
     * @return int the level of this element (zero means a most top element
157
     *             [a subelement of the root node])
158
     */
159
    public function getLevel(): int
160
    {
161
        if (0 === $this->level) {
162
            $element = $this->parent;
163
            $parent_id = $element->getParentID();
164
            while ($parent_id > 0) {
165
                /** @var StructuralDBElement $element */
166
                $element = $element->parent;
167
                $parent_id = $element->getParentID();
168
                ++$this->level;
169
            }
170
        }
171
172
        return $this->level;
173
    }
174
175
    /**
176
     * Get the full path.
177
     *
178
     * @param string $delimeter the delimeter of the returned string
179
     *
180
     * @return string the full path (incl. the name of this element), delimeted by $delimeter
181
     */
182
    public function getFullPath(string $delimeter = self::PATH_DELIMITER_ARROW): string
183
    {
184
        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...
185
            $this->full_path_strings = array();
186
            $this->full_path_strings[] = $this->getName();
187
            $element = $this;
188
189
            $overflow = 20; //We only allow 20 levels depth
190
191
            while (null != $element->parent && $overflow >= 0) {
192
                $element = $element->parent;
193
                $this->full_path_strings[] = $element->getName();
194
                //Decrement to prevent mem overflow.
195
                $overflow--;
196
            }
197
198
            $this->full_path_strings = array_reverse($this->full_path_strings);
199
        }
200
201
        return implode($delimeter, $this->full_path_strings);
202
    }
203
204
    /**
205
     * Get all subelements of this element.
206
     *
207
     * @param bool $recursive if true, the search is recursive
208
     *
209
     * @return static[] all subelements as an array of objects (sorted by their full path)
210
     */
211
    public function getSubelements(): PersistentCollection
212
    {
213
        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...
214
    }
215
216
    /******************************************************************************
217
     *
218
     * Setters
219
     *
220
     ******************************************************************************/
221
222
    /**
223
     * Sets the new parent object
224
     * @param self $new_parent The new parent object
225
     * @return StructuralDBElement
226
     */
227
    public function setParent(?self $new_parent) : self
228
    {
229
        /*
230
        if ($new_parent->isChildOf($this)) {
231
            throw new \InvalidArgumentException('You can not use one of the element childs as parent!');
232
        } */
233
234
        $this->parent = $new_parent;
235
236
        return $this;
237
    }
238
239
    /**
240
     *  Set the comment.
241
     * @param string $new_comment the new comment
242
     * @return StructuralDBElement
243
     */
244
    public function setComment(?string $new_comment): self
245
    {
246
        $this->comment = $new_comment;
247
248
        return $this;
249
    }
250
}
251