Encoder::encode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Frostaly\VarExporter;
6
7
use Frostaly\VarExporter\Contracts\EncoderInterface;
8
use Frostaly\VarExporter\Exception\CircularReferenceException;
9
use Frostaly\VarExporter\Exception\TypeNotSupportedException;
10
use WeakMap;
11
12
final class Encoder
13
{
14
    /**
15
     * @var WeakMap<object,array|int>
16
     */
17
    private WeakMap $encoded;
18
19
    /**
20
     * @param EncoderInterface[] $encoders
21
     */
22
    public function __construct(
23
        private array $encoders,
24
    ) {
25
        $this->encoded = new WeakMap();
26
    }
27
28
    /**
29
     * Encode the value to a formatted array of PHP code.
30
     */
31
    public function encode(mixed $value): array
32
    {
33
        return is_object($value)
34
            ? $this->encodeObject($value)
35
            : $this->tryEncode($value);
36
    }
37
38
    /**
39
     * Detect circular references and cache the encoded object.
40
     */
41
    private function encodeObject(object $object): array
42
    {
43
        if (!is_array($this->encoded[$object] ??= 0)) {
44
            if (is_int($this->encoded[$object]) && $this->encoded[$object]++) {
45
                throw new CircularReferenceException($object::class);
46
            }
47
            $this->encoded[$object] = $this->tryEncode($object);
48
        }
49
        return $this->encoded[$object]; /** @phpstan-ignore-line */
50
    }
51
52
    /**
53
     * Try encoding the value using the registered encoders.
54
     */
55
    private function tryEncode(mixed $value): array
56
    {
57
        foreach ($this->encoders as $encoder) {
58
            if ($encoder->supports($value)) {
59
                return $encoder->encode($this, $value);
60
            }
61
        }
62
        throw new TypeNotSupportedException($value);
63
    }
64
}
65