Patternizer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0
wmc 6
lcom 0
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isPattern() 0 4 2
A matches() 0 12 3
A getRegex() 0 6 1
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Support;
10
11
/**
12
 * Provides ability to process permissions as star based patterns. This is helper class which is
13
 * used in Tokenizer and Strempler components.
14
 *
15
 * Example:
16
 * post.*
17
 * post.(save|delete)
18
 */
19
class Patternizer
20
{
21
    /**
22
     * @param string $string
23
     *
24
     * @return bool
25
     */
26 8
    public function isPattern(string $string): bool
27
    {
28 8
        return strpos($string, '*') !== false || strpos($string, '|') !== false;
29
    }
30
31
    /**
32
     * Checks if string matches given pattent.
33
     *
34
     * @param string $string
35
     * @param string $pattern
36
     *
37
     * @return bool
38
     */
39 8
    public function matches(string $string, string $pattern): bool
40
    {
41 8
        if ($string === $pattern) {
42 1
            return true;
43
        }
44
45 7
        if (!$this->isPattern($pattern)) {
46 1
            return false;
47
        }
48
49 6
        return (bool)preg_match($this->getRegex($pattern), $string);
50
    }
51
52
    /**
53
     * @param string $pattern
54
     *
55
     * @return string
56
     */
57 6
    private function getRegex(string $pattern): string
58
    {
59 6
        $regex = str_replace('*', '[a-z0-9_\-]+', addcslashes($pattern, '.-'));
60
61 6
        return "#^{$regex}$#i";
62
    }
63
}