IsNotEntityValidator::isValid()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 22
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 33
rs 9.568
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasEntity\Validator;
6
7
use Arp\LaminasEntity\Constant\IsNotEntityError;
8
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...
9
10
/**
11
 * @author  Alex Patterson <[email protected]>
12
 * @package Validator
13
 */
14
class IsNotEntityValidator extends AbstractValidator
15
{
16
    /**
17
     * @var array
18
     */
19
    private $messageTemplates = [
0 ignored issues
show
introduced by
The private property $messageTemplates is not used, and could be removed.
Loading history...
20
        IsNotEntityError::FOUND
21
            => 'An entity of type \'%entityName%\' was found matching \'%value%\'.',
22
    ];
23
24
    /**
25
     * @param mixed $value
26
     * @param array $context
27
     *
28
     * @return bool
29
     *
30
     * @throws RuntimeException
31
     */
32
    public function isValid($value, array $context = []): bool
33
    {
34
        $criteria = $this->getFilterCriteria($value, $context);
35
        $entityName = $this->repository->getClassName();
36
37
        if (empty($criteria)) {
38
            throw new RuntimeException(
39
                sprintf(
40
                    'Unable to perform validation for entity \'%s\' in \'%s\' with an empty criteria',
41
                    $entityName,
42
                    static::class
43
                )
44
            );
45
        }
46
47
        try {
48
            $entity = $this->repository->findOneBy($criteria);
49
50
            if (null === $entity) {
51
                return true;
52
            }
53
54
            $this->error(IsNotEntityError::FOUND, $criteria);
55
            return false;
56
        } catch (\Throwable $e) {
57
            throw new RuntimeException(
58
                sprintf(
59
                    'Failed to perform the validation for entity of type \'%s\': %s',
60
                    $entityName,
61
                    $e->getMessage()
62
                ),
63
                $e->getCode(),
64
                $e
65
            );
66
        }
67
    }
68
}
69