UnicodeString::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 4
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\Lexer\Runtime\Unicode;
6
7
use IntlChar;
8
9
use function array_map;
10
use function chr;
11
use function implode;
12
13
/**
14
 * @psalm-immutable
15
 */
16
final class UnicodeString implements StringInterface
17
{
18
19
    private const MIN_CHAR = 0x00;
20
21
    private const MAX_ASCII_CHAR = 0x7F;
22
23
    private const MAX_UNICODE_CHAR = 0x10FFFF;
24
25
    /**
26
     * @var int[]
27
     * @psalm-var array<int, int>
28
     */
29
    private $characters = [];
30
31 13
    public function __construct(int ...$characters)
32
    {
33 13
        foreach ($characters as $character) {
34 10
            if ($character > self::MAX_UNICODE_CHAR || $character < self::MIN_CHAR) {
35 2
                throw new Exception\NonUnicodeCharacterException($character);
36
            }
37 8
            $this->characters[] = $character;
38
        }
39 11
    }
40
41
    /**
42
     * @return int[]
43
     * @psalm-return array<int, int>
44
     * @psalm-pure
45
     */
46 3
    public function asCharacters(): array
47
    {
48 3
        return $this->characters;
49
    }
50
51
    /**
52
     * @return string
53
     * @psalm-pure
54
     */
55 4
    public function asAscii(): string
56
    {
57 4
        return implode(array_map([$this, 'asciiChr'], $this->characters));
58
    }
59
60
    /**
61
     * @param int $character
62
     * @return string
63
     * @psalm-pure
64
     */
65 3
    private function asciiChr(int $character): string
66
    {
67 3
        if ($character > self::MAX_ASCII_CHAR) {
68 1
            throw new Exception\NonAsciiCharacterException($character);
69
        }
70
71 2
        return chr($character);
72
    }
73
74
    /**
75
     * @return string
76
     * @psalm-pure
77
     */
78 4
    public function asUtf8(): string
79
    {
80 4
        return implode('', array_map([IntlChar::class, 'chr'], $this->characters));
81
    }
82
}
83