Passed
Push — master ( db02fd...873e90 )
by Christopher
02:22 queued 48s
created

PatternTrait::matchesRegexPattern()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Barnso
5
 * Date: 30/06/2017
6
 * Time: 9:40 PM
7
 */
8
9
namespace AlgoWeb\xsdTypes\Facets;
10
11
trait PatternTrait
12
{
13
    /**
14
     * @Exclude
15
     * @var string Defines the exact sequence of characters that are acceptable
16
     */
17
    private $pattern = null;
18
19
    protected function setPatternFacet($value)
20
    {
21
        if (!$this->checkRegexValidPattern($value)) {
22
            $value = "/" . $value . "/";
23
            if (!$this->checkRegexValidPattern($value)) {
24
                throw new \InvalidArgumentException("Invalid regex Pattern provided: " . __CLASS__);
25
            }
26
        }
27
        $this->pattern = $value;
28
    }
29
30
    private function checkRegexValidPattern($pattern)
31
    {
32
        return (@preg_match($pattern, null) === false);
33
    }
34
35
36
    private function checkPattern($v)
37
    {
38
        if ($this->pattern != null) {
39
            if (!$this->matchesRegexPattern($this->pattern, $v)) {
40
                throw new \InvalidArgumentException("assigned value that dose not match pattern " . __CLASS__);
41
            }
42
        }
43
    }
44
45
    /**
46
     * Checks a pattern against a string
47
     *
48
     * @param  string $pattern the regex pattern
49
     * @param  string $string the string to check
50
     * @return bool true if string matches pattern
51
     */
52
    private function matchesRegexPattern($pattern, $string)
53
    {
54
        $matches = null;
55
        return (1 == preg_match($pattern, $string, $matches) && $string == $matches[0]);
56
    }
57
}
58