File tree Expand file tree Collapse file tree 3 files changed +78
-0
lines changed
Expand file tree Collapse file tree 3 files changed +78
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace PhpSchool \PhpWorkshop \Patch ;
4+
5+ use PhpParser \Node \Scalar \LNumber ;
6+ use PhpParser \Node \Stmt \Declare_ ;
7+ use PhpParser \Node \Stmt \DeclareDeclare ;
8+
9+ class ForceStrictTypes implements Transformer
10+ {
11+ public function transform (array $ ast ): array
12+ {
13+ if ($ this ->isFirstStatementStrictTypesDeclare ($ ast )) {
14+ return $ ast ;
15+ }
16+
17+ $ declare = new \PhpParser \Node \Stmt \Declare_ ([
18+ new DeclareDeclare (
19+ new \PhpParser \Node \Identifier ('strict_types ' ),
20+ new LNumber (1 )
21+ )
22+ ]);
23+
24+ return array_merge ([$ declare ], $ ast );
25+ }
26+
27+ public function isFirstStatementStrictTypesDeclare (array $ statements ): bool
28+ {
29+ return isset ($ statements [0 ]) && $ statements [0 ] instanceof Declare_;
30+ }
31+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace PhpSchool \PhpWorkshop \Patch ;
4+
5+ interface Transformer
6+ {
7+ public function transform (array $ ast ): array ;
8+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace PhpSchool \PhpWorkshopTest \Patch ;
4+
5+ use PhpParser \ParserFactory ;
6+ use PhpParser \PrettyPrinter \Standard ;
7+ use PhpSchool \PhpWorkshop \Patch \ForceStrictTypes ;
8+ use PHPUnit \Framework \TestCase ;
9+
10+ class ForceStrictTypesTest extends TestCase
11+ {
12+ public function testStrictTypesDeclareIsAppended (): void
13+ {
14+ $ parser = (new ParserFactory ())->create (ParserFactory::PREFER_PHP7 );
15+ $ ast = $ parser ->parse ("<?php echo 'Hello World'; " );
16+
17+ $ transformer = new ForceStrictTypes ();
18+ $ ast = $ transformer ->transform ($ ast );
19+
20+ self ::assertSame (
21+ "declare (strict_types=1); \necho 'Hello World'; " ,
22+ (new Standard ())->prettyPrint ($ ast )
23+ );
24+ }
25+
26+ public function testStrictTypesDeclareIsNotAppendedIfItAlreadyExists (): void
27+ {
28+ $ parser = (new ParserFactory ())->create (ParserFactory::PREFER_PHP7 );
29+ $ ast = $ parser ->parse ("<?php declare (strict_types=1); \necho 'Hello World'; " );
30+ $ transformer = new ForceStrictTypes ();
31+
32+ $ ast = $ transformer ->transform ($ ast );
33+
34+ self ::assertSame (
35+ "declare (strict_types=1); \necho 'Hello World'; " ,
36+ (new Standard ())->prettyPrint ($ ast )
37+ );
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments