Passed
Push — master ( 16b7fb...c68d79 )
by Evgeniy
02:19
created

FragmentCache::ttl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Widgets;
6
7
use RuntimeException;
8
use Yiisoft\Cache\CacheInterface;
9
use Yiisoft\Cache\Dependency\Dependency;
10
use Yiisoft\View\Cache\CachedContent;
11
use Yiisoft\View\Cache\DynamicContent;
12
use Yiisoft\Widget\Widget;
13
14
use function ob_end_clean;
15
use function ob_get_clean;
16
use function ob_implicit_flush;
17
use function ob_start;
18
19
/**
20
 * FragmentCache caches a fragment of content.
21
 *
22
 * @see CachedContent
23
 * @see DynamicContent
24
 *
25
 * Example of use:
26
 *
27
 * ```php
28
 * $dynamicContent = new Yiisoft\View\Cache\DynamicContent('dynamic-id', static function (array $parameters): string {
29
 *     return strtoupper("{$parameters['a']} - {$parameters['b']}");
30
 * }, ['a' => 'string-a', 'b' => 'string-b']);
31
 *
32
 * FragmentCache::widget()->id('cache-id')->ttl(30)->dynamicContents($dynamicContent)->begin();
33
 *     echo 'Content to be cached ...';
34
 *     echo $dynamicContent->placeholder();
35
 *     echo 'Content to be cached ...';
36
 * FragmentCache::end();
37
 * ```
38
 */
39
final class FragmentCache extends Widget
40
{
41
    private ?string $id = null;
42
    private CacheInterface $cache;
43
    private ?Dependency $dependency = null;
44
    private int $ttl = 60;
45
    private array $variations = [];
46
47
    /**
48
     * @var array<string, DynamicContent>
49
     */
50
    private array $dynamicContents = [];
51
52 6
    public function __construct(CacheInterface $cache)
53
    {
54 6
        $this->cache = $cache;
55 6
    }
56
57
    /**
58
     * Initializes the FragmentCache object.
59
     */
60 6
    public function begin(): ?string
61
    {
62 6
        parent::begin();
63 6
        ob_start();
64 6
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
65 6
        return null;
66
    }
67
68
    /**
69
     * Marks the end of content to be cached.
70
     *
71
     * Content displayed before this method call and after {@see init()} will be captured and saved in cache.
72
     *
73
     * This method does nothing if valid content is already found in cache.
74
     *
75
     * @return string The result of widget execution to be outputted.
76
     */
77 6
    protected function run(): string
78
    {
79 6
        if ($this->id === null) {
80 1
            ob_end_clean();
81 1
            throw new RuntimeException('You must assign the "id" using the "id()" setter.');
82
        }
83
84 5
        $cachedContent = new CachedContent($this->id, $this->cache, $this->dynamicContents, $this->variations);
85 5
        $content = $cachedContent->get();
86
87 5
        if ($content !== null) {
88 4
            ob_end_clean();
89 4
            return $content;
90
        }
91
92 5
        $content = ob_get_clean();
93
94 5
        if ($content === false || $content === '') {
95
            return '';
96
        }
97
98 5
        return $cachedContent->cache($content, $this->ttl, $this->dependency);
99
    }
100
101
    /**
102
     * @param string $value The unique identifier of the cache fragment.
103
     *
104
     * @return self
105
     */
106 5
    public function id(string $value): self
107
    {
108 5
        $this->id = $value;
109 5
        return $this;
110
    }
111
112
    /**
113
     * @param Dependency $value The dependency that the cached content depends on.
114
     *
115
     * This can be either a {@see Dependency} object or a configuration array for creating the dependency object.
116
     *
117
     * Would make the output cache depends on the last modified time of all posts. If any post has its modification time
118
     * changed, the cached content would be invalidated.
119
     *
120
     * @return self
121
     */
122 1
    public function dependency(Dependency $value): self
123
    {
124 1
        $this->dependency = $value;
125 1
        return $this;
126
    }
127
128
    /**
129
     * @param int $value The number of seconds that the data can remain valid in cache.
130
     *
131
     * @return self
132
     */
133 1
    public function ttl(int $value): self
134
    {
135 1
        $this->ttl = $value;
136 1
        return $this;
137
    }
138
139
    /**
140
     * @param DynamicContent ...$value The dynamic content instances.
141
     *
142
     * @return self
143
     */
144 3
    public function dynamicContents(DynamicContent ...$value): self
145
    {
146 3
        foreach ($value as $dynamicContent) {
147 3
            $this->dynamicContents[$dynamicContent->id()] = $dynamicContent;
148
        }
149 3
        return $this;
150
    }
151
152
    /**
153
     * @param string ...$value The factors that would cause the variation of the content being cached.
154
     *
155
     * Each factor is a string representing a variation (e.g. the language, a GET parameter). The following variation
156
     * setting will cause the content to be cached in different versions according to the current application language:
157
     *
158
     * ```php
159
     * $fragmentCache->variations('en');
160
     * ```
161
     *
162
     * @return self
163
     */
164 1
    public function variations(string ...$value): self
165
    {
166 1
        $this->variations = $value;
167 1
        return $this;
168
    }
169
}
170