Passed
Pull Request — master (#448)
by Alejandro
06:34
created

ValidationException   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 19
dl 0
loc 49
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A formMessagesToString() 0 9 2
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 Functional\reduce_left;
10
use function is_array;
11
use function print_r;
12
use function sprintf;
13
14
use const PHP_EOL;
15
16
class ValidationException extends RuntimeException
17
{
18
    /** @var array */
19
    private $invalidElements;
20
21 9
    public function __construct(
22
        string $message = '',
23
        array $invalidElements = [],
24
        int $code = 0,
25
        ?Throwable $previous = null
26
    ) {
27 9
        $this->invalidElements = $invalidElements;
28 9
        parent::__construct($message, $code, $previous);
29
    }
30
31 4
    public static function fromInputFilter(InputFilterInterface $inputFilter, ?Throwable $prev = null): self
32
    {
33 4
        return static::fromArray($inputFilter->getMessages(), $prev);
34
    }
35
36 4
    private static function fromArray(array $invalidData, ?Throwable $prev = null): self
37
    {
38 4
        return new self(
39 4
            sprintf(
40 4
                'Provided data is not valid. These are the messages:%s%s%s',
41 4
                PHP_EOL,
42 4
                self::formMessagesToString($invalidData),
43 4
                PHP_EOL
44
            ),
45
            $invalidData,
46 4
            -1,
47
            $prev
48
        );
49
    }
50
51 4
    private static function formMessagesToString(array $messages = []): string
52
    {
53
        return reduce_left($messages, function ($messageSet, $name, $_, string $acc) {
54 4
            return $acc . sprintf(
55 4
                "\n    '%s' => %s",
56 4
                $name,
57 4
                is_array($messageSet) ? print_r($messageSet, true) : $messageSet
58
            );
59 4
        }, '');
60
    }
61
62 6
    public function getInvalidElements(): array
63
    {
64 6
        return $this->invalidElements;
65
    }
66
}
67