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\ConstFetch;
18 use Psy\Exception\FatalErrorException;
21 * Validate that namespaced constant references will succeed.
23 * This pass throws a FatalErrorException rather than letting PHP run
24 * headfirst into a real fatal error and die.
26 * @todo Detect constants defined in the current code snippet?
27 * ... Might not be worth it, since it would need to both be defining and
28 * referencing a namespaced constant, which doesn't seem like that big of
29 * a target for failure
31 class ValidConstantPass extends NamespaceAwarePass
34 * Validate that namespaced constant references will succeed.
36 * Note that this does not (yet) detect constants defined in the current code
37 * snippet. It won't happen very often, so we'll punt for now.
39 * @throws FatalErrorException if a constant reference is not defined
43 public function leaveNode(Node $node)
45 if ($node instanceof ConstFetch && count($node->name->parts) > 1) {
46 $name = $this->getFullyQualifiedName($node->name);
47 if (!defined($name)) {
48 throw new FatalErrorException(sprintf('Undefined constant %s', $name), 0, 1, null, $node->getLine());
50 } elseif ($node instanceof ClassConstFetch) {
51 $this->validateClassConstFetchExpression($node);
56 * Validate a class constant fetch expression.
58 * @throws FatalErrorException if a class constant is not defined
60 * @param ClassConstFetch $stmt
62 protected function validateClassConstFetchExpression(ClassConstFetch $stmt)
64 // give the `class` pseudo-constant a pass
65 if ($stmt->name === 'class') {
69 // if class name is an expression, give it a pass for now
70 if (!$stmt->class instanceof Expr) {
71 $className = $this->getFullyQualifiedName($stmt->class);
73 // if the class doesn't exist, don't throw an exception… it might be
74 // defined in the same line it's used or something stupid like that.
75 if (class_exists($className) || interface_exists($className)) {
76 $constName = sprintf('%s::%s', $className, $stmt->name);
77 if (!defined($constName)) {
78 $constType = class_exists($className) ? 'Class' : 'Interface';
79 $msg = sprintf('%s constant \'%s\' not found', $constType, $constName);
80 throw new FatalErrorException($msg, 0, 1, null, $stmt->getLine());