| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
/*
|
|
|
4 |
* This file is part of Psy Shell.
|
|
|
5 |
*
|
| 200 |
lars |
6 |
* (c) 2012-2023 Justin Hileman
|
| 148 |
lars |
7 |
*
|
|
|
8 |
* For the full copyright and license information, please view the LICENSE
|
|
|
9 |
* file that was distributed with this source code.
|
|
|
10 |
*/
|
|
|
11 |
|
|
|
12 |
namespace Psy\CodeCleaner;
|
|
|
13 |
|
|
|
14 |
use PhpParser\Node;
|
|
|
15 |
use PhpParser\Node\Expr\ArrayDimFetch;
|
|
|
16 |
use PhpParser\Node\Expr\Assign;
|
| 1294 |
lars |
17 |
use PhpParser\Node\Expr\AssignRef;
|
|
|
18 |
use PhpParser\Node\Stmt\Foreach_;
|
| 148 |
lars |
19 |
use Psy\Exception\FatalErrorException;
|
|
|
20 |
|
|
|
21 |
/**
|
|
|
22 |
* Validate empty brackets are only used for assignment.
|
|
|
23 |
*/
|
|
|
24 |
class EmptyArrayDimFetchPass extends CodeCleanerPass
|
|
|
25 |
{
|
|
|
26 |
const EXCEPTION_MESSAGE = 'Cannot use [] for reading';
|
|
|
27 |
|
|
|
28 |
private $theseOnesAreFine = [];
|
|
|
29 |
|
|
|
30 |
/**
|
|
|
31 |
* @return Node[]|null Array of nodes
|
|
|
32 |
*/
|
|
|
33 |
public function beforeTraverse(array $nodes)
|
|
|
34 |
{
|
|
|
35 |
$this->theseOnesAreFine = [];
|
|
|
36 |
}
|
|
|
37 |
|
|
|
38 |
/**
|
| 1294 |
lars |
39 |
* @throws FatalErrorException if the user used empty array dim fetch outside of assignment
|
| 148 |
lars |
40 |
*
|
|
|
41 |
* @param Node $node
|
|
|
42 |
*
|
|
|
43 |
* @return int|Node|null Replacement node (or special return value)
|
|
|
44 |
*/
|
|
|
45 |
public function enterNode(Node $node)
|
|
|
46 |
{
|
|
|
47 |
if ($node instanceof Assign && $node->var instanceof ArrayDimFetch) {
|
|
|
48 |
$this->theseOnesAreFine[] = $node->var;
|
| 1294 |
lars |
49 |
} elseif ($node instanceof AssignRef && $node->expr instanceof ArrayDimFetch) {
|
|
|
50 |
$this->theseOnesAreFine[] = $node->expr;
|
|
|
51 |
} elseif ($node instanceof Foreach_ && $node->valueVar instanceof ArrayDimFetch) {
|
|
|
52 |
$this->theseOnesAreFine[] = $node->valueVar;
|
| 1663 |
lars |
53 |
} elseif ($node instanceof ArrayDimFetch && $node->var instanceof ArrayDimFetch) {
|
|
|
54 |
// $a[]['b'] = 'c'
|
|
|
55 |
if (\in_array($node, $this->theseOnesAreFine)) {
|
|
|
56 |
$this->theseOnesAreFine[] = $node->var;
|
|
|
57 |
}
|
| 148 |
lars |
58 |
}
|
|
|
59 |
|
|
|
60 |
if ($node instanceof ArrayDimFetch && $node->dim === null) {
|
|
|
61 |
if (!\in_array($node, $this->theseOnesAreFine)) {
|
|
|
62 |
throw new FatalErrorException(self::EXCEPTION_MESSAGE, $node->getLine());
|
|
|
63 |
}
|
|
|
64 |
}
|
|
|
65 |
}
|
|
|
66 |
}
|