SetStateEncoder::encode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Frostaly\VarExporter\Encoders;
6
7
use Frostaly\VarExporter\Contracts\EncoderInterface;
8
use Frostaly\VarExporter\Encoder;
9
use Frostaly\VarExporter\Exception\OverriddenPropertyException;
10
11
class SetStateEncoder implements EncoderInterface
12
{
13
    /**
14
     * {@inheritDoc}
15
     */
16
    public function supports(mixed $value): bool
17
    {
18
        return is_object($value)
19
            && method_exists($value, '__set_state');
20
    }
21
22
    /**
23
     * {@inheritDoc}
24
     *
25
     * @param object $object
26
     */
27
    public function encode(Encoder $encoder, mixed $object): array
28
    {
29
        return [
30
            $object::class . '::__set_state(',
31
            ...$encoder->encode($this->extract($object)),
32
            ')',
33
        ];
34
    }
35
36
    /**
37
     * Extract object properties as an associative array.
38
     */
39
    protected static function extract(object $object): array
40
    {
41
        $properties = (array) $object;
42
        foreach ($properties as $key => $value) {
43
            if (is_int($pos = strrpos((string) $key, "\0"))) {
44
                $name = substr((string) $key, $pos + 1);
45
                if (array_key_exists($name, $properties)) {
46
                    throw new OverriddenPropertyException($object::class, $name);
47
                }
48
                $properties[$name] = $value;
49
                unset($properties[$key]);
50
            }
51
        }
52
        return $properties;
53
    }
54
}
55