Completed
Pull Request — 2.0 (#150)
by Christopher
02:42
created

bootstrap.php ➔ fieldsInfo()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 23
c 0
b 0
f 0
nc 12
nop 1
dl 0
loc 35
rs 8.439
1
<?php
2
/**
3
 * Licensed under The GPL-3.0 License
4
 * For full copyright and license information, please see the LICENSE.txt
5
 * Redistributions of files must retain the above copyright notice.
6
 *
7
 * @since    2.0.0
8
 * @author   Christopher Castro <[email protected]>
9
 * @link     http://www.quickappscms.org
10
 * @license  http://opensource.org/licenses/gpl-3.0.html GPL-3.0 License
11
 */
12
13
use CMS\Event\EventDispatcher;
14
15
if (!function_exists('fieldsInfo')) {
16
    /**
17
     * Gets a collection of information of every registered field in the system, or
18
     * information for a particular field.
19
     *
20
     * Some fields may register themselves as hidden when they are intended to be
21
     * used exclusively by plugins. So users can not `attach` them to entities using
22
     * Field UI.
23
     *
24
     * ### Usage:
25
     *
26
     * ```php
27
     * $visibleOnly = fieldsInfo()->filter(function ($info) {
28
     *     return !$info['hidden'];
29
     * });
30
     * ```
31
     *
32
     * @param string|null $field Field for which get its information as an array, or
33
     *  null (default) to get all of them as a collection. e.g.
34
     *  `Field\Field\TextField`
35
     * @return \Cake\Collection\Collection|array A collection of fields information
36
     */
37
    function fieldsInfo($field = null)
38
    {
39
        $fields = [];
40
        $plugins = plugin()->filter(function ($plugin) {
41
            return $plugin->status;
42
        });
43
44
        foreach ($plugins as $plugin) {
45
            foreach ($plugin->fields as $className) {
46
                if (class_exists($className)) {
47
                    $handler = new $className();
48
                    $result = array_merge([
49
                        'type' => 'varchar',
50
                        'name' => null,
51
                        'description' => null,
52
                        'hidden' => false,
53
                        'handler' => $className,
54
                        'maxInstances' => 0,
55
                        'searchable' => true,
56
                    ], (array)$handler->info());
57
                    $fields[$className] = $result;
58
                }
59
            }
60
        }
61
62
        if ($field === null) {
63
            return collection(array_values($fields));
64
        }
65
66
        if (isset($fields[$field])) {
67
            return $fields[$field];
68
        }
69
70
        throw new \Exception(__d('field', 'The field handler "{0}" was not found.', $field));
71
    }
72
}
73