Version 1
[yaffs-website] / vendor / psy / psysh / src / Psy / CodeCleaner / PassableByReferencePass.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2017 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;
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;
23
24 /**
25  * Validate that only variables (and variable-like things) are passed by reference.
26  */
27 class PassableByReferencePass extends CodeCleanerPass
28 {
29     const EXCEPTION_MESSAGE = 'Only variables can be passed by reference';
30
31     /**
32      * @throws FatalErrorException if non-variables are passed by reference
33      *
34      * @param Node $node
35      */
36     public function enterNode(Node $node)
37     {
38         // TODO: support MethodCall and StaticCall as well.
39         if ($node instanceof FuncCall) {
40             $name = $node->name;
41
42             // if function name is an expression or a variable, give it a pass for now.
43             if ($name instanceof Expr || $name instanceof Variable) {
44                 return;
45             }
46
47             try {
48                 $refl = new \ReflectionFunction(implode('\\', $name->parts));
49             } catch (\ReflectionException $e) {
50                 // Well, we gave it a shot!
51                 return;
52             }
53
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);
59                     }
60                 }
61             }
62         }
63     }
64
65     private function isPassableByReference(Node $arg)
66     {
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;
75     }
76 }