Passed
Branch feature/first-release (4f172a)
by Andrea Marco
01:55
created

Source::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Cerbero\JsonParser\Sources;
4
5
use Cerbero\JsonParser\ValueObjects\Config;
6
use IteratorAggregate;
7
use Traversable;
8
9
/**
10
 * The JSON source.
11
 *
12
 * @implements IteratorAggregate<int, string>
13
 */
14
abstract class Source implements IteratorAggregate
15
{
16
    /**
17
     * The configuration.
18
     *
19
     * @var Config
20
     */
21
    protected Config $config;
22
23
    /**
24
     * The cached size of the JSON source.
25
     *
26
     * @var int|null
27
     */
28
    protected ?int $size;
29
30
    /**
31
     * Whether the JSON size has already been calculated.
32
     * Avoid re-calculations when the size is NULL (not computable).
33
     *
34
     * @var bool
35
     */
36
    protected bool $sizeWasSet = false;
37
38
    /**
39
     * Retrieve the JSON fragments
40
     *
41
     * @return Traversable<int, string>
42
     */
43
    abstract public function getIterator(): Traversable;
44
45
    /**
46
     * Determine whether the JSON source can be handled
47
     *
48
     * @return bool
49
     */
50
    abstract public function matches(): bool;
51
52
    /**
53
     * Retrieve the calculated size of the JSON source
54
     *
55
     * @return int|null
56
     */
57
    abstract protected function calculateSize(): ?int;
58
59
    /**
60
     * Enforce the factory method to instantiate the class.
61
     *
62
     * @param mixed $source
63
     * @param Config|null $config
64
     */
65 342
    final public function __construct(protected mixed $source, Config $config = null)
66
    {
67 342
        $this->config = $config ?: new Config();
68
    }
69
70
    /**
71
     * Retrieve the underlying configuration
72
     *
73
     * @return Config
74
     */
75
    public function config(): Config
76
    {
77
        return $this->config;
78
    }
79
80
    /**
81
     * Retrieve the size of the JSON source and cache it
82
     *
83
     * @return int|null
84
     */
85 315
    public function size(): ?int
86
    {
87 315
        if (!$this->sizeWasSet) {
88 315
            $this->size = $this->calculateSize();
89 315
            $this->sizeWasSet = true;
90
        }
91
92 315
        return $this->size;
93
    }
94
}
95