Completed
Pull Request — master (#758)
by Nicolas
01:35
created

Migrator::table()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Nwidart\Modules\Migrations;
4
5
use Illuminate\Contracts\Foundation\Application;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Str;
8
use Nwidart\Modules\Module;
9
use Nwidart\Modules\Support\Config\GenerateConfigReader;
10
11
class Migrator
12
{
13
    /**
14
     * Pingpong Module instance.
15
     *
16
     * @var \Nwidart\Modules\Module
17
     */
18
    protected $module;
19
20
    /**
21
     * Laravel Application instance.
22
     *
23
     * @var Application.
24
     */
25
    protected $laravel;
26
27
    /**
28
     * The database connection to be used
29
     *
30
     * @var string
31
     */
32
    protected $database = '';
33
34
    /**
35
     * Create new instance.
36
     *
37
     * @param \Nwidart\Modules\Module $module
38
     */
39 1
    public function __construct(Module $module)
40
    {
41 1
        $this->module = $module;
42 1
        $this->laravel = $module->getLaravel();
43 1
    }
44
45
    /**
46
     * Set the database connection to be used
47
     *
48
     * @param $database
49
     *
50
     * @return $this
51
     */
52
    public function setDatabase($database)
53
    {
54
        if (is_string($database) && $database) {
55
            $this->database = $database;
56
        }
57
58
        return $this;
59
    }
60
61
    /**
62
     * @return Module
63
     */
64 1
    public function getModule()
65
    {
66 1
        return $this->module;
67
    }
68
69
    /**
70
     * Get migration path.
71
     *
72
     * @return string
73
     */
74 1
    public function getPath()
75
    {
76 1
        $config = $this->module->get('migration');
77
78 1
        $migrationPath = GenerateConfigReader::read('migration');
79 1
        $path = (is_array($config) && array_key_exists('path', $config)) ? $config['path'] : $migrationPath->getPath();
80
81 1
        return $this->module->getExtraPath($path);
82
    }
83
84
    /**
85
     * Get migration files.
86
     *
87
     * @param boolean $reverse
88
     * @return array
89
     */
90
    public function getMigrations($reverse = false)
91
    {
92
        $files = $this->laravel['files']->glob($this->getPath() . '/*_*.php');
93
94
        // Once we have the array of files in the directory we will just remove the
95
        // extension and take the basename of the file which is all we need when
96
        // finding the migrations that haven't been run against the databases.
97
        if ($files === false) {
98
            return [];
99
        }
100
101
        $files = array_map(function ($file) {
102
            return str_replace('.php', '', basename($file));
103
        }, $files);
104
105
        // Once we have all of the formatted file names we will sort them and since
106
        // they all start with a timestamp this should give us the migrations in
107
        // the order they were actually created by the application developers.
108
        sort($files);
109
110
        if ($reverse) {
111
            return array_reverse($files);
112
        }
113
114
        return $files;
115
    }
116
117
    /**
118
     * Rollback migration.
119
     *
120
     * @return array
121
     */
122
    public function rollback()
123
    {
124
        $migrations = $this->getLast($this->getMigrations(true));
125
126
        $this->requireFiles($migrations->toArray());
127
128
        $migrated = [];
129
130
        foreach ($migrations as $migration) {
131
            $data = $this->find($migration);
132
133
            if ($data->count()) {
134
                $migrated[] = $migration;
135
136
                $this->down($migration);
137
138
                $data->delete();
139
            }
140
        }
141
142
        return $migrated;
143
    }
144
145
    /**
146
     * Run down schema from the given migration name.
147
     *
148
     * @param string $migration
149
     */
150
    public function down($migration)
151
    {
152
        $this->resolve($migration)->down();
153
    }
154
155
    /**
156
     * Run up schema from the given migration name.
157
     *
158
     * @param string $migration
159
     */
160
    public function up($migration)
161
    {
162
        $this->resolve($migration)->up();
163
    }
164
165
    /**
166
     * Resolve a migration instance from a file.
167
     *
168
     * @param string $file
169
     *
170
     * @return object
171
     */
172
    public function resolve($file)
173
    {
174
        $file = implode('_', array_slice(explode('_', $file), 4));
175
176
        $class = Str::studly($file);
177
178
        return new $class();
179
    }
180
181
    /**
182
     * Require in all the migration files in a given path.
183
     *
184
     * @param array  $files
185
     */
186
    public function requireFiles(array $files)
187
    {
188
        $path = $this->getPath();
189
        foreach ($files as $file) {
190
            $this->laravel['files']->requireOnce($path . '/' . $file . '.php');
191
        }
192
    }
193
194
    /**
195
     * Get table instance.
196
     *
197
     * @return \Illuminate\Database\Query\Builder
198
     */
199
    public function table()
200
    {
201
        return $this->laravel['db']->connection($this->database ?: null)->table(config('database.migrations'));
202
    }
203
204
    /**
205
     * Find migration data from database by given migration name.
206
     *
207
     * @param string $migration
208
     *
209
     * @return object
210
     */
211
    public function find($migration)
212
    {
213
        return $this->table()->whereMigration($migration);
214
    }
215
216
    /**
217
     * Save new migration to database.
218
     *
219
     * @param string $migration
220
     *
221
     * @return mixed
222
     */
223
    public function log($migration)
224
    {
225
        return $this->table()->insert([
226
            'migration' => $migration,
227
            'batch' => $this->getNextBatchNumber(),
228
        ]);
229
    }
230
231
    /**
232
     * Get the next migration batch number.
233
     *
234
     * @return int
235
     */
236
    public function getNextBatchNumber()
237
    {
238
        return $this->getLastBatchNumber() + 1;
239
    }
240
241
    /**
242
     * Get the last migration batch number.
243
     *
244
     * @param array|null $migrations
245
     * @return int
246
     */
247
    public function getLastBatchNumber($migrations = null)
248
    {
249
        $table = $this->table();
250
251
        if (is_array($migrations)) {
252
            $table = $table->whereIn('migration', $migrations);
253
        }
254
255
        return $table->max('batch');
256
    }
257
258
    /**
259
     * Get the last migration batch.
260
     *
261
     * @param array $migrations
262
     *
263
     * @return Collection
264
     */
265
    public function getLast($migrations)
266
    {
267
        $query = $this->table()
268
            ->where('batch', $this->getLastBatchNumber($migrations))
269
            ->whereIn('migration', $migrations);
270
271
        $result = $query->orderBy('migration', 'desc')->get();
272
273
        return collect($result)->map(function ($item) {
274
            return (array) $item;
275
        })->pluck('migration');
276
    }
277
278
    /**
279
     * Get the ran migrations.
280
     *
281
     * @return Collection
282
     */
283
    public function getRan()
284
    {
285
        return $this->table()->pluck('migration');
286
    }
287
}
288