IsEntityMatchValidator::isMatch()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 1
b 0
f 1
nc 2
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasDoctrine\Validator;
6
7
use Laminas\Validator\Exception\RuntimeException;
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