Completed
Push — master ( 131e79...afdc39 )
by Andreas
34:52 queued 12:29
created

name_is_clean()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
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 141
    public function __construct($object)
24
    {
25 141
        $this->_object = $object;
26 141
    }
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 141
    public function get_object_name(string $name_property = null) : ?string
35
    {
36 141
        if ($name_property === null) {
37 141
            $name_property = midcom_helper_reflector::get_name_property($this->_object);
38
        }
39 141
        if (    empty($name_property)
40 141
            || !midcom_helper_reflector::get($this->_object)->property_exists($name_property)) {
41
            // Could not resolve valid property
42 1
            return null;
43
        }
44 141
        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
        $sibling_classes = $this->get_sibling_classes($parent);
93 89
        if ($sibling_classes === null) {
94
            // This should not happen, logging error and returning true (even though it's potentially dangerous)
95 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);
96 4
            return true;
97
        }
98 86
        $stat = $this->check_sibling_classes($name, $sibling_classes, $parent);
99
100 86
        midcom::get()->auth->drop_sudo();
101 86
        return $stat;
102
    }
103
104 89
    private function get_sibling_classes($parent = null) : ?array
105
    {
106 89
        if (!empty($parent->guid)) {
107
            // We have parent, check siblings
108 84
            $parent_resolver = new midcom_helper_reflector_tree($parent);
109 84
            $sibling_classes = $parent_resolver->get_child_classes();
110 84
            if (!in_array('midgard_attachment', $sibling_classes)) {
111 84
                $sibling_classes[] = 'midgard_attachment';
112
            }
113
114 84
            return $sibling_classes;
115
        }
116
        // No parent, we might be a root level class
117 10
        $root_classes = midcom_helper_reflector_tree::get_root_classes();
118 10
        foreach ($root_classes as $classname) {
119 10
            if (midcom::get()->dbfactory->is_a($this->_object, $classname)) {
120 6
                return $root_classes;
121
            }
122
        }
123 4
        return null;
124
    }
125
126 86
    private function check_sibling_classes(string $name, array $schema_types, $parent = null) : bool
127
    {
128 86
        foreach ($schema_types as $schema_type) {
129 86
            $qb = $this->get_sibling_qb($schema_type, $parent);
130 86
            if (!$qb) {
131 86
                continue;
132
            }
133 86
            $child_name_property = midcom_helper_reflector::get_name_property(new $schema_type);
134
135 86
            $qb->add_constraint($child_name_property, '=', $name);
136 86
            if ($qb->count()) {
137 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

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

273
        $parent = midcom_helper_reflector_tree::get_parent(/** @scrutinizer ignore-type */ $this->_object);
Loading history...
274 8
        $sibling_classes = $this->get_sibling_classes($parent);
275 8
        if ($sibling_classes === null) {
276
            // This should not happen, logging error and returning true (even though it's potentially dangerous)
277 1
            midcom::get()->auth->drop_sudo();
278 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);
279 1
            return [$i, $base_name];
280
        }
281 7
        foreach ($sibling_classes as $schema_type) {
282 7
            $i = $this->process_schema_type($this->get_sibling_qb($schema_type, $parent), $i, $schema_type, $base_name, $extension);
283
        }
284 7
        midcom::get()->auth->drop_sudo();
285
286 7
        return [$i, $base_name];
287
    }
288
289 7
    private function process_schema_type($qb, $i, string $schema_type, string $base_name, string $extension) : int
290
    {
291 7
        if (!$qb) {
292 7
            return $i;
293
        }
294 7
        $child_name_property = midcom_helper_reflector::get_name_property(new $schema_type);
295
296 7
        $qb->add_constraint($child_name_property, 'LIKE', "{$base_name}-%" . $extension);
297 7
        $siblings = $qb->execute();
298 7
        if (!empty($siblings)) {
299
            $sibling = $siblings[0];
300
            $sibling_name = $sibling->{$child_name_property};
301
302
            $sibling_i = $this->_parse_filename($sibling_name, $extension)[0];
303
            if ($sibling_i >= $i) {
304
                $i = $sibling_i + 1;
305
            }
306
        }
307 7
        return $i;
308
    }
309
}
310