1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* This file is part of michael-rubel/laravel-value-objects. (https://github.com/michael-rubel/laravel-value-objects) |
7
|
|
|
* |
8
|
|
|
* @link https://github.com/michael-rubel/laravel-value-objects for the canonical source repository |
9
|
|
|
* @copyright Copyright (c) 2022 Michael Rubél. (https://github.com/michael-rubel/) |
10
|
|
|
* @license https://raw.githubusercontent.com/michael-rubel/laravel-value-objects/main/LICENSE.md MIT |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace MichaelRubel\ValueObjects\Collection\Primitive; |
14
|
|
|
|
15
|
|
|
use Illuminate\Support\Stringable; |
16
|
|
|
use InvalidArgumentException; |
17
|
|
|
use MichaelRubel\ValueObjects\ValueObject; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* "Text" object presenting the stringable values. |
21
|
|
|
* |
22
|
|
|
* @author Michael Rubél <[email protected]> |
23
|
|
|
* |
24
|
|
|
* @template TKey of array-key |
25
|
|
|
* @template TValue |
26
|
|
|
* |
27
|
|
|
* @method static static make(string|Stringable $value) |
28
|
|
|
* @method static static from(string|Stringable $value) |
29
|
|
|
* @method static static makeOrNull(string|Stringable|null $value) |
30
|
|
|
* |
31
|
|
|
* @extends ValueObject<TKey, TValue> |
32
|
|
|
*/ |
33
|
|
|
class Text extends ValueObject |
34
|
|
|
{ |
35
|
|
|
/** |
36
|
|
|
* @var string|Stringable |
37
|
|
|
*/ |
38
|
|
|
protected string|Stringable $value; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Create a new instance of the value object. |
42
|
|
|
* |
43
|
|
|
* @param string|Stringable $value |
44
|
|
|
*/ |
45
|
105 |
|
public function __construct(string|Stringable $value) |
46
|
|
|
{ |
47
|
105 |
|
if (isset($this->value)) { |
48
|
6 |
|
throw new InvalidArgumentException(static::IMMUTABLE_MESSAGE); |
49
|
|
|
} |
50
|
|
|
|
51
|
105 |
|
$this->value = $value; |
52
|
|
|
|
53
|
105 |
|
if (isset($this->before)) { |
54
|
26 |
|
($this->before)(); |
55
|
|
|
} |
56
|
|
|
|
57
|
105 |
|
$this->validate(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Get the object value. |
62
|
|
|
* |
63
|
|
|
* @return string |
64
|
|
|
*/ |
65
|
110 |
|
public function value(): string |
66
|
|
|
{ |
67
|
110 |
|
return (string) $this->value; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Validate the value object data. |
72
|
|
|
* |
73
|
|
|
* @return void |
74
|
|
|
*/ |
75
|
42 |
|
protected function validate(): void |
76
|
|
|
{ |
77
|
42 |
|
if ($this->value() === '') { |
78
|
6 |
|
throw new InvalidArgumentException('Text cannot be empty.'); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|