• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / caching / 6311829630

26 Sep 2023 11:12AM UTC coverage: 88.889%. Remained the same
6311829630

push

github

dg
removed Nette\SmartObject

536 of 603 relevant lines covered (88.89%)

0.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.44
/src/Caching/Cache.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Caching;
11

12
use Nette;
13

14

15
/**
16
 * Implements the cache for a application.
17
 */
18
class Cache
19
{
20
        /** dependency */
21
        public const
22
                Priority = 'priority',
23
                Expire = 'expire',
24
                Sliding = 'sliding',
25
                Tags = 'tags',
26
                Files = 'files',
27
                Items = 'items',
28
                Constants = 'consts',
29
                Callbacks = 'callbacks',
30
                Namespaces = 'namespaces',
31
                All = 'all';
32

33
        /** @deprecated use Cache::Priority */
34
        public const PRIORITY = self::Priority;
35

36
        /** @deprecated use Cache::Expire */
37
        public const EXPIRATION = self::Expire;
38

39
        /** @deprecated use Cache::Expire */
40
        public const EXPIRE = self::Expire;
41

42
        /** @deprecated use Cache::Sliding */
43
        public const SLIDING = self::Sliding;
44

45
        /** @deprecated use Cache::Tags */
46
        public const TAGS = self::Tags;
47

48
        /** @deprecated use Cache::Files */
49
        public const FILES = self::Files;
50

51
        /** @deprecated use Cache::Items */
52
        public const ITEMS = self::Items;
53

54
        /** @deprecated use Cache::Constants */
55
        public const CONSTS = self::Constants;
56

57
        /** @deprecated use Cache::Callbacks */
58
        public const CALLBACKS = self::Callbacks;
59

60
        /** @deprecated use Cache::Namespaces */
61
        public const NAMESPACES = self::Namespaces;
62

63
        /** @deprecated use Cache::All */
64
        public const ALL = self::All;
65

66
        /** @internal */
67
        public const NamespaceSeparator = "\x00";
68

69
        private Storage $storage;
70
        private string $namespace;
71

72

73
        public function __construct(Storage $storage, ?string $namespace = null)
1✔
74
        {
75
                $this->storage = $storage;
1✔
76
                $this->namespace = $namespace . self::NamespaceSeparator;
1✔
77
        }
1✔
78

79

80
        /**
81
         * Returns cache storage.
82
         */
83
        final public function getStorage(): Storage
84
        {
85
                return $this->storage;
×
86
        }
87

88

89
        /**
90
         * Returns cache namespace.
91
         */
92
        final public function getNamespace(): string
93
        {
94
                return substr($this->namespace, 0, -1);
1✔
95
        }
96

97

98
        /**
99
         * Returns new nested cache object.
100
         */
101
        public function derive(string $namespace): static
1✔
102
        {
103
                return new static($this->storage, $this->namespace . $namespace);
1✔
104
        }
105

106

107
        /**
108
         * Reads the specified item from the cache or generate it.
109
         */
110
        public function load(mixed $key, ?callable $generator = null, ?array $dependencies = null): mixed
1✔
111
        {
112
                $storageKey = $this->generateKey($key);
1✔
113
                $data = $this->storage->read($storageKey);
1✔
114
                if ($data === null && $generator) {
1✔
115
                        $this->storage->lock($storageKey);
1✔
116
                        try {
117
                                $data = $generator(...[&$dependencies]);
1✔
118
                        } catch (\Throwable $e) {
1✔
119
                                $this->storage->remove($storageKey);
1✔
120
                                throw $e;
1✔
121
                        }
122

123
                        $this->save($key, $data, $dependencies);
1✔
124
                }
125

126
                return $data;
1✔
127
        }
128

129

130
        /**
131
         * Reads multiple items from the cache.
132
         */
133
        public function bulkLoad(array $keys, ?callable $generator = null): array
1✔
134
        {
135
                if (count($keys) === 0) {
1✔
136
                        return [];
×
137
                }
138

139
                foreach ($keys as $key) {
1✔
140
                        if (!is_scalar($key)) {
1✔
141
                                throw new Nette\InvalidArgumentException('Only scalar keys are allowed in bulkLoad()');
1✔
142
                        }
143
                }
144

145
                $result = [];
1✔
146
                if (!$this->storage instanceof BulkReader) {
1✔
147
                        foreach ($keys as $key) {
1✔
148
                                $result[$key] = $this->load(
1✔
149
                                        $key,
1✔
150
                                        $generator
1✔
151
                                                ? fn(&$dependencies) => $generator(...[$key, &$dependencies])
1✔
152
                                                : null,
1✔
153
                                );
154
                        }
155

156
                        return $result;
1✔
157
                }
158

159
                $storageKeys = array_map([$this, 'generateKey'], $keys);
1✔
160
                $cacheData = $this->storage->bulkRead($storageKeys);
1✔
161
                foreach ($keys as $i => $key) {
1✔
162
                        $storageKey = $storageKeys[$i];
1✔
163
                        if (isset($cacheData[$storageKey])) {
1✔
164
                                $result[$key] = $cacheData[$storageKey];
1✔
165
                        } elseif ($generator) {
1✔
166
                                $result[$key] = $this->load($key, fn(&$dependencies) => $generator(...[$key, &$dependencies]));
1✔
167
                        } else {
168
                                $result[$key] = null;
1✔
169
                        }
170
                }
171

172
                return $result;
1✔
173
        }
174

175

176
        /**
177
         * Writes item into the cache.
178
         * Dependencies are:
179
         * - Cache::Priority => (int) priority
180
         * - Cache::Expire => (timestamp) expiration
181
         * - Cache::Sliding => (bool) use sliding expiration?
182
         * - Cache::Tags => (array) tags
183
         * - Cache::Files => (array|string) file names
184
         * - Cache::Items => (array|string) cache items
185
         * - Cache::Constants => (array|string) cache items
186
         * @return mixed  value itself
187
         * @throws Nette\InvalidArgumentException
188
         */
189
        public function save(mixed $key, mixed $data, ?array $dependencies = null): mixed
1✔
190
        {
191
                $key = $this->generateKey($key);
1✔
192

193
                if ($data instanceof \Closure) {
1✔
194
                        $this->storage->lock($key);
1✔
195
                        try {
196
                                $data = $data(...[&$dependencies]);
1✔
197
                        } catch (\Throwable $e) {
×
198
                                $this->storage->remove($key);
×
199
                                throw $e;
×
200
                        }
201
                }
202

203
                if ($data === null) {
1✔
204
                        $this->storage->remove($key);
1✔
205
                        return null;
1✔
206
                } else {
207
                        $dependencies = $this->completeDependencies($dependencies);
1✔
208
                        if (isset($dependencies[self::Expire]) && $dependencies[self::Expire] <= 0) {
1✔
209
                                $this->storage->remove($key);
1✔
210
                        } else {
211
                                $this->storage->write($key, $data, $dependencies);
1✔
212
                        }
213

214
                        return $data;
1✔
215
                }
216
        }
217

218

219
        private function completeDependencies(?array $dp): array
1✔
220
        {
221
                // convert expire into relative amount of seconds
222
                if (isset($dp[self::Expire])) {
1✔
223
                        $dp[self::Expire] = Nette\Utils\DateTime::from($dp[self::Expire])->format('U') - time();
1✔
224
                }
225

226
                // make list from TAGS
227
                if (isset($dp[self::Tags])) {
1✔
228
                        $dp[self::Tags] = array_values((array) $dp[self::Tags]);
1✔
229
                }
230

231
                // make list from NAMESPACES
232
                if (isset($dp[self::Namespaces])) {
1✔
233
                        $dp[self::Namespaces] = array_values((array) $dp[self::Namespaces]);
×
234
                }
235

236
                // convert FILES into CALLBACKS
237
                if (isset($dp[self::Files])) {
1✔
238
                        foreach (array_unique((array) $dp[self::Files]) as $item) {
1✔
239
                                $dp[self::Callbacks][] = [[self::class, 'checkFile'], $item, @filemtime($item) ?: null]; // @ - stat may fail
1✔
240
                        }
241

242
                        unset($dp[self::Files]);
1✔
243
                }
244

245
                // add namespaces to items
246
                if (isset($dp[self::Items])) {
1✔
247
                        $dp[self::Items] = array_unique(array_map([$this, 'generateKey'], (array) $dp[self::Items]));
1✔
248
                }
249

250
                // convert CONSTS into CALLBACKS
251
                if (isset($dp[self::Constants])) {
1✔
252
                        foreach (array_unique((array) $dp[self::Constants]) as $item) {
1✔
253
                                $dp[self::Callbacks][] = [[self::class, 'checkConst'], $item, constant($item)];
1✔
254
                        }
255

256
                        unset($dp[self::Constants]);
1✔
257
                }
258

259
                if (!is_array($dp)) {
1✔
260
                        $dp = [];
1✔
261
                }
262

263
                return $dp;
1✔
264
        }
265

266

267
        /**
268
         * Removes item from the cache.
269
         */
270
        public function remove(mixed $key): void
1✔
271
        {
272
                $this->save($key, null);
1✔
273
        }
1✔
274

275

276
        /**
277
         * Removes items from the cache by conditions.
278
         * Conditions are:
279
         * - Cache::Priority => (int) priority
280
         * - Cache::Tags => (array) tags
281
         * - Cache::All => true
282
         */
283
        public function clean(?array $conditions = null): void
1✔
284
        {
285
                $conditions = (array) $conditions;
1✔
286
                if (isset($conditions[self::Tags])) {
1✔
287
                        $conditions[self::Tags] = array_values((array) $conditions[self::Tags]);
1✔
288
                }
289

290
                $this->storage->clean($conditions);
1✔
291
        }
1✔
292

293

294
        /**
295
         * Caches results of function/method calls.
296
         */
297
        public function call(callable $function): mixed
1✔
298
        {
299
                $key = func_get_args();
1✔
300
                if (is_array($function) && is_object($function[0])) {
1✔
301
                        $key[0][0] = get_class($function[0]);
1✔
302
                }
303

304
                return $this->load($key, fn() => $function(...array_slice($key, 1)));
1✔
305
        }
306

307

308
        /**
309
         * Caches results of function/method calls.
310
         */
311
        public function wrap(callable $function, ?array $dependencies = null): \Closure
1✔
312
        {
313
                return function () use ($function, $dependencies) {
1✔
314
                        $key = [$function, $args = func_get_args()];
1✔
315
                        if (is_array($function) && is_object($function[0])) {
1✔
316
                                $key[0][0] = get_class($function[0]);
1✔
317
                        }
318

319
                        return $this->load($key, function (&$deps) use ($function, $args, $dependencies) {
1✔
320
                                $deps = $dependencies;
1✔
321
                                return $function(...$args);
1✔
322
                        });
1✔
323
                };
1✔
324
        }
325

326

327
        /**
328
         * Starts the output cache.
329
         */
330
        public function capture(mixed $key): ?OutputHelper
1✔
331
        {
332
                $data = $this->load($key);
1✔
333
                if ($data === null) {
1✔
334
                        return new OutputHelper($this, $key);
1✔
335
                }
336

337
                echo $data;
1✔
338
                return null;
1✔
339
        }
340

341

342
        /**
343
         * @deprecated  use capture()
344
         */
345
        public function start($key): ?OutputHelper
346
        {
347
                trigger_error(__METHOD__ . '() was renamed to capture()', E_USER_DEPRECATED);
×
348
                return $this->capture($key);
×
349
        }
350

351

352
        /**
353
         * Generates internal cache key.
354
         */
355
        protected function generateKey($key): string
356
        {
357
                return $this->namespace . md5(is_scalar($key) ? (string) $key : serialize($key));
1✔
358
        }
359

360

361
        /********************* dependency checkers ****************d*g**/
362

363

364
        /**
365
         * Checks CALLBACKS dependencies.
366
         */
367
        public static function checkCallbacks(array $callbacks): bool
1✔
368
        {
369
                foreach ($callbacks as $callback) {
1✔
370
                        if (!array_shift($callback)(...$callback)) {
1✔
371
                                return false;
1✔
372
                        }
373
                }
374

375
                return true;
1✔
376
        }
377

378

379
        /**
380
         * Checks CONSTS dependency.
381
         */
382
        private static function checkConst(string $const, $value): bool
1✔
383
        {
384
                return defined($const) && constant($const) === $value;
1✔
385
        }
386

387

388
        /**
389
         * Checks FILES dependency.
390
         */
391
        private static function checkFile(string $file, ?int $time): bool
1✔
392
        {
393
                return @filemtime($file) == $time; // @ - stat may fail
1✔
394
        }
395
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc