StringIteratorAggregate::getIterator()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
nc 4
nop 0
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
c 2
b 0
f 0
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 */
7
8
declare(strict_types=1);
9
10
namespace loophp\iterators;
11
12
use Generator;
13
use IteratorAggregate;
14
15
/**
16
 * @implements IteratorAggregate<int, string>
17
 */
18
final class StringIteratorAggregate implements IteratorAggregate
19
{
20 4
    public function __construct(private string $data, private string $delimiter = '')
21
    {
22 4
    }
23
24
    /**
25
     * @return Generator<int, string>
26
     */
27 4
    public function getIterator(): Generator
28
    {
29 4
        $input = $this->data;
30 4
        $delimiter = $this->delimiter;
31 4
        $offset = 0;
32
33
        while (
34 4
            mb_strlen($input) > $offset
35 4
            && false !== $nextOffset = '' !== $delimiter ? mb_strpos($input, $delimiter, $offset) : 1 + $offset
36
        ) {
37 4
            yield mb_substr($input, $offset, $nextOffset - $offset);
38
39 4
            $offset = $nextOffset + mb_strlen($delimiter);
40
        }
41
42 4
        if ('' !== $delimiter) {
43 2
            yield mb_substr($input, $offset);
44
        }
45
    }
46
}
47