|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of michael-rubel/laravel-value-objects. (https://github.com/michael-rubel/laravel-value-objects) |
|
5
|
|
|
* |
|
6
|
|
|
* @link https://github.com/michael-rubel/laravel-value-objects for the canonical source repository |
|
7
|
|
|
* @copyright Copyright (c) 2022 Michael Rubél. (https://github.com/michael-rubel/) |
|
8
|
|
|
* @license https://raw.githubusercontent.com/michael-rubel/laravel-value-objects/main/LICENSE.md MIT |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace MichaelRubel\ValueObjects\Collection\Complex; |
|
12
|
|
|
|
|
13
|
|
|
use Illuminate\Support\Stringable; |
|
14
|
|
|
use Illuminate\Validation\ValidationException; |
|
15
|
|
|
use MichaelRubel\ValueObjects\Collection\Primitive\Text; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* "Phone" object that represents a telephone number. |
|
19
|
|
|
* |
|
20
|
|
|
* @author Michael Rubél <[email protected]> |
|
21
|
|
|
* |
|
22
|
|
|
* @template TKey of array-key |
|
23
|
|
|
* @template TValue |
|
24
|
|
|
* |
|
25
|
|
|
* @method static static make(string|Stringable $value) |
|
26
|
|
|
* @method static static from(string|Stringable $value) |
|
27
|
|
|
* @method static static makeOrNull(string|Stringable|null $value) |
|
28
|
|
|
* |
|
29
|
|
|
* @extends Text<TKey, TValue> |
|
30
|
|
|
*/ |
|
31
|
|
|
class Phone extends Text |
|
32
|
|
|
{ |
|
33
|
|
|
/** |
|
34
|
|
|
* Create a new instance of the value object. |
|
35
|
|
|
* |
|
36
|
|
|
* @param string|Stringable $value |
|
37
|
|
|
*/ |
|
38
|
21 |
|
public function __construct(string|Stringable $value) |
|
39
|
|
|
{ |
|
40
|
21 |
|
parent::__construct($value); |
|
41
|
|
|
|
|
42
|
14 |
|
$this->trim(); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Get the sanitized phone number. |
|
47
|
|
|
* |
|
48
|
|
|
* @return string |
|
49
|
|
|
*/ |
|
50
|
21 |
|
public function sanitized(): string |
|
51
|
|
|
{ |
|
52
|
21 |
|
return str($this->value()) |
|
53
|
21 |
|
->replaceMatches('/\p{C}+/u', '') |
|
54
|
21 |
|
->replace(' ', '') |
|
55
|
21 |
|
->value(); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Validate the phone number. |
|
60
|
|
|
* |
|
61
|
|
|
* @return void |
|
62
|
|
|
*/ |
|
63
|
21 |
|
protected function validate(): void |
|
64
|
|
|
{ |
|
65
|
21 |
|
if (! preg_match('/^[+]?[0-9 ]{5,15}$/', $this->sanitized())) { |
|
66
|
7 |
|
throw ValidationException::withMessages(['Your phone number is invalid.']); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Trim the value. |
|
72
|
|
|
* |
|
73
|
|
|
* @return void |
|
74
|
|
|
*/ |
|
75
|
16 |
|
protected function trim(): void |
|
76
|
|
|
{ |
|
77
|
16 |
|
$this->value = trim($this->value()); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|