1<?php
2
3
4namespace ComboStrap;
5
6use http\Exception\RuntimeException;
7
8/**
9 * Class MetadataBoolean
10 * @package ComboStrap
11 */
12abstract class MetadataBoolean extends Metadata
13{
14
15    /**
16     * @var bool|null
17     */
18    protected $value;
19
20    public function getDataType(): string
21    {
22        return DataType::BOOLEAN_TYPE_VALUE;
23    }
24
25    public function getValue(): ?bool
26    {
27        $this->buildCheck();
28        return $this->value;
29    }
30
31
32    /**
33     * @param null|boolean $value
34     * @return Metadata
35     */
36    public function setValue($value): Metadata
37    {
38        if ($value === null) {
39            $this->value = null;
40            return $this;
41        }
42        if (!is_bool($value)) {
43            throw new ExceptionComboRuntime("The value is not a boolean: " . var_export($value, true));
44        }
45        $this->value = $value;
46        return $this;
47    }
48
49    public function toStoreDefaultValue()
50    {
51        $store = $this->getWriteStore();
52
53        if ($store instanceof MetadataFormDataStore) {
54            /**
55             * In a boolean form field, the data is returned only when the field is checked.
56             *
57             * By default, this is not checked, therefore, the default value is when this is not the default.
58             * It means that this is the inverse of the default value
59             */
60            return !$this->getDefaultValue();
61
62        }
63        return parent::toStoreDefaultValue();
64    }
65
66
67    /**
68     * @return bool|string|null
69     */
70    public function toStoreValue()
71    {
72
73        $store = $this->getWriteStore();
74        $value = $this->getValue();
75
76        if ($store instanceof MetadataFormDataStore) {
77            return $value;
78        }
79
80        if ($store instanceof MetadataDokuWikiStore) {
81            // The store modify it
82            return $value;
83        }
84
85        if ($store->isHierarchicalTextBased()) {
86            $value = Boolean::toString($value);
87        }
88
89        return $value;
90
91    }
92
93    /**
94     * @throws ExceptionCombo
95     */
96    public
97    function setFromStoreValue($value): Metadata
98    {
99        $value = $this->toBoolean($value);
100        return $this->setValue($value);
101    }
102
103
104    public
105    function valueIsNotNull(): bool
106    {
107        return $this->value !== null;
108    }
109
110    public
111    function buildFromStoreValue($value): Metadata
112    {
113        $this->value = $this->toBoolean($value);
114        return $this;
115    }
116
117    private
118    function toBoolean($value): ?bool
119    {
120        /**
121         * TODO: There is no validation
122         * If the value is not a boolean, the return value is false ...
123         */
124        return Boolean::toBoolean($value);
125
126    }
127
128
129}
130