Text::is()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Parser\Parsers;
4
5
use Stratadox\Parser\Parser;
6
use Stratadox\Parser\Result;
7
use Stratadox\Parser\Results\Error;
8
use Stratadox\Parser\Results\Ok;
9
use function str_starts_with;
10
use function strlen;
11
use function substr;
12
13
/**
14
 * Text
15
 *
16
 * Matches the predefined string, or returns an error result indicating where the input starts becoming
17
 * different. Multibyte safe, somehow, I think. If not, let me know.
18
 */
19
final class Text extends Parser
20
{
21
    private int $length;
22
23
    public function __construct(private string $text)
24
    {
25
        $this->length = strlen($this->text);
26
    }
27
28
    public static function is(string $text): Parser
29
    {
30
        return new self($text);
31
    }
32
33
    public function parse(string $input): Result
34
    {
35
        if (str_starts_with($input, $this->text)) {
36
            return Ok::with($this->text, substr($input, $this->length));
37
        }
38
        return Error::in(substr($input, strspn($input ^ $this->text, "\0")));
39
    }
40
}
41