Completed
Pull Request — master (#554)
by Alejandro
05:47
created

ValidationException::invalidElementsToString()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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