Issues (31)

src/model/ExternalCacheStatefulFile.php (1 issue)

Severity
1
<?php
2
declare(strict_types=1);
3
4
namespace tkanstantsin\fileupload\model;
5
6
/**
7
 * Class ExternalCacheStatefulFile
8
 */
9
class ExternalCacheStatefulFile extends ExternalFile implements ICacheStateful
10
{
11
    /**
12
     * @todo: formalize cache config.
13
     * @xample (current)
14
     * ```php
15
     *  [
16
     *      'formatter-name' => 123456789,
17
     *      ...
18
     *  ],
19
     * ```
20
     * @example (for todo)
21
     * ```php
22
     *  [
23
     *      'formatter-name' => [
24
     *          'is_cached' => true|false,
25
     *          'cached_at' => 123456789,
26
     *          'empty' => true|false,
27
     *          'error' => true|false,
28
     *      ],
29
     *      ...
30
     *  ],
31
     * ```
32
     * @var array
33
     */
34
    protected $cachedState = [];
35
    /**
36
     * @var \Closure
37
     */
38
    protected $saveStateCallback;
39
40
    /**
41
     * @param array $cachedState
42
     */
43
    public function setCachedState(array $cachedState): void
44
    {
45
        $this->cachedState = $cachedState;
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function getCachedState(): array
52
    {
53
        return $this->cachedState;
54
    }
55
56
    /**
57
     * @param string $format
58
     *
59
     * @see Factory::$formatterConfigArray
60
     * @return int
61
     */
62
    public function getCachedAt(string $format): ?int
63
    {
64
        $cachedAt = $this->cachedState[$format] ?? null;
65
        if ($cachedAt <= 0) {
66
            $cachedAt = null;
67
        }
68
69
        return $cachedAt;
70
    }
71
72
    /**
73
     * @param string $format
74
     * @param int|null $cachedAt
75
     */
76
    public function setCachedAt(string $format, ?int $cachedAt): void
77
    {
78
        // TODO: add max expire period.
79
80
        $this->cachedState[$format] = $cachedAt;
81
        if ($cachedAt === null || $cachedAt <= 0) {
82
            unset($this->cachedState[$format]);
83
        }
84
    }
85
86
    /**
87
     * @param string $format
88
     *
89
     * @return bool
90
     */
91
    public function getIsCached(string $format): bool
92
    {
93
        return $this->getCachedAt($format) !== null;
94
    }
95
96
    /**
97
     * @param \Closure $callback
98
     */
99
    public function setSaveStateCallback(\Closure $callback): void
100
    {
101
        $this->saveStateCallback = $callback;
102
    }
103
104
    /**
105
     * @return bool
106
     */
107
    public function saveState(): bool
108
    {
109
        if (!($this->saveStateCallback instanceof \Closure)) {
0 ignored issues
show
$this->saveStateCallback is always a sub-type of Closure.
Loading history...
110
            return true;
111
        }
112
113
        return (bool) \call_user_func($this->saveStateCallback, $this);
114
    }
115
}