1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Crossword\Domain\Model; |
6
|
|
|
|
7
|
|
|
use App\Crossword\Domain\Exception\SearchMaskIsShortException; |
8
|
|
|
use Stringable; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @psalm-immutable |
12
|
|
|
*/ |
13
|
|
|
final class Mask implements Stringable |
14
|
|
|
{ |
15
|
|
|
private const LIMIT = 3; |
16
|
|
|
|
17
|
|
|
private string $query; |
18
|
|
|
private string $limit; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @throws SearchMaskIsShortException |
22
|
|
|
*/ |
23
|
|
|
public function __construct(string $mask, int $limit = self::LIMIT) |
24
|
|
|
{ |
25
|
|
|
$this->limit = $this->stringBetween($mask, '{', '}'); |
26
|
|
|
$this->query = $this->limit ? str_replace($this->limit(), '', $mask) : $mask; |
27
|
|
|
|
28
|
|
|
if ((int) str_replace('0,', '', $this->limit) <= $limit) { |
29
|
|
|
throw new SearchMaskIsShortException(); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function query(): string |
34
|
|
|
{ |
35
|
|
|
return $this->query; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function limit(): string |
39
|
|
|
{ |
40
|
|
|
return sprintf('{%s}', $this->limit); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function shiftLeft(): self |
44
|
|
|
{ |
45
|
|
|
$query = $this->query[0] === '.' ? substr($this->query, 1) : $this->query; |
46
|
|
|
$query = '*' === $query[0] ? '.' . $query : $query; |
47
|
|
|
$limit = explode(',', $this->limit); |
48
|
|
|
|
49
|
|
|
return new self($query . sprintf('{%s,%s}', $limit[0], ((int) $limit[1]) - 1)); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function __toString(): string |
53
|
|
|
{ |
54
|
|
|
return $this->query() . $this->limit(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function stringBetween($string, $start, $end): string |
58
|
|
|
{ |
59
|
|
|
$string = ' ' . $string; |
60
|
|
|
$ini = strpos($string, $start); |
61
|
|
|
if (!$ini) { |
62
|
|
|
return '0,100'; |
63
|
|
|
} |
64
|
|
|
$ini += strlen($start); |
65
|
|
|
$len = strpos($string, $end, $ini) - $ini; |
66
|
|
|
|
67
|
|
|
return substr($string, $ini, $len); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|