|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Stadly\PasswordPolice\WordFormatter; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use Traversable; |
|
9
|
|
|
|
|
10
|
|
|
final class Substring extends ChainableFormatter |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var int Minimum substring length. |
|
14
|
|
|
*/ |
|
15
|
|
|
private $minLength; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var int|null Maximum substring length. |
|
19
|
|
|
*/ |
|
20
|
|
|
private $maxLength; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param int $minLength Ignore substrings shorter thant this. |
|
24
|
|
|
* @param int|null $maxLength Ignore substrings longer than this. |
|
25
|
|
|
*/ |
|
26
|
7 |
|
public function __construct(int $minLength = 3, ?int $maxLength = 25) |
|
27
|
|
|
{ |
|
28
|
7 |
|
if ($minLength < 1) { |
|
29
|
2 |
|
throw new InvalidArgumentException('Min length must be positive.'); |
|
30
|
|
|
} |
|
31
|
5 |
|
if ($maxLength !== null && $maxLength < $minLength) { |
|
32
|
1 |
|
throw new InvalidArgumentException('Max length cannot be smaller than min length.'); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
4 |
|
$this->minLength = $minLength; |
|
36
|
4 |
|
$this->maxLength = $maxLength; |
|
37
|
4 |
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param iterable<string> $words Words to format. |
|
41
|
|
|
* @return Traversable<string> All substrings of the words. May contain duplicates. |
|
42
|
|
|
*/ |
|
43
|
6 |
|
protected function applyCurrent(iterable $words): Traversable |
|
44
|
|
|
{ |
|
45
|
6 |
|
foreach ($words as $word) { |
|
46
|
6 |
|
yield from $this->formatWord($word); |
|
47
|
|
|
} |
|
48
|
6 |
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param string $word Word to format. |
|
52
|
|
|
* @return Traversable<string> All substrings of the word. May contain duplicates. |
|
53
|
|
|
*/ |
|
54
|
6 |
|
private function formatWord(string $word): Traversable |
|
55
|
|
|
{ |
|
56
|
6 |
|
for ($start = 0; $start < mb_strlen($word); ++$start) { |
|
57
|
6 |
|
$substring = mb_substr($word, $start, $this->maxLength); |
|
58
|
|
|
|
|
59
|
6 |
|
for ($length = mb_strlen($substring); $this->minLength <= $length; --$length) { |
|
60
|
6 |
|
yield mb_substr($substring, 0, $length); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
6 |
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|