AllowedSubsetConstraint::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 4
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 4
loc 4
rs 10
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace Weew\Validator\Constraints;
4
5
use Weew\Validator\IConstraint;
6
use Weew\Validator\IValidationData;
7
8
/**
9
 * Check that elements within array are allowed.
10
 */
11 View Code Duplication
class AllowedSubsetConstraint implements IConstraint {
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
12
    /**
13
     * @var array
14
     */
15
    protected $allowed;
16
17
    /**
18
     * @var string
19
     */
20
    protected $message;
21
22
    /**
23
     * @param array $allowed
24
     * @param string $message
25
     */
26
    public function __construct(array $allowed, $message = null) {
27
        $this->allowed = $allowed;
28
        $this->message = $message;
29
    }
30
31
    /**
32
     * @param $value
33
     * @param IValidationData $data
34
     *
35
     * @return bool
36
     */
37
    public function check($value, IValidationData $data = null) {
38
        if (is_array($value)) {
39
            foreach ($value as $item) {
40
                if ( ! array_contains($this->allowed, $item)) {
41
                    return false;
42
                }
43
            }
44
45
            return true;
46
        }
47
48
        return false;
49
    }
50
51
    /**
52
     * @return string
53
     */
54
    public function getMessage() {
55
        if ($this->message !== null) {
56
            return $this->message;
57
        }
58
59
        return s(
60
            'Contains not allowed values, allowed values are "%s".',
61
            implode(', ', $this->allowed)
62
        );
63
    }
64
65
    /**
66
     * @return array
67
     */
68
    public function getOptions() {
69
        return [
70
            'allowed' => $this->allowed,
71
        ];
72
    }
73
}
74