OutputHelper::end()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 10
c 1
b 0
f 1
dl 0
loc 19
ccs 0
cts 13
cp 0
rs 9.9332
cc 3
nc 2
nop 2
crap 12
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Biurad opensource projects.
7
 *
8
 * PHP version 7.1 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Biurad\Cache;
19
20
use Biurad\Cache\Exceptions\InvalidArgumentException;
21
use Psr\Cache\CacheItemInterface;
22
23
/**
24
 * Output caching helper.
25
 */
26
class OutputHelper
27
{
28
    /** @var FastCache|null */
29
    private $cache;
30
31
    /** @var string */
32
    private $key;
33
34
    /**
35
     * @param mixed $key
36
     */
37
    public function __construct(FastCache $cache, $key)
38
    {
39
        $this->cache = $cache;
40
        $this->key = $key;
41
42
        \ob_start();
43
    }
44
45
    /**
46
     * Stops and saves the cache.
47
     *
48
     * @param callable $callback
49
     *
50
     * @throws InvalidArgumentException
51
     */
52
    public function end(callable $callback = null, ?float $beta = null): void
53
    {
54
        if (null === $this->cache) {
55
            throw new InvalidArgumentException('Output cache has already been saved.');
56
        }
57
58
        $this->cache->save(
59
            $this->key,
60
            static function (CacheItemInterface $item) use ($callback) {
61
                if (null !== $callback) {
62
                    $callback($item);
63
                }
64
65
                return \ob_get_flush();
66
            },
67
            $beta
68
        );
69
70
        $this->cache = null;
71
    }
72
}
73