Modify::move()   D
last analyzed

Complexity

Conditions 9
Paths 11

Size

Total Lines 31
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 4.909
c 0
b 0
f 0
cc 9
eloc 10
nc 11
nop 1
1
<?php
2
3
/**
4
 * @package Cadmium\System\Modules\Entitizer
5
 * @author Anton Romanov
6
 * @copyright Copyright (c) 2015-2017, Anton Romanov
7
 * @link http://cadmium-cms.com
8
 */
9
10
namespace Modules\Entitizer\Utils\Entity {
11
12
	use Modules\Entitizer, DB;
13
14
	trait Modify {
15
16
		protected $definition = null, $dataset = null;
17
18
		/**
19
		 * Initialize the subtree connection
20
		 *
21
		 * @return bool : true on success or false on failure
22
		 */
23
24
		private function initSubtree() : bool {
25
26
			$data = ['ancestor' => $this->id, 'descendant' => $this->id, 'depth' => 0];
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
27
28
			DB::insert(static::$table_relations, $data, false, true);
29
30
			# ------------------------
31
32
			return (DB::getLast() && DB::getLast()->status);
33
		}
34
35
		/**
36
		 * Disconnect the subtree from the current position
37
		 *
38
		 * @return bool : true on success or false on failure
39
		 */
40
41 View Code Duplication
		private function disconnectSubtree() : bool {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
42
43
			$query = ("DELETE rla FROM " . static::$table_relations . " rla ") .
44
45
			         ("JOIN "  . static::$table_relations . " rlb ON rlb.descendant = rla.descendant ") .
46
47
			         ("LEFT JOIN " . static::$table_relations . " rlx ") .
48
49
			         ("ON rlx.ancestor = rlb.ancestor AND rlx.descendant = rla.ancestor ") .
50
51
			         ("WHERE rlb.ancestor = " . $this->id . " AND rlx.ancestor IS NULL");
52
53
			if (!(DB::send($query) && DB::getLast()->status)) return false;
54
55
			# Set path
56
57
			$this->dataset->update(['parent_id' => 0]);
58
59
			# ------------------------
60
61
			return true;
62
		}
63
64
		/**
65
		 * Connect the subtree under the new position
66
		 *
67
		 * @return bool : true on success or false on failure
68
		 */
69
70 View Code Duplication
		private function connectSubtree(int $parent_id) : bool {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
71
72
			$query = ("INSERT INTO " . static::$table_relations . " (ancestor, descendant, depth) ") .
73
74
			         ("SELECT sup.ancestor, sub.descendant, sup.depth + sub.depth + 1 ") .
75
76
			         ("FROM " . static::$table_relations . " sup ") .
77
78
			         ("JOIN " . static::$table_relations . " sub ") .
79
80
			         ("WHERE sub.ancestor = " . $this->id . " AND sup.descendant = " . $parent_id);
81
82
			if (!(DB::send($query) && (DB::getLast()->rows > 0))) return false;
83
84
			# Set path
85
86
			$this->dataset->update(['parent_id' => $parent_id]);
87
88
			# ------------------------
89
90
			return true;
91
		}
92
93
		/**
94
		 * Create the entity entry in DB
95
		 *
96
		 * @return bool : true on success or false on failure
97
		 */
98
99
		public function create(array $data) : bool {
100
101
			if (0 !== $this->id) return false;
102
103
			$data = $this->dataset->cast($data);
104
105
			if (static::$auto_increment && isset($data['id'])) $data['id'] = 0;
106
107
			# Insert entity
108
109
			DB::insert(static::$table, $data);
110
111
			if (!(DB::getLast() && DB::getLast()->status)) return false;
112
113
			# Update data
114
115
			if (static::$auto_increment) $data['id'] = DB::getLast()->id;
116
117
			$this->dataset->update($data);
118
119
			# Init subtreee
120
121
			if (static::$nesting) $this->initSubtree();
122
123
			# Cache entity
124
125
			self::$cache[static::$table][$this->id] = $this;
126
127
			# ------------------------
128
129
			return true;
130
		}
131
132
		/**
133
		 * Edit the entity entry in DB
134
		 *
135
		 * @return bool : true on success or false on failure
136
		 */
137
138
		public function edit(array $data) : bool {
139
140
			if (0 === $this->id) return false;
141
142
			$data = $this->dataset->cast($data);
143
144
			if (isset($data['id'])) unset($data['id']);
145
146
			# Update entity
147
148
			DB::update(static::$table, $data, ['id' => $this->id]);
149
150
			if (!(DB::getLast() && DB::getLast()->status)) return false;
151
152
			# Update data
153
154
			$this->dataset->update($data);
155
156
			# Init subtreee
157
158
			if (static::$nesting) $this->initSubtree();
159
160
			# ------------------------
161
162
			return true;
163
		}
164
165
		/**
166
		 * Move the entity to a new parent
167
		 *
168
		 * @return bool : true on success or false on failure
169
		 */
170
171
		public function move(int $parent_id) : bool {
172
173
			if (0 === $this->id) return false;
174
175
			# Re-connect entity if not in tree
176
177
			if (!$this->initSubtree()) return false;
178
179
			# Get parent entity
180
181
			if (0 !== ($parent = Entitizer::get(static::$table, $parent_id))->id) {
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Modules\Entitizer\Utils\Entity>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
182
183
				if (false === ($path = $parent->getPath())) return false;
184
185
				if (false === ($depth = $this->getSubtreeDepth())) return false;
0 ignored issues
show
Bug introduced by
It seems like getSubtreeDepth() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
186
187
				if ((count($path) + $depth + 1) > CONFIG_ENTITIZER_MAX_DEPTH) return false;
188
			}
189
190
			# Disconnect subtree from current position
191
192
			if (!$this->disconnectSubtree()) return false;
193
194
			# Connect subtree under new position
195
196
		 	if (0 !== $parent->id) $this->connectSubtree($parent->id);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Modules\Entitizer\Utils\Entity>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
197
198
			# ------------------------
199
200
			return true;
201
		}
202
203
		/**
204
		 * Remove the entity entry from DB
205
		 *
206
		 * @return bool : true on success or false on failure
207
		 */
208
209
		public function remove() : bool {
210
211
			if (0 === $this->id) return false;
212
213
			# Check if entity is removable
214
215
			if (static::$super && ($this->id === 1)) return false;
216
217
			if (static::$nesting && (0 !== $this->getSubtreeCount())) return false;
0 ignored issues
show
Bug introduced by
It seems like getSubtreeCount() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
218
219
			# Remove entity
220
221
			DB::delete(static::$table, ['id' => $this->id]);
222
223
			if (!(DB::getLast() && DB::getLast()->status)) return false;
224
225
			# Uncache entity
226
227
			unset(self::$cache[static::$table][$this->id]);
228
229
			# Reset data
230
231
			$this->dataset->reset();
232
233
			# ------------------------
234
235
			return true;
236
		}
237
	}
238
}
239