BadCommandRequestException   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A convertViolationsToStrings() 0 10 2
A withViolations() 0 6 1
A getErrors() 0 3 1
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\ApiBundle\Exception;
20
21
use Symfony\Component\Validator\ConstraintViolationInterface;
22
use Symfony\Component\Validator\ConstraintViolationListInterface;
23
use Throwable;
24
25
/**
26
 * Thrown when a client provided invalid command input to the application.
27
 */
28
class BadCommandRequestException extends RuntimeException
29
{
30
    public static function withViolations(string $message, ConstraintViolationListInterface $violations): self
31
    {
32
        $violationStrings = self::convertViolationsToStrings($violations);
33
        $message = sprintf('%s (%s)', $message, implode('; ', $violationStrings));
34
35
        return new self($violationStrings, $message);
36
    }
37
38
    /**
39
     * @return string[]
40
     */
41
    private static function convertViolationsToStrings(ConstraintViolationListInterface $violations): array
42
    {
43
        $violationStrings = [];
44
45
        foreach ($violations as $violation) {
46
            /** @var ConstraintViolationInterface $violation */
47
            $violationStrings[] = sprintf('%s: %s', $violation->getPropertyPath(), $violation->getMessage());
48
        }
49
50
        return $violationStrings;
51
    }
52
53
    public function __construct(
54
        private readonly array $errors,
55
        string $message = 'JSON could not be reconstituted into valid object.',
56
        int $code = 0,
57
        ?Throwable $previous = null,
58
    ) {
59
        parent::__construct($message, $code, $previous);
60
    }
61
62
    /**
63
     * @return string[]
64
     */
65
    public function getErrors(): array
66
    {
67
        return $this->errors;
68
    }
69
}
70