Completed
Push — master ( 890702...fa33d5 )
by Nicolas
06:41
created

Migrator::setDatabase()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 3
nc 2
nop 1
crap 12
1
<?php
2
3
namespace Nwidart\Modules\Migrations;
4
5
use Illuminate\Support\Collection;
6
use Nwidart\Modules\Module;
7
8
class Migrator
9
{
10
    /**
11
     * Pingpong Module instance.
12
     *
13
     * @var \Nwidart\Modules\Module
14
     */
15
    protected $module;
16
17
    /**
18
     * Laravel Application instance.
19
     *
20
     * @var \Illuminate\Foundation\Application.
21
     */
22
    protected $laravel;
23
24
    /**
25
     * The database connection to be used
26
     *
27
     * @var string
28
     */
29
    protected $database = '';
30
31
    /**
32
     * Create new instance.
33
     *
34
     * @param \Nwidart\Modules\Module $module
35
     */
36 1
    public function __construct(Module $module)
37
    {
38 1
        $this->module = $module;
39 1
        $this->laravel = $module->getLaravel();
0 ignored issues
show
Documentation Bug introduced by
It seems like $module->getLaravel() of type object<Illuminate\Foundation\Application> is incompatible with the declared type object<Illuminate\Foundation\Application.> of property $laravel.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
40 1
    }
41
42
    /**
43
     * Set the database connection to be used
44
     *
45
     * @param $database
46
     *
47
     * @return $this
48
     */
49
    public function setDatabase($database)
50
    {
51
        if (is_string($database) && $database) {
52
            $this->database = $database;
53
        }
54
    }
55
56
    /**
57
     * @return Module
58
     */
59 1
    public function getModule()
60
    {
61 1
        return $this->module;
62
    }
63
64
    /**
65
     * Get migration path.
66
     *
67
     * @return string
68
     */
69 1
    public function getPath()
70
    {
71 1
        $config = $this->module->get('migration');
72
73 1
        $path = (is_array($config) && array_key_exists('path', $config)) ? $config['path'] : config('modules.paths.generator.migration');
74
75 1
        return $this->module->getExtraPath($path);
76
    }
77
78
    /**
79
     * Get migration files.
80
     *
81
     * @param boolean $reverse
82
     * @return array
83
     */
84
    public function getMigrations($reverse = false)
85
    {
86
        $files = $this->laravel['files']->glob($this->getPath() . '/*_*.php');
87
88
        // Once we have the array of files in the directory we will just remove the
89
        // extension and take the basename of the file which is all we need when
90
        // finding the migrations that haven't been run against the databases.
91
        if ($files === false) {
92
            return array();
93
        }
94
95
        $files = array_map(function ($file) {
96
            return str_replace('.php', '', basename($file));
97
98
        }, $files);
99
100
        // Once we have all of the formatted file names we will sort them and since
101
        // they all start with a timestamp this should give us the migrations in
102
        // the order they were actually created by the application developers.
103
        sort($files);
104
105
        if ($reverse) {
106
            return array_reverse($files);
107
        }
108
109
        return $files;
110
    }
111
112
    /**
113
     * Rollback migration.
114
     *
115
     * @return array
116
     */
117 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...
118
    {
119
        $migrations = $this->getLast($this->getMigrations(true));
120
121
        $this->requireFiles($migrations->toArray());
122
123
        $migrated = [];
124
125
        foreach ($migrations as $migration) {
126
            $data = $this->find($migration);
127
128
            if ($data->count()) {
129
                $migrated[] = $migration;
130
131
                $this->down($migration);
132
133
                $data->delete();
134
            }
135
        }
136
137
        return $migrated;
138
    }
139
140
    /**
141
     * Reset migration.
142
     *
143
     * @return array
144
     */
145 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...
146
    {
147
        $migrations = $this->getMigrations(true);
148
149
        $this->requireFiles($migrations);
150
151
        $migrated = [];
152
153
        foreach ($migrations as $migration) {
154
            $data = $this->find($migration);
155
156
            if ($data->count()) {
157
                $migrated[] = $migration;
158
159
                $this->down($migration);
160
161
                $data->delete();
162
            }
163
        }
164
165
        return $migrated;
166
    }
167
168
    /**
169
     * Run down schema from the given migration name.
170
     *
171
     * @param string $migration
172
     */
173
    public function down($migration)
174
    {
175
        $this->resolve($migration)->down();
176
    }
177
178
    /**
179
     * Run up schema from the given migration name.
180
     *
181
     * @param string $migration
182
     */
183
    public function up($migration)
184
    {
185
        $this->resolve($migration)->up();
186
    }
187
188
    /**
189
     * Resolve a migration instance from a file.
190
     *
191
     * @param string $file
192
     *
193
     * @return object
194
     */
195
    public function resolve($file)
196
    {
197
        $file = implode('_', array_slice(explode('_', $file), 4));
198
199
        $class = studly_case($file);
200
201
        return new $class();
202
    }
203
204
    /**
205
     * Require in all the migration files in a given path.
206
     *
207
     * @param array  $files
208
     */
209
    public function requireFiles(array $files)
210
    {
211
        $path = $this->getPath();
212
        foreach ($files as $file) {
213
            $this->laravel['files']->requireOnce($path . '/' . $file . '.php');
214
        }
215
    }
216
217
    /**
218
     * Get table instance.
219
     *
220
     * @return string
221
     */
222
    public function table()
223
    {
224
        return $this->database ? $this->laravel['db']->connection($this->database)->table(config('database.migrations')) : $this->laravel['db']->table(config('database.migrations'));
225
    }
226
227
    /**
228
     * Find migration data from database by given migration name.
229
     *
230
     * @param string $migration
231
     *
232
     * @return object
233
     */
234
    public function find($migration)
235
    {
236
        return $this->table()->whereMigration($migration);
0 ignored issues
show
Bug introduced by
The method whereMigration cannot be called on $this->table() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
237
    }
238
239
    /**
240
     * Save new migration to database.
241
     *
242
     * @param string $migration
243
     *
244
     * @return mixed
245
     */
246
    public function log($migration)
247
    {
248
        return $this->table()->insert([
0 ignored issues
show
Bug introduced by
The method insert cannot be called on $this->table() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
249
            'migration' => $migration,
250
            'batch' => $this->getNextBatchNumber(),
251
        ]);
252
    }
253
254
    /**
255
     * Get the next migration batch number.
256
     *
257
     * @return int
258
     */
259
    public function getNextBatchNumber()
260
    {
261
        return $this->getLastBatchNumber() + 1;
0 ignored issues
show
Bug introduced by
The call to getLastBatchNumber() misses a required argument $migrations.

This check looks for function calls that miss required arguments.

Loading history...
262
    }
263
264
    /**
265
     * Get the last migration batch number.
266
     *
267
     * @param array $migrations
268
     * @return int
269
     */
270
    public function getLastBatchNumber($migrations)
271
    {
272
        return $this->table()
0 ignored issues
show
Bug introduced by
The method whereIn cannot be called on $this->table() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
273
            ->whereIn('migration', $migrations)
274
            ->max('batch');
275
    }
276
277
    /**
278
     * Get the last migration batch.
279
     *
280
     * @param array $migrations
281
     *
282
     * @return Collection
283
     */
284
    public function getLast($migrations)
285
    {
286
        $query = $this->table()
0 ignored issues
show
Bug introduced by
The method where cannot be called on $this->table() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
287
            ->where('batch', $this->getLastBatchNumber($migrations))
288
            ->whereIn('migration', $migrations);
289
290
        $result = $query->orderBy('migration', 'desc')->get();
291
292
        return collect($result)->map(function ($item) {
293
            return (array) $item;
294
        })->pluck('migration');
295
    }
296
297
    /**
298
     * Get the ran migrations.
299
     *
300
     * @return Collection
301
     */
302
    public function getRan()
303
    {
304
        return $this->table()->pluck('migration');
0 ignored issues
show
Bug introduced by
The method pluck cannot be called on $this->table() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
305
    }
306
}
307