convertDefinitionToString()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 7

Importance

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