Completed
Push — master ( 05840b...9b2a73 )
by Richard
05:47
created

_PropertyMatches::compile_to_source()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
crap 1
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 31
    public function __construct($name, $regexp) {
31 31
        assert('is_string($name)');
32 31
        if (!is_string($regexp) || @preg_match("%^$regexp\$%", "") === false) {
33
            throw new \InvalidArgumentException("'%^$regexp\$%' is no valid regex.");
34
        }
35 31
        $this->name = $name;
36 31
        $this->regexp = $regexp;
37 31
    }
38
39
    /**
40
     * @inheritdocs
41
     */
42
    public function _compile() {
43
        $name = $this->name;
44
        $regexp = $this->regexp;
45
        return function(Entity $e) use ($name, $regexp) { 
46
            if (!$e->has_property($name)) {
47
                return false;
48
            }
49
            return preg_match("%^$regexp\$%", $e->property($name)) == 1;
50
        };
51
    }
52
53
    /**
54
     * @inheritdocs
55
     */
56 29
    public function compile_to_source(array &$custom_closures) {
57 29
        $name = $this->name;
58 29
        $regexp = $this->regexp;
59
        return
60
            "   \$value = \n".
61 29
            "       \$e->has_property(\"$name\")\n".
62 29
            "       && (preg_match(\"%^$regexp\\\$%\", \$e->property(\"$name\")) == 1);\n";
63
    }
64
65
    /**
66
     * @inheritdocs
67
     */
68 11
    public function for_types(array $existing_types) {
69 11
        return $existing_types;
70
    }
71
}
72