Updated from some -dev modules to alpha, beta or full releases
[yaffs-website] / vendor / psy / psysh / src / CodeCleaner / ListPass.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2018 Justin Hileman
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\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;
21
22 /**
23  * Validate that the list assignment.
24  */
25 class ListPass extends CodeCleanerPass
26 {
27     private $atLeastPhp71;
28
29     public function __construct()
30     {
31         $this->atLeastPhp71 = version_compare(PHP_VERSION, '7.1', '>=');
32     }
33
34     /**
35      * Validate use of list assignment.
36      *
37      * @throws ParseErrorException if the user used empty with anything but a variable
38      *
39      * @param Node $node
40      */
41     public function enterNode(Node $node)
42     {
43         if (!$node instanceof Assign) {
44             return;
45         }
46
47         if (!$node->var instanceof Array_ && !$node->var instanceof List_) {
48             return;
49         }
50
51         if (!$this->atLeastPhp71 && $node->var instanceof Array_) {
52             $msg = "syntax error, unexpected '='";
53             throw new ParseErrorException($msg, $node->expr->getLine());
54         }
55
56         // Polyfill for PHP-Parser 2.x
57         $items = isset($node->var->items) ? $node->var->items : $node->var->vars;
58
59         if ($items === [] || $items === [null]) {
60             throw new ParseErrorException('Cannot use empty list', $node->var->getLine());
61         }
62
63         foreach ($items as $item) {
64             if ($item === null) {
65                 throw new ParseErrorException('Cannot use empty list', $item->getLine());
66             }
67
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());
72             }
73
74             $value = ($item instanceof ArrayItem) ? $item->value : $item;
75
76             if (!$value instanceof Variable) {
77                 $msg = 'Assignments can only happen to writable values';
78                 throw new ParseErrorException($msg, $item->getLine());
79             }
80         }
81     }
82 }