Passed
Push — master ( de3d61...be839c )
by Alec
13:42 queued 13s
created

AnsiColorParser::assertValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace AlecRabbit\Spinner\Extras\Color;
7
8
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
9
use AlecRabbit\Spinner\Extras\Color\Contract\IColor;
10
use AlecRabbit\Spinner\Extras\Contract\IAnsiColorParser;
11
use AlecRabbit\Spinner\Extras\Contract\IHexColorToAnsiCodeConverter;
12
13
final class AnsiColorParser implements IAnsiColorParser
14
{
15
    private const FORMAT = '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/';
16
17
    public function __construct(
18
        protected IHexColorToAnsiCodeConverter $converter,
19
    ) {
20
    }
21
22
    public function parseColor(IColor|null|string $color): string
23
    {
24
        if ($color === '' || $color === null) {
25
            return '';
26
        }
27
28
        self::assertValid($color);
29
30
        return $this->converter->convert($color);
0 ignored issues
show
Bug introduced by
It seems like $color can also be of type AlecRabbit\Spinner\Extras\Color\Contract\IColor; however, parameter $color of AlecRabbit\Spinner\Extra...odeConverter::convert() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

30
        return $this->converter->convert(/** @scrutinizer ignore-type */ $color);
Loading history...
31
    }
32
33
    private static function assertValid(IColor|string $color): void
34
    {
35
        match (true) {
36
            self::correctFormat($color) => null,
37
            default => throw new InvalidArgumentException(
38
                sprintf('Invalid color format: "%s".,', $color)
0 ignored issues
show
Bug introduced by
It seems like $color can also be of type AlecRabbit\Spinner\Extras\Color\Contract\IColor; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

38
                sprintf('Invalid color format: "%s".,', /** @scrutinizer ignore-type */ $color)
Loading history...
39
            ),
40
        };
41
    }
42
43
    private static function correctFormat(IColor|string $color): bool
44
    {
45
        if ($color instanceof IColor) {
46
            return false; // not supported yet
47
        }
48
        return (bool)preg_match(self::FORMAT, $color);
49
    }
50
}
51