Completed
Push — master ( 4fd125...05840b )
by Richard
05:36
created

ContainText   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 168
Duplicated Lines 10.12 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 96.04%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 10
dl 17
loc 168
ccs 97
cts 101
cp 0.9604
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A fetch_arguments() 0 4 1
A arguments_are_valid() 10 10 4
B compile() 7 63 4
A get_source_for() 0 10 3
A get_source_for_defined_in() 0 13 1
A get_source_for_file() 0 7 1
A regexp_source_filter() 0 13 2
A get_source_location() 0 6 1
A pprint() 0 3 1
A register_listeners() 0 2 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
class ContainText extends Schema {
25
    /**
26
     * @inheritdoc
27
     */
28 46
    public function name() {
29 46
        return "contain text";
30
    } 
31
32
    /**
33
     * @inheritdoc
34
     */
35 7
    public function fetch_arguments(ArgumentParser $parser) {
36 7
        $regexp = $parser->fetch_string();
37 7
        return array($regexp);
38
    }
39
40
    /**
41
     * @inheritdoc
42
     */
43 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...
44 20
        if (count($arguments) != 1) {
45 1
            return false;
46
        }
47 20
        $regexp = $arguments[0];
48 20
        if (!is_string($regexp) || @preg_match("%$regexp%", "") === false) {
49
            return false;
50
        }
51 20
        return true;
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57 12
    public function compile(Index $index, Rule $rule) {
58 12
        $mode = $rule->mode();
59 12
        $pred_factory = $index->query()->predicate_factory();
60 12
        $filter = $rule->checked_on()->compile($pred_factory);
61
        // ContainText needs to have to kinds of queries, one for files, one
62
        // for none-files. To make the queries faster, we separate the filters
63
        // to the different types.
64 12
        $filter_non_files = $pred_factory->_and
65 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...
66 12
            , $filter
67 12
            ]);
68 12
        $filter_files = $pred_factory->_and
69 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...
70 12
            , $filter
71 12
            ]);
72 12
        $regexp = $rule->argument(0);
73
74 12
        if ($mode == Rule::MODE_CANNOT || $mode == Rule::MODE_ONLY_CAN) {
75
            return
76 9
                [ $index->query()
77 9
                    ->filter($filter_non_files)
0 ignored issues
show
Bug introduced by
It seems like $filter_non_files defined by $pred_factory->_and(arra..._is('file')), $filter)) on line 64 can be null; however, Lechimp\Dicto\Graph\Query::filter() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
78 9
                    ->expand_relations(["defined in"])
79 9
                    ->filter($this->regexp_source_filter($pred_factory, $regexp, false))
80
                    ->extract(function($e,&$r) use ($regexp) {
81 1
                        $file = $e->target();
82 1
                        $found_at_line = $this->get_source_location($e, $regexp);
83 1
                        $start_line = $e->property("start_line");
84 1
                        $line = $start_line + $found_at_line - 1;
85
                        // -1 is for the line where the class starts, this would
86
                        // count double otherwise.
87 1
                        $r["file"] = $file->property("path");
88 1
                        $r["line"] = $line;
89 1
                        $r["source"] = $file->property("source")[$line-1];
90 9
                    })
91 9
                , $index->query()
92 9
                    ->filter($filter_files)
0 ignored issues
show
Bug introduced by
It seems like $filter_files defined by $pred_factory->_and(arra...e_is('file'), $filter)) on line 68 can be null; however, Lechimp\Dicto\Graph\Query::filter() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
93 9
                    ->filter($this->regexp_source_filter($pred_factory, $regexp, false))
94
                    ->extract(function($e,&$r) use ($regexp) {
95 3
                        $line = $this->get_source_location($e, $regexp);
96 2
                        $r["file"] = $e->property("path");
97 2
                        $r["line"] = $line;
98 2
                        $r["source"] = $e->property("source")[$line-1];
99 9
                    })
100 9
                ];
101
        }
102 3
        if ($mode == Rule::MODE_MUST) {
103
            return
104 3
                [ $index->query()
105 3
                    ->filter($filter_non_files)
0 ignored issues
show
Bug introduced by
It seems like $filter_non_files defined by $pred_factory->_and(arra..._is('file')), $filter)) on line 64 can be null; however, Lechimp\Dicto\Graph\Query::filter() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
106 3
                    ->expand_relations(["defined in"])
107 3
                    ->filter($this->regexp_source_filter($pred_factory, $regexp, true))
108 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...
109 1
                        $file = $e->target();
110 1
                        $r["file"] = $file->property("path");
111 1
                        $line = $e->property("start_line");
112 1
                        $r["line"] = $line;
113 1
                        $r["source"] = $file->property("source")[$line - 1];
114 3
                    })
115
                // TODO: add implementation for files here.
116 3
                ];
117
        }
118
        throw new \LogicException("Unknown rule mode: '$mode'");
119
    }
120
121
    // Helpers for compile
122
123 9
    protected function get_source_for(Graph\Entity $e) {
124 9
        if ($e->type() == "defined in") {
125 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...
126
        }
127 4
        if ($e->type() == "file") {
128 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...
129
        }
130
        throw new \LogicException(
131
            "Can't get source for entity with type '".$e->type()."'");
132
    }
133
134 5
    protected function get_source_for_defined_in(Graph\Relation $r) {
135 5
        assert('$r->type() == "defined in"');
136 5
        $start_line = $r->property("start_line");
137 5
        $end_line = $r->property("end_line");
138
        return implode
139 5
            ( "\n"
140 5
            , array_slice
141 5
                ( $r->target()->property("source")
142 5
                , $start_line - 1
143 5
                , $end_line - $start_line
144 5
                )
145 5
            );
146
    }
147
148 4
    protected function get_source_for_file(Graph\Node $f) {
149 4
        assert('$f->type() == "file"');
150
        return implode
151 4
            ( "\n"
152 4
            , $f->property("source")
153 4
            );
154
    }
155
156 12
    protected function regexp_source_filter(PredicateFactory $f, $regexp, $negate) {
157 12
        assert('is_string($regexp)');
158 12
        assert('is_bool($negate)');
159 12
        return $f->_custom(function(Graph\Entity $e) use ($regexp, $negate) {
160 9
            $source = $this->get_source_for($e);
161 9
            if(!$negate) {
162 7
                return preg_match("%$regexp%", $source) == 1;
163
            }
164
            else {
165 2
                return preg_match("%$regexp%", $source) == 0;
166
            }
167 12
        });
168
    }
169
170 3
    protected function get_source_location(Graph\Entity $e, $regexp) {
171 3
        $matches = [];
172 3
        $source = $this->get_source_for($e);
173 3
        preg_match("%(.*)$regexp%s", $source, $matches);
174 3
        return substr_count($matches[0], "\n") + 1;
175
    }
176
177
    /**
178
     * @inheritdoc
179
     */
180 12
    public function pprint(Rule $rule) {
181 12
        return $this->name().' "'.$rule->argument(0).'"';
182
    }
183
184
    /**
185
     * No listeners required for contains text. 
186
     *
187
     * @inheritdoc
188
     */
189 11
    public function register_listeners(ListenerRegistry $registry) {
190 11
    }
191
}
192