Completed
Push — master ( 1e9ef5...3740bc )
by Richard
05:53 queued 29s
created

_PropertyMatches::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 2
crap 3.0261
1
<?php
2
/******************************************************************************
3
 * An implementation of dicto (scg.unibe.ch/dicto) in and for PHP.
4
 * 
5
 * Copyright (c) 2016 Richard Klees <[email protected]>
6
 *
7
 * This software is licensed under The MIT License. You should have received 
8
 * a copy of the license along with the code.
9
 */
10
11
namespace Lechimp\Dicto\Graph\Predicate;
12
13
use Lechimp\Dicto\Graph\Predicate;
14
use Lechimp\Dicto\Graph\Entity;
15
16
/**
17
 * A predicate that is true if a property of the entity matches a regex.
18
 */
19
class _PropertyMatches extends Predicate {
20
    /**
21
     * @var string
22
     */
23
    protected $name;
24
25
    /**
26
     * @var string
27
     */
28
    protected $regexp;
29
30 30
    public function __construct($name, $regexp) {
31 30
        assert('is_string($name)');
32 30
        if (!is_string($regexp) || @preg_match("%^$regexp\$%", "") === false) {
33
            throw new \InvalidArgumentException("'%^$regexp\$%' is no valid regex.");
34
        }
35 30
        $this->name = $name;
36 30
        $this->regexp = $regexp;
37 30
    }
38
39
    /**
40
     * @inheritdocs
41
     */
42 28
    public function compile() {
43 28
        $name = $this->name;
44 28
        $regexp = $this->regexp;
45 28
        return function(Entity $e) use ($name, $regexp) { 
46 26
            if (!$e->has_property($name)) {
47 1
                return false;
48
            }
49 26
            return preg_match("%^$regexp\$%", $e->property($name)) == 1;
50 28
        };
51
    }
52
53
    /**
54
     * @inheritdocs
55
     */
56 11
    public function for_types($existing_types) {
57 11
        return $existing_types;
58
    }
59
}
60