Passed
Pull Request — master (#14)
by Sergei
06:49
created

convertDefinitionToString()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.0796

Importance

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