2020-05-03 23:40:28 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Rector\Order;
|
|
|
|
|
2020-08-08 00:21:17 +02:00
|
|
|
use PhpParser\Node\Stmt;
|
2020-08-07 18:23:40 +02:00
|
|
|
use PhpParser\Node\Stmt\ClassLike;
|
2020-08-08 00:21:17 +02:00
|
|
|
use PhpParser\Node\Stmt\ClassMethod;
|
|
|
|
use PhpParser\Node\Stmt\Property;
|
2020-05-03 23:40:28 +02:00
|
|
|
|
|
|
|
final class StmtOrder
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param string[] $desiredStmtOrder
|
|
|
|
* @return int[]
|
|
|
|
*/
|
|
|
|
public function createOldToNewKeys(array $desiredStmtOrder, array $currentStmtOrder): array
|
|
|
|
{
|
|
|
|
$newKeys = [];
|
|
|
|
foreach ($desiredStmtOrder as $desiredClassMethod) {
|
|
|
|
foreach ($currentStmtOrder as $currentKey => $classMethodName) {
|
|
|
|
if ($classMethodName === $desiredClassMethod) {
|
|
|
|
$newKeys[] = $currentKey;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
$oldKeys = array_values($newKeys);
|
|
|
|
sort($oldKeys);
|
|
|
|
|
|
|
|
return array_combine($oldKeys, $newKeys);
|
|
|
|
}
|
|
|
|
|
2020-08-07 18:23:40 +02:00
|
|
|
public function reorderClassStmtsByOldToNewKeys(ClassLike $classLike, array $oldToNewKeys): ClassLike
|
2020-05-03 23:40:28 +02:00
|
|
|
{
|
2020-05-04 01:42:56 +02:00
|
|
|
$reorderedStmts = [];
|
|
|
|
|
2020-08-07 18:23:40 +02:00
|
|
|
$stmtCount = count($classLike->stmts);
|
2020-05-04 01:42:56 +02:00
|
|
|
|
2020-08-07 18:23:40 +02:00
|
|
|
foreach ($classLike->stmts as $key => $stmt) {
|
2020-05-04 01:42:56 +02:00
|
|
|
if (! array_key_exists($key, $oldToNewKeys)) {
|
|
|
|
$reorderedStmts[$key] = $stmt;
|
2020-05-03 23:40:28 +02:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// reorder here
|
|
|
|
$newKey = $oldToNewKeys[$key];
|
2020-05-04 01:42:56 +02:00
|
|
|
|
2020-08-07 18:23:40 +02:00
|
|
|
$reorderedStmts[$key] = $classLike->stmts[$newKey];
|
2020-05-04 01:42:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for ($i = 0; $i < $stmtCount; ++$i) {
|
|
|
|
if (! array_key_exists($i, $reorderedStmts)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2020-08-07 18:23:40 +02:00
|
|
|
$classLike->stmts[$i] = $reorderedStmts[$i];
|
2020-05-03 23:40:28 +02:00
|
|
|
}
|
|
|
|
|
2020-08-07 18:23:40 +02:00
|
|
|
return $classLike;
|
2020-05-03 23:40:28 +02:00
|
|
|
}
|
2020-08-08 00:21:17 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param ClassMethod|Property $stmt
|
|
|
|
*/
|
|
|
|
public function getOrderByVisibility(Stmt $stmt): int
|
|
|
|
{
|
|
|
|
if ($stmt->isPrivate()) {
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($stmt->isProtected()) {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
2020-05-03 23:40:28 +02:00
|
|
|
}
|