Completed
Pull Request — master (#430)
by Anton
04:25
created

InRule::getDescription()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Validator\Rule;
12
13
/**
14
 * Check for value in set
15
 *
16
 * @package Bluz\Validator\Rule
17
 */
18
class InRule extends AbstractRule
19
{
20
    /**
21
     * @var string|array haystack for search, can be array or string
22
     */
23
    protected $haystack;
24
25
    /**
26
     * Setup validation rule
27
     *
28
     * @param string|array $haystack
29
     */
30 21
    public function __construct($haystack)
31
    {
32 21
        $this->haystack = $haystack;
33 21
    }
34
35
    /**
36
     * Check input data
37
     *
38
     * @param  string $input
39
     *
40
     * @return bool
41
     */
42 11
    public function validate($input): bool
43
    {
44 11
        if (is_array($this->haystack)) {
45 5
            return in_array($input, $this->haystack, false);
46
        }
47
48 6
        if (!is_string($this->haystack)) {
49 1
            return false;
50
        }
51
52 5
        if (empty($input)) {
53 1
            return false;
54
        }
55
56 4
        $enc = mb_detect_encoding($input);
57
58 4
        return mb_stripos($this->haystack, $input, 0, $enc) !== false;
59
    }
60
61
    /**
62
     * Get error template
63
     *
64
     * @return string
65
     */
66 21
    public function getDescription() : string
67
    {
68 21
        if (is_array($this->haystack)) {
69 10
            $haystack = implode(', ', $this->haystack);
70
        } else {
71 11
            $haystack = $this->haystack;
72
        }
73 21
        return __('must be in %s', $haystack);
74
    }
75
}
76