|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace MichaelRubel\ValueObjects; |
|
6
|
|
|
|
|
7
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
|
8
|
|
|
use Illuminate\Support\Traits\Conditionable; |
|
9
|
|
|
use Illuminate\Support\Traits\Macroable; |
|
10
|
|
|
|
|
11
|
|
|
abstract class ValueObject implements Arrayable |
|
12
|
|
|
{ |
|
13
|
|
|
use Macroable, Conditionable; |
|
|
|
|
|
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Get the object value. |
|
17
|
|
|
* |
|
18
|
|
|
* @return mixed |
|
19
|
|
|
*/ |
|
20
|
|
|
abstract public function value(); |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Convenient method to create a value object statically. |
|
24
|
|
|
* |
|
25
|
|
|
* @param mixed $values |
|
26
|
|
|
* |
|
27
|
|
|
* @return static |
|
28
|
|
|
*/ |
|
29
|
7 |
|
public static function make(mixed ...$values): static |
|
30
|
|
|
{ |
|
31
|
7 |
|
return new static(...$values); |
|
|
|
|
|
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Check if objects are instances of same class |
|
36
|
|
|
* and share the same properties and values. |
|
37
|
|
|
* |
|
38
|
|
|
* @param ValueObject $object |
|
39
|
|
|
* |
|
40
|
|
|
* @return bool |
|
41
|
|
|
*/ |
|
42
|
1 |
|
public function equals(ValueObject $object): bool |
|
43
|
|
|
{ |
|
44
|
1 |
|
return $this == $object; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Get the length of the value. |
|
49
|
|
|
* |
|
50
|
|
|
* @return int |
|
51
|
|
|
*/ |
|
52
|
1 |
|
public function length(): int |
|
53
|
|
|
{ |
|
54
|
1 |
|
return strlen((string) $this->value()); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Make sure value object is immutable. |
|
59
|
|
|
* |
|
60
|
|
|
* @param string $name |
|
61
|
|
|
* @param mixed $value |
|
62
|
|
|
* |
|
63
|
|
|
* @return void |
|
64
|
|
|
*/ |
|
65
|
4 |
|
public function __set(string $name, mixed $value): void |
|
66
|
|
|
{ |
|
67
|
4 |
|
throw new \InvalidArgumentException('Value objects are immutable. You cannot modify properties. Create a new object instead.'); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Get an array representation of the value object. |
|
72
|
|
|
* |
|
73
|
|
|
* @return array |
|
74
|
|
|
*/ |
|
75
|
4 |
|
public function toArray(): array |
|
76
|
|
|
{ |
|
77
|
4 |
|
return (array) $this->value(); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* Get string representation of the value object. |
|
82
|
|
|
* |
|
83
|
|
|
* @return string |
|
84
|
|
|
*/ |
|
85
|
14 |
|
public function __toString(): string |
|
86
|
|
|
{ |
|
87
|
14 |
|
return (string) $this->value(); |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|