Completed
Push — master ( 4a7f1b...1a5eaf )
by Richard
05:32
created

Indexer   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 332
Duplicated Lines 17.77 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 85.21%

Importance

Changes 15
Bugs 0 Features 1
Metric Value
wmc 37
c 15
b 0
f 1
lcom 1
cbo 6
dl 59
loc 332
ccs 144
cts 169
cp 0.8521
rs 8.6

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 1
B index_file() 0 27 4
A lines_from_to() 0 5 1
A on_enter_entity() 0 4 1
A on_leave_entity() 0 4 1
A on_enter_misc() 0 4 1
A on_leave_misc() 0 4 1
A on_enter_or_leave_something() 0 15 4
A call_misc_listener() 12 12 4
A call_entity_listener() 11 11 4
A file_path() 0 3 1
A in_entities() 0 3 1
A beforeTraverse() 0 18 1
A file_content() 0 10 2
A afterTraverse() 0 7 1
B enterNode() 36 52 5
A leaveNode() 0 12 4

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, 2015 Richard Klees <[email protected]>
6
 *
7
 * This software is licensed under The MIT License. You should have received
8
 * a copy of the licence along with the code.
9
 */
10
11
namespace Lechimp\Dicto\Indexer;
12
13
use Lechimp\Dicto\Indexer as I;
14
use Lechimp\Dicto\Variables\Variable;
15
use PhpParser\Node as N;
16
17
/**
18
 * Implementation of Indexer with PhpParser.
19
 */
