Completed
Pull Request — master (#139)
by Kévin
15:46 queued 02:25
created

UnexpectedUseOfThis::pass()   C

Complexity

Conditions 10
Paths 9

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 10.0454

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
eloc 16
nc 9
nop 2
dl 0
loc 22
ccs 12
cts 13
cp 0.9231
crap 10.0454
rs 6.1368
c 2
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @author Kévin Gomez https://github.com/K-Phoen <[email protected]>
4
 */
5
6
namespace PHPSA\Analyzer\Pass\Statement;
7
8
use PhpParser\Node\Stmt;
9
use PhpParser\Node;
10
use PHPSA\Analyzer\Helper\DefaultMetadataPassTrait;
11
use PHPSA\Analyzer\Pass;
12
use PHPSA\Context;
13
14
class UnexpectedUseOfThis implements Pass\AnalyzerPassInterface
15
{
16
    use DefaultMetadataPassTrait;
17
18
    /**
19
     * @param Node\Stmt $stmt
20 37
     * @param Context $context
21
     * @return bool
22 37
     */
23 37
    public function pass(Node\Stmt $stmt, Context $context)
24 3
    {
25 1
        if ($stmt instanceof Stmt\ClassMethod || $stmt instanceof Stmt\Function_) {
26 3
            return $this->inspectParams($stmt, $context);
27 1
        } elseif ($stmt instanceof Stmt\TryCatch) {
28 3
            return $this->inspectTryCatch($stmt, $context);
29 2
        } elseif ($stmt instanceof Stmt\Foreach_) {
30 2
            return $this->inspectForeach($stmt, $context);
31 2
        } elseif ($stmt instanceof Stmt\Static_) {
32 1
            return $this->inspectStaticVar($stmt, $context);
33 1
        } elseif ($stmt instanceof Stmt\Global_) {
34
            return $this->inspectGlobalVar($stmt, $context);
35
        } elseif ($stmt instanceof Stmt\Unset_) {
36
            return $this->inspectUnset($stmt, $context);
37
        }
38
39
        if ($stmt instanceof Stmt\Unset_) {
40
            return $this->inspectUnset($stmt, $context) || $result;
0 ignored issues
show
Bug introduced by
The variable $result does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
41
        }
42 1
43
        return false;
44
    }
45 1
46 1
    /**
47 1
     * @return array
48 1
     */
49 1
    public function getRegister()
50 1
    {
51 1
        return [
52 1
            Stmt\ClassMethod::class,
53
            Stmt\Function_::class,
54
            Stmt\TryCatch::class,
55
            Stmt\Foreach_::class,
56
            Stmt\Static_::class,
57
            Stmt\Global_::class,
58
            Stmt\Unset_::class,
59
        ];
60 37
    }
61
62
    /**
63 37
     * @param Stmt\ClassMethod|Stmt\Function_ $stmt
64 4
     * @param Context $context
65 1
     * @return bool
66 1
     */
67 1
    private function inspectParams(Stmt $stmt, Context $context)
68
    {
69 1
        /** @var \PhpParser\Node\Param $param */
70
        foreach ($stmt->getParams() as $param) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class PhpParser\Node\Stmt as the method getParams() does only exist in the following sub-classes of PhpParser\Node\Stmt: PhpParser\Node\Stmt\ClassMethod, PhpParser\Node\Stmt\Function_. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
71 1
            if ($param->name === 'this') {
72
                $context->notice(
73 37
                    'unexpected_use.this',
74
                    sprintf('Method/Function %s can not have a parameter named "this".', $stmt->name),
0 ignored issues
show
Bug introduced by
The property name does not seem to exist in PhpParser\Node\Stmt.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
75 37
                    $param
76
                );
77
78
                return true;
79
            }
80
        }
81
82
        return false;
83 1
    }
84
85 1
    /**
86
     * @param Stmt\TryCatch $tryCatchStmt
87
     * @param Context $context
88 1
     * @return bool
89 1
     */
90 1
    private function inspectTryCatch(Stmt\TryCatch $tryCatchStmt, Context $context)
91 1
    {
92 1
        $result = false;
93 1
94
        /** @var Stmt\Catch_ $catch */
95 1
        foreach ($tryCatchStmt->catches as $catch) {
96 1
            if ($catch->var === 'this') {
97 1
                $result = true;
98
                $context->notice(
99 1
                    'unexpected_use.this',
100
                    'Catch block can not have a catch variable named "this".',
101
                    $catch
102
                );
103
            }
104
        }
105
106
        return $result;
107 1
    }
108
109 1
    /**
110 1
     * @param Stmt\Foreach_ $foreachStmt
111 1
     * @param Context $context
112 1
     * @return bool
113 1
     */
114 1
    private function inspectForeach(Stmt\Foreach_ $foreachStmt, Context $context)
115
    {
116 1
        if ($foreachStmt->valueVar->name === 'this') {
0 ignored issues
show
Bug introduced by
The property name does not seem to exist in PhpParser\Node\Expr.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
117
            $context->notice(
118
                'unexpected_use.this',
119 1
                'Foreach loop can not use a value variable named "this".',
120
                $foreachStmt->valueVar
121
            );
122
123
            return true;
124
        }
125
126
        return false;
127 2
    }
128
129 2
    /**
130
     * @param Stmt\Static_ $staticStmt
131
     * @param Context $context
132 2
     * @return bool
133 2
     */
134 1
    private function inspectStaticVar(Stmt\Static_ $staticStmt, Context $context)
135
    {
136 1
        $result = false;
137 1
138 1
        /** @var Stmt\StaticVar $var */
139
        foreach ($staticStmt->vars as $var) {
140 1
            if ($var->name === 'this') {
141 1
                $result = true;
142 2
143
                $context->notice(
144 2
                    'unexpected_use.this',
145
                    'Can not declare a static variable named "this".',
146
                    $var
147
                );
148
            }
149
        }
150
151
        return $result;
152 2
    }
153
154 2
    /**
155
     * @param Stmt\Global_ $globalStmt
156 2
     * @param Context $context
157 2
     * @return bool
158 1
     */
159
    private function inspectGlobalVar(Stmt\Global_ $globalStmt, Context $context)
160 1
    {
161 1
        $result = false;
162 1
163
        foreach ($globalStmt->vars as $var) {
164 1
            if ($var->name === 'this') {
0 ignored issues
show
Bug introduced by
The property name does not seem to exist in PhpParser\Node\Expr.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
165 1
                $result = true;
166 2
167
                $context->notice(
168 2
                    'unexpected_use.this',
169
                    'Can not declare a global variable named "this".',
170
                    $var
171
                );
172
            }
173
        }
174
175
        return $result;
176 1
    }
177
178 1
    /**
179
     * @param Stmt\Unset_ $unsetStmt
180 1
     * @param Context $context
181 1
     * @return bool
182 1
     */
183
    private function inspectUnset(Stmt\Unset_ $unsetStmt, Context $context)
184 1
    {
185 1
        $result = false;
186 1
187
        foreach ($unsetStmt->vars as $var) {
188 1
            if ($var->name === 'this') {
0 ignored issues
show
Bug introduced by
The property name does not seem to exist in PhpParser\Node\Expr.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
189 1
                $result = true;
190 1
191
                $context->notice(
192 1
                    'unexpected_use.this',
193
                    'Can not unset $this.',
194
                    $var
195
                );
196
            }
197
        }
198
199
        return $result;
200
    }
201
}
202