Completed
Pull Request — master (#201)
by Enrico
04:20
created

UnexpectedUseOfThis::inspectParams()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 3
rs 9.4285
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\Pass;
11
use PHPSA\Context;
12
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
13
14
class UnexpectedUseOfThis implements Pass\ConfigurablePassInterface, Pass\AnalyzerPassInterface
15
{
16
    /**
17
     * @param Node\Stmt $stmt
18
     * @param Context $context
19
     * @return bool
20
     */
21 28
    public function pass(Node\Stmt $stmt, Context $context)
22
    {
23 28
        if ($stmt instanceof Stmt\ClassMethod || $stmt instanceof Stmt\Function_) {
24 28
            return $this->inspectParams($stmt, $context);
25 1
        } elseif ($stmt instanceof Stmt\TryCatch) {
26 1
            return $this->inspectTryCatch($stmt, $context);
27 1
        } elseif ($stmt instanceof Stmt\Foreach_) {
28 1
            return $this->inspectForeach($stmt, $context);
29 1
        } elseif ($stmt instanceof Stmt\Static_) {
30 1
            return $this->inspectStaticVar($stmt, $context);
31 1
        } elseif ($stmt instanceof Stmt\Global_) {
32 1
            return $this->inspectGlobalVar($stmt, $context);
33 1
        } elseif ($stmt instanceof Stmt\Unset_) {
34 1
            return $this->inspectUnset($stmt, $context);
35
        }
36
37
        return false;
38
    }
39
40
    /**
41
     * @return TreeBuilder
42
     */
43
    public function getConfiguration()
44
    {
45
        $treeBuilder = new TreeBuilder();
46
        $treeBuilder->root('unexpected_use.this')
47
            ->canBeDisabled()
48
        ;
49
50
        return $treeBuilder;
51
    }
52
53
    /**
54
     * @return array
55
     */
56 1
    public function getRegister()
57
    {
58
        return [
59 1
            Stmt\ClassMethod::class,
60 1
            Stmt\Function_::class,
61 1
            Stmt\TryCatch::class,
62 1
            Stmt\Foreach_::class,
63 1
            Stmt\Static_::class,
64 1
            Stmt\Global_::class,
65 1
            Stmt\Unset_::class,
66 1
        ];
67
    }
68
69
    /**
70
     * @param Stmt\ClassMethod|Stmt\Function_ $stmt
71
     * @param Context $context
72
     * @return bool
73
     */
74 28
    private function inspectParams(Stmt $stmt, Context $context)
75
    {
76
        /** @var \PhpParser\Node\Param $param */
77 28
        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...
78 3
            if ($param->name === 'this') {
79 1
                $context->notice(
80 1
                    'unexpected_use.this',
81 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...
82
                    $param
83 1
                );
84
85 1
                return true;
86
            }
87 28
        }
88
89 28
        return false;
90
    }
91
92
    /**
93
     * @param Stmt\TryCatch $tryCatchStmt
94
     * @param Context $context
95
     * @return bool
96
     */
97 1
    private function inspectTryCatch(Stmt\TryCatch $tryCatchStmt, Context $context)
98
    {
99 1
        $result = false;
100
101
        /** @var Stmt\Catch_ $catch */
102 1
        foreach ($tryCatchStmt->catches as $catch) {
103 1
            if ($catch->var === 'this') {
104 1
                $result = true;
105 1
                $context->notice(
106 1
                    'unexpected_use.this',
107 1
                    'Catch block can not have a catch variable named "this".',
108
                    $catch
109 1
                );
110 1
            }
111 1
        }
112
113 1
        return $result;
114
    }
115
116
    /**
117
     * @param Stmt\Foreach_ $foreachStmt
118
     * @param Context $context
119
     * @return bool
120
     */
121 1
    private function inspectForeach(Stmt\Foreach_ $foreachStmt, Context $context)
122
    {
123 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...
124 1
            $context->notice(
125 1
                'unexpected_use.this',
126 1
                'Foreach loop can not use a value variable named "this".',
127 1
                $foreachStmt->valueVar
128 1
            );
129
130 1
            return true;
131
        }
132
133 1
        return false;
134
    }
135
136
    /**
137
     * @param Stmt\Static_ $staticStmt
138
     * @param Context $context
139
     * @return bool
140
     */
141 1
    private function inspectStaticVar(Stmt\Static_ $staticStmt, Context $context)
142
    {
143 1
        $result = false;
144
145
        /** @var Stmt\StaticVar $var */
146 1
        foreach ($staticStmt->vars as $var) {
147 1
            if ($var->name === 'this') {
148 1
                $result = true;
149
150 1
                $context->notice(
151 1
                    'unexpected_use.this',
152 1
                    'Can not declare a static variable named "this".',
153
                    $var
154 1
                );
155 1
            }
156 1
        }
157
158 1
        return $result;
159
    }
160
161
    /**
162
     * @param Stmt\Global_ $globalStmt
163
     * @param Context $context
164
     * @return bool
165
     */
166 1
    private function inspectGlobalVar(Stmt\Global_ $globalStmt, Context $context)
167
    {
168 1
        $result = false;
169
170 1
        foreach ($globalStmt->vars as $var) {
171 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...
172 1
                $result = true;
173
174 1
                $context->notice(
175 1
                    'unexpected_use.this',
176 1
                    'Can not declare a global variable named "this".',
177
                    $var
178 1
                );
179 1
            }
180 1
        }
181
182 1
        return $result;
183
    }
184
185
    /**
186
     * @param Stmt\Unset_ $unsetStmt
187
     * @param Context $context
188
     * @return bool
189
     */
190 1
    private function inspectUnset(Stmt\Unset_ $unsetStmt, Context $context)
191
    {
192 1
        $result = false;
193
194 1
        foreach ($unsetStmt->vars as $var) {
195 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...
196 1
                $result = true;
197
198 1
                $context->notice(
199 1
                    'unexpected_use.this',
200 1
                    'Can not unset $this.',
201
                    $var
202 1
                );
203 1
            }
204 1
        }
205
206 1
        return $result;
207
    }
208
}
209