Passed
Push — master ( 130df2...007dfb )
by Alexis
10:23
created

ValidationErrorsConstraint::toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Liip/FunctionalTestBundle
7
 *
8
 * (c) Lukas Kahwe Smith <[email protected]>
9
 *
10
 * This source file is subject to the MIT license that is bundled
11
 * with this source code in the file LICENSE.
12
 */
13
14
namespace Liip\FunctionalTestBundle\Test;
15
16
use PHPUnit\Framework\Constraint\Constraint;
17
use PHPUnit\Framework\ExpectationFailedException;
18
use Symfony\Component\Validator\ConstraintViolationList;
19
20
class ValidationErrorsConstraint extends Constraint
21
{
22
    private $expect;
23
24
    /**
25
     * ValidationErrorsConstraint constructor.
26
     *
27
     * @param array $expect
28
     */
29 3
    public function __construct(array $expect)
30
    {
31 3
        $this->expect = $expect;
32 3
        sort($this->expect);
33 3
    }
34
35
    /**
36
     * @param ConstraintViolationList $other
37
     * @param string                  $description
38
     * @param bool                    $returnResult
39
     *
40
     * @return mixed
41
     */
42 3
    public function evaluate($other, $description = '', $returnResult = false): ?bool
43
    {
44 3
        $actual = [];
45
46 3
        foreach ($other as $error) {
47 3
            $actual[$error->getPropertyPath()][] = $error->getMessage();
48
        }
49
50 3
        ksort($actual);
51
52 3
        if (array_keys($actual) === $this->expect) {
53 2
            return true;
54
        }
55
56 1
        if ($returnResult) {
57
            return false;
58
        }
59
60
        // Generate failure message
61 1
        $mismatchedKeys = array_merge(
62 1
            array_diff(array_keys($actual), $this->expect),
63 1
            array_diff($this->expect, array_keys($actual))
64
        );
65 1
        sort($mismatchedKeys);
66
67 1
        $lines = [];
68
69 1
        foreach ($mismatchedKeys as $key) {
70 1
            if (isset($actual[$key])) {
71 1
                foreach ($actual[$key] as $unexpectedErrorMessage) {
72 1
                    $lines[] = '+ '.$key.' ('.$unexpectedErrorMessage.')';
73
                }
74
            } else {
75 1
                $lines[] = '- '.$key;
76
            }
77
        }
78
79 1
        throw new ExpectationFailedException($description."\n".implode("\n", $lines));
80
    }
81
82
    /**
83
     * Returns a string representation of the object.
84
     *
85
     * @return string
86
     */
87
    public function toString(): string
88
    {
89
        return 'validation errors match';
90
    }
91
}
92