Test Failed
Push — master ( 85ca69...144c12 )
by Roman
15:41
created

Mask   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 22
c 0
b 0
f 0
dl 0
loc 55
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 3 1
A query() 0 3 1
A limit() 0 3 1
A stringBetween() 0 11 2
A __construct() 0 7 3
A shiftLeft() 0 7 3
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