Passed
Push — master ( b9b37f...a27485 )
by Alec
02:44 queued 14s
created

CharFrameCollectionRenderer::createFromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
// 10.03.23
5
6
namespace AlecRabbit\Spinner\Core;
7
8
use AlecRabbit\Spinner\Contract\IFrame;
9
use AlecRabbit\Spinner\Core\A\AFrameCollectionRenderer;
10
use AlecRabbit\Spinner\Core\Factory\FrameFactory;
11
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
12
use Stringable;
13
14
use function is_string;
15
16
final class CharFrameCollectionRenderer extends AFrameCollectionRenderer
17
{
18
    /**
19
     * @throws InvalidArgumentException
20
     */
21
    protected function createFromArray(array $entry): IFrame
22
    {
23
        self::assertEntryArray($entry);
24
        return
25
            FrameFactory::create(
26
                (string)$entry[0],
27
                self::refineNullableInt($entry[1])
28
            );
29
    }
30
31
    /**
32
     * @throws InvalidArgumentException
33
     */
34
    protected static function assertEntryArray(array $entry): void
35
    {
36
        // array size should be 2
37
        $size = count($entry);
38
        if (2 !== $size) {
39
            throw new InvalidArgumentException(
40
                sprintf(
41
                    'Entry array size should be 2, %d given',
42
                    $size
43
                )
44
            );
45
        }
46
        // first element should be string
47
        $first = $entry[0];
48
        if (!is_string($first) && !($first instanceof Stringable)) {
49
            throw new InvalidArgumentException(
50
                sprintf(
51
                    'First element of entry array should be string|Stringable, %s given.',
52
                    get_debug_type($first)
53
                )
54
            );
55
        }
56
        // second element should be non-negative integer
57
        $second = $entry[1] ?? null;
58
        if (null === $second) {
59
            return;
60
        }
61
        if (!is_int($second) || $second < 0) {
62
            throw new InvalidArgumentException(
63
                sprintf(
64
                    'Second element of entry array should be non-negative integer, %s given.',
65
                    get_debug_type($second)
66
                )
67
            );
68
        }
69
    }
70
71
    protected static function refineNullableInt(mixed $value): ?int
72
    {
73
        if (null === $value) {
74
            return null;
75
        }
76
        return (int)$value;
77
    }
78
79
    protected function createFrame(int|string $entry): IFrame
80
    {
81
        return FrameFactory::create((string)$entry, WidthDeterminer::determine((string)$entry));
82
    }
83
}
84