Completed
Push — master ( 8a6d54...cd96dc )
by Philip
02:15
created

Contains::adjustCaseInsensitive()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.2
cc 4
eloc 5
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Valdi package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Valdi\Validator;
13
14
use Valdi\ValidationException;
15
16
/**
17
 * Validator for strings containing a substring.
18
 */
19
class Contains implements ValidatorInterface {
20
21
    /**
22
     * Throws an exception if the parameters don't fullfill the expected
23
     * parameter count.
24
     *
25
     * @param integer $parameterAmount
26
     * the amount of expected parameters
27
     */
28
    protected function validateParameterCount($parameterAmount) {
29
        if ($parameterAmount < 1) {
30
            throw new ValidationException('"contains" expects at least 1 parameter.');
31
        }
32
    }
33
34
    /**
35
     * Adjusts value and parameters to be case insensitive if the second
36
     * parameter says so or is not given.
37
     *
38
     * @param mixed $value
39
     * the value to validate
40
     *
41
     * @param array $parameters
42
     * the other parameters the validator need
43
     */
44
    protected function adjustCaseInsensitive(&$value, &$parameters) {
45
        $parameterAmount = count($parameters);
46
        if ($parameterAmount == 1 || $parameterAmount > 1 && $parameters[1]) {
47
            $parameters[0] = strtolower($parameters[0]);
48
            $value         = strtolower($value);
49
        }
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function isValid($value, array $parameters) {
56
        $parameterAmount = count($parameters);
57
58
        $this->validateParameterCount($parameterAmount);
59
        $this->adjustCaseInsensitive($value, $parameters);
60
61
        return in_array($value, array('', null), true) || strpos($value, $parameters[0]) !== false;
62
    }
63
}
64