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\Stmt\Class_;
16 use PhpParser\Node\Stmt\ClassMethod;
17 use PhpParser\Node\Stmt\Namespace_;
18 use Psy\Exception\FatalErrorException;
21 * Validate that the old-style constructor function is not static.
23 * As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name
24 * will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
26 * Validation of the __construct method ensures the PHP Parser.
28 * @author Martin HasoĊ <martin.hason@gmail.com>
30 class StaticConstructorPass extends CodeCleanerPass
35 public function __construct()
37 $this->isPHP533 = version_compare(PHP_VERSION, '5.3.3', '>=');
40 public function beforeTraverse(array $nodes)
42 $this->namespace = array();
46 * Validate that the old-style constructor function is not static.
48 * @throws FatalErrorException if the old-style constructor function is static
52 public function enterNode(Node $node)
54 if ($node instanceof Namespace_) {
55 $this->namespace = isset($node->name) ? $node->name->parts : array();
56 } elseif ($node instanceof Class_) {
57 // Bail early if this is PHP 5.3.3 and we have a namespaced class
58 if (!empty($this->namespace) && $this->isPHP533) {
63 foreach ($node->stmts as $stmt) {
64 if ($stmt instanceof ClassMethod) {
65 // Bail early if we find a new-style constructor
66 if ('__construct' === strtolower($stmt->name)) {
70 // We found a possible old-style constructor
71 // (unless there is also a __construct method)
72 if (strtolower($node->name) === strtolower($stmt->name)) {
78 if ($constructor && $constructor->isStatic()) {
80 'Constructor %s::%s() cannot be static',
81 implode('\\', array_merge($this->namespace, (array) $node->name)),
84 throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());