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

ValidationException   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
dl 0
loc 69
rs 10
c 0
b 0
f 0
ccs 24
cts 26
cp 0.9231
wmc 7
lcom 1
cbo 2

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A fromInputFilter() 0 4 1
A fromArray() 0 14 1
A formMessagesToString() 0 13 3
A getInvalidElements() 0 4 1
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