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@13
|
22 */
|
Chris@13
|
23 class LegacyEmptyPass extends CodeCleanerPass
|
Chris@13
|
24 {
|
Chris@13
|
25 private $atLeastPhp55;
|
Chris@13
|
26
|
Chris@13
|
27 public function __construct()
|
Chris@13
|
28 {
|
Chris@13
|
29 $this->atLeastPhp55 = version_compare(PHP_VERSION, '5.5', '>=');
|
Chris@13
|
30 }
|
Chris@13
|
31
|
Chris@13
|
32 /**
|
Chris@13
|
33 * Validate use of empty in PHP < 5.5.
|
Chris@13
|
34 *
|
Chris@13
|
35 * @throws ParseErrorException if the user used empty with anything but a variable
|
Chris@13
|
36 *
|
Chris@13
|
37 * @param Node $node
|
Chris@13
|
38 */
|
Chris@13
|
39 public function enterNode(Node $node)
|
Chris@13
|
40 {
|
Chris@13
|
41 if ($this->atLeastPhp55) {
|
Chris@13
|
42 return;
|
Chris@13
|
43 }
|
Chris@13
|
44
|
Chris@13
|
45 if (!$node instanceof Empty_) {
|
Chris@13
|
46 return;
|
Chris@13
|
47 }
|
Chris@13
|
48
|
Chris@13
|
49 if (!$node->expr instanceof Variable) {
|
Chris@13
|
50 $msg = sprintf('syntax error, unexpected %s', $this->getUnexpectedThing($node->expr));
|
Chris@13
|
51
|
Chris@13
|
52 throw new ParseErrorException($msg, $node->expr->getLine());
|
Chris@13
|
53 }
|
Chris@13
|
54 }
|
Chris@13
|
55
|
Chris@13
|
56 private function getUnexpectedThing(Node $node)
|
Chris@13
|
57 {
|
Chris@13
|
58 switch ($node->getType()) {
|
Chris@13
|
59 case 'Scalar_String':
|
Chris@13
|
60 case 'Scalar_LNumber':
|
Chris@13
|
61 case 'Scalar_DNumber':
|
Chris@13
|
62 return json_encode($node->value);
|
Chris@13
|
63
|
Chris@13
|
64 case 'Expr_ConstFetch':
|
Chris@13
|
65 return (string) $node->name;
|
Chris@13
|
66
|
Chris@13
|
67 default:
|
Chris@13
|
68 return $node->getType();
|
Chris@13
|
69 }
|
Chris@13
|
70 }
|
Chris@13
|
71 }
|