rector/src/Rector/ClassMethod/WrapReturnRector.php

118 lines
2.6 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
2018-12-12 19:34:32 +00:00
namespace Rector\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Expr\Array_;
2019-01-14 18:21:23 +00:00
use PhpParser\Node\Expr\ArrayItem;
2018-12-12 19:34:32 +00:00
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Return_;
use Rector\Rector\AbstractRector;
2018-12-14 19:38:47 +00:00
use Rector\RectorDefinition\ConfiguredCodeSample;
2018-12-12 19:34:32 +00:00
use Rector\RectorDefinition\RectorDefinition;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\Rector\ClassMethod\WrapReturnRector\WrapReturnRectorTest
*/
2018-12-12 19:34:32 +00:00
final class WrapReturnRector extends AbstractRector
{
/**
* @var mixed[][]
*/
private $typeToMethodToWrap = [];
/**
* @param mixed[][] $typeToMethodToWrap
*/
public function __construct(array $typeToMethodToWrap = [])
2018-12-12 19:34:32 +00:00
{
$this->typeToMethodToWrap = $typeToMethodToWrap;
}
public function getDefinition(): RectorDefinition
{
2018-12-14 19:38:47 +00:00
return new RectorDefinition('Wrap return value of specific method', [
new ConfiguredCodeSample(
2019-09-18 06:14:35 +00:00
<<<'PHP'
2018-12-12 19:34:32 +00:00
final class SomeClass
{
public function getItem()
{
return 1;
}
}
2019-09-18 06:14:35 +00:00
PHP
2018-12-12 19:34:32 +00:00
,
2019-09-18 06:14:35 +00:00
<<<'PHP'
2018-12-12 19:34:32 +00:00
final class SomeClass
{
public function getItem()
{
return [1];
}
}
2019-09-18 06:14:35 +00:00
PHP
2018-12-14 19:38:47 +00:00
,
[
'SomeClass' => [
'getItem' => 'array',
],
]
2018-12-12 19:34:32 +00:00
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->typeToMethodToWrap as $type => $methodToType) {
2019-09-04 12:10:29 +00:00
if (! $this->isObjectType($node, $type)) {
2018-12-12 19:34:32 +00:00
continue;
}
foreach ($methodToType as $method => $type) {
if (! $this->isName($node, $method)) {
continue;
}
if (! $node->stmts) {
continue;
}
$this->wrap($node, $type);
}
}
return $node;
}
2019-02-22 17:25:31 +00:00
private function wrap(ClassMethod $classMethod, string $type): void
2018-12-12 19:34:32 +00:00
{
2019-02-22 17:25:31 +00:00
if (! is_iterable($classMethod->stmts)) {
2018-12-12 19:34:32 +00:00
return;
}
2019-02-22 17:25:31 +00:00
foreach ($classMethod->stmts as $i => $stmt) {
2019-01-14 18:21:23 +00:00
if ($stmt instanceof Return_ && $stmt->expr !== null) {
2019-03-07 23:18:45 +00:00
if ($type === 'array' && ! $stmt->expr instanceof Array_) {
2019-01-14 18:21:23 +00:00
$stmt->expr = new Array_([new ArrayItem($stmt->expr)]);
2018-12-12 19:34:32 +00:00
}
2019-02-22 17:25:31 +00:00
$classMethod->stmts[$i] = $stmt;
2018-12-12 19:34:32 +00:00
}
}
}
}