4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\CodeCleaner;
15 use PhpParser\Node\Expr\Array_;
16 use PhpParser\Node\Expr\ArrayItem;
17 use PhpParser\Node\Expr\Assign;
18 use PhpParser\Node\Expr\List_;
19 use PhpParser\Node\Expr\Variable;
20 use Psy\Exception\ParseErrorException;
23 * Validate that the list assignment.
25 class ListPass extends CodeCleanerPass
27 private $atLeastPhp71;
29 public function __construct()
31 $this->atLeastPhp71 = version_compare(PHP_VERSION, '7.1', '>=');
35 * Validate use of list assignment.
37 * @throws ParseErrorException if the user used empty with anything but a variable
41 public function enterNode(Node $node)
43 if (!$node instanceof Assign) {
47 if (!$node->var instanceof Array_ && !$node->var instanceof List_) {
51 if (!$this->atLeastPhp71 && $node->var instanceof Array_) {
52 $msg = "syntax error, unexpected '='";
53 throw new ParseErrorException($msg, $node->expr->getLine());
56 // Polyfill for PHP-Parser 2.x
57 $items = isset($node->var->items) ? $node->var->items : $node->var->vars;
59 if ($items === [] || $items === [null]) {
60 throw new ParseErrorException('Cannot use empty list', $node->var->getLine());
63 foreach ($items as $item) {
65 throw new ParseErrorException('Cannot use empty list', $item->getLine());
68 // List_->$vars in PHP-Parser 2.x is Variable instead of ArrayItem.
69 if (!$this->atLeastPhp71 && $item instanceof ArrayItem && $item->key !== null) {
70 $msg = 'Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting \',\' or \')\'';
71 throw new ParseErrorException($msg, $item->key->getLine());
74 $value = ($item instanceof ArrayItem) ? $item->value : $item;
76 if (!$value instanceof Variable) {
77 $msg = 'Assignments can only happen to writable values';
78 throw new ParseErrorException($msg, $item->getLine());