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;
14 use PhpParser\Node\Scalar\LNumber;
15 use PhpParser\Node\Stmt\Declare_ as DeclareStmt;
16 use PhpParser\Node\Stmt\DeclareDeclare;
17 use Psy\Exception\FatalErrorException;
20 * Provide implicit strict types declarations for for subsequent execution.
22 * The strict types pass remembers the last strict types declaration:
24 * declare(strict_types=1);
26 * ... which it then applies implicitly to all future evaluated code, until it
27 * is replaced by a new declaration.
29 class StrictTypesPass extends CodeCleanerPass
31 private $strictTypes = false;
34 * If this is a standalone strict types declaration, remember it for later.
36 * Otherwise, apply remembered strict types declaration to to the code until
37 * a new declaration is encountered.
39 * @throws FatalErrorException if an invalid `strict_types` declaration is found
43 public function beforeTraverse(array $nodes)
45 if (version_compare(PHP_VERSION, '7.0', '<')) {
49 $prependStrictTypes = $this->strictTypes;
51 foreach ($nodes as $key => $node) {
52 if ($node instanceof DeclareStmt) {
53 foreach ($node->declares as $declare) {
54 if ($declare->key === 'strict_types') {
55 $value = $declare->value;
56 if (!$value instanceof LNumber || ($value->value !== 0 && $value->value !== 1)) {
57 throw new FatalErrorException('strict_types declaration must have 0 or 1 as its value');
60 $this->strictTypes = $value->value === 1;
66 if ($prependStrictTypes) {
67 $first = reset($nodes);
68 if (!$first instanceof DeclareStmt) {
69 $declare = new DeclareStmt(array(new DeclareDeclare('strict_types', new LNumber(1))));
70 array_unshift($nodes, $declare);