|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Brazanation\Documents; |
|
4
|
|
|
|
|
5
|
|
|
use Brazanation\Documents\Exception\InvalidDocument as InvalidArgumentException; |
|
6
|
|
|
|
|
7
|
|
|
final class Cnpj implements DocumentInterface |
|
8
|
|
|
{ |
|
9
|
|
|
const LENGTH = 14; |
|
10
|
|
|
|
|
11
|
|
|
const LABEL = 'CNPJ'; |
|
12
|
|
|
|
|
13
|
|
|
const REGEX = '/^([\d]{2,3})([\d]{3})([\d]{3})([\d]{4})([\d]{2})$/'; |
|
14
|
|
|
|
|
15
|
|
|
const FORMAT_REGEX = '/^[\d]{2,3}\.[\d]{3}\.[\d]{3}\/[\d]{4}-[\d]{2}$/'; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var string |
|
19
|
|
|
*/ |
|
20
|
|
|
private $cnpj; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Cnpj constructor. |
|
24
|
|
|
* |
|
25
|
|
|
* @param string $cnpj Only accept numbers |
|
26
|
|
|
*/ |
|
27
|
11 |
|
public function __construct($cnpj) |
|
28
|
|
|
{ |
|
29
|
11 |
|
$cnpj = preg_replace('/\D/', '', $cnpj); |
|
30
|
11 |
|
$this->validate($cnpj); |
|
31
|
4 |
|
$this->cnpj = $cnpj; |
|
32
|
4 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Check if CNPJ is not empty and is a valid number. |
|
36
|
|
|
* |
|
37
|
|
|
* @param string $number |
|
38
|
|
|
* |
|
39
|
|
|
* @throws InvalidArgumentException when CNPJ is empty |
|
40
|
|
|
* @throws InvalidArgumentException when CNPJ is not valid number |
|
41
|
|
|
*/ |
|
42
|
11 |
|
private function validate($number) |
|
43
|
|
|
{ |
|
44
|
11 |
|
if (empty($number)) { |
|
45
|
3 |
|
throw InvalidArgumentException::notEmpty(static::LABEL); |
|
46
|
|
|
} |
|
47
|
8 |
|
if (!$this->isValidCV($number)) { |
|
48
|
4 |
|
throw InvalidArgumentException::isNotValid(static::LABEL, $number); |
|
49
|
|
|
} |
|
50
|
4 |
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Validates cnpj is a valid number. |
|
54
|
|
|
* |
|
55
|
|
|
* @param string $number A number to be validate. |
|
56
|
|
|
* |
|
57
|
|
|
* @return bool Returns true if it is a valid number, otherwise false. |
|
58
|
|
|
*/ |
|
59
|
8 |
|
private function isValidCV($number) |
|
60
|
|
|
{ |
|
61
|
8 |
|
if (strlen($number) != static::LENGTH) { |
|
62
|
1 |
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
7 |
|
if (preg_match("/^{$number[0]}{" . static::LENGTH . '}$/', $number)) { |
|
66
|
1 |
|
return false; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
6 |
|
return (new Modulo11(2, 9))->validate($number); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* Formats CNPJ number |
|
74
|
|
|
* |
|
75
|
|
|
* @return string Returns formatted number, such as: 00.000.000/0000-00 |
|
76
|
|
|
*/ |
|
77
|
2 |
|
public function format() |
|
78
|
|
|
{ |
|
79
|
2 |
|
return preg_replace(static::REGEX, '$1.$2.$3/$4-$5', $this->cnpj); |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
/** |
|
83
|
|
|
* Returns the CNPJ number |
|
84
|
|
|
* |
|
85
|
|
|
* @return string |
|
86
|
|
|
*/ |
|
87
|
2 |
|
public function __toString() |
|
88
|
|
|
{ |
|
89
|
2 |
|
return $this->cnpj; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|