Passed
Push — main ( 4c0730...701096 )
by Michael
01:05 queued 13s
created

Phone::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
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 17
    public function __construct(protected string|Stringable $value)
39
    {
40 17
        parent::__construct($this->value);
41
42 11
        $this->validate();
43
    }
44
45
    /**
46
     * Get the sanitized phone number.
47
     *
48
     * @return string
49
     */
50 17
    public function sanitized(): string
51
    {
52 17
        return str($this->value())
53 17
            ->replace(' ', '')
54 17
            ->replaceMatches('/\p{C}+/u', '')
55 17
            ->value();
56
    }
57
58
    /**
59
     * Validate the phone number.
60
     *
61
     * @return void
62
     */
63 17
    protected function validate(): void
64
    {
65 17
        if (! preg_match('/^[+]?[0-9 ]{5,15}$/', $this->sanitized())) {
66 6
            throw ValidationException::withMessages([__('Your phone number is invalid.')]);
67
        }
68
    }
69
}
70