Completed
Push — master ( b2545f...e44389 )
by Divine Niiquaye
02:25
created

OutputHelper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of BiuradPHP 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 null|FastCache */
29
    private $cache;
30
31
    /** @var string */
32
    private $key;
33
34
    /**
35
     * @param FastCache $cache
36
     * @param mixed $key
37
     */
38
    public function __construct(FastCache $cache, $key)
39
    {
40
        $this->cache = $cache;
41
        $this->key   = $key;
42
        \ob_start();
43
    }
44
45
    /**
46
     * Stops and saves the cache.
47
     *
48
     * @param callable   $callback
49
     * @param null|float $beta
50
     *
51
     * @throws InvalidArgumentException
52
     */
53
    public function end(callable $callback = null, ?float $beta = null): void
54
    {
55
        if (null === $this->cache) {
56
            throw new InvalidArgumentException('Output cache has already been saved.');
57
        }
58
        $this->cache->save(
59
            $this->key,
60
            function (CacheItemInterface $item, bool $save) use ($callback) {
61
                if (null !== $callback) {
62
                    $callback(...[&$item, &$save]);
63
                }
64
65
                return \ob_get_flush();
66
            },
67
            $beta
68
        );
69
70
        $this->cache = null;
71
    }
72
}
73