Completed
Push — master ( b0bb77...848444 )
by Alejandro
19s queued 11s
created

ValidationException   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 92%

Importance

Changes 0
Metric Value
wmc 7
eloc 20
dl 0
loc 65
rs 10
c 0
b 0
f 0
ccs 23
cts 25
cp 0.92

5 Methods

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