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;
16 use PhpParser\Node\Expr\ClassConstFetch;
17 use PhpParser\Node\Expr\FuncCall;
18 use PhpParser\Node\Expr\MethodCall;
19 use PhpParser\Node\Expr\PropertyFetch;
20 use PhpParser\Node\Expr\StaticCall;
21 use PhpParser\Node\Expr\Variable;
22 use Psy\Exception\FatalErrorException;
25 * Validate that only variables (and variable-like things) are passed by reference.
27 class PassableByReferencePass extends CodeCleanerPass
29 const EXCEPTION_MESSAGE = 'Only variables can be passed by reference';
32 * @throws FatalErrorException if non-variables are passed by reference
36 public function enterNode(Node $node)
38 // TODO: support MethodCall and StaticCall as well.
39 if ($node instanceof FuncCall) {
42 // if function name is an expression or a variable, give it a pass for now.
43 if ($name instanceof Expr || $name instanceof Variable) {
48 $refl = new \ReflectionFunction(implode('\\', $name->parts));
49 } catch (\ReflectionException $e) {
50 // Well, we gave it a shot!
54 foreach ($refl->getParameters() as $key => $param) {
55 if (array_key_exists($key, $node->args)) {
56 $arg = $node->args[$key];
57 if ($param->isPassedByReference() && !$this->isPassableByReference($arg)) {
58 throw new FatalErrorException(self::EXCEPTION_MESSAGE);
65 private function isPassableByReference(Node $arg)
67 // FuncCall, MethodCall and StaticCall are all PHP _warnings_ not fatal errors, so we'll let
68 // PHP handle those ones :)
69 return $arg->value instanceof ClassConstFetch ||
70 $arg->value instanceof PropertyFetch ||
71 $arg->value instanceof Variable ||
72 $arg->value instanceof FuncCall ||
73 $arg->value instanceof MethodCall ||
74 $arg->value instanceof StaticCall;