Passed
Pull Request — master (#406)
by Théo
02:37
created

CompactorProxy   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 10
dl 0
loc 46
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A compact() 0 3 1
A unserialize() 0 3 1
A __construct() 0 8 1
A serialize() 0 3 1
A getCompactor() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Compactor;
16
17
use Closure;
18
use function Opis\Closure\serialize as opis_serialize;
19
use function Opis\Closure\unserialize as opis_unserialize;
20
use Serializable;
21
22
final class CompactorProxy implements Compactor, Serializable
23
{
24
    private $createCompactor;
25
    private $compactor;
26
27
    public function __construct(Closure $createCompactor)
28
    {
29
        $this->createCompactor = $createCompactor;
30
31
        // Instantiate a compactor instead of lazily instantiate it in order to ensure the factory closure is correct
32
        // and that the created object is of the created type. Since compactors instantiation should be fast, this is
33
        // a minimal overhead which is an acceptable trade-off for providing early errors.
34
        $this->getCompactor();
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function compact(string $file, string $contents): string
41
    {
42
        return $this->getCompactor()->compact($file, $contents);
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function serialize(): string
49
    {
50
        return opis_serialize($this->createCompactor);
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function unserialize($serialized): void
57
    {
58
        $this->createCompactor = opis_unserialize($serialized);
59
    }
60
61
    public function getCompactor(): Compactor
62
    {
63
        if (null === $this->compactor) {
64
            $this->compactor = ($this->createCompactor)();
65
        }
66
67
        return $this->compactor;
68
    }
69
}
70