Passed
Pull Request — master (#951)
by Stefano
01:13
created

CustomComponentControl::control()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 5
eloc 15
c 2
b 1
f 0
nc 2
nop 3
dl 0
loc 21
rs 9.4555
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2023 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
14
namespace App\Form;
15
16
use Cake\Utility\Hash;
17
18
/**
19
 * Return a custom component to handle input for a property
20
 */
21
class CustomComponentControl implements CustomHandlerInterface
22
{
23
    /**
24
     * @inheritDoc
25
     */
26
    public function control(string $name, $value, array $options): array
27
    {
28
        // you can define a custom component via `tag` option, default is <key-value-list>
29
        $tag = Hash::get($options, 'tag', 'key-value-list');
30
        $label = (string)Hash::get($options, 'label', $name);
31
        $readonly = (bool)Hash::get($options, 'readonly', false);
32
        $type = (string)Hash::get($options, 'type');
33
        if ($type === 'json' || is_array($value) || is_object($value)) {
34
            $value = htmlspecialchars($this->jsonValue($value));
35
        }
36
        $html = sprintf(
37
            '<%s label="%s" name="%s" value="%s" :readonly=%s></%s>',
38
            $tag,
39
            $label,
40
            $name,
41
            $value,
42
            $readonly ? 'true' : 'false',
43
            $tag,
44
        );
45
46
        return compact('type', 'html');
47
    }
48
49
    /**
50
     * Return a string representing the json value.
51
     *
52
     * @param mixed|null $value The value
53
     * @return string
54
     */
55
    protected function jsonValue($value): string
56
    {
57
        if (empty($value)) {
58
            return '';
59
        }
60
        if (is_array($value) || is_object($value)) {
61
            return json_encode($value);
62
        }
63
64
        return json_encode(json_decode($value, true));
65
    }
66
}
67