Passed
Pull Request — master (#34)
by Aleksei
02:10
created

__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Middleware\Dispatcher\Exception;
6
7
use InvalidArgumentException;
8
9
use function get_class;
10
use function is_array;
11
use function is_object;
12
use function is_string;
13
14
final class InvalidMiddlewareDefinitionException extends InvalidArgumentException
15
{
16
    private const DEFAULT_MESSAGE = 'Parameter should be either PSR middleware class name or a callable.';
17
18
    /**
19
     * @param mixed $middlewareDefinition
20
     */
21 16
    public function __construct($middlewareDefinition, string $message = self::DEFAULT_MESSAGE)
22
    {
23 16
        $definitionString = $this->convertDefinitionToString($middlewareDefinition);
24 16
        if ($definitionString !== null) {
25 12
            $message .= ' Got ' . $definitionString . '.';
26
        }
27
28 16
        parent::__construct($message);
29 16
    }
30
31
    /**
32
     * @param mixed $middlewareDefinition
33
     */
34 16
    private function convertDefinitionToString($middlewareDefinition): ?string
35
    {
36 16
        if (is_object($middlewareDefinition)) {
37 3
            return 'an instance of "' . get_class($middlewareDefinition) . '"';
38
        }
39
40 13
        if (is_string($middlewareDefinition)) {
41 3
            return '"' . $middlewareDefinition . '"';
42
        }
43
44 10
        if (is_array($middlewareDefinition)) {
45 9
            $items = $middlewareDefinition;
46 9
            foreach ($middlewareDefinition as $item) {
47 9
                if (!is_string($item)) {
48 3
                    return null;
49
                }
50
            }
51 6
            array_walk(
52 6
                $items,
53
                /**
54
                 * @param mixed $item
55
                 * @psalm-param array-key $key
56
                 */
57 6
                static function (&$item, $key) {
58 6
                    $item = (string)$item;
59 6
                    $item = '"' . $item . '"';
60 6
                    if (is_string($key)) {
61 2
                        $item = '"' . $key . '" => ' . $item;
62
                    }
63 6
                }
64
            );
65 6
            return '[' . implode(', ', $items) . ']';
66
        }
67
68 1
        return null;
69
    }
70
}
71