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\FuncCall;
17 use PhpParser\Node\Expr\Variable;
18 use PhpParser\Node\Stmt\Do_;
19 use PhpParser\Node\Stmt\Function_;
20 use PhpParser\Node\Stmt\If_;
21 use PhpParser\Node\Stmt\Switch_;
22 use PhpParser\Node\Stmt\While_;
23 use Psy\Exception\FatalErrorException;
26 * Validate that function calls will succeed.
28 * This pass throws a FatalErrorException rather than letting PHP run
29 * headfirst into a real fatal error and die.
31 class ValidFunctionNamePass extends NamespaceAwarePass
33 private $conditionalScopes = 0;
36 * Store newly defined function names on the way in, to allow recursion.
40 public function enterNode(Node $node)
42 parent::enterNode($node);
44 if (self::isConditional($node)) {
45 $this->conditionalScopes++;
46 } elseif ($node instanceof Function_) {
47 $name = $this->getFullyQualifiedName($node->name);
49 // @todo add an "else" here which adds a runtime check for instances where we can't tell
50 // whether a function is being redefined by static analysis alone.
51 if ($this->conditionalScopes === 0) {
52 if (function_exists($name) ||
53 isset($this->currentScope[strtolower($name)])) {
54 $msg = sprintf('Cannot redeclare %s()', $name);
55 throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
59 $this->currentScope[strtolower($name)] = true;
64 * Validate that function calls will succeed.
66 * @throws FatalErrorException if a function is redefined
67 * @throws FatalErrorException if the function name is a string (not an expression) and is not defined
71 public function leaveNode(Node $node)
73 if (self::isConditional($node)) {
74 $this->conditionalScopes--;
75 } elseif ($node instanceof FuncCall) {
76 // if function name is an expression or a variable, give it a pass for now.
78 if (!$name instanceof Expr && !$name instanceof Variable) {
79 $shortName = implode('\\', $name->parts);
80 $fullName = $this->getFullyQualifiedName($name);
81 $inScope = isset($this->currentScope[strtolower($fullName)]);
82 if (!$inScope && !function_exists($shortName) && !function_exists($fullName)) {
83 $message = sprintf('Call to undefined function %s()', $name);
84 throw new FatalErrorException($message, 0, E_ERROR, null, $node->getLine());
90 private static function isConditional(Node $node)
92 return $node instanceof If_ ||
93 $node instanceof While_ ||
94 $node instanceof Do_ ||
95 $node instanceof Switch_;