Passed
Push — master ( 1f40d1...402cf9 )
by Alexander
02:17
created

convertDefinitionToString()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 35
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 7

Importance

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