Passed
Push — master ( 12ec71...6a4e7a )
by Magnar Ovedal
02:59
created

Substring::__construct()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 3
nop 2
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\PasswordPolice\WordFormatter;
6
7
use InvalidArgumentException;
8
use Stadly\PasswordPolice\WordFormatter;
9
use Traversable;
10
11
final class Substring implements WordFormatter
12
{
13
    /**
14
     * @var int Minimum substring length.
15
     */
16
    private $minLength;
17
18
    /**
19
     * @var int|null Maximum substring length.
20
     */
21
    private $maxLength;
22
23
    /**
24
     * @param int $minLength Ignore substrings shorter thant this.
25
     * @param int|null $maxLength Ignore substrings longer than this.
26
     */
27 7
    public function __construct(int $minLength = 3, ?int $maxLength = 25)
28
    {
29 7
        if ($minLength < 1) {
30 2
            throw new InvalidArgumentException('Min length must be positive.');
31
        }
32 5
        if ($maxLength !== null && $maxLength < $minLength) {
33 1
            throw new InvalidArgumentException('Max length cannot be smaller than min length.');
34
        }
35
36 4
        $this->minLength = $minLength;
37 4
        $this->maxLength = $maxLength;
38 4
    }
39
40
    /**
41
     * {@inheritDoc}
42
     */
43 4
    public function apply(string $word): Traversable
44
    {
45 4
        for ($start = 0; $start < mb_strlen($word); ++$start) {
46 4
            $substring = mb_substr($word, $start, $this->maxLength);
47
48 4
            for ($length = mb_strlen($substring); $this->minLength <= $length; --$length) {
49 4
                yield mb_substr($substring, 0, $length);
50
            }
51
        }
52 4
    }
53
}
54