HandlesRegularExpressions   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 42
rs 10
c 2
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A parseWhere() 0 3 2
A getRegularExpression() 0 15 1
A where() 0 7 2
A matchesRegularExpression() 0 3 1
1
<?php
2
3
namespace BeyondCode\Mailbox\Concerns;
4
5
use Symfony\Component\Routing\Route;
6
7
trait HandlesRegularExpressions
8
{
9
    protected function matchesRegularExpression(string $subject)
10
    {
11
        return (bool) preg_match($this->getRegularExpression(), $subject, $this->matches);
12
    }
13
14
    /**
15
     * We do not want to create the regular expression on our own,
16
     * so we just use Symfonys Route for this.
17
     *
18
     * @return string
19
     */
20
    protected function getRegularExpression(): string
21
    {
22
        $route = new Route($this->pattern);
23
        $route->setRequirements($this->wheres);
24
25
        $regex = $route->compile()->getRegex();
26
27
        $regex = preg_replace('/^(#|{)\^\/(.*)/', '$1^$2', $regex);
28
29
        $regex = str_replace('>[^/]+)', '>.+)', $regex);
30
31
        $regex = str_replace('$#sD', '$#sDi', $regex);
32
        $regex = str_replace('$}sD', '$}sDi', $regex);
33
34
        return $regex;
35
    }
36
37
    public function where($name, $expression = null)
38
    {
39
        foreach ($this->parseWhere($name, $expression) as $name => $expression) {
0 ignored issues
show
introduced by
$name is overwriting one of the parameters of this function.
Loading history...
40
            $this->wheres[$name] = $expression;
0 ignored issues
show
Bug Best Practice introduced by
The property wheres does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
41
        }
42
43
        return $this;
44
    }
45
46
    protected function parseWhere($name, $expression)
47
    {
48
        return is_array($name) ? $name : [$name => $expression];
49
    }
50
}
51