InvalidParameterException::withViolations()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 12
cts 12
cp 1
rs 9.584
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\Exception;
13
14
use FOS\RestBundle\Controller\Annotations\ParamInterface;
15
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
16
use Symfony\Component\Validator\ConstraintViolationListInterface;
17
18
class InvalidParameterException extends BadRequestHttpException
19
{
20
    private $parameter;
21
    private $violations;
22
23 1
    public function getParameter()
24
    {
25 1
        return $this->parameter;
26
    }
27
28 1
    public function getViolations()
29
    {
30 1
        return $this->violations;
31
    }
32
33 2
    public static function withViolations(ParamInterface $parameter, ConstraintViolationListInterface $violations)
34
    {
35 2
        $message = '';
36
37 2
        foreach ($violations as $key => $violation) {
38 1
            if ($key > 0) {
39 1
                $message .= "\n";
40
            }
41
42 1
            $invalidValue = $violation->getInvalidValue();
43
44 1
            $message .= sprintf(
45 1
                'Parameter "%s" of value "%s" violated a constraint "%s"',
46 1
                $parameter->getName(),
47 1
                is_scalar($invalidValue) ? $invalidValue : var_export($invalidValue, true),
48 1
                $violation->getMessage()
49
            );
50
        }
51
52 2
        return self::withViolationsAndMessage($parameter, $violations, $message);
53
    }
54
55
    /**
56
     * Do not use this method. It will be removed in 2.0.
57
     *
58
     * @internal
59
     */
60 2
    public static function withViolationsAndMessage(ParamInterface $parameter, ConstraintViolationListInterface $violations, string $message): self
61
    {
62 2
        $exception = new self($message);
63 2
        $exception->parameter = $parameter;
64 2
        $exception->violations = $violations;
65
66 2
        return $exception;
67
    }
68
}
69