1<?php
2
3
4namespace ComboStrap\Meta\Api;
5
6use ComboStrap\DataType;
7use ComboStrap\ExceptionCompile;
8use ComboStrap\Json;
9use ComboStrap\LogUtility;
10
11/**
12 * Class MetadataJson
13 * @package ComboStrap
14 * A text that can be saved as array
15 * TODO: Should be based on an array
16 */
17abstract class MetadataJson extends MetadataText
18{
19
20
21    /**
22     * Helper function for date metadata
23     * @throws ExceptionCompile
24     */
25    public function toStoreValue()
26    {
27        $value = parent::toStoreValue();
28
29        if ($this->getWriteStore()->isHierarchicalTextBased()) {
30            return Json::createFromString($value)->toArray();
31        }
32
33        return $value;
34
35    }
36
37
38    static public function getDataType(): string
39    {
40        return DataType::JSON_TYPE_VALUE;
41    }
42
43
44    public function setFromStoreValueWithoutException($value): Metadata
45    {
46        try {
47            parent::setFromStoreValueWithoutException($this->toInternalValue($value));
48        } catch (ExceptionCompile $e) {
49            LogUtility::msg("Value in the store is not a valid json. Message:" . $e->getMessage(), LogUtility::LVL_MSG_ERROR, $e->getCanonical());
50        }
51        return $this;
52    }
53
54    /**
55     * @throws ExceptionCompile
56     */
57    private function toInternalValue($value)
58    {
59        if ($value === null) {
60            // html form return empty string
61            return null;
62        }
63        if (is_array($value)) {
64            return Json::createFromArray($value)->toPrettyJsonString();
65        }
66        if (!is_string($value)) {
67            throw new ExceptionCompile("The json persistent value is not an array, nor a string");
68        }
69        // the json is normalized when setting to verify
70        return $value;
71    }
72
73
74}
75