Passed
Push — master ( e40592...aa7b79 )
by Andreas
37:05
created

midgard_admin_asgard_navigation::draw()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 49
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 28
nc 9
nop 0
dl 0
loc 49
ccs 0
cts 29
cp 0
crap 42
rs 8.8497
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midgard.admin.asgard
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
/**
10
 * Navigation class for Asgard
11
 *
12
 * @package midgard.admin.asgard
13
 */
14
class midgard_admin_asgard_navigation
15
{
16 1
    use midcom_baseclasses_components_base;
0 ignored issues
show
introduced by
The trait midcom_baseclasses_components_base requires some properties which are not provided by midgard_admin_asgard_navigation: $i18n, $head
Loading history...
17
18
    /**
19
     * @var array
20
     */
21
    public $root_types = [];
22
23
    /**
24
     * @var midgard\portable\api\mgdobject
25
     */
26
    protected $_object;
27
28
    /**
29
     * Object path to the current object.
30
     *
31
     * @var array
32
     */
33
    private $_object_path = [];
34
35
    private $_request_data = [];
36
    private $expanded_root_types = [];
37
    protected $shown_objects = [];
38
39 2
    public function __construct(?object $object, array &$request_data)
40
    {
41 2
        $this->_component = 'midgard.admin.asgard';
42
43 2
        $this->_object = $object;
44 2
        $this->_request_data =& $request_data;
45
46 2
        $this->root_types = midcom_helper_reflector_tree::get_root_classes();
47
48 2
        if (array_key_exists('current_type', $request_data)) {
49
            $expanded_type = $request_data['current_type'];
50
            if (!in_array($expanded_type, $this->root_types)) {
51
                $expanded_type = midcom_helper_reflector_tree::get($expanded_type)->get_parent_class();
0 ignored issues
show
introduced by
The method get_parent_class() does not exist on midcom_helper_reflector. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

51
                $expanded_type = midcom_helper_reflector_tree::get($expanded_type)->/** @scrutinizer ignore-call */ get_parent_class();
Loading history...
52
            }
53
            $this->expanded_root_types[] = $expanded_type;
54 2
        } elseif (isset($this->_object)) {
55 2
            $this->_object_path = array_column(midcom_helper_reflector_tree::resolve_path_parts($object), 'object');
56
57
            // we go through the path bottom up and show the first root type we find
58 2
            foreach (array_reverse($this->_object_path) as $node) {
59 2
                foreach ($this->root_types as $root_type) {
60 2
                    if (   is_a($node, $root_type)
61 2
                        || midcom_helper_reflector::is_same_class($root_type, $node->__midcom_class_name__)) {
62 2
                        $this->expanded_root_types[] = $root_type;
63 2
                        break;
64
                    }
65
                }
66
            }
67
        }
68 2
    }
69
70
    protected function _is_collapsed(string $type, int $total) : bool
71
    {
72
        return (   $total > $this->_config->get('max_navigation_entries')
73
                && empty($_GET['show_all_' . $type]));
74
    }
75
76 2
    protected function _list_child_elements(object $object, int $level = 0)
77
    {
78 2
        if ($level > 25) {
79
            debug_add('Recursion level 25 exceeded, aborting', MIDCOM_LOG_ERROR);
80
            return;
81
        }
82 2
        $ref = midcom_helper_reflector_tree::get($object);
83
84 2
        $child_types = [];
85 2
        foreach ($ref->get_child_classes() as $class) {
0 ignored issues
show
introduced by
The method get_child_classes() does not exist on midcom_helper_reflector. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

85
        foreach ($ref->/** @scrutinizer ignore-call */ get_child_classes() as $class) {
Loading history...
86 2
            $qb = $ref->_child_objects_type_qb($class, $object, false);
0 ignored issues
show
introduced by
The method _child_objects_type_qb() does not exist on midcom_helper_reflector. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

86
            /** @scrutinizer ignore-call */ 
87
            $qb = $ref->_child_objects_type_qb($class, $object, false);
Loading history...
87
88 2
            if (   !$qb
89 2
                || !($count = $qb->count_unchecked())) {
90 2
                continue;
91
            }
92 1
            midcom_helper_reflector_tree::add_schema_sorts_to_qb($qb, $class);
93 1
            if ($this->_is_collapsed($class, $count)) {
94
                $qb->set_limit($this->_config->get('max_navigation_entries'));
95
            }
96 1
            $child_types[$class] = ['total' => $count, 'qb' => $qb];
97
        }
98
99 2
        if (!empty($child_types)) {
100 1
            echo "<ul>\n";
101 1
            foreach ($child_types as $type => $data) {
102 1
                $children = $data['qb']->execute();
103 1
                $label_mapping = [];
104 1
                foreach ($children as $i => $child) {
105 1
                    if (isset($this->shown_objects[$child->guid])) {
106
                        continue;
107
                    }
108
109 1
                    $ref = midcom_helper_reflector_tree::get($child);
110 1
                    $label_mapping[$i] = htmlspecialchars($ref->get_object_label($child));
0 ignored issues
show
Bug introduced by
It seems like $ref->get_object_label($child) can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

110
                    $label_mapping[$i] = htmlspecialchars(/** @scrutinizer ignore-type */ $ref->get_object_label($child));
Loading history...
111
                }
112
113 1
                asort($label_mapping);
114
115 1
                foreach ($label_mapping as $index => $label) {
116 1
                    $child = $children[$index];
117 1
                    $this->_draw_element($child, $label, $level);
118
                }
119 1
                if ($this->_is_collapsed($type, $data['total'])) {
120
                    $this->_draw_collapsed_element($level, $type, $data['total']);
121
                }
122
            }
123 1
            echo "</ul>\n";
124
        }
125 2
    }
126
127
    /**
128
     * Renders the given root objects to HTML and calls _list_child_elements()
129
     */
130
    private function _list_root_elements(midcom_helper_reflector_tree $ref)
131
    {
132
        $qb = $ref->_root_objects_qb();
133
134
        if (   !$qb
135
            || !($total = $qb->count_unchecked())) {
136
            return;
137
        }
138
        midcom_helper_reflector_tree::add_schema_sorts_to_qb($qb, $ref->mgdschema_class);
139
        if ($this->_is_collapsed($ref->mgdschema_class, $total)) {
140
            $qb->set_limit($this->_config->get('max_navigation_entries'));
141
        }
142
143
        echo "<ul class=\"midgard_admin_asgard_navigation\">\n";
144
145
        $root_objects = $qb->execute();
146
147
        $label_mapping = [];
148
        foreach ($root_objects as $i => $object) {
149
            $label_mapping[$i] = htmlspecialchars($ref->get_object_label($object));
0 ignored issues
show
Bug introduced by
It seems like $ref->get_object_label($object) can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

149
            $label_mapping[$i] = htmlspecialchars(/** @scrutinizer ignore-type */ $ref->get_object_label($object));
Loading history...
150
        }
151
152
        asort($label_mapping);
153
        $autoexpand = (count($root_objects) == 1);
154
        foreach ($label_mapping as $index => $label) {
155
            $object = $root_objects[$index];
156
            $this->_draw_element($object, $label, 1, $autoexpand);
157
        }
158
        if ($this->_is_collapsed($ref->mgdschema_class, $total)) {
159
            $this->_draw_collapsed_element(0, $ref->mgdschema_class, $total);
160
        }
161
162
        echo "</ul>\n";
163
    }
164
165
    private function _draw_collapsed_element(int $level, string $type, int $total)
166
    {
167
        $ref = midcom_helper_reflector::get($type);
168
        if (!empty($this->_object_path[$level])) {
169
            if ($this->_object_path[$level]->__mgdschema_class_name__ == $type) {
170
                $object = $this->_object_path[$level];
171
            } elseif ($level == 0) {
172
                // this is the case where our object has parents, but we're in its type view directly
173
                foreach ($this->_object_path as $candidate) {
174
                    if ($candidate->__mgdschema_class_name__ == $type) {
175
                        $object = $candidate;
176
                        break;
177
                    }
178
                }
179
            }
180
            if (!empty($object)) {
181
                $label = htmlspecialchars($ref->get_object_label($object));
0 ignored issues
show
Bug introduced by
It seems like $ref->get_object_label($object) can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

181
                $label = htmlspecialchars(/** @scrutinizer ignore-type */ $ref->get_object_label($object));
Loading history...
182
                $this->_draw_element($object, $label, $level);
183
            }
184
        }
185
        $icon = midcom_helper_reflector::get_object_icon(new $type);
186
        echo '<li><a class="expand-type-children" href="?show_all_' . $type . '=1">' . $icon . ' ' . sprintf($this->_l10n->get('show all %s %s entries'), $total, $ref->get_class_label()) . '</a></li>';
187
    }
188
189
    protected function _draw_element(object $object, string $label, int $level, bool $autoexpand = false)
190
    {
191
        $ref = midcom_helper_reflector_tree::get($object);
192
193
        $selected = $this->_is_selected($object);
194
        $css_class = $this->get_css_classes($object, $ref->mgdschema_class);
195
196
        $mode = $this->_request_data['default_mode'];
197
        if (str_contains($css_class, 'readonly')) {
198
            $mode = 'view';
199
        }
200
201
        $this->shown_objects[$object->guid] = true;
202
203
        echo "    <li class=\"{$css_class}\">";
204
205
        $icon = $ref->get_object_icon($object);
206
207
        if (trim($label) == '') {
208
            $label = $ref->get_class_label() . ' #' . $object->id;
209
        }
210
211
        echo "<a href=\"" . midcom_connection::get_url('self') . "__mfa/asgard/object/{$mode}/{$object->guid}/\" title=\"GUID: {$object->guid}, ID: {$object->id}\">{$icon}{$label}</a>\n";
212
        if (   $selected
213
            || $autoexpand) {
214
            $this->_list_child_elements($object, $level + 1);
215
        }
216
        echo "    </li>\n";
217
    }
218
219
    private function _draw_plugins()
220
    {
221
        $customdata = midcom::get()->componentloader->get_all_manifest_customdata('asgard_plugin');
222
        foreach ($customdata as $component => $plugin_config) {
223
            $this->_request_data['section_url'] = midcom_connection::get_url('self') . "__mfa/asgard_{$component}/";
224
            $this->_request_data['section_name'] = $this->_i18n->get_string($component, $component);
225
            $class = $plugin_config['class'];
226
227
            if (!midcom::get()->auth->can_user_do("{$component}:access", null, $class)) {
228
                // Disabled plugin
229
                continue;
230
            }
231
232
            if (   method_exists($class, 'navigation')
233
                && ($this->_request_data['plugin_name'] == "asgard_{$component}")) {
234
                $this->_request_data['expanded'] = true;
235
                midcom_show_style('midgard_admin_asgard_navigation_section_header');
236
                $class::navigation();
237
            } else {
238
                $this->_request_data['expanded'] = false;
239
                midcom_show_style('midgard_admin_asgard_navigation_section_header');
240
            }
241
242
            midcom_show_style('midgard_admin_asgard_navigation_section_footer');
243
        }
244
    }
245
246 1
    private function _is_selected(object $object) : bool
247
    {
248 1
        foreach ($this->_object_path as $path_object) {
249 1
            if ($object->guid == $path_object->guid) {
250
                return true;
251
            }
252
        }
253 1
        return false;
254
    }
255
256 1
    protected function get_css_classes(object $object, string $mgdschema_class) : string
257
    {
258 1
        $css_class = get_class($object) . " {$mgdschema_class}";
259
260
        // Populate common properties
261 1
        $css_class = midcom::get()->metadata->get_object_classes($object, $css_class);
262
263 1
        if ($this->_is_selected($object)) {
264
            $css_class .= ' selected';
265
        }
266 1
        if (   is_object($this->_object)
267 1
            && (   $object->guid == $this->_object->guid
268 1
                || (   is_a($this->_object, midcom_db_parameter::class)
269 1
                    && $object->guid == $this->_object->parentguid))) {
270
            $css_class .= ' current';
271
        }
272 1
        if ( !$object->can_do('midgard:update')) {
273
            $css_class .= ' readonly';
274
        }
275 1
        return $css_class;
276
    }
277
278
    /**
279
     * Apply visibility restrictions from various sources
280
     *
281
     * @return array Alphabetically sorted list of class => title pairs
282
     */
283
    private function _process_root_types() : array
284
    {
285
        // Get the types that might have special display conditions
286
        // @TODO: Should this just include to the configuration selection, although it would break the consistency
287
        // of other similar preference sets, which simply override the global settings?
288
        $selected = midgard_admin_asgard_plugin::get_preference('midgard_types');
289
290
        // Get the inclusion/exclusion model
291
        $model = midgard_admin_asgard_plugin::get_preference('midgard_types_model');
292
        $exclude = ($model == 'exclude');
293
294
        $label_mapping = midgard_admin_asgard_plugin::get_root_classes();
295
296
        if (preg_match_all('/\|([a-z0-9\.\-_]+)/', $selected, $regs)) {
297
            $types = array_flip($regs[1]);
298
            if ($exclude) {
299
                $label_mapping = array_diff_key($label_mapping, $types);
300
            } else {
301
                $label_mapping = array_intersect_key($label_mapping, $types);
302
            }
303
        }
304
305
        // Get the possible regular expression
306
        if ($regexp = midgard_admin_asgard_plugin::get_preference('midgard_types_regexp')) {
307
            // "Convert" quickly to PERL regular expression
308
            if (!preg_match('/^[\/|]/', $regexp)) {
309
                $regexp = "/{$regexp}/";
310
            }
311
312
            // If the regular expression has been set, check which types should be shown
313
            $label_mapping = array_filter($label_mapping, function ($root_type) use ($regexp, $exclude) {
314
                return preg_match($regexp, $root_type) == $exclude;
315
            }, ARRAY_FILTER_USE_KEY);
316
        }
317
318
        return $label_mapping;
319
    }
320
321
    public function draw()
322
    {
323
        $this->_request_data['chapter_name'] = midcom::get()->config->get('midcom_site_title');
324
        midcom_show_style('midgard_admin_asgard_navigation_chapter');
325
326
        $this->_draw_plugins();
327
328
        if (!midcom::get()->auth->can_user_do('midgard.admin.asgard:manage_objects', null, 'midgard_admin_asgard_plugin')) {
329
            return;
330
        }
331
332
        $label_mapping = $this->_process_root_types();
333
334
        $expanded_types = array_intersect(array_keys($label_mapping), $this->expanded_root_types);
335
336
        /*
337
         * Use a dropdown for displaying the navigation if at least one type is expanded
338
         * and the user has the corresponding preference set. That way, you expanded types
339
         * can take up the maximum available space while all types are still accessible with one
340
         * click if nothing is expanded
341
         */
342
        $types_shown = false;
343
        if (    !empty($expanded_types)
344
             && midgard_admin_asgard_plugin::get_preference('navigation_type') === 'dropdown') {
345
            $this->_draw_select_navigation();
346
            $types_shown = true;
347
        }
348
349
        foreach ($expanded_types as $root_type) {
350
            $this->_request_data['section_url'] = midcom_connection::get_url('self') . "__mfa/asgard/{$root_type}";
351
            $this->_request_data['section_name'] = $label_mapping[$root_type];
352
            $this->_request_data['expanded'] = true;
353
            midcom_show_style('midgard_admin_asgard_navigation_section_header');
354
            $ref = midcom_helper_reflector_tree::get($root_type);
355
            $this->_list_root_elements($ref);
356
357
            midcom_show_style('midgard_admin_asgard_navigation_section_footer');
358
        }
359
360
        if (!$types_shown) {
361
            $this->_request_data['section_name'] = $this->_l10n->get('midgard objects');
362
            $this->_request_data['section_url'] = null;
363
            $this->_request_data['expanded'] = true;
364
            midcom_show_style('midgard_admin_asgard_navigation_section_header');
365
            $collapsed_types = array_diff_key($label_mapping, array_flip($expanded_types));
366
367
            $this->_draw_type_list($collapsed_types);
368
369
            midcom_show_style('midgard_admin_asgard_navigation_section_footer');
370
        }
371
    }
372
373
    private function _draw_type_list(array $types)
374
    {
375
        echo "<ul class=\"midgard_admin_asgard_navigation\">\n";
376
377
        foreach ($types as $type => $label) {
378
            $url = midcom_connection::get_url('self') . "__mfa/asgard/{$type}/";
379
            echo "    <li class=\"mgdschema-type\">";
380
381
            if ($dbaclass = midcom::get()->dbclassloader->get_midcom_class_name_for_mgdschema_object($type)) {
382
                $object = new $dbaclass;
383
            } else {
384
                $object = new $type;
385
            }
386
            $icon = midcom_helper_reflector::get_object_icon($object);
387
388
            echo "<a href=\"" . $url . "\" title=\"{$label}\">{$icon}{$label}</a>\n";
389
390
            echo "    </li>\n";
391
        }
392
393
        echo "</ul>\n";
394
    }
395
396
    private function _draw_select_navigation()
397
    {
398
        if (!empty($this->_object_path)) {
399
            $this->_request_data['root_object'] = $this->_object_path[0];
400
            $this->_request_data['navigation_type'] = $this->_object_path[0]->__mgdschema_class_name__;
401
        } elseif (isset($this->expanded_root_types[0])) {
402
            $this->_request_data['navigation_type'] = $this->expanded_root_types[0];
403
        } else {
404
            $this->_request_data['navigation_type'] = '';
405
        }
406
407
        $this->_request_data['label_mapping'] = midgard_admin_asgard_plugin::get_root_classes();
408
        $this->_request_data['expanded_root_types'] = $this->expanded_root_types;
409
410
        midcom_show_style('midgard_admin_asgard_navigation_sections');
411
    }
412
}
413