Passed
Branch master (e894a3)
by Melech
15:39 queued 01:19
created

SerializedObject   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 9
dl 0
loc 64
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Valkyrja\Type\BuiltIn;
15
16
use JsonException;
17
use Valkyrja\Type\BuiltIn\Contract\SerializedObject as Contract;
18
use Valkyrja\Type\BuiltIn\Support\Obj as Helper;
19
use Valkyrja\Type\Type;
20
21
use function is_string;
22
23
/**
24
 * Class SerializedObject.
25
 *
26
 * @author Melech Mizrachi
27
 *
28
 * @extends Type<object>
29
 */
30
class SerializedObject extends Type implements Contract
31
{
32
    /**
33
     * Allowed classes for serialization of object type properties.
34
     *
35
     *  <code>
36
     *       [
37
     *           // An array of allowed classes for serialization for object types
38
     *           ClassName::class,
39
     *       ]
40
     *  </code>
41
     *
42
     * @return class-string[]
43
     */
44
    protected const array ALLOWED_CLASSES = [];
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting '=' on line 44 at column 26
Loading history...
45
46
    public function __construct(object $subject)
47
    {
48
        $this->subject = $subject;
49
    }
50
51
    /**
52
     * @inheritDoc
53
     *
54
     * @throws JsonException
55
     */
56
    public static function fromValue(mixed $value): static
57
    {
58
        if (is_string($value)) {
59
            /** @var class-string[] $allowedClasses */
60
            $allowedClasses = static::ALLOWED_CLASSES;
61
62
            return new static(Helper::fromSerializedString($value, $allowedClasses));
63
        }
64
65
        return new static((object) $value);
66
    }
67
68
    /**
69
     * @inheritDoc
70
     */
71
    public function asValue(): object
72
    {
73
        return $this->subject;
74
    }
75
76
    /**
77
     * @inheritDoc
78
     *
79
     * @throws JsonException
80
     */
81
    public function asFlatValue(): string
82
    {
83
        return Helper::toSerializedString($this->subject);
84
    }
85
86
    /**
87
     * @inheritDoc
88
     *
89
     * @throws JsonException
90
     */
91
    public function modify(callable $closure): static
92
    {
93
        return static::fromValue($closure(clone $this->subject));
94
    }
95
}
96