1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Maba\DatabaseInconsistencyFinder\Service; |
5
|
|
|
|
6
|
|
|
use Maba\DatabaseInconsistencyFinder\Entity\Interval; |
7
|
|
|
use Generator; |
8
|
|
|
|
9
|
|
|
class IntervalManager |
10
|
|
|
{ |
11
|
|
|
private $sizeForSeeking; |
12
|
|
|
private $sizeForJobDistribution; |
13
|
|
|
|
14
|
4 |
|
public function __construct(int $sizeForSeeking, int $sizeForJobDistribution) |
15
|
|
|
{ |
16
|
4 |
|
$this->sizeForSeeking = $sizeForSeeking; |
17
|
4 |
|
$this->sizeForJobDistribution = $sizeForJobDistribution; |
18
|
4 |
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Divides interval into parts for job distribution. |
22
|
|
|
* Always includes first and last part without from/until restrictions to handle new added IDs |
23
|
|
|
* |
24
|
|
|
* @param Interval $idRange |
25
|
|
|
* @return Generator|Interval[] |
26
|
|
|
*/ |
27
|
4 |
|
public function divideForJobDistribution(Interval $idRange): Generator |
28
|
|
|
{ |
29
|
4 |
|
$from = $idRange->getFrom() + $this->sizeForSeeking; |
30
|
4 |
|
$max = $idRange->getUntil() - $this->sizeForSeeking; |
31
|
|
|
|
32
|
4 |
|
if ($from >= $max) { |
33
|
|
|
yield (new Interval()); |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
yield (new Interval())->setUntil($from); |
38
|
|
|
|
39
|
4 |
View Code Duplication |
while ($from < $max) { |
|
|
|
|
40
|
4 |
|
$until = min($from + $this->sizeForJobDistribution, $max); |
41
|
4 |
|
yield (new Interval())->setFrom($from)->setUntil($until); |
42
|
4 |
|
$from = $until; |
43
|
|
|
} |
44
|
|
|
|
45
|
4 |
|
yield (new Interval())->setFrom($max); |
46
|
4 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Divides interval into smaller ones which could be used for in-memory seeking. |
50
|
|
|
* If interval is already small enough, null is returned |
51
|
|
|
* |
52
|
|
|
* @param Interval $interval |
53
|
|
|
* @return Interval[]|Generator |
54
|
|
|
*/ |
55
|
3 |
|
public function divideForSeeking(Interval $interval): Generator |
56
|
|
|
{ |
57
|
3 |
|
if ($interval->getUntil() === null || $interval->getFrom() === null) { |
58
|
3 |
|
yield $interval; |
59
|
3 |
|
return; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$from = $interval->getFrom(); |
63
|
|
View Code Duplication |
while ($from < $interval->getUntil()) { |
|
|
|
|
64
|
|
|
$until = min($from + $this->sizeForSeeking, $interval->getUntil()); |
65
|
|
|
yield (new Interval())->setFrom($from)->setUntil($until); |
66
|
|
|
$from = $until; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.