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