Completed
Pull Request — master (#139)
by Kévin
06:24
created

UnexpectedUseOfThis::inspectForeach()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 14
ccs 9
cts 9
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
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
     * @param Context $context
21
     * @return bool
22
     */
23 35
    public function pass(Node\Stmt $stmt, Context $context)
24
    {
25 35
        if ($stmt instanceof Stmt\ClassMethod || $stmt instanceof Stmt\Function_) {
26 35
            return $this->inspectParams($stmt, $context);
27 3
        } elseif ($stmt instanceof Stmt\TryCatch) {
28 1
            return $this->inspectTryCatch($stmt, $context);
29 3
        } elseif ($stmt instanceof Stmt\Foreach_) {
30 1
            return $this->inspectForeach($stmt, $context);
31 3
        } elseif ($stmt instanceof Stmt\Static_) {
32 2
            return $this->inspectStaticVar($stmt, $context);
33 2
        } elseif ($stmt instanceof Stmt\Global_) {
34 2
            return $this->inspectGlobalVar($stmt, $context);
35 1
        } elseif ($stmt instanceof Stmt\Unset_) {
36 1
            return $this->inspectUnset($stmt, $context);
37
        }
38
39
        if ($stmt instanceof Stmt\Unset_) {
40
            $result = $this->inspectUnset($stmt, $context) || $result;
0 ignored issues
show
Bug introduced by
The variable $result seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
41
        }
42
43
        return $result;
0 ignored issues
show
Bug introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
44
    }
45
46
    /**
47
     * @return array
48
     */
49 1
    public function getRegister()
50
    {
51
        return [
52 1
            Stmt\ClassMethod::class,
53 1
            Stmt\Function_::class,
54 1
            Stmt\TryCatch::class,
55 1
            Stmt\Foreach_::class,
56 1
            Stmt\Static_::class,
57 1
            Stmt\Global_::class,
58 1
            Stmt\Unset_::class,
59 1
        ];
60
    }
61
62
    /**
63
     * @param Stmt\ClassMethod|Stmt\Function_ $stmt
64
     * @param Context $context
65
     * @return bool
66
     */
67 35
    private function inspectParams(Stmt $stmt, Context $context)
68
    {
69
        /** @var \PhpParser\Node\Param $param */
70 35
        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 4
            if ($param->name === 'this') {
72 1
                $context->notice(
73 1
                    'unexpected_use.this',
74 1
                    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
                    $param
76 1
                );
77
78 1
                return true;
79
            }
80 35
        }
81
82 35
        return false;
83
    }
84
85
    /**
86
     * @param Stmt\TryCatch $tryCatchStmt
87
     * @param Context $context
88
     * @return bool
89
     */
90 1
    private function inspectTryCatch(Stmt\TryCatch $tryCatchStmt, Context $context)
91
    {
92 1
        $result = false;
93
94
        /** @var Stmt\Catch_ $catch */
95 1
        foreach ($tryCatchStmt->catches as $catch) {
96 1
            if ($catch->var === 'this') {
97 1
                $result = true;
98 1
                $context->notice(
99 1
                    'unexpected_use.this',
100 1
                    'Catch block can not have a catch variable named "this".',
101
                    $catch
102 1
                );
103 1
            }
104 1
        }
105
106 1
        return $result;
107
    }
108
109
    /**
110
     * @param Stmt\Foreach_ $foreachStmt
111
     * @param Context $context
112
     * @return bool
113
     */
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 1
            $context->notice(
118 1
                'unexpected_use.this',
119 1
                'Foreach loop can not use a value variable named "this".',
120 1
                $foreachStmt->valueVar
121 1
            );
122
123 1
            return true;
124
        }
125
126 1
        return false;
127
    }
128
129
    /**
130
     * @param Stmt\Static_ $staticStmt
131
     * @param Context $context
132
     * @return bool
133
     */
134 2
    private function inspectStaticVar(Stmt\Static_ $staticStmt, Context $context)
135
    {
136 2
        $result = false;
137
138
        /** @var Stmt\StaticVar $var */
139 2
        foreach ($staticStmt->vars as $var) {
140 2
            if ($var->name === 'this') {
141 1
                $result = true;
142
143 1
                $context->notice(
144 1
                    'unexpected_use.this',
145 1
                    'Can not declare a static variable named "this".',
146
                    $var
147 1
                );
148 1
            }
149 2
        }
150
151 2
        return $result;
152
    }
153
154
    /**
155
     * @param Stmt\Global_ $globalStmt
156
     * @param Context $context
157
     * @return bool
158
     */
159 2
    private function inspectGlobalVar(Stmt\Global_ $globalStmt, Context $context)
160
    {
161 2
        $result = false;
162
163 2
        foreach ($globalStmt->vars as $var) {
164 2
            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
167 1
                $context->notice(
168 1
                    'unexpected_use.this',
169 1
                    'Can not declare a global variable named "this".',
170
                    $var
171 1
                );
172 1
            }
173 2
        }
174
175 2
        return $result;
176
    }
177
178
    /**
179
     * @param Stmt\Unset_ $unsetStmt
180
     * @param Context $context
181
     * @return bool
182
     */
183 1
    private function inspectUnset(Stmt\Unset_ $unsetStmt, Context $context)
184
    {
185 1
        $result = false;
186
187 1
        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
191 1
                $context->notice(
192 1
                    'unexpected_use.this',
193 1
                    'Can not unset $this.',
194
                    $var
195 1
                );
196 1
            }
197 1
        }
198
199 1
        return $result;
200
    }
201
}
202