Completed
Push — master ( 4bc86f...82906d )
by Hannes
02:44
created

Line::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace byrokrat\autogiro;
6
7
/**
8
 * Line value object
9
 */
10
class Line
11
{
12
    /**
13
     * @var string Line content
14
     */
15
    private $string;
16
17
    /**
18
     * @var string Current string encoding
19
     */
20
    private $encoding;
21
22
    /**
23
     * Construct line
24
     *
25
     * @param string $string   Should not contain new line characters
26
     * @param string $encoding Will be autodetected if missing
27
     */
28
    public function __construct(string $string, string $encoding = '')
29
    {
30
        $this->string = $string;
31
        $this->encoding = $encoding ?: mb_detect_encoding($string);
32
    }
33
34
    /**
35
     * Get part of line
36
     *
37
     * @todo The returned part should always be encoded in utf8
38
     */
39
    public function substr(int $startPos, int $length): string
40
    {
41
        return substr($this->string, $startPos, $length);
42
    }
43
44
    /**
45
     * Get line content
46
     */
47
    public function __toString(): string
48
    {
49
        return $this->string;
50
    }
51
52
    /**
53
     * Get line encoding
54
     */
55
    public function getEncoding(): string
56
    {
57
        return $this->encoding;
58
    }
59
60
    /**
61
     * Get a new line object converted to encoding
62
     */
63
    public function convertTo(string $encoding): Line
64
    {
65
        return new static(
66
            mb_convert_encoding($this->string, $encoding, $this->getEncoding()),
67
            $encoding
68
        );
69
    }
70
71
    /**
72
     * Check if line starts with string
73
     */
74
    public function startsWith(string $string): bool
75
    {
76
        return 0 === strpos($this->string, $string);
77
    }
78
79
    /**
80
     * Check if line contains string
81
     */
82
    public function contains(string $string): bool
83
    {
84
        return false !== strpos($this->string, $string);
85
    }
86
87
    /**
88
     * Check if line matches regular expression
89
     */
90
    public function matches(string $regexp): bool
91
    {
92
        return !!preg_match($regexp, $this->string);
93
    }
94
95
    /**
96
     * Capture parts of line using regular expression
97
     *
98
     * @return string[] The captured parts
99
     */
100
    public function capture(string $regexp): array
101
    {
102
        preg_match($regexp, $this->string, $matches);
103
        return (array)$matches;
104
    }
105
106
    /**
107
     * Check if line is empty
108
     */
109
    public function isEmpty(): bool
110
    {
111
        return !trim($this->string);
112
    }
113
}
114