Passed
Push — master ( aa9dcd...aacb55 )
by Andreas
16:50
created

get_sibling_qb()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0061

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 7
nop 2
dl 0
loc 26
ccs 15
cts 16
cp 0.9375
crap 5.0061
rs 9.4222
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom.helper.reflector
4
 * @author CONTENT CONTROL http://www.contentcontrol-berlin.de/
5
 * @copyright CONTENT CONTROL http://www.contentcontrol-berlin.de/
6
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License
7
 */
8
9
/**
10
 * Helper class for object name handling
11
 *
12
 * @package midcom.helper.reflector
13
 */
14
class midcom_helper_reflector_nameresolver
15
{
16
    /**
17
     * The object we're working with
18
     *
19
     * @var midcom_core_dbaobject
20
     */
21
    private $_object;
22
23 140
    public function __construct($object)
24
    {
25 140
        $this->_object = $object;
26 140
    }
27
28
    /**
29
     * Resolves the "name" of given object
30
     *
31
     * @param string $name_property property to use as "name", if left to default (null), will be reflected
32
     * @return string value of name property or null on failure
33
     */
34 140
    public function get_object_name(string $name_property = null) : ?string
35
    {
36 140
        if ($name_property === null) {
37 140
            $name_property = midcom_helper_reflector::get_name_property($this->_object);
38
        }
39 140
        if (    empty($name_property)
40 140
            || !midcom_helper_reflector::get($this->_object)->property_exists($name_property)) {
41
            // Could not resolve valid property
42 1
            return null;
43
        }
44 140
        return $this->_object->{$name_property};
45
    }
46
47
    /**
48
     * Checks for "clean" URL name
49
     *
50
     * @see http://trac.midgard-project.org/ticket/809
51
     * @param string $name_property property to use as "name", if left to default (null), will be reflected
52
     */
53 1
    public function name_is_clean(string $name_property = null) : bool
54
    {
55 1
        if ($name_copy = $this->get_object_name($name_property)) {
56 1
            return $name_copy === midcom_helper_misc::urlize($name_copy);
57
        }
58
        // empty name is not "clean"
59
        return false;
60
    }
61
62
    /**
63
     * Checks for URL-safe name
64
     *
65
     * @see http://trac.midgard-project.org/ticket/809
66
     * @param string $name_property property to use as "name", if left to default (null), will be reflected
67
     */
68 90
    public function name_is_safe(string $name_property = null) : bool
69
    {
70 90
        if ($name_copy = $this->get_object_name($name_property)) {
71 90
            return $name_copy === rawurlencode($name_copy);
72
        }
73
        // empty name is not url-safe
74
        return false;
75
    }
76
77
    /**
78
     * Check that none of given object's siblings have same name.
79
     */
80 89
    public function name_is_unique() : bool
81
    {
82
        // Get current name and sanity-check
83 89
        $name = $this->get_object_name();
84 89
        if (empty($name)) {
85
            // We do not check for empty names, and do not consider them to be unique
86 4
            return false;
87
        }
88
89
        // Start the magic
90 89
        midcom::get()->auth->request_sudo('midcom.helper.reflector');
91 89
        $parent = midcom_helper_reflector_tree::get_parent($this->_object);
0 ignored issues
show
Bug introduced by
$this->_object of type midcom_core_dbaobject is incompatible with the type midgard\portable\api\mgdobject expected by parameter $object of midcom_helper_reflector_tree::get_parent(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

91
        $parent = midcom_helper_reflector_tree::get_parent(/** @scrutinizer ignore-type */ $this->_object);
Loading history...
92 89
        if (!empty($parent->guid)) {
93
            // We have parent, check siblings
94 84
            $parent_resolver = new midcom_helper_reflector_tree($parent);
95 84
            $sibling_classes = $parent_resolver->get_child_classes();
96 84
            if (!in_array('midgard_attachment', $sibling_classes)) {
97 84
                $sibling_classes[] = 'midgard_attachment';
98
            }
99
100 84
            $stat = $this->check_sibling_classes($name, $sibling_classes, $parent);
101
        } else {
102
            // No parent, we might be a root level class
103 10
            $is_root_class = false;
104 10
            $root_classes = midcom_helper_reflector_tree::get_root_classes();
105 10
            foreach ($root_classes as $classname) {
106 10
                if (midcom::get()->dbfactory->is_a($this->_object, $classname)) {
107 6
                    $is_root_class = true;
108 6
                    break;
109
                }
110
            }
111 10
            if (!$is_root_class) {
112
                // This should not happen, logging error and returning true (even though it's potentially dangerous)
113 4
                debug_add("Object " . get_class($this->_object) . " #" . $this->_object->id . " has no valid parent but is not listed in the root classes, don't know what to do, returning true and supposing user knows what he is doing", MIDCOM_LOG_ERROR);
114 4
                $stat = true;
115
            } else {
116 6
                $stat = $this->check_sibling_classes($name, $root_classes);
117
            }
118
        }
119
120 89
        midcom::get()->auth->drop_sudo();
121 89
        return $stat;
122
    }
123
124 86
    private function check_sibling_classes(string $name, array $schema_types, $parent = null) : bool
125
    {
126 86
        foreach ($schema_types as $schema_type) {
127 86
            $qb = $this->get_sibling_qb($schema_type, $parent);
128 86
            if (!$qb) {
129 86
                continue;
130
            }
131 86
            $child_name_property = midcom_helper_reflector::get_name_property(new $schema_type);
132
133 86
            $qb->add_constraint($child_name_property, '=', $name);
134 86
            if ($qb->count()) {
135 1
                debug_add("Name clash in sibling class {$schema_type} for " . get_class($this->_object) . " #{$this->_object->id} (path '" . midcom_helper_reflector_tree::resolve_path($this->_object, '/') . "')" );
0 ignored issues
show
Bug introduced by
$this->_object of type midcom_core_dbaobject is incompatible with the type midgard\portable\api\mgdobject expected by parameter $object of midcom_helper_reflector_tree::resolve_path(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
                debug_add("Name clash in sibling class {$schema_type} for " . get_class($this->_object) . " #{$this->_object->id} (path '" . midcom_helper_reflector_tree::resolve_path(/** @scrutinizer ignore-type */ $this->_object, '/') . "')" );
Loading history...
136 1
                return false;
137
            }
138
        }
139 86
        return true;
140
    }
141
142
    /**
143
     * Generates an unique name for the given object.
144
     *
145
     * 1st IF name is empty, we generate one from title (if title is empty too, we return false)
146
     * Then we check if it's unique, if not we add an incrementing
147
     * number to it (before this we make some educated guesses about a
148
     * good starting value)
149
     *
150
     * @param string $title_property Property of the object to use at title, if null will be reflected (see midcom_helper_reflector::get_object_title())
151
     * @param string $extension The file extension, when working with attachments
152
     * @return string string usable as name or boolean false on critical failures
153
     */
154 69
    public function generate_unique_name($title_property = null, $extension = '')
155
    {
156
        // Get current name and sanity-check
157 69
        $original_name = $this->get_object_name();
158 69
        if ($original_name === null) {
159
            // Fatal error with name resolution
160
            debug_add("Object " . get_class($this->_object) . " #{$this->_object->id} returned critical failure for name resolution, aborting", MIDCOM_LOG_WARN);
161
            return false;
162
        }
163
164
        // We need the name of the "name" property later
165 69
        $name_prop = midcom_helper_reflector::get_name_property($this->_object);
166
167 69
        if (!empty($original_name)) {
168
            $current_name = $original_name;
169
        } else {
170
            // Empty name, try to generate from title
171 69
            $title_copy = midcom_helper_reflector::get_object_title($this->_object, $title_property);
172 69
            if ($title_copy === false) {
0 ignored issues
show
introduced by
The condition $title_copy === false is always false.
Loading history...
173
                // Fatal error with title resolution
174
                debug_add("Object " . get_class($this->_object) . " #{$this->_object->id} returned critical failure for title resolution when name was empty, aborting", MIDCOM_LOG_WARN);
175
                return false;
176
            }
177 69
            if (empty($title_copy)) {
178 65
                debug_add("Object " . get_class($this->_object) . " #{$this->_object->id} has empty name and title, aborting", MIDCOM_LOG_WARN);
179 65
                return false;
180
            }
181 8
            $current_name = midcom_helper_misc::urlize($title_copy);
182 8
            unset($title_copy);
183
        }
184
185
        // incrementer, the number to add as suffix and the base name. see _generate_unique_name_resolve_i()
186 8
        list($i, $base_name) = $this->_generate_unique_name_resolve_i($current_name, $extension);
187
188 8
        $this->_object->name = $base_name;
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
189
        // decrementer, do not try more than this many times (the incrementer can raise above this if we start high enough.
190 8
        $d = 100;
191
192
        // The loop, usually we *should* hit gold in first try
193
        do {
194 8
            if ($i > 1) {
195
                // Start suffixes from -002
196 4
                $this->_object->{$name_prop} = $base_name . sprintf('-%03d', $i) . $extension;
197
            }
198
199
            // Handle the decrementer
200 8
            --$d;
201 8
            if ($d < 1) {
202
                // Decrementer underflowed
203
                debug_add("Maximum number of tries exceeded, current name was: " . $this->_object->{$name_prop}, MIDCOM_LOG_ERROR);
204
                $this->_object->{$name_prop} = $original_name;
205
                return false;
206
            }
207
            // and the incrementer
208 8
            ++$i;
209 8
        } while (!$this->name_is_unique());
210
211
        // Get a copy of the current, usable name
212 8
        $ret = (string)$this->_object->{$name_prop};
213
        // Restore the original name
214 8
        $this->_object->{$name_prop} = $original_name;
215 8
        return $ret;
216
    }
217
218 86
    private function get_sibling_qb(string $schema_type, $parent = null)
219
    {
220 86
        $dummy = new $schema_type();
221 86
        $child_name_property = midcom_helper_reflector::get_name_property($dummy);
222 86
        if (empty($child_name_property)) {
223
            // This sibling class does not use names
224 86
            return false;
225
        }
226 86
        if ($parent === null) {
227 6
            $qb = midcom_helper_reflector_tree::get($schema_type)->_root_objects_qb(false);
228
        } else {
229 84
            $resolver = midcom_helper_reflector_tree::get($schema_type);
230 84
            $qb = $resolver->_child_objects_type_qb($schema_type, $parent, false);
231
        }
232 86
        if (!$qb) {
233
            return false;
234
        }
235
236
        // Do not include current object in results, this is the easiest way
237 86
        if (!empty($this->_object->guid)) {
238 17
            $qb->add_constraint('guid', '<>', $this->_object->guid);
239
        }
240 86
        $qb->add_order($child_name_property, 'DESC');
241
        // One result should be enough
242 86
        $qb->set_limit(1);
243 86
        return $qb;
244
245
    }
246
247 8
    private function _parse_filename(string $name, string $extension, $default = 0) : array
248
    {
249 8
        if (preg_match('/(.*?)-([0-9]{3,})' . $extension . '$/', $name, $name_matches)) {
250
            // Name already has i and base parts, split them.
251
            return [(int) $name_matches[2], (string) $name_matches[1]];
252
        }
253
        // Defaults
254 8
        return [$default, $name];
255
    }
256
257
    /**
258
     * Resolve the base value for the incrementing suffix and for the name.
259
     *
260
     * @see midcom_helper_reflector_nameresolver::generate_unique_name()
261
     * @param string $current_name the "current name" of the object (might not be the actual name value see the title logic in generate_unique_name())
262
     * @param string $extension The file extension, when working with attachments
263
     * @return array first key is the resolved $i second is the $base_name, which is $current_name without numeric suffix
264
     */
265 8
    private function _generate_unique_name_resolve_i(string $current_name, string $extension) : array
266
    {
267 8
        list($i, $base_name) = $this->_parse_filename($current_name, $extension, 1);
268
269
        // Look for siblings with similar names and see if they have higher i.
270 8
        midcom::get()->auth->request_sudo('midcom.helper.reflector');
271 8
        $parent = midcom_helper_reflector_tree::get_parent($this->_object);
0 ignored issues
show
Bug introduced by
$this->_object of type midcom_core_dbaobject is incompatible with the type midgard\portable\api\mgdobject expected by parameter $object of midcom_helper_reflector_tree::get_parent(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

271
        $parent = midcom_helper_reflector_tree::get_parent(/** @scrutinizer ignore-type */ $this->_object);
Loading history...
272 8
        if (!empty($parent->guid)) {
273
            // We have parent, check siblings
274 6
            $parent_resolver = new midcom_helper_reflector_tree($parent);
275 6
            $sibling_classes = $parent_resolver->get_child_classes();
276 6
            if (!in_array('midgard_attachment', $sibling_classes)) {
277 6
                $sibling_classes[] = 'midgard_attachment';
278
            }
279 6
            foreach ($sibling_classes as $schema_type) {
280 6
                $i = $this->process_schema_type($this->get_sibling_qb($schema_type, $parent), $i, $schema_type, $base_name, $extension);
281
            }
282
        } else {
283
            // No parent, we might be a root level class
284 2
            $is_root_class = false;
285 2
            $root_classes = midcom_helper_reflector_tree::get_root_classes();
286 2
            foreach ($root_classes as $schema_type) {
287 2
                if (midcom::get()->dbfactory->is_a($this->_object, $schema_type)) {
288 1
                    $is_root_class = true;
289 1
                    break;
290
                }
291
            }
292 2
            if (!$is_root_class) {
293
                // This should not happen, logging error and returning true (even though it's potentially dangerous)
294 1
                midcom::get()->auth->drop_sudo();
295 1
                debug_add("Object " . get_class($this->_object) . " #" . $this->_object->id . " has no valid parent but is not listed in the root classes, don't know what to do, letting higher level decide", MIDCOM_LOG_ERROR);
296 1
                return [$i, $base_name];
297
            }
298 1
            foreach ($root_classes as $schema_type) {
299 1
                $i = $this->process_schema_type($this->get_sibling_qb($schema_type), $i, $schema_type, $base_name, $extension);
300
            }
301
        }
302 7
        midcom::get()->auth->drop_sudo();
303
304 7
        return [$i, $base_name];
305
    }
306
307 7
    private function process_schema_type($qb, $i, string $schema_type, string $base_name, string $extension) : int
308
    {
309 7
        if (!$qb) {
310 7
            return $i;
311
        }
312 7
        $child_name_property = midcom_helper_reflector::get_name_property(new $schema_type);
313
314 7
        $qb->add_constraint($child_name_property, 'LIKE', "{$base_name}-%" . $extension);
315 7
        $siblings = $qb->execute();
316 7
        if (!empty($siblings)) {
317
            $sibling = $siblings[0];
318
            $sibling_name = $sibling->{$child_name_property};
319
320
            $sibling_i = $this->_parse_filename($sibling_name, $extension)[0];
321
            if ($sibling_i >= $i) {
322
                $i = $sibling_i + 1;
323
            }
324
        }
325 7
        return $i;
326
    }
327
}
328