Debian Codegraph @

vendor/ipl/validator/src/CidrValidator.php

raw
1 <?php
2
3 namespace ipl\Validator;
4
5 use ipl\Stdlib\Str;
6
7 /**
8 * Validate a classless inter-domain routing (CIDR)
9 */
10 class CidrValidator extends BaseValidator
11 {
12 /**
13 * Check whether the value is a valid CIDR notation string
14 *
15 * @param string $value
16 *
17 * @return bool
18 */
19 public function isValid($value): bool
20 {
21 $this->clearMessages();
22
23 $pieces = Str::trimSplit($value, '/');
24 if (count($pieces) !== 2) {
25 $this->addMessage(sprintf(
26 $this->translate('CIDR "%s" does not conform to the required format $address/$prefix'),
27 $value
28 ));
29
30 return false;
31 }
32
33 list($address, $prefix) = $pieces;
34 $inaddr = @inet_pton($address);
35 if ($inaddr === false) {
36 $this->addMessage(sprintf($this->translate('CIDR "%s" contains an invalid address'), $value));
37
38 return false;
39 }
40
41 if (! is_numeric($prefix)) {
42 $this->addMessage(sprintf($this->translate('Prefix of CIDR "%s" must be a number'), $value));
43
44 return false;
45 }
46
47 $isIPv6 = isset($inaddr[4]);
48 $prefix = (int) $prefix;
49 $maxPrefixLength = $isIPv6 ? 128 : 32;
50
51 if ($prefix < 0 || $prefix > $maxPrefixLength) {
52 $this->addMessage(sprintf(
53 $this->translate('Prefix length of CIDR "%s" must be between 0 and %d for IPv%d addresses'),
54 $value,
55 $maxPrefixLength,
56 $isIPv6 ? 6 : 4
57 ));
58
59 return false;
60 }
61
62 return true;
63 }
64 }