Passed
Pull Request — master (#5)
by Alex
12:40
created

IsEntityMatchValidator::isValid()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 10
c 1
b 0
f 1
nc 3
nop 2
dl 0
loc 20
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasDoctrine\Validator;
6
7
use Laminas\Validator\Exception\RuntimeException;
0 ignored issues
show
Bug introduced by
The type Laminas\Validator\Exception\RuntimeException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
final class IsEntityMatchValidator extends AbstractEntityValidator
10
{
11
    public const NO_MATCH = 'no_match';
12
13
    /**
14
     * @var array<string, string>
15
     */
16
    protected array $messageTemplates = [
17
        self::CRITERIA_EMPTY => 'No criteria was provided',
18
        self::NO_MATCH => 'Value could not be matched to an existing entity',
19
    ];
20
21
    /**
22
     * @param mixed $value
23
     * @param array<string, mixed> $context
24
     *
25
     * @throws RuntimeException
26
     */
27
    public function isValid(mixed $value, array $context = []): bool
28
    {
29
        // If we have just one field to check, try for a match with the provided value
30
        // This prevents issues is the context contains the same named field
31
        if (
32
            isset($this->fieldNames[0])
33
            && 1 === count($this->fieldNames)
34
            && $this->isMatch([$this->fieldNames[0] => $value])
35
        ) {
36
            return true;
37
        }
38
39
        // Fallback to allowing for $context
40
        $criteria = $this->getMatchCriteria($value, $context);
41
        if (empty($criteria)) {
42
            $this->error(self::CRITERIA_EMPTY);
43
            return false;
44
        }
45
46
        return $this->isMatch($criteria);
47
    }
48
49
    /**
50
     * @param array<string, mixed> $criteria
51
     *
52
     * @throws RuntimeException
53
     */
54
    private function isMatch(array $criteria): bool
55
    {
56
        $match = $this->getMatchedEntity($criteria);
57
        if (null !== $match) {
58
            return true;
59
        }
60
61
        $this->error(self::NO_MATCH);
62
        return false;
63
    }
64
}
65