4 * This file is part of Psy Shell.
6 * (c) 2012-2017 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_ as ArrayNode;
16 use PhpParser\Node\Expr\Assign as AssignNode;
17 use PhpParser\Node\Expr\Empty_ as EmptyNode;
18 use PhpParser\Node\Expr\FuncCall as FunctionCall;
19 use PhpParser\Node\Expr\Isset_ as IssetNode;
20 use PhpParser\Node\Expr\MethodCall;
21 use PhpParser\Node\Expr\StaticCall;
22 use Psy\Exception\FatalErrorException;
25 * Validate that the functions are used correctly.
27 * @author Martin HasoĊ <martin.hason@gmail.com>
29 class FunctionReturnInWriteContextPass extends CodeCleanerPass
31 const EXCEPTION_MESSAGE = "Can't use function return value in write context";
35 public function __construct()
37 $this->isPhp55 = version_compare(PHP_VERSION, '5.5', '>=');
41 * Validate that the functions are used correctly.
43 * @throws FatalErrorException if a function is passed as an argument reference
44 * @throws FatalErrorException if a function is used as an argument in the isset
45 * @throws FatalErrorException if a function is used as an argument in the empty, only for PHP < 5.5
46 * @throws FatalErrorException if a value is assigned to a function
50 public function enterNode(Node $node)
52 if ($node instanceof ArrayNode || $this->isCallNode($node)) {
53 $items = $node instanceof ArrayNode ? $node->items : $node->args;
54 foreach ($items as $item) {
55 if ($item->byRef && $this->isCallNode($item->value)) {
56 throw new FatalErrorException(self::EXCEPTION_MESSAGE);
59 } elseif ($node instanceof IssetNode) {
60 foreach ($node->vars as $var) {
61 if (!$this->isCallNode($var)) {
66 throw new FatalErrorException('Cannot use isset() on the result of a function call (you can use "null !== func()" instead)');
68 throw new FatalErrorException(self::EXCEPTION_MESSAGE);
71 } elseif ($node instanceof EmptyNode && !$this->isPhp55 && $this->isCallNode($node->expr)) {
72 throw new FatalErrorException(self::EXCEPTION_MESSAGE);
73 } elseif ($node instanceof AssignNode && $this->isCallNode($node->var)) {
74 throw new FatalErrorException(self::EXCEPTION_MESSAGE);
78 private function isCallNode(Node $node)
80 return $node instanceof FunctionCall || $node instanceof MethodCall || $node instanceof StaticCall;