1<?php
2
3
4namespace ComboStrap;
5
6
7use ComboStrap\Meta\Api\Metadata;
8use ComboStrap\Meta\Api\MetadataText;
9use ComboStrap\Meta\Store\MetadataDokuWikiStore;
10
11class CacheExpirationFrequency extends MetadataText
12{
13
14    /**
15     * The meta that has the cron expression
16     */
17    public const PROPERTY_NAME = "cache_expiration_frequency";
18    public const CANONICAL = "page-cache-expiration-frequency";
19
20    public static function createForPage(ResourceCombo $page): CacheExpirationFrequency
21    {
22        return (new CacheExpirationFrequency())
23            ->setResource($page);
24    }
25
26    public static function getTab(): string
27    {
28        return MetaManagerForm::TAB_CACHE_VALUE;
29    }
30
31    /**
32     * @param string|null $value
33     * @return Metadata
34     * @throws ExceptionBadArgument - if the value cannot be persisted
35     * @throws ExceptionBadSyntax - if the frequency has not the good syntax
36     */
37    public function setValue($value): Metadata
38    {
39
40        if ($value === null) {
41            parent::setValue($value);
42            return $this;
43        }
44
45        $value = trim($value);
46        if ($value === "") {
47            // html form send an empty string
48            return $this;
49        }
50
51        try {
52            $cacheExpirationCalculatedDate = Cron::getDate($value);
53        } catch (ExceptionBadSyntax $e) {
54            throw new ExceptionBadSyntax("The cache frequency expression ($value) is not a valid cron expression. <a href=\"https://crontab.guru/\">Validate it on this website</a>", CacheExpirationFrequency::PROPERTY_NAME, 0, $e);
55        }
56        $cacheExpirationDate = CacheExpirationDate::createForPage($this->getResource());
57        $cacheExpirationDate
58            ->setValue($cacheExpirationCalculatedDate)
59            ->persist();
60        parent::setValue($value);
61        return $this;
62
63
64    }
65
66
67    public static function getDescription(): string
68    {
69        return "A page expiration frequency expressed as a cron expression";
70    }
71
72    public static function getLabel(): string
73    {
74        return "Cache Expiration Frequency";
75    }
76
77    public static function getName(): string
78    {
79        return self::PROPERTY_NAME;
80    }
81
82    public static function getPersistenceType(): string
83    {
84        return MetadataDokuWikiStore::PERSISTENT_DOKUWIKI_KEY;
85    }
86
87    public static function isMutable(): bool
88    {
89        return true;
90    }
91
92    public function getDefaultValue()
93    {
94        return null;
95    }
96
97    public static function getCanonical(): string
98    {
99        return self::CANONICAL;
100    }
101
102
103    public static function isOnForm(): bool
104    {
105        return true;
106    }
107}
108