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
|
|
|
|