Completed
Push — master ( 038254...115ca0 )
by Alejandro
06:27
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 12
    public function __construct(
23
        string $message = '',
24
        array $invalidElements = [],
25
        int $code = 0,
26
        ?Throwable $previous = null
27
    ) {
28 12
        $this->invalidElements = $invalidElements;
29 12
        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 7
    private static function fromArray(array $invalidData, ?Throwable $prev = null): self
38
    {
39 7
        return new self(
40 7
            sprintf(
41 7
                'Provided data is not valid. These are the messages:%s%s%s',
42 7
                PHP_EOL,
43 7
                self::formMessagesToString($invalidData),
44 7
                PHP_EOL
45
            ),
46 7
            $invalidData,
47 7
            -1,
48 7
            $prev
49
        );
50
    }
51
52 7
    private static function formMessagesToString(array $messages = []): string
53
    {
54
        return reduce_left($messages, function ($messageSet, $name, $_, string $acc) {
55 7
            return $acc . sprintf(
56 7
                "\n    '%s' => %s",
57 7
                $name,
58 7
                is_array($messageSet) ? print_r($messageSet, true) : $messageSet
59
            );
60 7
        }, '');
61
    }
62
63 6
    public function getInvalidElements(): array
64
    {
65 6
        return $this->invalidElements;
66
    }
67
}
68