Completed
Push — master ( f78b67...642bc2 )
by Richard
05:33
created

ContainText::get_source_for_defined_in()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
ccs 11
cts 11
cp 1
rs 9.4285
cc 1
eloc 10
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\Rules;
12
13
use Lechimp\Dicto\Analysis\Index;
14
use Lechimp\Dicto\Analysis\Violation;
15
use Lechimp\Dicto\Definition\ArgumentParser;
16
use Lechimp\Dicto\Indexer\ListenerRegistry;
17
use Lechimp\Dicto\Graph\Node;
18
use Lechimp\Dicto\Graph\PredicateFactory;
19
use Lechimp\Dicto\Graph;
20
21
/**
22
 * This checks wheather there is some text in some entity.
23
 *
24
 * TODO: Test if ContainText finds text in files.
25
 */
26
class ContainText extends Schema {
27
    /**
28
     * @inheritdoc
29
     */
30 46
    public function name() {
31 46
        return "contain text";
32
    } 
33
34
    /**
35
     * @inheritdoc
36
     */
37 7
    public function fetch_arguments(ArgumentParser $parser) {
38 7
        $regexp = $parser->fetch_string();
39 7
        return array($regexp);
40
    }
41
42
    /**
43
     * @inheritdoc
44
     */
45 20 View Code Duplication
    public function arguments_are_valid(array &$arguments) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
46 20
        if (count($arguments) != 1) {
47
            return false;
48
        }
49 20
        $regexp = $arguments[0];
50 20
        if (!is_string($regexp) || @preg_match("%$regexp%", "") === false) {
51
            return false;
52
        }
53 20
        return true;
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59 12
    public function compile(Index $index, Rule $rule) {
60 12
        $mode = $rule->mode();
61 12
        $pred_factory = $index->query()->predicate_factory();
62 12
        $filter = $rule->checked_on()->compile($pred_factory);
63
        // ContainText needs to have to kinds of queries, one for files, one
64
        // for none-files. To make the queries faster, we separate the filters
65
        // to the different types.
66 12
        $filter_non_files = $pred_factory->_and
67 12
            ([$pred_factory->_not($pred_factory->_type_is("file"))
0 ignored issues
show
Documentation introduced by
array($pred_factory->_no...e_is('file')), $filter) is of type array<integer,object<Lec...h\\PredicateFactory>"}>, but the function expects a array<integer,object<Lec...Dicto\Graph\Predicate>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
68 12
            , $filter
69 12
            ]);
70 12
        $filter_files = $pred_factory->_and
71 12
            ([$pred_factory->_type_is("file")
0 ignored issues
show
Documentation introduced by
array($pred_factory->_type_is('file'), $filter) is of type array<integer,object<Lec...h\\PredicateFactory>"}>, but the function expects a array<integer,object<Lec...Dicto\Graph\Predicate>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72 12
            , $filter
73 12
            ]);
74 12
        $regexp = $rule->argument(0);
75
76 12
        if ($mode == Rule::MODE_CANNOT || $mode == Rule::MODE_ONLY_CAN) {
77
            return
78 9
                [ $index->query()
79 9
                    ->filter($filter_non_files)
80 9
                    ->expand_relations(["defined in"])
81 9
                    ->filter($this->regexp_source_filter($pred_factory, $regexp, false))
82
                    ->extract(function($e,&$r) use ($regexp) {
83 1
                        $file = $e->target();
84 1
                        $found_at_line = $this->get_source_location($e, $regexp);
85 1
                        $start_line = $e->property("start_line");
86 1
                        $line = $start_line + $found_at_line - 1;
87
                        // -1 is for the line where the class starts, this would
88
                        // count double otherwise.
89 1
                        $r["file"] = $file->property("path");
90 1
                        $r["line"] = $line;
91 1
                        $r["source"] = $file->property("source")[$line-1];
92 9
                    })
93 9
                , $index->query()
94 9
                    ->filter($filter_files)
95 9
                    ->filter($this->regexp_source_filter($pred_factory, $regexp, false))
96
                    ->extract(function($e,&$r) use ($regexp) {
97 2
                        $line = $this->get_source_location($e, $regexp);
98 2
                        $r["file"] = $e->property("path");
99 2
                        $r["line"] = $line;
100 2
                        $r["source"] = $e->property("source")[$line-1];
101 9
                    })
102 9
                ];
103
        }
104 3
        if ($mode == Rule::MODE_MUST) {
105
            return
106 3
                [ $index->query()
107 3
                    ->filter($filter_non_files)
108 3
                    ->expand_relations(["defined in"])
109 3
                    ->filter($this->regexp_source_filter($pred_factory, $regexp, true))
110 View Code Duplication
                    ->extract(function($e,&$r) use ($rule) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111 1
                        $file = $e->target();
112 1
                        $r["file"] = $file->property("path");
113 1
                        $line = $e->property("start_line");
114 1
                        $r["line"] = $line;
115 1
                        $r["source"] = $file->property("source")[$line - 1];
116 3
                    })
117
                // TODO: add implementation for files here.
118 3
                ];
119
        }
