Passed
Push — master ( 02c721...85d97d )
by Alexander
01:37
created

FragmentCache::getCachedContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Widgets;
6
7
use Yiisoft\Cache\CacheInterface;
8
use Yiisoft\Cache\Dependency\Dependency;
9
use Yiisoft\View\DynamicContentAwareInterface;
10
use Yiisoft\View\DynamicContentAwareTrait;
11
use Yiisoft\View\WebView;
12
use Yiisoft\Widget\Widget;
13
14
use function array_merge;
15
use function ob_get_clean;
16
use function ob_implicit_flush;
17
use function ob_start;
18
19
final class FragmentCache extends Widget implements DynamicContentAwareInterface
20
{
21
    use DynamicContentAwareTrait;
22
23
    private string $id;
24
    private CacheInterface $cache;
25
    private int $duration = 60;
26
    private ?Dependency $dependency = null;
27
    private $variations;
28
    private ?string $content = null;
29
30
    private WebView $webView;
31
32 5
    public function __construct(CacheInterface $cache, WebView $webview)
33
    {
34 5
        $this->cache = $cache;
35 5
        $this->webView = $webview;
36 5
    }
37
38
    /**
39
     * Initializes the FragmentCache object.
40
     */
41 5
    public function start(): void
42
    {
43 5
        if ($this->getCachedContent() === null) {
44 5
            $this->webView->pushDynamicContent($this);
45 5
            ob_start();
46 5
            PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type integer expected by parameter $flag of ob_implicit_flush(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

46
            PHP_VERSION_ID >= 80000 ? ob_implicit_flush(/** @scrutinizer ignore-type */ false) : ob_implicit_flush(0);
Loading history...
47
        }
48 5
    }
49
50
    /**
51
     * Marks the end of content to be cached.
52
     *
53
     * Content displayed before this method call and after {@see init()} will be captured and saved in cache.
54
     *
55
     * This method does nothing if valid content is already found in cache.
56
     *
57
     * @return string the result of widget execution to be outputted.
58
     */
59 5
    public function run(): string
60
    {
61 5
        $content = $this->getCachedContent();
62
63 5
        if ($content !== null) {
64 4
            return $content;
65
        }
66
67 5
        $this->webView->popDynamicContent();
68
69 5
        $content = ob_get_clean();
70
71 5
        if ($content === false || $content === '') {
72
            return '';
73
        }
74
75 5
        $data = [$content, $this->getDynamicPlaceholders()];
76
77 5
        $this->cache->set($this->calculateKey(), $data, $this->duration, $this->dependency);
78
79 5
        return $this->updateDynamicContent($content, $this->getDynamicPlaceholders());
80
    }
81
82
    /**
83
     * Returns the cached content if available.
84
     *
85
     * @return string|null the cached content. False is returned if valid content is not found in the cache.
86
     */
87 5
    public function getCachedContent(): ?string
88
    {
89 5
        $key = $this->calculateKey();
90
91 5
        if (!$this->cache->has($key)) {
92 5
            return null;
93
        }
94
95 4
        $data = $this->cache->get($key);
96
97 4
        [$this->content, $placeholders] = $data;
98
99 4
        $this->content = $this->updateDynamicContent($this->content, $placeholders, true);
0 ignored issues
show
Bug introduced by
It seems like $this->content can also be of type null; however, parameter $content of Yiisoft\Yii\Widgets\Frag...:updateDynamicContent() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

99
        $this->content = $this->updateDynamicContent(/** @scrutinizer ignore-type */ $this->content, $placeholders, true);
Loading history...
100
101 4
        return $this->content;
102
    }
103
104
    /**
105
     * Generates a unique key used for storing the content in cache.
106
     *
107
     * The key generated depends on both {@see id} and {@see variations}.
108
     *
109
     * @return mixed a valid cache key
110
     */
111 5
    public function calculateKey()
112
    {
113 5
        $key = array_merge([__CLASS__, $this->id], (array) $this->variations);
114
115 5
        $jsonKey = json_encode($key);
116
117 5
        return ctype_alnum($jsonKey) && mb_strlen($jsonKey, '8bit') <= 32 ? $jsonKey : md5($jsonKey);
118
    }
119
120
    /**
121
     * @param Dependency|null $value the dependency that the cached content depends on.
122
     *
123
     * This can be either a {@see Dependency} object or a configuration array for creating the dependency object.
124
     *
125
     * Would make the output cache depends on the last modified time of all posts. If any post has its modification time
126
     * changed, the cached content would be invalidated.
127
     *
128
     * @return $this
129
     */
130
    public function dependency(?Dependency $value): self
131
    {
132
        $this->dependency = $value;
133
134
        return $this;
135
    }
136
137
    /**
138
     * @param int $value number of seconds that the data can remain valid in cache.
139
     *
140
     * @return $this
141
     */
142
    public function duration(int $value): self
143
    {
144
        $this->duration = $value;
145
146
        return $this;
147
    }
148
149 5
    public function id(string $value): self
150
    {
151 5
        $this->id = $value;
152
153 5
        return $this;
154
    }
155
156
    /**
157
     * @param array|string $value list of factors that would cause the variation of the content being cached.
158
     *
159
     * Each factor is a string representing a variation (e.g. the language, a GET parameter). The following variation
160
     * setting will cause the content to be cached in different versions according to the current application language:
161
     *
162
     * @return $this
163
     */
164 1
    public function variations($value): self
165
    {
166 1
        $this->variations = $value;
167
168 1
        return $this;
169
    }
170
171 3
    protected function getView(): WebView
172
    {
173 3
        return $this->webView;
174
    }
175
}
176