33namespace Tempest \Upgrade \Tempest2 ;
44
55use PhpParser \Node ;
6+ use PhpParser \Node \Name ;
7+ use PhpParser \Node \Stmt \ClassMethod ;
68use Rector \Rector \AbstractRector ;
79
810final class MigrationRector extends AbstractRector
@@ -14,18 +16,74 @@ public function getNodeTypes(): array
1416 ];
1517 }
1618
17- public function refactor (Node $ node ): ? int
19+ public function refactor (Node $ node ): void
1820 {
1921 if (! $ node instanceof Node \Stmt \Class_) {
20- return null ;
22+ return ;
2123 }
2224
25+ // Check whether this class implements Tempest\Database\DatabaseMigration
2326 $ implements = $ node ->implements ;
24- ld ($ implements );
25- // if (! in_array('', $implements)) {
2627
27- // }
28+ $ implementsDatabaseMigration = array_find_key (
29+ $ implements ,
30+ static fn (Node \Name $ name ) => $ name ->toString () === 'Tempest\Database\DatabaseMigration ' ,
31+ );
2832
29- ld ($ implements );
33+ if ($ implementsDatabaseMigration === null ) {
34+ return ;
35+ }
36+
37+ // Unset the old interface
38+ unset($ implements [$ implementsDatabaseMigration ]);
39+
40+ // Add the new MigrateUp interface
41+ $ implements [] = new Node \Name ('\Tempest\Database\MigratesUp ' );
42+ $ node ->getMethod ('up ' )->returnType = new Name ('QueryStatement ' );
43+
44+
45+ // Check whether the migration has a down method implemented or not
46+ $ downStatements = $ node ->getMethod ('down ' )->stmts ;
47+
48+ $ migratesDown = true ;
49+
50+ foreach ($ downStatements as $ statement ) {
51+ if (! $ statement instanceof Node \Stmt \Return_) {
52+ continue ;
53+ }
54+
55+ if (! $ statement ->expr instanceof Node \Expr \ConstFetch) {
56+ continue ;
57+ }
58+
59+ $ migratesDown = $ statement ->expr ->name ->toString () !== 'null ' ;
60+
61+ break ;
62+ }
63+
64+ if ($ migratesDown ) {
65+ // If the migration has a down method implemented, we'll add the new MigrateDown interface
66+ $ implements [] = new Node \Name ('\Tempest\Database\MigratesDown ' );
67+ $ node ->getMethod ('down ' )->returnType = new Name ('QueryStatement ' );
68+ } else {
69+ // If the migration does not have a down method implemented, we'll remove it entirely
70+ $ statements = $ node ->stmts ;
71+
72+ foreach ($ node ->stmts as $ key => $ statement ) {
73+ if (! $ statement instanceof ClassMethod) {
74+ continue ;
75+ }
76+
77+ if ($ statement ->name ->toString () !== 'down ' ) {
78+ continue ;
79+ }
80+
81+ unset($ statements [$ key ]);
82+
83+ $ node ->stmts = $ statements ;
84+ }
85+ }
86+
87+ $ node ->implements = $ implements ;
3088 }
3189}
0 commit comments