Passed
Push — master ( 010340...caf629 )
by Sebastian
03:00
created

StringCompare::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 3
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Linna Filter
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2018, Sebastian Rapetti
8
 * @license http://opensource.org/licenses/MIT MIT License
9
 */
10
declare(strict_types = 1);
11
12
namespace Linna\Filter\Rules;
13
14
use UnexpectedValueException;
15
16
/**
17
 * Compare two strings using >, <, >=, <=, = operators.
18
 */
19
class StringCompare extends AbstractString
20
{
21
    /**
22
     * @var array Arguments expected.
23
     */
24
    private $arguments = ['string', 'string'];
0 ignored issues
show
introduced by
The private property $arguments is not used, and could be removed.
Loading history...
25
26
    /**
27
     * Validate.
28
     *
29
     * @param mixed $received
30
     * @param string $operator
31
     * @param mixed $compare
32
     * @return bool
33
     */
34 20
    public function validate($received, string $operator, $compare): bool
35
    {
36 20
        if (!is_string($received)) {
37 1
            return true;
38
        }
39
40 19
        if ($this->switchOperator($operator, $received, $compare)) {
41 8
            return false;
42
        }
43
44 10
        return true;
45
    }
46
47
    /**
48
     * Perform correct operation from passed operator.
49
     *
50
     * @param string $operator
51
     * @param mixed $strReceived
52
     * @param mixed $strCompare
53
     *
54
     * @return bool
55
     *
56
     * @throws UnexpectedValueException if unknown operator is provided.
57
     */
58 19
    private function switchOperator(string $operator, &$strReceived, &$strCompare): bool
59
    {
60
        switch ($operator) {
61 19
            case 'len>': //greater than
62 3
                return strlen($strReceived) > strlen($strCompare);
63 16
            case 'len<': //less than
64 3
                return strlen($strReceived) < strlen($strCompare);
65 13
            case 'len>=': //greater than or equal
66 3
                return strlen($strReceived) >= strlen($strCompare);
67 10
            case 'len<=': //less than or equal
68 3
                return strlen($strReceived) <= strlen($strCompare);
69 7
            case 'len=': //equal
70 3
                return strlen($strReceived) === strlen($strCompare);
71 4
            case '=': //equal
72 3
                return $strReceived === $strCompare;
73
            default:
74 1
                throw new UnexpectedValueException("Unknown comparson operator ({$operator}). Permitted >, <, >=, <=, =");
75
        }
76
    }
77
}
78