Passed
Branch feature/first-release (f081ea)
by Andrea Marco
10:18
created

Source::config()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
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 352
    final public function __construct(protected mixed $source, Config $config = null)
66
    {
67 352
        $this->config = $config ?: new Config();
68
    }
69
70
    /**
71
     * Retrieve the size of the JSON source and cache it
72
     *
73
     * @return int|null
74
     */
75 329
    public function size(): ?int
76
    {
77 329
        if (!$this->sizeWasSet) {
78 329
            $this->size = $this->calculateSize();
79 329
            $this->sizeWasSet = true;
80
        }
81
82 329
        return $this->size;
83
    }
84
}
85