20
class Indexer implements Location, ListenerRegistry, \PhpParser\NodeVisitor {
21
    /**
22
     * @var string
23
     */
24
    protected $project_root_path;
25
26
    /**
27
     * @var I\Insert|null
28
     */
29
    protected $insert;
30
31
    /**
32
     * @var \PhpParser\Parser
33
     */
34
    protected $parser;
35
36
    /**
37
     * @var array   string => array()
38
     */
39
    protected $listeners_enter_entity;
40
41
    /**
42
     * @var array   string => array()
43
     */
44
    protected $listeners_leave_entity;
45
46
    /**
47
     * @var array   string => array()
48
     */
49
    protected $listeners_enter_misc;
50
51
    /**
52
     * @var array   string => array()
53
     */
54
    protected $listeners_leave_misc;
55
56
    // state for parsing a file
57
58
    /**
59
     * @var string|null
60
     */
61
    protected $file_path = null;
62
63
    /**
64
     * @var string[]|null
65
     */
66
    protected $file_content = null;
67
68
    /**
69
     * This contains the stack of ids were currently in, i.e. the nesting of
70
     * known code blocks we are in.
71
     *
72
     * @var array|null  contain ($entity_type, $entity_id)
73
     */
74
    protected $entity_stack = null;
75
76
    /**
77
     * @param   string  $project_root_path
78
     * @param   Schema[]  $rule_schemas
0 ignored issues
show
Bug introduced by
There is no parameter named $rule_schemas. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
79
     */
80 24
    public function __construct(\PhpParser\Parser $parser, $project_root_path, Insert $insert) {
81 24
        $this->parser = $parser;
82 24
        assert('is_string($project_root_path)');
83 24
        $this->project_root_path = $project_root_path;
84 24
        $this->insert = $insert;
85 24
        $this->listeners_enter_entity = array
86 24
            ( 0 => array()
87 24
            );
88 24
        $this->listeners_leave_entity = array
89 24
            ( 0 => array()
90 24
            );
91 24
        $this->listeners_enter_misc = array
92 24
            ( 0 => array()
93 24
            );
94 24
        $this->listeners_leave_misc = array
95 24
            ( 0 => array()
96 24
            );
97 24
    }
98
99
    /**
100
     * @param   string  $path
101
     */
102 23
    public function index_file($path) {
103 23
        if ($this->insert === null) {
104
            throw new \RuntimeException(
105
                "Set an inserter to be used before starting to index files.");
106
        }
107
108 23
        $content = file_get_contents($this->project_root_path."/$path");
109 23
        if ($content === false) {
110
            throw \InvalidArgumentException("Can't read file $path.");
111
        }
112
113 23
        $stmts = $this->parser->parse($content);
114 23
        if ($stmts === null) {
115
            throw new \RuntimeException("Can't parse file $path.");
116
        }
117
118 23
        $traverser = new \PhpParser\NodeTraverser;
119 23
        $traverser->addVisitor($this);
120
121 23
        $this->entity_stack = array();
122 23
        $this->file_path = $path;
123 23
        $this->file_content = explode("\n", $content);
124 23
        $traverser->traverse($stmts);
125 23
        $this->entity_stack = null; 
126 23
        $this->file_path = null;
127 23
        $this->file_content = null;
128 23
    }
129
130
    // helper
131
132 23
    private function lines_from_to($start, $end) {
133 23
        assert('is_int($start)');
134 23
        assert('is_int($end)');
135 23
        return implode("\n", array_slice($this->file_content, $start-1, $end-$start+1));
136
    }
137
138
   // from ListenerRegistry 
139
140
    /**
141
     * @inheritdoc
142
     */
143 1
    public function on_enter_entity($types, \Closure $listener) {
144 1
        $this->on_enter_or_leave_something("listeners_enter_entity", $types, $listener);
145 1
        return $this;
146
    }
147
148
    /**
149
     * @inheritdoc
150
     */
151 1
    public function on_leave_entity($types, \Closure $listener) {
152 1
        $this->on_enter_or_leave_something("listeners_leave_entity", $types, $listener);
153 1
        return $this;
154
    }
155
156
    /**
157
     * @inheritdoc
158
     */
159 23
    public function on_enter_misc($classes, \Closure $listener) {
160 23
        $this->on_enter_or_leave_something("listeners_enter_misc", $classes, $listener);
161 23
        return $this;
162
    }
163
164
    /**
165
     * @inheritdoc
166
     */
167 1
    public function on_leave_misc($classes, \Closure $listener) {
168 1
        $this->on_enter_or_leave_something("listeners_leave_misc", $classes, $listener);
169 1
        return $this;
170
    }
171
172
    // generalizes over over on_enter/leave_xx
173 23
    protected function on_enter_or_leave_something($what, $things, \Closure $listener) {
174 23
        $loc = &$this->$what;
175 23
        if ($things === null) {
176 1
            $loc[0][] = $listener;
177 1
        }
178
        else {
179 23
            foreach ($things as $thing) {
180 23
                assert('is_string($thing)');
181 23
                if (!array_key_exists($thing, $loc)) {
182 23
                    $loc[$thing] = array();
183 23
                }
184 23
                $loc[$thing][] = $listener;
185 23
            }
186
        }
187 23
    }
188
189
    // generalizes over calls to misc listeners
190 23 View Code Duplication
    protected function call_misc_listener($which, $node) {
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...
191 23
        $listeners = &$this->$which;
192 23
        foreach ($listeners[0] as $listener) {
193
            $listener($this->insert, $this, $node);
194 23
        }
195 23
        $cls = get_class($node);
196 23
        if (array_key_exists($cls, $listeners)) {
197 21
            foreach ($listeners[$cls] as $listener) {
198 21
                $listener($this->insert, $this, $node);
199 21
            }
200 21
        }
201 23
    }
202
203 23 View Code Duplication
    protected function call_entity_listener($which, $type, $id, $node) {
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...
204 23
        $listeners = &$this->$which;
205 23
        foreach ($listeners[0] as $listener) {
206 1
            $listener($this->insert, $this, $type, $id, $node);
207 23
        }
208 23
        if (array_key_exists($type, $listeners)) {
209
            foreach ($listeners[$type] as $listener) {
210
                $listener($this->insert, $this, $type, $id, $node);
211
            }
212
        }
213 23
    }
214
215
   // from Location
216
217
    /**
218
     * @inheritdoc
219
     */
220 17
    public function file_path() {
221 17
        return $this->file_path;
222
    }
223
224
    /**
225
     * @inheritdoc
226
     */
227
    public function file_content($from_line = null, $to_line = null) {
228
        if ($from_line !== null) {
229
            assert('$to_line !== null');
230
            return $this->lines_from_to($from_line, $to_line);
231
        }
232
        else {
233
            assert('$to_line === null');
234
            return implode("\n", $this->file_content);
235
        }
236
    }
237
238
    /**
239
     * @inheritdoc
240
     */
241 17
    public function in_entities() {
242 17
        return $this->entity_stack;
243
    }
244
245
    // from \PhpParser\NodeVisitor
246
247
    /**
248
     * @inheritdoc
249
     */
250 23
    public function beforeTraverse(array $nodes) {
251 23
        $this->insert->source_file($this->file_path, implode("\n", $this->file_content));
252
253
        // for sure found a file
254 23
        $id = $this->insert->entity
255 23
            ( Variable::FILE_TYPE
256 23
            , $this->file_path
257 23
            , $this->file_path
258 23
            , 1
259 23
            , count($this->file_content)
260 23
            );
261
262 23
        $this->entity_stack[] = array(Variable::FILE_TYPE, $id);
263
264 23
        $this->call_entity_listener("listeners_enter_entity", Variable::FILE_TYPE, $id, null);
265
266 23
        return null;
267
    }
268
269
    /**
270
     * @inheritdoc
271
     */
272 23
    public function afterTraverse(array $nodes) {
273 23
        list($type, $id) = array_pop($this->entity_stack);
274
275 23
        $this->call_entity_listener("listeners_leave_entity", $type, $id, null);
276
277 23
        return null;
278
    }
279
280
    /**
281
     * @inheritdoc
282
     */
283 23
    public function enterNode(\PhpParser\Node $node) {
284 23
        $start_line = $node->getAttribute("startLine");
285 23
        $end_line = $node->getAttribute("endLine");
286 23
        $source = $this->lines_from_to($start_line, $end_line);
287
288 23
        $id = null;
289 23
        $type = null;
290
291
        // Class
292 23
        if ($node instanceof N\Stmt\Class_) {
293 22
            $type = Variable::CLASS_TYPE;
294 22
            $id = $this->insert->entity
295 22
                ( $type
296 22
                , $node->name
297 22
                , $this->file_path
298 22
                , $start_line
299 22
                , $end_line
300 22
                , $source
0 ignored issues
show
Unused Code introduced by
The call to Insert::entity() has too many arguments starting with $source.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
301 22
                );
302 22
        }
303
        // Method or Function
304 23 View Code Duplication
        elseif ($node instanceof N\Stmt\ClassMethod) {
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...
305 22
            $type = Variable::METHOD_TYPE;
306 22
            $id = $this->insert->entity
307 22
                ( $type
308 22
                , $node->name
309 22
                , $this->file_path
310 22
                , $start_line
311 22
                , $end_line
312 22
                , $source
0 ignored issues
show
Unused Code introduced by
The call to Insert::entity() has too many arguments starting with $source.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
313 22
                );
314 22
        }
315 23 View Code Duplication
        elseif ($node instanceof N\Stmt\Function_) {
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...
316
            $type = Variable::FUNCTION_TYPE;
317
            $id = $this->insert->entity
318
                ( $type 
319
                , $node->name
320
                , $this->file_path
321
                , $start_line
322
                , $end_line
323
                , $source
0 ignored issues
show
Unused Code introduced by
The call to Insert::entity() has too many arguments starting with $source.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
324
                );
325
        }
326
327 23
        if ($id !== null) {
328 22
            $this->call_entity_listener("listeners_enter_entity",  $type, $id, $node);
329 22
            $this->entity_stack[] = array($type, $id);
330 22
        }
331
        else {
332 23
            $this->call_misc_listener("listeners_enter_misc", $node);
333
        }
334 23
    }
335
336
    /**
337
     * @inheritdoc
338
     */
339 23
    public function leaveNode(\PhpParser\Node $node) {
340
        // Class
341
        if($node instanceof N\Stmt\Class_
342 23
        or $node instanceof N\Stmt\ClassMethod
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
343 23
        or $node instanceof N\Stmt\Function_) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
344 22
            list($type, $id) = array_pop($this->entity_stack);
345 22
            $this->call_entity_listener("listeners_leave_entity", $type, $id, $node);
346 22
        }
347
        else {
348 23
            $this->call_misc_listener("listeners_leave_misc", $node);
349
        }
350 23
    }
351
}
352