Completed
Push — feature/more-metadata-values ( 480338...88cb5d )
by Daan van
05:19 queued 03:11
created

RegularExpression::deserialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace OpenConext\Value;
4
5
use OpenConext\Value\Assert\Assertion;
6
use OpenConext\Value\Exception\InvalidArgumentException;
7
8
final class RegularExpression implements Serializable
9
{
10
    /**
11
     * @var string
12
     */
13
    private $pattern;
14
15
    /**
16
     * @param $regularExpression
17
     * @return bool
18
     */
19
    public static function isValidRegularExpression($regularExpression)
20
    {
21
        try {
22
            Assertion::validRegularExpression($regularExpression, 'regularExpression');
23
        } catch (InvalidArgumentException $exception) {
24
            return false;
25
        }
26
27
        return true;
28
    }
29
30
    /**
31
     * @param string $pattern
32
     */
33
    public function __construct($pattern)
34
    {
35
        Assertion::nonEmptyString($pattern, 'pattern');
36
        Assertion::validRegularExpression($pattern, 'pattern');
37
38
        $this->pattern = $pattern;
39
    }
40
41
    /**
42
     * @param string
43
     * @return bool
44
     */
45
    public function matches($string)
46
    {
47
        Assertion::string($string, 'String to match pattern against is not a string, "%s" given');
48
49
        return preg_match($this->pattern, $string) === 1;
50
    }
51
52
    /**
53
     * @return string
54
     */
55
    public function getPattern()
56
    {
57
        return $this->pattern;
58
    }
59
60
    /**
61
     * @param RegularExpression $other
62
     * @return bool
63
     */
64
    public function equals(RegularExpression $other)
65
    {
66
        return $this->pattern === $other->pattern;
67
    }
68
69
    public static function deserialize($data)
70
    {
71
        return new self($data);
72
    }
73
74
    public function serialize()
75
    {
76
        return $this->pattern;
77
    }
78
79
    public function __toString()
80
    {
81
        return $this->pattern;
82
    }
83
}
84