Completed
Pull Request — master (#286)
by algo13
04:39
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
    const DESCRIPTION = 'Checks for behavior that would result in overwriting $this variable.';
19
20
    /**
21
     * @param Node\Stmt $stmt
22
     * @param Context $context
23
     * @return bool
24
     */
25 4
    public function pass(Node\Stmt $stmt, Context $context)
26
    {
27 4
        if ($stmt instanceof Stmt\ClassMethod || $stmt instanceof Stmt\Function_) {
28 4
            return $this->inspectParams($stmt, $context);
29 1
        } elseif ($stmt instanceof Stmt\TryCatch) {
30 1
            return $this->inspectTryCatch($stmt, $context);
31 1
        } elseif ($stmt instanceof Stmt\Foreach_) {
32 1
            return $this->inspectForeach($stmt, $context);
33 1
        } elseif ($stmt instanceof Stmt\Static_) {
34 1
            return $this->inspectStaticVar($stmt, $context);
35 1
        } elseif ($stmt instanceof Stmt\Global_) {
36 1
            return $this->inspectGlobalVar($stmt, $context);
37 1
        } elseif ($stmt instanceof Stmt\Unset_) {
38 1
            return $this->inspectUnset($stmt, $context);
39
        }
40
41
        return false;
42
    }
43
44
    /**
45
     * @return array
46
     */
47 2
    public function getRegister()
48
    {
49
        return [
50 2
            Stmt\ClassMethod::class,
51 2
            Stmt\Function_::class,
52 2
            Stmt\TryCatch::class,
53 2
            Stmt\Foreach_::class,
54 2
            Stmt\Static_::class,
55 2
            Stmt\Global_::class,
56 2
            Stmt\Unset_::class,
57 2
        ];
58
    }
59
60
    /**
61
     * @param Stmt\ClassMethod|Stmt\Function_ $stmt
62
     * @param Context $context
63
     * @return bool
64
     */
65 4
    private function inspectParams(Stmt $stmt, Context $context)
66
    {
67
        /** @var \PhpParser\Node\Param $param */
68 4
        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...
69 1
            if ($param->name === 'this') {
70 1
                $context->notice(
71 1
                    'unexpected_use.this',
72 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...
73
                    $param
74 1
                );
75
76 1
                return true;
77
            }
78 4
        }
79
80 4
        return false;
81
    }
82
83
    /**
84
     * @param Stmt\TryCatch $tryCatchStmt
85
     * @param Context $context
86
     * @return bool
87
     */
88 1
    private function inspectTryCatch(Stmt\TryCatch $tryCatchStmt, Context $context)
89
    {
90 1
        $result = false;
91
92
        /** @var Stmt\Catch_ $catch */
93 1
        foreach ($tryCatchStmt->catches as $catch) {
94 1
            if ($catch->var === 'this') {
95 1
                $result = true;
96 1
                $context->notice(
97 1
                    'unexpected_use.this',
98 1
                    'Catch block can not have a catch variable named "this".',
99
                    $catch
100 1
                );
101 1
            }
102 1
        }
103
104 1
        return $result;
105
    }
106
107
    /**
108
     * @param Stmt\Foreach_ $foreachStmt
109
     * @param Context $context
110
     * @return bool
111
     */
112 1
    private function inspectForeach(Stmt\Foreach_ $foreachStmt, Context $context)
113
    {
114 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...
115 1
            $context->notice(
116 1
                'unexpected_use.this',
117 1
                'Foreach loop can not use a value variable named "this".',
118 1
                $foreachStmt->valueVar
119 1
            );
120
121 1
            return true;
122
        }
123
124 1
        return false;
125
    }
126
127
    /**
128
     * @param Stmt\Static_ $staticStmt
129
     * @param Context $context
130
     * @return bool
131
     */
132 1
    private function inspectStaticVar(Stmt\Static_ $staticStmt, Context $context)
133
    {
134 1
        $result = false;
135
136
        /** @var Stmt\StaticVar $var */
137 1
        foreach ($staticStmt->vars as $var) {
138 1
            if ($var->name === 'this') {
139 1
                $result = true;
140
141 1
                $context->notice(
142 1
                    'unexpected_use.this',
143 1
                    'Can not declare a static variable named "this".',
144
                    $var
145 1
                );
146 1
            }
147 1
        }
148
149 1
        return $result;
150
    }
151
152
    /**
153
     * @param Stmt\Global_ $globalStmt
154
     * @param Context $context
155
     * @return bool
156
     */
157 1
    private function inspectGlobalVar(Stmt\Global_ $globalStmt, Context $context)
158
    {
159 1
        $result = false;
160
161 1
        foreach ($globalStmt->vars as $var) {
162 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...
163 1
                $result = true;
164
165 1
                $context->notice(
166 1
                    'unexpected_use.this',
167 1
                    'Can not declare a global variable named "this".',
168
                    $var
169 1
                );
170 1
            }
171 1
        }
172
173 1
        return $result;
174
    }
175
176
    /**
177
     * @param Stmt\Unset_ $unsetStmt
178
     * @param Context $context
179
     * @return bool
180
     */
181 1
    private function inspectUnset(Stmt\Unset_ $unsetStmt, Context $context)
182
    {
183 1
        $result = false;
184
185 1
        foreach ($unsetStmt->vars as $var) {
186 1
            if (($var instanceof Node\Expr\Variable)
187 1
             && ($var->name === 'this')
188 1
            ) {
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