Passed
Push — master ( 409c3f...e5371a )
by Andreas
09:22
created

midcom_admin_help_help::read_schema_properties()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6.0052

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 6
nop 0
dl 0
loc 28
ccs 18
cts 19
cp 0.9474
crap 6.0052
rs 8.9777
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom.admin.help
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
use Michelf\MarkdownExtra;
10
use midgard\portable\storage\connection;
11
12
/**
13
 * Online help display
14
 *
15
 * @package midcom.admin.help
16
 */
17
class midcom_admin_help_help extends midcom_baseclasses_components_plugin
18
{
19
    private array $mgdtypes = [
20
        MGD_TYPE_STRING => "string",
21
        MGD_TYPE_INT => "integer",
22
        MGD_TYPE_UINT => "unsigned integer",
23
        MGD_TYPE_FLOAT => "float",
24
        MGD_TYPE_BOOLEAN => "boolean",
25
        MGD_TYPE_TIMESTAMP => "datetime",
26
        MGD_TYPE_LONGTEXT => "longtext",
27
        MGD_TYPE_GUID => "guid",
28
        MGD_TYPE_NONE => 'none'
29
    ];
30
31 3
    public function _on_initialize()
32
    {
33 3
        midcom::get()->auth->require_valid_user();
34
35 3
        midcom::get()->skip_page_style = true;
36
        // doing this here as this component most probably will not be called by itself.
37 3
        midcom::get()->style->prepend_component_styledir('midcom.admin.help');
38
    }
39
40
    /**
41
     * Get component's documentation directory path
42
     */
43 8
    private static function get_documentation_dir(string $component) : string
44
    {
45 8
        return midcom::get()->componentloader->path_to_snippetpath($component) . '/documentation/';
46
    }
47
48 8
    public static function generate_file_path(string $help_id, string $component, string $language = null) : ?string
49
    {
50 8
        $language ??= midcom::get()->i18n->get_current_language();
51
52 8
        $file = self::get_documentation_dir($component) . "{$help_id}.{$language}.txt";
53 8
        if (!file_exists($file)) {
54 8
            if ($language != midcom::get()->i18n->get_fallback_language()) {
55
                // Try MidCOM's default fallback language
56 1
                return self::generate_file_path($help_id, $component, midcom::get()->i18n->get_fallback_language());
57
            }
58 8
            return null;
59
        }
60
61 5
        return $file;
62
    }
63
64 4
    private function get_help_title(string $help_id, string $component) : string
65
    {
66 4
        if ($path = self::generate_file_path($help_id, $component)) {
67 4
            $file_contents = file($path);
68 4
            if (trim($file_contents[0])) {
69 4
                return trim($file_contents[0]);
70
            }
71
        }
72
73 1
        return $this->_l10n->get("help_" . $help_id);
74
    }
75
76
    /**
77
     * Load the file from the component's documentation directory.
78
     */
79 5
    private function _load_file(string $help_id, string $component) : ?string
80
    {
81
        // Try loading the file
82 5
        $file = self::generate_file_path($help_id, $component);
83 5
        if (!$file) {
84 4
            return null;
85
        }
86
87
        // Load the contents
88 1
        $help_contents = file_get_contents($file);
89
90
        // Replace static URLs (URLs for screenshots etc)
91 1
        return str_replace('MIDCOM_STATIC_URL', MIDCOM_STATIC_URL, $help_contents);
92
    }
93
94
    /**
95
     * Load a help file and markdownize it
96
     */
97 5
    public function get_help_contents(string $help_id, string $component) : ?string
98
    {
99 5
        $text = $this->_load_file($help_id, $component);
100 5
        if (!$text) {
101 4
            return null;
102
        }
103 1
        return MarkdownExtra::defaultTransform($text);
104
    }
105
106 5
    public function list_files(string $component, bool $with_index = false) : array
107
    {
108 5
        $files = $this->_list_physical_files($component);
109 5
        $files = $this->_add_virtual_files($files, $component);
110
111 5
        ksort($files);
112
        // prepend 'index' URL if required
113 5
        if ($with_index) {
114 1
            $files = array_merge([
115 1
                'index' => [
116 1
                    'path' => '/',
117 1
                    'subject' => $this->_l10n->get('help_index'),
118 1
                    'lang' => 'en',
119 1
                ]],
120 1
                $files
121 1
            );
122
        }
123 5
        return $files;
124
    }
125
126 5
    private function _add_virtual_files(array $files, string $component) : array
127
    {
128
        // Schemas
129 5
        $this->_request_data['mgdschemas'] = midcom::get()->dbclassloader->get_component_classes($component);
130 5
        if (!empty($this->_request_data['mgdschemas'])) {
131 3
            $files['mgdschemas'] = [
132 3
                'path' => '/mgdschemas',
133 3
                'subject' => $this->_l10n->get('help_mgdschemas'),
134 3
                'lang' => 'en',
135 3
            ];
136
        }
137
138
        // URL Methods
139 5
        $this->_request_data['urlmethods'] = $this->read_url_methods($component);
140 5
        if (!empty($this->_request_data['urlmethods'])) {
141 4
            $files['urlmethods'] = [
142 4
                'path' => '/urlmethods',
143 4
                'subject' => $this->_l10n->get('help_urlmethods'),
144 4
                'lang' => 'en',
145 4
            ];
146
        }
147
148
        // Break if dealing with MidCOM Core docs
149 5
        if ($component == 'midcom') {
150
            return $files;
151
        }
152
153
        // handlers
154 5
        $this->_request_data['request_switch_info'] = $this->read_component_handlers($component);
155 5
        if (!empty($this->_request_data['request_switch_info'])) {
156 4
            $files['handlers'] = [
157 4
                'path' => '/handlers',
158 4
                'subject' => $this->_l10n->get('help_handlers'),
159 4
                'lang' => 'en',
160 4
            ];
161
        }
162
163 5
        return $files;
164
    }
165
166 5
    private function _list_physical_files(string $component) : array
167
    {
168 5
        $component_dir = self::get_documentation_dir($component);
169 5
        if (!is_dir($component_dir)) {
170 1
            return [];
171
        }
172
173 4
        $files = [];
174 4
        $pattern = $component_dir . '*.{' . $this->_i18n->get_current_language() . ',' . $this->_i18n->get_fallback_language() . '}.txt';
175
176 4
        foreach (glob($pattern, GLOB_NOSORT|GLOB_BRACE) as $path) {
177 4
            $entry = basename($path);
178 4
            if (   str_starts_with($entry, 'index')
179 4
                || str_starts_with($entry, 'handler')
180 4
                || str_starts_with($entry, 'urlmethod')) {
181
                // Ignore dotfiles, handlers & index.lang.txt
182 1
                continue;
183
            }
184
185 4
            $filename_parts = explode('.', $entry);
186
187 4
            $files[$filename_parts[0]] = [
188 4
                'path' => $path,
189 4
                'subject' => $this->get_help_title($filename_parts[0], $component),
190 4
                'lang' => $filename_parts[1],
191 4
            ];
192
        }
193
194 4
        return $files;
195
    }
196
197 5
    private function read_component_handlers(string $component) : array
198
    {
199 5
        $data = [];
200
201 5
        $handler = midcom::get()->componentloader->get_interface_class($component);
202 5
        $viewer = $handler->get_viewer(new midcom_db_topic);
203 5
        $routes = $viewer->get_router()->getRouteCollection()->all();
204 5
        foreach ($routes as $request_handler_id => $route) {
205 4
            $details = [
206 4
                'route' => preg_replace('/args_(\d+)/', 'args[\1]', $route->getPath())
207 4
            ];
208
209 4
            list ($details['controller'], $details['action']) = explode('::', $route->getDefault('_controller'), 2);
210
211 4
            if (self::generate_file_path('handlers_' . $request_handler_id, $component)) {
212 1
                $details['info'] = $this->get_help_contents('handlers_' . $request_handler_id, $component);
213 1
                $details['handler_help_url'] = 'handlers_' . $request_handler_id;
214
            }
215 4
            $data[$request_handler_id] = $details;
216
        }
217
218 5
        return $data;
219
    }
220
221 5
    private function read_url_methods(string $component) : array
222
    {
223 5
        $data = [];
224
225 5
        $exec_path = midcom::get()->componentloader->path_to_snippetpath($component) . '/exec/';
226 5
        if (   !is_dir($exec_path)
227 5
            || !is_readable($exec_path)) {
228
            // Directory not accessible, skip loading it
229 1
            return $data;
230
        }
231
232 4
        foreach (glob($exec_path . '/*.php', GLOB_NOSORT) as $path) {
233 4
            $file = basename($path);
234 4
            $info_id = "urlmethod_" . str_replace('.php', '', $file);
235
236 4
            $data[$file] = [
237 4
                'url' => '/midcom-exec-' . $component . '/' . $file,
238 4
            ];
239
240 4
            if (self::generate_file_path($info_id, $component)) {
241
                $data[$file]['handler_help_url'] = $info_id;
242
                $data[$file]['description'] = $this->get_help_contents($info_id, $component);
243
            }
244
        }
245
246 4
        return $data;
247
    }
248
249 1
    private function read_schema_properties()
250
    {
251 1
        foreach (array_keys($this->_request_data['mgdschemas']) as $mgdschema_class) {
252 1
            $mrp = new midgard_reflection_property($mgdschema_class);
253 1
            $class_props = connection::get_em()->getClassMetadata($mgdschema_class)->get_schema_properties();
0 ignored issues
show
introduced by
The method get_schema_properties() does not exist on Doctrine\ORM\Mapping\ClassMetadata. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

253
            $class_props = connection::get_em()->getClassMetadata($mgdschema_class)->/** @scrutinizer ignore-call */ get_schema_properties();
Loading history...
254
255 1
            unset($class_props['metadata']);
256 1
            $default_properties = [];
257 1
            $additional_properties = [];
258
259 1
            foreach ($class_props as $prop) {
260
                switch ($prop) {
261 1
                    case 'action':
262
                        // Midgard-internal properties, skip
263
                        break;
264 1
                    case 'guid':
265 1
                    case 'id':
266 1
                        $default_properties[$prop] = $this->_get_property_data($mrp, $prop);
267 1
                        break;
268
                    default:
269 1
                        $additional_properties[$prop] = $this->_get_property_data($mrp, $prop);
270 1
                        break;
271
                }
272
            }
273 1
            ksort($default_properties);
274 1
            ksort($additional_properties);
275
276 1
            $this->_request_data['properties'][$mgdschema_class] = array_merge($default_properties, $additional_properties);
277
        }
278
    }
279
280 1
    private function _get_property_data(midgard_reflection_property $mrp, string $prop) : array
281
    {
282 1
        return [
283 1
            'value' => $mrp->description($prop) ?? '',
284 1
            'link' => $mrp->is_link($prop),
285 1
            'link_name' => $mrp->get_link_name($prop),
286 1
            'link_target' => $mrp->get_link_target($prop),
287 1
            'midgard_type' => $this->mgdtypes[$mrp->get_midgard_type($prop)]
288 1
        ];
289
    }
290
291 3
    private function _prepare_breadcrumb(string $handler_id)
292
    {
293 3
        $this->add_breadcrumb($this->router->generate('welcome'), $this->_l10n->get('help'));
294
295 3
        if (in_array($handler_id, ['help', 'component'])) {
296 2
            $this->add_breadcrumb(
297 2
                $this->router->generate('component', ['component' => $this->_request_data['component']]),
298 2
                $this->_i18n->get_string($this->_request_data['component'], $this->_request_data['component'])
299 2
            );
300
        }
301
    }
302
303 1
    public function _handler_welcome(string $handler_id, array &$data)
304
    {
305 1
        $data['view_title'] = $this->_l10n->get($this->_component);
306 1
        midcom::get()->head->set_pagetitle($data['view_title']);
307
308 1
        $data['components'] = [];
309 1
        $data['libraries'] = [];
310
311 1
        foreach (midcom::get()->componentloader->get_manifests() as $manifest) {
312 1
            $type = $manifest->purecode ? 'libraries' : 'components';
313 1
            $title = $manifest->get_name_translated();
314 1
            if ($title == $manifest->name) {
315 1
                $title = '';
316
            }
317
318 1
            $data[$type][$manifest->name] = [
319 1
                'name' => $manifest->name,
320 1
                'title' => $title,
321 1
                'icon' => midcom::get()->componentloader->get_component_icon($manifest->name),
322 1
                'description' => $manifest->description,
323 1
            ];
324
        }
325
326 1
        asort($data['components']);
327 1
        asort($data['libraries']);
328
329 1
        $this->_prepare_breadcrumb($handler_id);
330
    }
331
332
    /**
333
     * Shows the help system main screen
334
     */
335 1
    public function _show_welcome(string $handler_id, array &$data)
336
    {
337 1
        midcom_show_style('midcom_admin_help_header');
338 1
        midcom_show_style('midcom_admin_help_about');
339 1
        $list_types = ['components', 'libraries'];
340
341 1
        foreach ($list_types as $list_type) {
342 1
            $data['list_type'] = $list_type;
343 1
            midcom_show_style('midcom_admin_help_list_header');
344 1
            foreach ($data[$list_type] as $component_data) {
345 1
                $data['component_data'] = $component_data;
346 1
                midcom_show_style('midcom_admin_help_list_item');
347
            }
348 1
            midcom_show_style('midcom_admin_help_list_footer');
349
        }
350
351 1
        midcom_show_style('midcom_admin_help_footer');
352
    }
353
354 1
    public function _handler_component(string $handler_id, string $component, array &$data)
355
    {
356 1
        $data['component'] = $component;
357 1
        $data['view_title'] = sprintf($this->_l10n->get('help for %s'), $this->_i18n->get_string($component, $component));
358 1
        midcom::get()->head->set_pagetitle($data['view_title']);
359
360 1
        $data['help_files'] = $this->list_files($component);
361 1
        $data['html'] = $this->get_help_contents('index', $component);
362 1
        $this->_prepare_breadcrumb($handler_id);
363
    }
364
365
    /**
366
     * Shows the component help ToC.
367
     */
368 1
    public function _show_component(string $handler_id, array &$data)
369
    {
370 1
        midcom_show_style('midcom_admin_help_header');
371
372 1
        midcom_show_style('midcom_admin_help_show');
373 1
        midcom_show_style('midcom_admin_help_component');
374
375 1
        midcom_show_style('midcom_admin_help_footer');
376
    }
377
378 1
    public function _handler_help(string $handler_id, string $component, string $help_id, array &$data)
379
    {
380 1
        $data['help_id'] = $help_id;
381 1
        $data['component'] = $component;
382 1
        $data['help_files'] = $this->list_files($component);
383
384 1
        if ($help_id == 'mgdschemas') {
385 1
            $this->read_schema_properties();
386
        }
387 1
        $data['html'] = $this->get_help_contents($help_id, $component);
388
389 1
        midcom::get()->head->add_jsfile(MIDCOM_STATIC_URL . '/midcom.admin.help/twisty.js');
390 1
        $this->add_stylesheet(MIDCOM_STATIC_URL . '/stock-icons/font-awesome-4.7.0/css/font-awesome.min.css');
391
392
        // Table of contents navi
393 1
        $data['view_title'] = sprintf(
394 1
            $this->_l10n->get('help for %s in %s'),
395 1
            $this->get_help_title($help_id, $component),
396 1
            $this->_i18n->get_string($component, $component)
397 1
        );
398 1
        midcom::get()->head->set_pagetitle($data['view_title']);
399 1
        $this->_prepare_breadcrumb($handler_id);
400 1
        if (in_array($help_id, ['handlers', 'urlmethods', 'mgdschemas'])) {
401 1
            $this->add_breadcrumb("", $this->_l10n->get($help_id));
402
        } else {
403
            $this->add_breadcrumb("", $this->get_help_title($help_id, $component));
404
        }
405
    }
406
407
    /**
408
     * Shows the help page.
409
     */
410 1
    public function _show_help(string $handler_id, array &$data)
411
    {
412 1
        midcom_show_style('midcom_admin_help_header');
413 1
        midcom_show_style('midcom_admin_help_show');
414 1
        if (in_array($data['help_id'], ['handlers', 'mgdschemas', 'urlmethods'])) {
415 1
            midcom_show_style('midcom_admin_help_' . $data['help_id']);
416
        } elseif (!$data['html']) {
417
            $data['html'] = $this->get_help_contents('notfound', $this->_component);
418
            midcom_show_style('midcom_admin_help_show');
419
            midcom_show_style('midcom_admin_help_component');
420
        }
421 1
        midcom_show_style('midcom_admin_help_footer');
422
    }
423
}
424