Chris@13
|
1 <?php
|
Chris@13
|
2
|
Chris@13
|
3 /*
|
Chris@13
|
4 * This file is part of Psy Shell.
|
Chris@13
|
5 *
|
Chris@13
|
6 * (c) 2012-2018 Justin Hileman
|
Chris@13
|
7 *
|
Chris@13
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@13
|
9 * file that was distributed with this source code.
|
Chris@13
|
10 */
|
Chris@13
|
11
|
Chris@13
|
12 namespace Psy\CodeCleaner;
|
Chris@13
|
13
|
Chris@13
|
14 use PhpParser\Node;
|
Chris@13
|
15 use PhpParser\Node\Expr\Empty_;
|
Chris@13
|
16 use PhpParser\Node\Expr\Variable;
|
Chris@13
|
17 use Psy\Exception\ParseErrorException;
|
Chris@13
|
18
|
Chris@13
|
19 /**
|
Chris@13
|
20 * Validate that the user did not call the language construct `empty()` on a
|
Chris@13
|
21 * statement in PHP < 5.5.
|
Chris@16
|
22 *
|
Chris@16
|
23 * @codeCoverageIgnore
|
Chris@13
|
24 */
|
Chris@13
|
25 class LegacyEmptyPass extends CodeCleanerPass
|
Chris@13
|
26 {
|
Chris@13
|
27 private $atLeastPhp55;
|
Chris@13
|
28
|
Chris@13
|
29 public function __construct()
|
Chris@13
|
30 {
|
Chris@17
|
31 $this->atLeastPhp55 = \version_compare(PHP_VERSION, '5.5', '>=');
|
Chris@13
|
32 }
|
Chris@13
|
33
|
Chris@13
|
34 /**
|
Chris@13
|
35 * Validate use of empty in PHP < 5.5.
|
Chris@13
|
36 *
|
Chris@13
|
37 * @throws ParseErrorException if the user used empty with anything but a variable
|
Chris@13
|
38 *
|
Chris@13
|
39 * @param Node $node
|
Chris@13
|
40 */
|
Chris@13
|
41 public function enterNode(Node $node)
|
Chris@13
|
42 {
|
Chris@13
|
43 if ($this->atLeastPhp55) {
|
Chris@13
|
44 return;
|
Chris@13
|
45 }
|
Chris@13
|
46
|
Chris@13
|
47 if (!$node instanceof Empty_) {
|
Chris@13
|
48 return;
|
Chris@13
|
49 }
|
Chris@13
|
50
|
Chris@13
|
51 if (!$node->expr instanceof Variable) {
|
Chris@17
|
52 $msg = \sprintf('syntax error, unexpected %s', $this->getUnexpectedThing($node->expr));
|
Chris@13
|
53
|
Chris@13
|
54 throw new ParseErrorException($msg, $node->expr->getLine());
|
Chris@13
|
55 }
|
Chris@13
|
56 }
|
Chris@13
|
57
|
Chris@13
|
58 private function getUnexpectedThing(Node $node)
|
Chris@13
|
59 {
|
Chris@13
|
60 switch ($node->getType()) {
|
Chris@13
|
61 case 'Scalar_String':
|
Chris@13
|
62 case 'Scalar_LNumber':
|
Chris@13
|
63 case 'Scalar_DNumber':
|
Chris@17
|
64 return \json_encode($node->value);
|
Chris@13
|
65
|
Chris@13
|
66 case 'Expr_ConstFetch':
|
Chris@13
|
67 return (string) $node->name;
|
Chris@13
|
68
|
Chris@13
|
69 default:
|
Chris@13
|
70 return $node->getType();
|
Chris@13
|
71 }
|
Chris@13
|
72 }
|
Chris@13
|
73 }
|