FaceValidator   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 12
dl 0
loc 61
c 0
b 0
f 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A extractPath() 0 11 4
A evaluateConditions() 0 7 3
A validate() 0 21 4
1
<?php
2
3
namespace XSolve\FaceValidatorBundle\Validator\Constraints;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
8
use XSolve\FaceValidatorBundle\Detector\FaceDetector;
9
use XSolve\FaceValidatorBundle\Exception\NoFaceDetectedException;
10
use XSolve\FaceValidatorBundle\Result\FaceDetectionResult;
11
use XSolve\FaceValidatorBundle\Validator\Specification\FaceValidationSpecification;
12
13
class FaceValidator extends ConstraintValidator
14
{
15
    /**
16
     * @var FaceDetector
17
     */
18
    private $faceDetector;
19
20
    /**
21
     * @var FaceValidationSpecification[]
22
     */
23
    private $conditions;
24
25
    public function __construct(FaceDetector $faceDetector, array $conditions)
26
    {
27
        $this->faceDetector = $faceDetector;
28
        $this->conditions = $conditions;
29
    }
30
31
    public function validate($value, Constraint $constraint)
32
    {
33
        if (!$constraint instanceof Face) {
34
            throw new UnexpectedTypeException($constraint, Face::class);
35
        }
36
37
        $path = $this->extractPath($value);
38
39
        if (null === $path) {
40
            return;
41
        }
42
43
        try {
44
            $detectionResult = $this->faceDetector->detect($path);
45
        } catch (NoFaceDetectedException $e) {
46
            $this->context->addViolation($constraint->noFaceMessage);
47
48
            return;
49
        }
50
51
        $this->evaluateConditions($detectionResult, $constraint);
52
    }
53
54
    private function extractPath($value)
55
    {
56
        if (is_string($value)) {
57
            return $value;
58
        }
59
60
        if ($value instanceof \SplFileInfo && $value->isFile()) {
61
            return $value->getRealPath();
62
        }
63
64
        return null;
65
    }
66
67
    private function evaluateConditions(FaceDetectionResult $result, Face $constraint)
68
    {
69
        foreach ($this->conditions as $condition) {
70
            $evaluation = $condition->evaluate($result, $constraint);
71
72
            if (!$evaluation->isSuccessful()) {
73
                $this->context->addViolation($evaluation->getMessage());
74
            }
75
        }
76
    }
77
}
78