Completed
Push — master ( 27235c...6df80b )
by Beñat
02:06
created

Phone::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Shared Kernel library.
5
 *
6
 * Copyright (c) 2016 LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LIN3S\SharedKernel\Domain\Model;
13
14
/**
15
 * @author Beñat Espiña <[email protected]>
16
 */
17
class Phone
18
{
19
    private $phone;
20
21
    public function __construct($phone)
22
    {
23
        $this->phone = $phone ? $this->cleanPhone($phone) : '';
24
    }
25
26
    public function equals(Phone $phone)
27
    {
28
        return strtolower((string)$this) === strtolower((string)$phone);
29
    }
30
31
    public function __toString()
32
    {
33
        return (string)$this->phone;
34
    }
35
36
    private function cleanPhone($phone)
37
    {
38
        $absolute = $phone[0] === '+';
39
        $numbers = preg_replace('/\D/', '', $phone);
40
41
        if (!$numbers) {
42
            throw new PhoneFormatInvalidException();
43
        }
44
45
        // special logic for russian local phone notation
46
        if ($numbers[0] === '8' && !$absolute && strlen($numbers) == 11) {
47
            $numbers[0] = '7';
48
        }
49
50
        if ($numbers[0] !== '7' || strlen($numbers) != 11) {
51
            throw new PhoneFormatInvalidException();
52
        }
53
54
        return $numbers;
55
    }
56
}
57