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

CustomComponentControl   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 42
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A jsonValue() 0 10 4
A control() 0 17 2
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 JSON field
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
        $json = htmlspecialchars($this->jsonValue($value));
33
34
        return [
35
            'class' => 'json',
36
            'html' => sprintf(
37
                '<%s label="%s" name="%s" value="%s" :readonly=%s />',
38
                $tag,
39
                $label,
40
                $name,
41
                $json,
42
                $readonly ? 'true' : 'false',
43
            ),
44
        ];
45
    }
46
47
    /**
48
     * Return a string representing the json value.
49
     *
50
     * @param mixed|null $value The value
51
     * @return string
52
     */
53
    protected function jsonValue($value): string
54
    {
55
        if (empty($value)) {
56
            return '';
57
        }
58
        if (is_array($value) || is_object($value)) {
59
            return json_encode($value);
60
        }
61
62
        return json_encode(json_decode($value, true));
63
    }
64
}
65