Completed
Pull Request — master (#554)
by Alejandro
11:37 queued 08:50
created

ValidationException::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 10
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 12
rs 9.9332
ccs 11
cts 11
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Exception;
6
7
use Fig\Http\Message\StatusCodeInterface;
8
use Throwable;
9
use Zend\InputFilter\InputFilterInterface;
10
use Zend\ProblemDetails\Exception\CommonProblemDetailsExceptionTrait;
11
use Zend\ProblemDetails\Exception\ProblemDetailsExceptionInterface;
12
13
use function Functional\reduce_left;
14
use function is_array;
15
use function print_r;
16
use function sprintf;
17
18
use const PHP_EOL;
19
20
class ValidationException extends InvalidArgumentException implements ProblemDetailsExceptionInterface
21
{
22
    use CommonProblemDetailsExceptionTrait;
23
24
    private const TITLE = 'Invalid data';
25
    private const TYPE = 'INVALID_ARGUMENT';
26
27 7
    public static function fromInputFilter(InputFilterInterface $inputFilter, ?Throwable $prev = null): self
28
    {
29 7
        return static::fromArray($inputFilter->getMessages(), $prev);
30
    }
31
32 14
    public static function fromArray(array $invalidData, ?Throwable $prev = null): self
33
    {
34 14
        $status = StatusCodeInterface::STATUS_BAD_REQUEST;
35 14
        $e = new self('Provided data is not valid', $status, $prev);
36
37 14
        $e->detail = $e->getMessage();
38 14
        $e->title = self::TITLE;
39 14
        $e->type = self::TYPE;
40 14
        $e->status = StatusCodeInterface::STATUS_BAD_REQUEST;
41 14
        $e->additional = ['invalidElements' => $invalidData];
42
43 14
        return $e;
44
    }
45
46 1
    public function getInvalidElements(): array
47
    {
48 1
        return $this->additional['invalidElements'];
49
    }
50
51 1
    public function __toString(): string
52
    {
53 1
        return sprintf(
54 1
            '%s %s in %s:%s%s%sStack trace:%s%s',
55 1
            __CLASS__,
56 1
            $this->getMessage(),
57 1
            $this->getFile(),
58 1
            $this->getLine(),
59 1
            $this->invalidElementsToString(),
60 1
            PHP_EOL,
61 1
            PHP_EOL,
62 1
            $this->getTraceAsString()
63
        );
64
    }
65
66 1
    private function invalidElementsToString(): string
67
    {
68
        return reduce_left($this->getInvalidElements(), function ($messageSet, string $name, $_, string $acc) {
69 1
            return $acc . sprintf(
70 1
                "\n    '%s' => %s",
71 1
                $name,
72 1
                is_array($messageSet) ? print_r($messageSet, true) : $messageSet
73
            );
74 1
        }, '');
75
    }
76
}
77