Skip to content

Commit c57a516

Browse files
ArshidArshid
authored andcommitted
WakeupToUnserializeRector - auto assign
1 parent 65ad358 commit c57a516

3 files changed

Lines changed: 43 additions & 1 deletion

File tree

rector.php

100644100755
File mode changed.

rules-tests/Php85/Rector/Class_/WakeupToUnserializeRector/Fixture/wakeup.php.inc

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@ class User {
2323
private $name;
2424

2525
public function __unserialize(array $data): void{
26-
$this->id = 1;
26+
foreach ($data as $property => $value) {
27+
if (property_exists($this, $property)) {
28+
$this->{$property} = $value;
29+
}
30+
}
2731
}
2832
}
2933
?>

rules/Php85/Rector/Class_/WakeupToUnserializeRector.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,18 @@
55
namespace Rector\Php85\Rector\Class_;
66

77
use PhpParser\Node;
8+
use PhpParser\Node\Expr\Assign;
9+
use PhpParser\Node\Expr\FuncCall;
10+
use PhpParser\Node\Expr\PropertyFetch;
811
use PhpParser\Node\Expr\Variable;
912
use PhpParser\Node\Identifier;
13+
use PhpParser\Node\Name;
1014
use PhpParser\Node\Param;
1115
use PhpParser\Node\Stmt\Class_;
1216
use PhpParser\Node\Stmt\ClassMethod;
17+
use PhpParser\Node\Stmt\Expression;
18+
use PhpParser\Node\Stmt\Foreach_;
19+
use PhpParser\Node\Stmt\If_;
1320
use Rector\Rector\AbstractRector;
1421
use Rector\ValueObject\PhpVersionFeature;
1522
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
@@ -83,6 +90,37 @@ public function refactor(Node $node): ?Node
8390
);
8491

8592
$classMethod->params[] = $param;
93+
94+
$classMethod->stmts = [$this->assignProperties()];
95+
8696
return $node;
8797
}
98+
99+
protected function assignProperties(): Foreach_{
100+
$assign = new Assign(
101+
new PropertyFetch(new Variable('this'), new Variable('property')),
102+
new Variable('value')
103+
);
104+
105+
$if = new If_(
106+
new FuncCall(new Name('property_exists'), [
107+
new Node\Arg(new Variable('this')),
108+
new Node\Arg(new Variable('property')),
109+
]),
110+
[
111+
'stmts' => [new Expression($assign)],
112+
]
113+
);
114+
115+
$foreach = new Foreach_(
116+
new Variable('data'),
117+
new Variable('value'),
118+
[
119+
'keyVar' => new Variable('property'),
120+
'stmts' => [$if],
121+
]
122+
);
123+
124+
return $foreach;
125+
}
88126
}

0 commit comments

Comments
 (0)