Cidr::check()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 24
ccs 5
cts 5
cp 1
crap 5
rs 9.6111
1
<?php
2
3
/**
4
 * This file is part of Dimtrovich/Validation.
5
 *
6
 * (c) 2023 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\Validation\Rules;
13
14
class Cidr extends AbstractRule
15
{
16
    /**
17
     * Check if the value is a Classless Inter-Domain Routing notation (CIDR).
18
     *
19
     * @see https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
20
     * @credit <a href="https://github.com/Intervention/validation">Intervention/validation - \Intervention\Validation\Rules\Cidr</a>
21
     *
22
     * @param mixed $value
23
     */
24
    public function check($value): bool
25
    {
26
        // A CIDR should consist of an IP part and a mask bit number delimited by a `/`
27
28
        // split by the slash that should be there
29 2
        $parts = explode('/', $value, 2);
30
        // we should have 2 parts (the ip and mask)
31
        if (count($parts) !== 2) {
32 2
            return false;
33
        }
34
35
        // validate the ip part
36
        if (filter_var($parts[0], FILTER_VALIDATE_IP) === false) {
37 2
            return false;
38
        }
39
40
        // check the mask part
41
        // first of all, this should be an integer
42
        if (filter_var($parts[1], FILTER_VALIDATE_INT) === false) {
43 2
            return false;
44
        }
45
46
        // and it should be between 0 and 32 inclusive
47 2
        return ! ($parts[1] < 0 || $parts[1] > 32);
48
    }
49
}
50