Passed
Push — main ( 701096...f61da3 )
by Michael
04:14 queued 47s
created

Phone::trim()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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