Source::size()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 3
b 0
f 0
nc 2
nop 0
dl 0
loc 8
ccs 5
cts 5
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 cached size of the JSON source.
18
     *
19
     * @var int|null
20
     */
21
    protected ?int $size;
22
23
    /**
24
     * Whether the JSON size has already been calculated.
25
     * Avoid re-calculations when the size is NULL (not computable).
26
     *
27
     * @var bool
28
     */
29
    protected bool $sizeWasSet = false;
30
31
    /**
32
     * Retrieve the JSON fragments
33
     *
34
     * @return Traversable<int, string>
35
     */
36
    abstract public function getIterator(): Traversable;
37
38
    /**
39
     * Determine whether the JSON source can be handled
40
     *
41
     * @return bool
42
     */
43
    abstract public function matches(): bool;
44
45
    /**
46
     * Retrieve the calculated size of the JSON source
47
     *
48
     * @return int|null
49
     */
50
    abstract protected function calculateSize(): ?int;
51
52
    /**
53
     * Instantiate the class.
54
     *
55
     * @param mixed $source
56
     * @param Config $config
57
     */
58 373
    final public function __construct(
59
        protected readonly mixed $source,
60
        protected readonly Config $config = new Config(),
61
    ) {
62 373
    }
63
64
    /**
65
     * Retrieve the size of the JSON source and cache it
66
     *
67
     * @return int|null
68
     */
69 341
    public function size(): ?int
70
    {
71 341
        if (!$this->sizeWasSet) {
72 341
            $this->size = $this->calculateSize();
73 341
            $this->sizeWasSet = true;
74
        }
75
76 341
        return $this->size;
77
    }
78
}
79