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\New_;
18 use PhpParser\Node\Expr\StaticCall;
19 use PhpParser\Node\Stmt;
20 use PhpParser\Node\Stmt\Class_;
21 use PhpParser\Node\Stmt\Do_;
22 use PhpParser\Node\Stmt\If_;
23 use PhpParser\Node\Stmt\Interface_;
24 use PhpParser\Node\Stmt\Switch_;
25 use PhpParser\Node\Stmt\Trait_;
26 use PhpParser\Node\Stmt\While_;
27 use Psy\Exception\FatalErrorException;
30 * Validate that classes exist.
32 * This pass throws a FatalErrorException rather than letting PHP run
33 * headfirst into a real fatal error and die.
35 class ValidClassNamePass extends NamespaceAwarePass
37 const CLASS_TYPE = 'class';
38 const INTERFACE_TYPE = 'interface';
39 const TRAIT_TYPE = 'trait';
41 protected $checkTraits;
42 private $conditionalScopes = 0;
44 public function __construct()
46 $this->checkTraits = function_exists('trait_exists');
50 * Validate class, interface and trait definitions.
52 * Validate them upon entering the node, so that we know about their
53 * presence and can validate constant fetches and static calls in class or
58 public function enterNode(Node $node)
60 parent::enterNode($node);
62 if (self::isConditional($node)) {
63 $this->conditionalScopes++;
65 // @todo add an "else" here which adds a runtime check for instances where we can't tell
66 // whether a class is being redefined by static analysis alone.
67 if ($this->conditionalScopes === 0) {
68 if ($node instanceof Class_) {
69 $this->validateClassStatement($node);
70 } elseif ($node instanceof Interface_) {
71 $this->validateInterfaceStatement($node);
72 } elseif ($node instanceof Trait_) {
73 $this->validateTraitStatement($node);
80 * Validate `new` expressions, class constant fetches, and static calls.
82 * @throws FatalErrorException if a class, interface or trait is referenced which does not exist
83 * @throws FatalErrorException if a class extends something that is not a class
84 * @throws FatalErrorException if a class implements something that is not an interface
85 * @throws FatalErrorException if an interface extends something that is not an interface
86 * @throws FatalErrorException if a class, interface or trait redefines an existing class, interface or trait name
90 public function leaveNode(Node $node)
92 if (self::isConditional($node)) {
93 $this->conditionalScopes--;
94 } elseif ($node instanceof New_) {
95 $this->validateNewExpression($node);
96 } elseif ($node instanceof ClassConstFetch) {
97 $this->validateClassConstFetchExpression($node);
98 } elseif ($node instanceof StaticCall) {
99 $this->validateStaticCallExpression($node);
103 private static function isConditional(Node $node)
105 return $node instanceof If_ ||
106 $node instanceof While_ ||
107 $node instanceof Do_ ||
108 $node instanceof Switch_;
112 * Validate a class definition statement.
114 * @param Class_ $stmt
116 protected function validateClassStatement(Class_ $stmt)
118 $this->ensureCanDefine($stmt);
119 if (isset($stmt->extends)) {
120 $this->ensureClassExists($this->getFullyQualifiedName($stmt->extends), $stmt);
122 $this->ensureInterfacesExist($stmt->implements, $stmt);
126 * Validate an interface definition statement.
128 * @param Interface_ $stmt
130 protected function validateInterfaceStatement(Interface_ $stmt)
132 $this->ensureCanDefine($stmt);
133 $this->ensureInterfacesExist($stmt->extends, $stmt);
137 * Validate a trait definition statement.
139 * @param Trait_ $stmt
141 protected function validateTraitStatement(Trait_ $stmt)
143 $this->ensureCanDefine($stmt);
147 * Validate a `new` expression.
151 protected function validateNewExpression(New_ $stmt)
153 // if class name is an expression or an anonymous class, give it a pass for now
154 if (!$stmt->class instanceof Expr && !$stmt->class instanceof Class_) {
155 $this->ensureClassExists($this->getFullyQualifiedName($stmt->class), $stmt);
160 * Validate a class constant fetch expression's class.
162 * @param ClassConstFetch $stmt
164 protected function validateClassConstFetchExpression(ClassConstFetch $stmt)
166 // there is no need to check exists for ::class const for php 5.5 or newer
167 if (strtolower($stmt->name) === 'class'
168 && version_compare(PHP_VERSION, '5.5', '>=')) {
172 // if class name is an expression, give it a pass for now
173 if (!$stmt->class instanceof Expr) {
174 $this->ensureClassOrInterfaceExists($this->getFullyQualifiedName($stmt->class), $stmt);
179 * Validate a class constant fetch expression's class.
181 * @param StaticCall $stmt
183 protected function validateStaticCallExpression(StaticCall $stmt)
185 // if class name is an expression, give it a pass for now
186 if (!$stmt->class instanceof Expr) {
187 $this->ensureMethodExists($this->getFullyQualifiedName($stmt->class), $stmt->name, $stmt);
192 * Ensure that no class, interface or trait name collides with a new definition.
194 * @throws FatalErrorException
198 protected function ensureCanDefine(Stmt $stmt)
200 $name = $this->getFullyQualifiedName($stmt->name);
202 // check for name collisions
204 if ($this->classExists($name)) {
205 $errorType = self::CLASS_TYPE;
206 } elseif ($this->interfaceExists($name)) {
207 $errorType = self::INTERFACE_TYPE;
208 } elseif ($this->traitExists($name)) {
209 $errorType = self::TRAIT_TYPE;
212 if ($errorType !== null) {
213 throw $this->createError(sprintf('%s named %s already exists', ucfirst($errorType), $name), $stmt);
216 // Store creation for the rest of this code snippet so we can find local
218 $this->currentScope[strtolower($name)] = $this->getScopeType($stmt);
222 * Ensure that a referenced class exists.
224 * @throws FatalErrorException
226 * @param string $name
229 protected function ensureClassExists($name, $stmt)
231 if (!$this->classExists($name)) {
232 throw $this->createError(sprintf('Class \'%s\' not found', $name), $stmt);
237 * Ensure that a referenced class _or interface_ exists.
239 * @throws FatalErrorException
241 * @param string $name
244 protected function ensureClassOrInterfaceExists($name, $stmt)
246 if (!$this->classExists($name) && !$this->interfaceExists($name)) {
247 throw $this->createError(sprintf('Class \'%s\' not found', $name), $stmt);
252 * Ensure that a statically called method exists.
254 * @throws FatalErrorException
256 * @param string $class
257 * @param string $name
260 protected function ensureMethodExists($class, $name, $stmt)
262 $this->ensureClassExists($class, $stmt);
264 // let's pretend all calls to self, parent and static are valid
265 if (in_array(strtolower($class), array('self', 'parent', 'static'))) {
269 // ... and all calls to classes defined right now
270 if ($this->findInScope($class) === self::CLASS_TYPE) {
274 // if method name is an expression, give it a pass for now
275 if ($name instanceof Expr) {
279 if (!method_exists($class, $name) && !method_exists($class, '__callStatic')) {
280 throw $this->createError(sprintf('Call to undefined method %s::%s()', $class, $name), $stmt);
285 * Ensure that a referenced interface exists.
287 * @throws FatalErrorException
292 protected function ensureInterfacesExist($interfaces, $stmt)
294 foreach ($interfaces as $interface) {
295 /** @var string $name */
296 $name = $this->getFullyQualifiedName($interface);
297 if (!$this->interfaceExists($name)) {
298 throw $this->createError(sprintf('Interface \'%s\' not found', $name), $stmt);
304 * Get a symbol type key for storing in the scope name cache.
310 protected function getScopeType(Stmt $stmt)
312 if ($stmt instanceof Class_) {
313 return self::CLASS_TYPE;
314 } elseif ($stmt instanceof Interface_) {
315 return self::INTERFACE_TYPE;
316 } elseif ($stmt instanceof Trait_) {
317 return self::TRAIT_TYPE;
322 * Check whether a class exists, or has been defined in the current code snippet.
324 * Gives `self`, `static` and `parent` a free pass.
326 * @param string $name
330 protected function classExists($name)
332 // Give `self`, `static` and `parent` a pass. This will actually let
333 // some errors through, since we're not checking whether the keyword is
334 // being used in a class scope.
335 if (in_array(strtolower($name), array('self', 'static', 'parent'))) {
339 return class_exists($name) || $this->findInScope($name) === self::CLASS_TYPE;
343 * Check whether an interface exists, or has been defined in the current code snippet.
345 * @param string $name
349 protected function interfaceExists($name)
351 return interface_exists($name) || $this->findInScope($name) === self::INTERFACE_TYPE;
355 * Check whether a trait exists, or has been defined in the current code snippet.
357 * @param string $name
361 protected function traitExists($name)
363 return $this->checkTraits && (trait_exists($name) || $this->findInScope($name) === self::TRAIT_TYPE);
367 * Find a symbol in the current code snippet scope.
369 * @param string $name
371 * @return string|null
373 protected function findInScope($name)
375 $name = strtolower($name);
376 if (isset($this->currentScope[$name])) {
377 return $this->currentScope[$name];
382 * Error creation factory.
387 * @return FatalErrorException
389 protected function createError($msg, $stmt)
391 return new FatalErrorException($msg, 0, E_ERROR, null, $stmt->getLine());