-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHasImmutability.php
More file actions
59 lines (53 loc) · 1.52 KB
/
HasImmutability.php
File metadata and controls
59 lines (53 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
declare(strict_types=1);
namespace ComplexHeart\Domain\Model\Traits;
use ComplexHeart\Domain\Model\Errors\ImmutabilityError;
/**
* Trait HasImmutability
*
* Non-canonical way to enforce immutability of an object. Will be
* removed in the future as is not an intuitive and explicit way to
* have immutability in PHP. For PHP >= 8.1 use readonly keyword.
*
* @author Unay Santisteban <usantisteban@othercode.io>
* @package ComplexHeart\Domain\Model\Traits
* @deprecated Will be removed in future versions.
*/
trait HasImmutability
{
/**
* Enforces the immutability by blocking any attempts of update any property.
*
* @param string $name
* @param mixed $_
* @return void
*/
final public function __set(string $name, mixed $_): void
{
$class = static::class;
throw new ImmutabilityError("Cannot modify property $name from immutable $class object.");
}
/**
* Accessor for the protected or private properties.
*
* @param string $name
* @return mixed
*/
final public function __get(string $name): mixed
{
return method_exists($this, 'get')
? $this->get($name)
: $this->{$name};
}
/**
* Creates a new instance overriding the given values.
*
* @param array<string, mixed> $overrides
*
* @return static
*/
protected function withOverrides(array $overrides): static
{
return self::make(...array_values(array_merge($this->values(), $overrides)));
}
}