Completed
Pull Request — master (#196)
by Enrico
05:34 queued 41s
created

Context::debug()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 6.7968

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 2
dl 0
loc 16
ccs 3
cts 12
cp 0.25
crap 6.7968
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
4
 */
5
6
namespace PHPSA;
7
8
use PHPSA\Compiler\Expression;
9
use PHPSA\Compiler\GlobalVariable;
10
use PHPSA\Definition\AbstractDefinition;
11
use PHPSA\Definition\ParentDefinition;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Webiny\Component\EventManager\EventManager;
14
15
class Context
16
{
17
    /**
18
     * For FunctionDefinition it's null, use scopePointer
19
     *
20
     * @var ParentDefinition|null
21
     */
22
    public $scope;
23
24
    /**
25
     * @var AliasManager
26
     */
27
    public $aliasManager;
28
29
    /**
30
     * @var Application
31
     */
32
    public $application;
33
34
    /**
35
     * @var string|integer
36
     */
37
    public $currentBranch;
38
39
    /**
40
     * @var OutputInterface
41
     */
42
    public $output;
43
44
    /**
45
     * @var Variable[]
46
     */
47
    protected $symbols = [];
48
49
    /**
50
     * @var ScopePointer|null
51
     */
52
    public $scopePointer;
53
54
    /**
55
     * @var string
56
     */
57
    protected $filepath;
58
59
    /**
60
     * @var EventManager
61
     */
62
    protected $eventManager;
63
64
    /**
65
     * Construct our Context with all needed information
66
     *
67
     * @param OutputInterface $output
68
     * @param Application $application
69
     * @param EventManager $eventManager
70
     */
71 857
    public function __construct(OutputInterface $output, Application $application, EventManager $eventManager)
72
    {
73 857
        $this->output = $output;
74 857
        $this->application = $application;
75
76 857
        $this->initGlobals();
77 857
        $this->eventManager = $eventManager;
78 857
    }
79
80
    /**
81
     * @return Expression
82
     */
83 849
    public function getExpressionCompiler()
84
    {
85 849
        return new Expression($this, $this->eventManager);
86
    }
87
88
    /**
89
     * Adds all global variables to the context.
90
     */
91 857
    public function initGlobals()
92
    {
93
        /**
94
         * http://php.net/manual/language.variables.superglobals.php
95
         */
96 857
        $this->addVariable(new GlobalVariable('GLOBALS', [], CompiledExpression::ARR));
97 857
        $this->addVariable(new GlobalVariable('_SERVER', [], CompiledExpression::ARR));
98 857
        $this->addVariable(new GlobalVariable('_GET', [], CompiledExpression::ARR));
99 857
        $this->addVariable(new GlobalVariable('_POST', [], CompiledExpression::ARR));
100 857
        $this->addVariable(new GlobalVariable('_FILES', [], CompiledExpression::ARR));
101 857
        $this->addVariable(new GlobalVariable('_COOKIE', [], CompiledExpression::ARR));
102 857
        $this->addVariable(new GlobalVariable('_SESSION', [], CompiledExpression::ARR));
103 857
        $this->addVariable(new GlobalVariable('_REQUEST', [], CompiledExpression::ARR));
104 857
        $this->addVariable(new GlobalVariable('_ENV', [], CompiledExpression::ARR));
105 857
    }
106
107
    /**
108
     * Creates a variable from a symbol and adds it to the context.
109
     *
110
     * @param string $name
111
     * @return Variable
112
     */
113 1
    public function addSymbol($name)
114
    {
115 1
        $variable = new Variable($name);
116 1
        $this->symbols[$name] = $variable;
117
118 1
        return $variable;
119
    }
120
121
    /**
122
     * Adds a variable to the context.
123
     *
124
     * @param Variable $variable
125
     * @return bool
126
     */
127 857
    public function addVariable(Variable $variable)
128
    {
129 857
        $this->symbols[$variable->getName()] = $variable;
130
131 857
        return true;
132
    }
133
134
    /**
135
     * Resets context to beginning stage.
136
     */
137 30
    public function clear()
138
    {
139 30
        $this->symbols = [];
140 30
        $this->scope = null;
141 30
        $this->scopePointer = null;
142 30
        $this->currentBranch = null;
143 30
        $this->aliasManager = null;
144
145 30
        $this->initGlobals();
146 30
    }
147
148
    /**
149
     * Clears only all symbols.
150
     */
151 28
    public function clearSymbols()
152
    {
153 28
        unset($this->symbols);
154 28
        $this->symbols = [];
155 28
    }
156
157
    /**
158
     * Returns a variable if it exists.
159
     *
160
     * @param $name
161
     * @return Variable|null
162
     */
163 72
    public function getSymbol($name)
164
    {
165 72
        return isset($this->symbols[$name]) ? $this->symbols[$name] : null;
166
    }
167
168
    /**
169
     * Creates a warning message.
170
     *
171
     * @param string $type
172
     * @param string $message
173
     * @return bool
174
     */
175 5
    public function warning($type, $message)
176
    {
177 5
        $this->output
178 5
            ->writeln('<comment>Warning:  ' . $message . ' in ' . $this->filepath . '  [' . $type . ']</comment>');
179
180 5
        $this->output->writeln('');
181
182 5
        return true;
183
    }
184
185
    /**
186
     * Creates a notice message.
187
     *
188
     * @param string $type
189
     * @param string $message
190
     * @param \PhpParser\NodeAbstract $expr
191
     * @param int $status
192
     * @return bool
193
     */
194 30
    public function notice($type, $message, \PhpParser\NodeAbstract $expr, $status = Check::CHECK_SAFE)
0 ignored issues
show
Unused Code introduced by
The parameter $status is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
195
    {
196 30
        $filepath = $this->filepath;
197 30
        $code = file($filepath);
198
199 30
        $this->output->writeln('<comment>Notice:  ' . $message . " in {$filepath} on {$expr->getLine()} [{$type}]</comment>");
200 30
        $this->output->writeln('');
201
202 30
        if ($this->application->getConfiguration()->valueIsTrue('blame')) {
203
            exec("git blame --show-email -L {$expr->getLine()},{$expr->getLine()} " . $filepath, $result);
204
            if ($result && isset($result[0])) {
205
                $result[0] = trim($result[0]);
206
207
                $this->output->writeln("<comment>\t {$result[0]}</comment>");
208
            }
209
        } else {
210 30
            $code = trim($code[$expr->getLine() - 1]);
211 30
            $this->output->writeln("<comment>\t {$code} </comment>");
212
        }
213
214 30
        $this->output->writeln('');
215
216 30
        $this->application->getIssuesCollector()
217 30
            ->addIssue($type, $message, basename($this->filepath), $expr->getLine() - 1);
218
219 30
        return true;
220
    }
221
222
    /**
223
     * Creates a syntax error message.
224
     *
225
     * @param \PhpParser\Error $exception
226
     * @param string $filepath
227
     * @return bool
228
     */
229
    public function syntaxError(\PhpParser\Error $exception, $filepath)
230
    {
231
        $code = file($filepath);
232
233
        $this->output->writeln('<error>Syntax error:  ' . $exception->getMessage() . " in {$filepath} </error>");
234
        $this->output->writeln('');
235
236
        $this->application->getIssuesCollector()
237
            ->addIssue('syntax-error', 'syntax-error', $filepath, $exception->getStartLine() - 2);
238
239
        $code = trim($code[$exception->getStartLine()-2]);
240
        $this->output->writeln("<comment>\t {$code} </comment>");
241
242
        return true;
243
    }
244
245
    /**
246
     * Returns an array of all variables.
247
     *
248
     * @return Variable[]
249
     */
250 28
    public function getSymbols()
251
    {
252 28
        return $this->symbols;
253
    }
254
255
    /**
256
     * @param AbstractDefinition $scope
257
     */
258 857
    public function setScope(AbstractDefinition $scope = null)
259
    {
260 857
        $this->scope = $scope;
0 ignored issues
show
Documentation Bug introduced by
It seems like $scope can also be of type object<PHPSA\Definition\AbstractDefinition>. However, the property $scope is declared as type object<PHPSA\Definition\ParentDefinition>|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
261 857
    }
262
263
    /**
264
     * Creates a debug message.
265
     */
266 30
    public function debug($message, \PhpParser\Node $expr = null)
267
    {
268 30
        if ($this->output->isDebug()) {
269
            $this->output->writeln('[DEBUG] ' . $message);
270
            $this->output->write($this->filepath);
271
272
            if ($expr) {
273
                $this->output->write(':' . $expr->getLine());
274
275
                $code = trim($code[$expr->getLine() - 1]);
0 ignored issues
show
Bug introduced by
The variable $code 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...
276
                $this->output->writeln("<comment>\t {$code} </comment>");
277
            }
278
279
            $this->output->writeln('');
280
        }
281 30
    }
282
283
    /**
284
     * @return string
285
     */
286
    public function getFilepath()
287
    {
288
        return $this->filepath;
289
    }
290
291
    /**
292
     * @param string $filepath
293
     */
294 30
    public function setFilepath($filepath)
295
    {
296 30
        $this->filepath = $filepath;
297 30
    }
298
299
    /**
300
     * @return integer
301
     */
302 29
    public function getCurrentBranch()
303
    {
304 29
        return $this->currentBranch;
305
    }
306
307
    /**
308
     * @param int|string $currentBranch
309
     */
310 5
    public function setCurrentBranch($currentBranch)
311
    {
312 5
        $this->currentBranch = $currentBranch;
313 5
    }
314
315
    /**
316
     * Updates all references on the given variable.
317
     *
318
     * @param Variable $variable
319
     * @param $type
320
     * @param $value
321
     */
322 4
    public function modifyReferencedVariables(Variable $variable, $type, $value)
323
    {
324 4
        foreach ($this->symbols as $symbol) {
325 4
            $referencedTo = $symbol->getReferencedTo();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $referencedTo is correct as $symbol->getReferencedTo() (which targets PHPSA\Variable::getReferencedTo()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
326 4
            if ($referencedTo) {
327 2
                if ($referencedTo === $variable) {
328 2
                    $symbol->modify($type, $value);
329 2
                }
330 2
            }
331 4
        }
332 4
    }
333
334
    /**
335
     * @return EventManager
336
     */
337 43
    public function getEventManager()
338
    {
339 43
        return $this->eventManager;
340
    }
341
}
342