Passed
Push — main ( 0b9249...4cadd4 )
by Pol
16:53
created

StringIteratorAggregate::__construct()   A

Complexity

Conditions 5
Paths 1

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 12
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 24
ccs 13
cts 13
cp 1
crap 5
rs 9.5555
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 Closure;
13
use Generator;
14
use IteratorAggregate;
15
16
/**
17
 * @implements IteratorAggregate<int, string>
18
 */
19
final class StringIteratorAggregate implements IteratorAggregate
20
{
21
    private Closure $callable;
22
23
    private string $data;
24
25
    private string $delimiter;
26
27 2
    public function __construct(string $data, string $delimiter = '')
28
    {
29 2
        $this->callable =
30
            /**
31
             * @return Generator<int, string>
32
             */
33 2
            static function (string $input, string $delimiter): Generator {
34 2
                $offset = 0;
35
36
                while (
37 2
                    mb_strlen($input) > $offset
38 2
                    && false !== $nextOffset = '' !== $delimiter ? mb_strpos($input, $delimiter, $offset) : 1 + $offset
39
                ) {
40 2
                    yield mb_substr($input, $offset, $nextOffset - $offset);
41
42 2
                    $offset = $nextOffset + mb_strlen($delimiter);
43
                }
44
45 2
                if ('' !== $delimiter) {
46 1
                    yield mb_substr($input, $offset);
47
                }
48 2
            };
49 2
        $this->data = $data;
50 2
        $this->delimiter = $delimiter;
51 2
    }
52
53
    /**
54
     * @return Generator<int, string>
55
     */
56 2
    public function getIterator(): Generator
57
    {
58 2
        yield from new ClosureIteratorAggregate($this->callable, [$this->data, $this->delimiter]);
59 2
    }
60
}
61