Completed
Push — master ( de7438...b51e5e )
by Nicolas
12:59
created

Migrator::getNextBatchNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Nwidart\Modules\Migrations;
4
5
use Illuminate\Contracts\Foundation\Application;
6
use Illuminate\Support\Collection;
7
use Nwidart\Modules\Module;
8
9
class Migrator
10
{
11
    /**
12
     * Pingpong Module instance.
13
     *
14
     * @var \Nwidart\Modules\Module
15
     */
16
    protected $module;
17
18
    /**
19
     * Laravel Application instance.
20
     *
21
     * @var Application.
22
     */
23
    protected $laravel;
24
25
    /**
26
     * The database connection to be used
27
     *
28
     * @var string
29
     */
30
    protected $database = '';
31
32
    /**
33
     * Create new instance.
34
     *
35
     * @param \Nwidart\Modules\Module $module
36
     */
37 1
    public function __construct(Module $module)
38
    {
39 1
        $this->module = $module;
40 1
        $this->laravel = $module->getLaravel();
41 1
    }
42
43
    /**
44
     * Set the database connection to be used
45
     *
46
     * @param $database
47
     *
48
     * @return $this
49
     */
50
    public function setDatabase($database)
51
    {
52
        if (is_string($database) && $database) {
53
            $this->database = $database;
54
        }
55
56
        return $this;
57
    }
58
59
    /**
60
     * @return Module
61
     */
62 1
    public function getModule()
63
    {
64 1
        return $this->module;
65
    }
66
67
    /**
68
     * Get migration path.
69
     *
70
     * @return string
71
     */
72 1
    public function getPath()
73
    {
74 1
        $config = $this->module->get('migration');
75
76 1
        $path = (is_array($config) && array_key_exists('path', $config)) ? $config['path'] : config('modules.paths.generator.migration');
77
78 1
        return $this->module->getExtraPath($path);
79
    }
80
81
    /**
82
     * Get migration files.
83
     *
84
     * @param boolean $reverse
85
     * @return array
86
     */
87
    public function getMigrations($reverse = false)
88
    {
89
        $files = $this->laravel['files']->glob($this->getPath() . '/*_*.php');
90
91
        // Once we have the array of files in the directory we will just remove the
92
        // extension and take the basename of the file which is all we need when
93
        // finding the migrations that haven't been run against the databases.
94
        if ($files === false) {
95
            return array();
96
        }
97
98
        $files = array_map(function ($file) {
99
            return str_replace('.php', '', basename($file));
100
        }, $files);
101
102
        // Once we have all of the formatted file names we will sort them and since
103
        // they all start with a timestamp this should give us the migrations in
104
        // the order they were actually created by the application developers.
105
        sort($files);
106
107
        if ($reverse) {
108
            return array_reverse($files);
109
        }
110
111
        return $files;
112
    }
113
114
    /**
115
     * Rollback migration.
116
     *
117
     * @return array
118
     */
119 View Code Duplication
    public function rollback()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
120
    {
121
        $migrations = $this->getLast($this->getMigrations(true));
122
123
        $this->requireFiles($migrations->toArray());
124
125
        $migrated = [];
126
127
        foreach ($migrations as $migration) {
128
            $data = $this->find($migration);
129
130
            if ($data->count()) {
131
                $migrated[] = $migration;
132
133
                $this->down($migration);
134
135
                $data->delete();
136
            }
137
        }
138
139
        return $migrated;
140
    }
141
142
    /**
143
     * Reset migration.
144
     *
145
     * @return array
146
     */
147 View Code Duplication
    public function reset()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
    {
149
        $migrations = $this->getMigrations(true);
150
151
        $this->requireFiles($migrations);
152
153
        $migrated = [];
154
155
        foreach ($migrations as $migration) {
156
            $data = $this->find($migration);
157
158
            if ($data->count()) {
159
                $migrated[] = $migration;
160
161
                $this->down($migration);
162
163
                $data->delete();
164
            }
165
        }
166
167
        return $migrated;
168
    }
169
170
    /**
171
     * Run down schema from the given migration name.
172
     *
173
     * @param string $migration
174
     */
175
    public function down($migration)
176
    {
177
        $this->resolve($migration)->down();
178
    }
179
180
    /**
181
     * Run up schema from the given migration name.
182
     *
183
     * @param string $migration
184
     */
185
    public function up($migration)
186
    {
187
        $this->resolve($migration)->up();
188
    }
189
190
    /**
191
     * Resolve a migration instance from a file.
192
     *
193
     * @param string $file
194
     *
195
     * @return object
196
     */
197
    public function resolve($file)
198
    {
199
        $file = implode('_', array_slice(explode('_', $file), 4));
200
201
        $class = studly_case($file);
202
203
        return new $class();
204
    }
205
206
    /**
207
     * Require in all the migration files in a given path.
208
     *
209
     * @param array  $files
210
     */
211
    public function requireFiles(array $files)
212
    {
213
        $path = $this->getPath();
214
        foreach ($files as $file) {
215
            $this->laravel['files']->requireOnce($path . '/' . $file . '.php');
216
        }
217
    }
218
219
    /**
220
     * Get table instance.
221
     *
222
     * @return \Illuminate\Database\Query\Builder
223
     */
224
    public function table()
225
    {
226
        return $this->laravel['db']->connection($this->database ?: null)->table(config('database.migrations'));
227
    }
228
229
    /**
230
     * Find migration data from database by given migration name.
231
     *
232
     * @param string $migration
233
     *
234
     * @return object
235
     */
236
    public function find($migration)
237
    {
238
        return $this->table()->whereMigration($migration);
239
    }
240
241
    /**
242
     * Save new migration to database.
243
     *
244
     * @param string $migration
245
     *
246
     * @return mixed
247
     */
248
    public function log($migration)
249
    {
250
        return $this->table()->insert([
251
            'migration' => $migration,
252
            'batch' => $this->getNextBatchNumber(),
253
        ]);
254
    }
255
256
    /**
257
     * Get the next migration batch number.
258
     *
259
     * @return int
260
     */
261
    public function getNextBatchNumber()
262
    {
263
        return $this->getLastBatchNumber() + 1;
264
    }
265
266
    /**
267
     * Get the last migration batch number.
268
     *
269
     * @param array|null $migrations
270
     * @return int
271
     */
272
    public function getLastBatchNumber($migrations = null)
273
    {
274
        $table = $this->table();
275
276
        if (is_array($migrations)) {
277
            $table = $table->whereIn('migration', $migrations);
278
        }
279
280
        return $table->max('batch');
281
    }
282
283
    /**
284
     * Get the last migration batch.
285
     *
286
     * @param array $migrations
287
     *
288
     * @return Collection
289
     */
290
    public function getLast($migrations)
291
    {
292
        $query = $this->table()
293
            ->where('batch', $this->getLastBatchNumber($migrations))
294
            ->whereIn('migration', $migrations);
295
296
        $result = $query->orderBy('migration', 'desc')->get();
297
298
        return collect($result)->map(function ($item) {
299
            return (array) $item;
300
        })->pluck('migration');
301
    }
302
303
    /**
304
     * Get the ran migrations.
305
     *
306
     * @return Collection
307
     */
308
    public function getRan()
309
    {
310
        return $this->table()->pluck('migration');
311
    }
312
}
313