@@ -28,6 +28,7 @@ class PhpmigApplication
2828 protected $ container ;
2929 protected $ output ;
3030 protected $ migrations ;
31+ protected $ adapter ;
3132
3233 public function __construct (\ArrayAccess $ container , OutputInterface $ output )
3334 {
@@ -50,6 +51,7 @@ public function __construct(\ArrayAccess $container, OutputInterface $output)
5051 }
5152
5253 $ this ->migrations = array_unique ($ migrations );
54+ $ this ->adapter = $ container ['phpmig.adapter ' ];
5355 }
5456
5557 /**
@@ -100,34 +102,67 @@ public function down($version = 0)
100102 */
101103 public function getMigrations ($ from , $ to = null )
102104 {
103- $ migrations = array ();
104-
105- if ($ to > $ from || $ to === null ) {
106- ksort ($ this ->migrations );
107- } else {
108- krsort ($ this ->migrations );
105+ $ to_run = array ();
106+
107+ $ migrations = $ this ->migrations ;
108+ $ versions = $ this ->adapter ->fetchAll ();
109+
110+ sort ($ migrations );
111+ sort ($ versions );
112+
113+ $ direction = 'up ' ;
114+ if ($ to !== null ){
115+ $ direction = $ to > $ from ? 'up ' : 'down ' ;
109116 }
110-
111- foreach ($ this ->migrations as $ path ) {
112- preg_match ('/^[0-9]+/ ' , basename ($ path ), $ matches );
113- if (!array_key_exists (0 , $ matches )) {
114- continue ;
117+
118+
119+ if ($ direction == 'down ' ) {
120+ /**
121+ * Run downs first
122+ */
123+ rsort ($ migrations );
124+
125+ foreach ($ migrations as $ path ) {
126+ preg_match ('/^[0-9]+/ ' , basename ($ path ), $ matches );
127+ if (!array_key_exists (0 , $ matches )) {
128+ continue ;
129+ }
130+
131+ $ version = $ matches [0 ];
132+
133+ if ($ version > $ from ) {
134+ continue ;
135+ }
136+ if ($ version <= $ to ) {
137+ continue ;
138+ }
139+
140+ if (in_array ($ version , $ versions )) {
141+ $ to_run [] = $ path ;
142+ }
115143 }
116-
117- $ version = $ matches [0 ];
118-
119- // up
120- if ($ to > $ from || $ to === null ) {
121- if ($ version > $ from && ($ version <= $ to || $ to === null )) {
122- $ migrations [] = $ path ;
144+ }else {
145+ sort ($ migrations );
146+ foreach ($ migrations as $ path ) {
147+ preg_match ('/^[0-9]+/ ' , basename ($ path ), $ matches );
148+ if (!array_key_exists (0 , $ matches )) {
149+ continue ;
150+ }
151+
152+ $ version = $ matches [0 ];
153+
154+ if ($ to !== null && ($ version > $ to )) {
155+ continue ;
156+ }
157+
158+ if (!in_array ($ version , $ versions )) {
159+ $ to_run [] = $ path ;
123160 }
124- // down
125- } elseif ($ to < $ from && $ version > $ to && $ version <= $ from ) {
126- $ migrations [] = $ path ;
127161 }
162+
128163 }
129-
130- return $ this ->loadMigrations ($ migrations );
164+
165+ return $ this ->loadMigrations ($ to_run );
131166 }
132167
133168 /**
0 commit comments