Total Complexity | 10 |
Total Lines | 63 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | <?php |
||
10 | class Imei implements Model, JsonSerializable |
||
11 | { |
||
12 | const IMEI_LENGTH = 15; |
||
13 | |||
14 | /** |
||
15 | * @var string |
||
16 | */ |
||
17 | private $imei; |
||
18 | |||
19 | /** |
||
20 | * @param string $imei |
||
21 | * |
||
22 | * @throws InvalidArgumentException |
||
23 | */ |
||
24 | public function __construct(string $imei) |
||
25 | { |
||
26 | if (!$this->isLuhn($imei) || strlen($imei) !== self::IMEI_LENGTH) { |
||
27 | throw new InvalidArgumentException("IMEI number is not valid."); |
||
28 | } |
||
29 | |||
30 | $this->imei = $imei; |
||
31 | } |
||
32 | |||
33 | /** |
||
34 | * @return string |
||
35 | */ |
||
36 | public function getImei(): string |
||
37 | { |
||
38 | return $this->imei; |
||
39 | } |
||
40 | |||
41 | public function jsonSerialize(): array |
||
42 | { |
||
43 | return [ |
||
44 | 'imei' => $this->getImei() |
||
45 | ]; |
||
46 | } |
||
47 | |||
48 | public function __toString(): string |
||
49 | { |
||
50 | return $this->getImei(); |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @param string $imei |
||
55 | * |
||
56 | * @return bool |
||
57 | */ |
||
58 | private function isLuhn(string $imei): bool |
||
59 | { |
||
60 | $str = ''; |
||
61 | foreach (str_split(strrev((string)$imei)) as $i => $d) { |
||
62 | $str .= $i % 2 !== 0 ? $d * 2 : $d; |
||
63 | } |
||
64 | |||
65 | return array_sum(str_split($str)) % 10 === 0; |
||
66 | } |
||
67 | |||
68 | public static function createFromHex(string $hexData): Imei |
||
73 | } |
||
74 | } |
||
75 |