Version 1
[yaffs-website] / vendor / psy / psysh / src / Psy / CodeCleaner / StrictTypesPass.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2017 Justin Hileman
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Psy\CodeCleaner;
13
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;
18
19 /**
20  * Provide implicit strict types declarations for for subsequent execution.
21  *
22  * The strict types pass remembers the last strict types declaration:
23  *
24  *     declare(strict_types=1);
25  *
26  * ... which it then applies implicitly to all future evaluated code, until it
27  * is replaced by a new declaration.
28  */
29 class StrictTypesPass extends CodeCleanerPass
30 {
31     private $strictTypes = false;
32
33     /**
34      * If this is a standalone strict types declaration, remember it for later.
35      *
36      * Otherwise, apply remembered strict types declaration to to the code until
37      * a new declaration is encountered.
38      *
39      * @throws FatalErrorException if an invalid `strict_types` declaration is found
40      *
41      * @param array $nodes
42      */
43     public function beforeTraverse(array $nodes)
44     {
45         if (version_compare(PHP_VERSION, '7.0', '<')) {
46             return;
47         }
48
49         $prependStrictTypes = $this->strictTypes;
50
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');
58                         }
59
60                         $this->strictTypes = $value->value === 1;
61                     }
62                 }
63             }
64         }
65
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);
71             }
72         }
73
74         return $nodes;
75     }
76 }