Completed
Push — master ( bdaaad...4f4372 )
by personal
04:35 queued 45s
created

RoleOfMethodDetector   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 2

1 Method

Rating   Name   Duplication   Size   Complexity  
C detects() 0 35 8
1
<?php
2
namespace Hal\Metric\Helper;
3
4
5
use PhpParser\Node\Expr\Cast;
6
use PhpParser\Node\Expr\Variable;
7
use PhpParser\Node\Stmt\ClassMethod;
8
use PhpParser\Node\Stmt\Return_;
9
10
/**
11
 * Class RoleOfMethodDetector
12
 * @package Hal\Metric\Helper
13
 */
14
class RoleOfMethodDetector
15
{
16
17
    /**
18
     * @var array
19
     */
20
    private $fingerprints = [
21
        'getter' => [
22
            'PhpParser\\Node\\Stmt\\ClassMethod',
23
            'PhpParser\\Node\\Stmt\\Return_',
24
            'PhpParser\\Node\\Expr\\PropertyFetch',
25
            'PhpParser\\Node\\Expr\\Variable',
26
        ],
27
        'setter' => [
28
            'PhpParser\\Node\\Stmt\\ClassMethod',
29
            'PhpParser\\Node\\Expr\\Assign',
30
            'PhpParser\\Node\\Expr\\Variable',
31
            'PhpParser\\Node\\Expr\\PropertyFetch',
32
            'PhpParser\\Node\\Expr\\Variable',
33
            'PhpParser\\Node\\Param',
34
        ]
35
    ];
36
37
    /**
38
     * @param $node
39
     * @return string|null
40
     */
41
    public function detects($node)
42
    {
43
44
        if (!$node instanceof ClassMethod) {
45
            return null;
46
        }
47
48
        // build a fingerprint of the given method
49
        $fingerprintOfMethod = [];
50
        iterate_over_node($node, function ($node) use (&$fingerprintOfMethod) {
51
52
            // avoid cast
53
            if ($node instanceof Cast) {
54
                return;
55
            }
56
57
            // avoid fluent interface
58
            if ($node instanceof Return_ && $node->expr instanceof Variable && $node->expr->name === 'this') {
59
                unset($fingerprintOfMethod[sizeof($fingerprintOfMethod) - 1]);
60
                return;
61
            }
62
63
            $fingerprintOfMethod[] = get_class($node);
64
        });
65
        $fingerprintOfMethod = array_reverse($fingerprintOfMethod);
66
67
        // compare with database of fingerprints
68
        foreach ($this->fingerprints as $type => $fingerprint) {
69
            if ($fingerprint == $fingerprintOfMethod) {
70
                return $type;
71
            }
72
        }
73
74
        return null;
75
    }
76
77
}