Skip to content

Commit 8fea0f5

Browse files
authored
[Php54] Use token base replace on LongArrayToShortArrayRector (#6616)
* [Php54] Use token base replace on LongArrayToShortArrayRector * fixture
1 parent e9e88d4 commit 8fea0f5

File tree

3 files changed

+110
-1
lines changed

3 files changed

+110
-1
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Rector\Tests\Php54\Rector\Array_\LongArrayToShortArrayTest\Fixture;
4+
5+
final class MultiNested
6+
{
7+
public function run()
8+
{
9+
return array(
10+
array(
11+
array(
12+
'abc' => true,
13+
),
14+
),
15+
);
16+
}
17+
}
18+
19+
?>
20+
-----
21+
<?php
22+
23+
namespace Rector\Tests\Php54\Rector\Array_\LongArrayToShortArrayTest\Fixture;
24+
25+
final class MultiNested
26+
{
27+
public function run()
28+
{
29+
return [
30+
[
31+
[
32+
'abc' => true,
33+
],
34+
],
35+
];
36+
}
37+
}
38+
39+
?>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Rector\Tests\Php54\Rector\Array_\LongArrayToShortArrayTest\Fixture;
4+
5+
final class SpacedArray
6+
{
7+
public function run()
8+
{
9+
return array (
10+
array (
11+
array (
12+
'abc' => true,
13+
),
14+
),
15+
);
16+
}
17+
}
18+
19+
?>
20+
-----
21+
<?php
22+
23+
namespace Rector\Tests\Php54\Rector\Array_\LongArrayToShortArrayTest\Fixture;
24+
25+
final class SpacedArray
26+
{
27+
public function run()
28+
{
29+
return [
30+
[
31+
[
32+
'abc' => true,
33+
],
34+
],
35+
];
36+
}
37+
}
38+
39+
?>

rules/Php54/Rector/Array_/LongArrayToShortArrayRector.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,39 @@ public function refactor(Node $node): ?Node
7676
return null;
7777
}
7878

79-
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
8079
$node->setAttribute(AttributeKey::KIND, Array_::KIND_SHORT);
80+
81+
$tokens = $this->file->getOldTokens();
82+
83+
$startTokenPos = $node->getStartTokenPos();
84+
$endTokenPos = $node->getEndTokenPos();
85+
86+
if (! isset($tokens[$startTokenPos], $tokens[$endTokenPos])) {
87+
return null;
88+
}
89+
90+
// replace array opening
91+
$tokens[$startTokenPos]->text = '';
92+
93+
$iteration = 1;
94+
while (isset($tokens[$startTokenPos + $iteration])) {
95+
if (trim($tokens[$startTokenPos + $iteration]->text) === '') {
96+
++$iteration;
97+
continue;
98+
}
99+
100+
if (trim($tokens[$startTokenPos + $iteration]->text) !== '(') {
101+
break;
102+
}
103+
104+
// replace ( parentheses opening
105+
$tokens[$startTokenPos + $iteration]->text = '[';
106+
// replace ) parentheses closing
107+
$tokens[$endTokenPos]->text = ']';
108+
109+
break;
110+
}
111+
81112
return $node;
82113
}
83114
}

0 commit comments

Comments
 (0)