Completed
Push — master ( aca90e...8ef0e7 )
by Alejandro
10s
created

ValidationException::formMessagesToString()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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