Skip to content

Commit

Permalink
[TypeDeclaration] Allow multiple declare on DeclareStrictTypesRector (#…
Browse files Browse the repository at this point in the history
…3628)

Co-authored-by: GitHub Action <actions@github.com>
  • Loading branch information
samsonasik and actions-user committed Apr 18, 2023
1 parent 8605fb9 commit 14cc7d4
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector\Fixture;

$count = 0;
function example() {
global $count;
$count++;
echo "$count instructions executed<br>";
}

register_tick_function('example');

declare(ticks=1) {
$cars = ["Ford", "Volvo", "BMW"];
foreach($cars as $car) {
echo "$car <br>";
}
}

?>
-----
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector\Fixture;

$count = 0;
function example() {
global $count;
$count++;
echo "$count instructions executed<br>";
}

register_tick_function('example');

declare(ticks=1) {
$cars = ["Ford", "Volvo", "BMW"];
foreach($cars as $car) {
echo "$car <br>";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(ticks=1);

?>
-----
<?php

declare(strict_types=1);
declare(ticks=1);
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PhpParser\Node\Stmt\Declare_;
use PhpParser\Node\Stmt\DeclareDeclare;
use PhpParser\Node\Stmt\Nop;
use Rector\ChangesReporting\ValueObject\RectorWithLineChange;
use Rector\Core\Contract\PhpParser\Node\StmtsAwareInterface;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
Expand Down Expand Up @@ -50,15 +51,30 @@ public function beforeTraverse(array $nodes): ?array
{
parent::beforeTraverse($nodes);

// has declare already?
$declare = $this->betterNodeFinder->findFirstInstanceOf($nodes, Declare_::class);
if ($declare instanceof Declare_) {
return $nodes;
$newStmts = $this->file->getNewStmts();

if ($newStmts === []) {
return null;
}

$stmt = current($newStmts);

// when first stmt is Declare_, verify if there is strict_types definition already,
// as multiple declare is allowed, with declare(strict_types=1) only allowed on very first stmt
if ($stmt instanceof Declare_) {
foreach ($stmt->declares as $declare) {
if ($declare->key->toString() === 'strict_types') {
return null;
}
}
}

$declareDeclare = new DeclareDeclare(new Identifier('strict_types'), new LNumber(1));
$strictTypesDeclare = new Declare_([$declareDeclare]);

$rectorWithLineChange = new RectorWithLineChange(self::class, $stmt->getLine());
$this->file->addRectorClassWithLine($rectorWithLineChange);

return array_merge([$strictTypesDeclare, new Nop()], $nodes);
}

Expand Down

0 comments on commit 14cc7d4

Please sign in to comment.