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

InRule::getDescription()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 9
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
    public function __construct($haystack)
31
    {
32
        $this->haystack = $haystack;
33
    }
34
35
    /**
36
     * Check input data
37
     *
38
     * @param  string $input
39
     *
40
     * @return bool
41
     */
42
    public function validate($input): bool
43
    {
44
        if (is_array($this->haystack)) {
45
            return in_array($input, $this->haystack, false);
46
        }
47
48
        if (!is_string($this->haystack)) {
49
            return false;
50
        }
51
52
        if (empty($input)) {
53
            return false;
54
        }
55
56
        $enc = mb_detect_encoding($input);
57
58
        return mb_stripos($this->haystack, $input, 0, $enc) !== false;
59
    }
60
61
    /**
62
     * Get error template
63
     *
64
     * @return string
65
     */
66
    public function getDescription() : string
67
    {
68
        if (is_array($this->haystack)) {
69
            $haystack = implode(', ', $this->haystack);
70
        } else {
71
            $haystack = $this->haystack;
72
        }
73
        return __('must be in %s', $haystack);
74
    }
75
}
76