4 * This file is part of Psy Shell.
6 * (c) 2012-2018 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;
14 use PhpParser\Node\Identifier;
15 use PhpParser\Node\Scalar\LNumber;
16 use PhpParser\Node\Stmt\Declare_;
17 use PhpParser\Node\Stmt\DeclareDeclare;
18 use Psy\Exception\FatalErrorException;
21 * Provide implicit strict types declarations for for subsequent execution.
23 * The strict types pass remembers the last strict types declaration:
25 * declare(strict_types=1);
27 * ... which it then applies implicitly to all future evaluated code, until it
28 * is replaced by a new declaration.
30 class StrictTypesPass extends CodeCleanerPass
32 const EXCEPTION_MESSAGE = 'strict_types declaration must have 0 or 1 as its value';
34 private $strictTypes = false;
37 public function __construct()
39 $this->atLeastPhp7 = version_compare(PHP_VERSION, '7.0', '>=');
43 * If this is a standalone strict types declaration, remember it for later.
45 * Otherwise, apply remembered strict types declaration to to the code until
46 * a new declaration is encountered.
48 * @throws FatalErrorException if an invalid `strict_types` declaration is found
52 public function beforeTraverse(array $nodes)
54 if (!$this->atLeastPhp7) {
58 $prependStrictTypes = $this->strictTypes;
60 foreach ($nodes as $key => $node) {
61 if ($node instanceof Declare_) {
62 foreach ($node->declares as $declare) {
64 $declareKey = $declare->key instanceof Identifier ? $declare->key->toString() : $declare->key;
65 if ($declareKey === 'strict_types') {
66 $value = $declare->value;
67 if (!$value instanceof LNumber || ($value->value !== 0 && $value->value !== 1)) {
68 throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine());
71 $this->strictTypes = $value->value === 1;
77 if ($prependStrictTypes) {
78 $first = reset($nodes);
79 if (!$first instanceof Declare_) {
80 $declare = new Declare_([new DeclareDeclare('strict_types', new LNumber(1))]);
81 array_unshift($nodes, $declare);