1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace DavidGarcia\ValueObject\Primitive; |
6
|
|
|
|
7
|
|
|
use DavidGarcia\ValueObject\Exception\InvalidValueException; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
use Webmozart\Assert\Assert; |
10
|
|
|
|
11
|
|
|
class StringValue extends AbstractValue |
12
|
|
|
{ |
13
|
|
|
private string $value; |
14
|
|
|
|
15
|
8 |
|
private function __construct(string $value, bool $cache) |
16
|
|
|
{ |
17
|
8 |
|
$this->value = $value; |
18
|
|
|
|
19
|
8 |
|
if ($cache) { |
20
|
2 |
|
self::cacheStore($value, $this); |
21
|
|
|
} |
22
|
8 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Exposes the stored string value. |
26
|
|
|
* |
27
|
|
|
* @return string The string value |
28
|
|
|
*/ |
29
|
4 |
|
public function __toString(): string |
30
|
|
|
{ |
31
|
4 |
|
return $this->getValue(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Creates the value object. |
36
|
|
|
* |
37
|
|
|
* @param string $value The string value |
38
|
|
|
* @param bool $cache Cache the value so we reuse the same object |
39
|
|
|
* |
40
|
|
|
* @throws InvalidValueException The initial validation of the value has failed |
41
|
|
|
* |
42
|
|
|
* @return StringValue The value object |
43
|
|
|
*/ |
44
|
13 |
|
public static function create(string $value, bool $cache = false): self |
45
|
|
|
{ |
46
|
13 |
|
$trimmed = trim($value); |
47
|
|
|
|
48
|
|
|
try { |
49
|
13 |
|
Assert::stringNotEmpty($trimmed, 'String value cannot be empty'); |
50
|
1 |
|
} catch (InvalidArgumentException $exception) { |
51
|
1 |
|
throw new InvalidValueException($exception->getMessage(), $exception); |
52
|
|
|
} |
53
|
|
|
|
54
|
12 |
|
$object = $cache ? parent::cacheRetrieve($trimmed) : null; |
55
|
|
|
|
56
|
12 |
|
if (null === $object) { |
57
|
8 |
|
$object = new self($trimmed, $cache); |
58
|
|
|
} |
59
|
|
|
|
60
|
12 |
|
return $object; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Exposes the stored string value. |
65
|
|
|
* |
66
|
|
|
* @return string The string value |
67
|
|
|
*/ |
68
|
8 |
|
public function getValue(): string |
69
|
|
|
{ |
70
|
8 |
|
return $this->value; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Compares if the value of a given object matches with this object. |
75
|
|
|
* |
76
|
|
|
* @param StringValue $object The input object to be compared |
77
|
|
|
* |
78
|
|
|
* @return bool TRUE if the value matches; FALSE otherwise |
79
|
|
|
*/ |
80
|
4 |
|
public function equals(StringValue $object): bool |
81
|
|
|
{ |
82
|
4 |
|
return $this->getValue() === $object->getValue(); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|