Completed
Push — master ( f7852e...e666ea )
by Richard
06:08
created

ContainText   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 134
Duplicated Lines 13.43 %

Coupling/Cohesion

Components 0
Dependencies 8

Test Coverage

Coverage 83.95%

Importance

Changes 0
Metric Value
wmc 15
lcom 0
cbo 8
dl 18
loc 134
ccs 68
cts 81
cp 0.8395
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A fetch_arguments() 0 4 1
A arguments_are_valid() 10 10 4
A compile() 8 54 4
A get_source_for() 0 13 1
A regexp_source_filter() 0 13 2
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\Relation;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Lechimp\Dicto\Rules\Relation.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
20
/**
21
 * This checks wheather there is some text in some entity.
22
 *
23
 * TODO: Test if ContainText finds text in files.
24
 */
25
class ContainText extends Schema {
26
    /**
27
     * @inheritdoc
28
     */
29 38
    public function name() {
30 38
        return "contain text";
31
    } 
32
33
    /**
34
     * @inheritdoc
35
     */
36 5
    public function fetch_arguments(ArgumentParser $parser) {
37 5
        $regexp = $parser->fetch_string();
38 5
        return array($regexp);
39
    }
40
41
    /**
42
     * @inheritdoc
43
     */
44 14 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...
45 14
        if (count($arguments) != 1) {
46
            return false;
47
        }
48 14
        $regexp = $arguments[0];
49 14
        if (!is_string($regexp) || @preg_match("%$regexp%", "") === false) {
50
            return false;
51
        }
52 14
        return true;
53
    }
54
55
    /**
56
     * @inheritdoc
57
     */
58 8
    public function compile(Index $index, Rule $rule) {
59 8
        $mode = $rule->mode();
60 8
        $filter = $rule->checked_on()->compile();
61 8
        $regexp = $rule->argument(0);
62
        $regexp_filter = function(Relation $r) use ($regexp) {
0 ignored issues
show
Unused Code introduced by
$regexp_filter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
63
            $start_line = $r->property("start_line");
64
            $end_line = $r->property("end_line");
65
            $source = implode
66
                ( "\n"
67
                , array_slice
68
                    ( $r->target()->property("source")
69
                    , $start_line - 1
70
                    , $end_line - $start_line
71
                    )
72
                );
73
            return preg_match("%$regexp%", $source) == 1;
74 8
        };
75
76 8
        if ($mode == Rule::MODE_CANNOT || $mode == Rule::MODE_ONLY_CAN) {
77 5
            return $index->query()
0 ignored issues
show
Bug introduced by
The method expand_relation() does not exist on Lechimp\Dicto\Graph\Query. Did you maybe mean expand()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
78 5
                ->filter($filter)
79 5
                ->expand_relation(["defined in"])
80 5
                ->filter($this->regexp_source_filter($regexp, false))
81
                ->extract(function($e,&$r) use ($rule, $regexp) {
82 1
                    $matches = [];
83 1
                    $source = $this->get_source_for($e);
84 1
                    preg_match("%(.*)$regexp%", $source, $matches);
85
86 1
                    $file = $e->target();
87 1
                    $r["rule"] = $rule;
88 1
                    $r["file"] = $file->property("path");
89 1
                    $start_line = $e->property("start_line");
90 1
                    $found_at_line = substr_count($matches[0], "\n") + 1;
91 1
                    $line = $start_line + $found_at_line;
92 1
                    $r["line"] = $line + 1;
93 1
                    $r["source"] = $file->property("source")[$line];
94 5
                });
95
        }
96 3
        if ($mode == Rule::MODE_MUST) {
97 3
            return $index->query()
0 ignored issues
show
Bug introduced by
The method expand_relation() does not exist on Lechimp\Dicto\Graph\Query. Did you maybe mean expand()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
98 3
                ->filter($filter)
99 3
                ->expand_relation(["defined in"])
100 3
                ->filter($this->regexp_source_filter($regexp, true))
101 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...
102 1
                    $file = $e->target();
103 1
                    $r["rule"] = $rule;
104 1
                    $r["file"] = $file->property("path");
105 1
                    $line = $e->property("start_line");
106 1
                    $r["line"] = $line;
107 1
                    $r["source"] = $file->property("source")[$line - 1];
108 3
                });
109
        }
110
        throw new \LogicException("Unknown rule mode: '$mode'");
111
    }
112
113
    // Helpers for compile
114
115 5
    protected function get_source_for(Relation $r) {
116 5
        assert('$r->type() == "defined in"');
117 5
        $start_line = $r->property("start_line");
118 5
        $end_line = $r->property("end_line");
119
        return implode
120 5
            ( "\n"
121 5
            , array_slice
122 5
                ( $r->target()->property("source")
123 5
                , $start_line - 1
124 5
                , $end_line - $start_line
125 5
                )
126 5
            );
127
    }
128
129 8
    protected function regexp_source_filter($regexp, $negate) {
130 8
        assert('is_string($regexp)');
131 8
        assert('is_bool($negate)');
132 8
        return function(Relation $r) use ($regexp, $negate) {
133 5
            $source = $this->get_source_for($r);
134 5
            if(!$negate) {
135 3
                return preg_match("%$regexp%", $source) == 1;
136
            }
137
            else {
138 2
                return preg_match("%$regexp%", $source) == 0;
139
            }
140 8
        };
141
    }
142
143
    /**
144
     * @inheritdoc
145
     */
146 8
    public function pprint(Rule $rule) {
147 8
        return $this->name().' "'.$rule->argument(0).'"';
148
    }
149
150
    /**
151
     * No listeners required for contains text. 
152
     *
153
     * @inheritdoc
154
     */
155 7
    public function register_listeners(ListenerRegistry $registry) {
156 7
    }
157
158
}
159