Url::__invoke()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 17
nc 4
nop 2
dl 0
loc 28
ccs 14
cts 14
cp 1
crap 7
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Validate;
4
5
class Url implements ValidateRuleInterface
6
{
7
    /**
8
     * Validates the value as a URL.
9
     *
10
     * The value must match a generic URL format; for example, ``http://example.com``, ``mms://example.org``, and so on.
11
     *
12
     * @param object $subject The subject to be filtered.
13
     * @param string $field The subject field name.
14
     *
15
     * @return bool True if valid, false if not.
16
     */
17 42
    public function __invoke($subject, string $field): bool
18
    {
19 42
        $value = $subject->$field;
20 42
        if (!is_scalar($value)) {
21 3
            return false;
22
        }
23
24
        // first, make sure there are no invalid chars, list from ext/filter
25
        $other = "$-_.+"        // safe
26
            . "!*'(),"       // extra
27
            . "{}|\\^~[]`"   // national
28
            . "<>#%\""       // punctuation
29 39
            . ";/?:@&=";     // reserved
30
31 39
        $valid = 'a-zA-Z0-9' . preg_quote($other, '/');
32 39
        $clean = preg_replace("/[^$valid]/", '', $value);
33 39
        if ($value != $clean) {
34 12
            return false;
35
        }
36
37
        // now make sure it parses as a URL with scheme and host
38 27
        $result = @parse_url($value);
39 27
        if (empty($result['scheme']) || trim($result['scheme']) == '' ||
40 27
            empty($result['host'])   || trim($result['host']) == '') {
41 9
            return false;
42
        }
43
44 18
        return true;
45
    }
46
}
47