Skip to content

Commit 7673ce7

Browse files
committed
Add new interface for transformers + add force strict types transformer
1 parent db5ae96 commit 7673ce7

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

src/Patch/ForceStrictTypes.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
}

src/Patch/Transformer.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
namespace PhpSchool\PhpWorkshop\Patch;
4+
5+
interface Transformer
6+
{
7+
public function transform(array $ast): array;
8+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)