120
        throw new \LogicException("Unknown rule mode: '$mode'");
121
    }
122
123
    // Helpers for compile
124
125 9
    protected function get_source_for(Graph\Entity $e) {
126 9
        if ($e->type() == "defined in") {
127 5
            return $this->get_source_for_defined_in($e);
0 ignored issues
show
Compatibility introduced by
$e of type object<Lechimp\Dicto\Graph\Entity> is not a sub-type of object<Lechimp\Dicto\Graph\Relation>. It seems like you assume a child class of the class Lechimp\Dicto\Graph\Entity to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
128
        }
129 4
        if ($e->type() == "file") {
130 4
            return $this->get_source_for_file($e);
0 ignored issues
show
Compatibility introduced by
$e of type object<Lechimp\Dicto\Graph\Entity> is not a sub-type of object<Lechimp\Dicto\Graph\Node>. It seems like you assume a child class of the class Lechimp\Dicto\Graph\Entity to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
131
        }
132
        throw new \LogicException(
133
            "Can't get source for entity with type '".$e->type()."'");
134
    }
135
136 5
    protected function get_source_for_defined_in(Graph\Relation $r) {
137 5
        assert('$r->type() == "defined in"');
138 5
        $start_line = $r->property("start_line");
139 5
        $end_line = $r->property("end_line");
140
        return implode
141 5
            ( "\n"
142 5
            , array_slice
143 5
                ( $r->target()->property("source")
144 5
                , $start_line - 1
145 5
                , $end_line - $start_line
146 5
                )
147 5
            );
148
    }
149
150 4
    protected function get_source_for_file(Graph\Node $f) {
151 4
        assert('$f->type() == "file"');
152
        return implode
153 4
            ( "\n"
154 4
            , $f->property("source")
155 4
            );
156
    }
157
158 12
    protected function regexp_source_filter(PredicateFactory $f, $regexp, $negate) {
159 12
        assert('is_string($regexp)');
160 12
        assert('is_bool($negate)');
161 12
        return $f->_custom(function(Graph\Entity $e) use ($regexp, $negate) {
162 9
            $source = $this->get_source_for($e);
163 9
            if(!$negate) {
164 7
                return preg_match("%$regexp%", $source) == 1;
165
            }
166
            else {
167 2
                return preg_match("%$regexp%", $source) == 0;
168
            }
169 12
        });
170
    }
171
172 3
    protected function get_source_location(Graph\Entity $e, $regexp) {
173 3
        $matches = [];
174 3
        $source = $this->get_source_for($e);
175 3
        preg_match("%(.*)$regexp%s", $source, $matches);
176 3
        return substr_count($matches[0], "\n") + 1;
177
    }
178
179
    /**
180
     * @inheritdoc
181
     */
182 12
    public function pprint(Rule $rule) {
183 12
        return $this->name().' "'.$rule->argument(0).'"';
184
    }
185
186
    /**
187
     * No listeners required for contains text. 
188
     *
189
     * @inheritdoc
190
     */
191 11
    public function register_listeners(ListenerRegistry $registry) {
192 11
    }
193
}
194