Completed
Push — master ( 5f981d...ed2304 )
by Bernhard
02:17 queued 48s
created

MigrateGenerateCommand::fire()   C

Complexity

Conditions 7
Paths 36

Size

Total Lines 45
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 32
nc 36
nop 0
1
<?php namespace Xethron\MigrationsGenerator;
2
3
use Way\Generators\Commands\GeneratorCommand;
4
use Symfony\Component\Console\Input\InputOption;
5
use Symfony\Component\Console\Input\InputArgument;
6
7
use Way\Generators\Generator;
8
use Way\Generators\Filesystem\Filesystem;
9
use Way\Generators\Compilers\TemplateCompiler;
10
use Illuminate\Database\Migrations\MigrationRepositoryInterface;
11
12
use Xethron\MigrationsGenerator\Generators\SchemaGenerator;
13
use Xethron\MigrationsGenerator\Syntax\AddToTable;
14
use Xethron\MigrationsGenerator\Syntax\DroppedTable;
15
use Xethron\MigrationsGenerator\Syntax\AddForeignKeysToTable;
16
use Xethron\MigrationsGenerator\Syntax\RemoveForeignKeysFromTable;
17
18
use Illuminate\Config\Repository as Config;
19
20
class MigrateGenerateCommand extends GeneratorCommand {
21
22
	/**
23
	 * The console command name.
24
	 * @var string
25
	 */
26
	protected $name = 'migrate:generate';
27
28
	/**
29
	 * The console command description.
30
	 * @var string
31
	 */
32
	protected $description = 'Generate a migration from an existing table structure.';
33
34
	/**
35
	 * @var \Way\Generators\Filesystem\Filesystem
36
	 */
37
	protected $file;
38
39
	/**
40
	 * @var \Way\Generators\Compilers\TemplateCompiler
41
	 */
42
	protected $compiler;
43
44
	/**
45
	 * @var \Illuminate\Database\Migrations\MigrationRepositoryInterface  $repository
46
	 */
47
	protected $repository;
48
49
	/**
50
	 * @var \Illuminate\Config\Repository  $config
51
	 */
52
	protected $config;
53
54
	/**
55
	 * @var \Xethron\MigrationsGenerator\Generators\SchemaGenerator
56
	 */
57
	protected $schemaGenerator;
58
59
	/**
60
	 * Array of Fields to create in a new Migration
61
	 * Namely: Columns, Indexes and Foreign Keys
62
	 * @var array
63
	 */
64
	protected $fields = array();
65
66
	/**
67
	 * List of Migrations that has been done
68
	 * @var array
69
	 */
70
	protected $migrations = array();
71
72
	/**
73
	 * @var bool
74
	 */
75
	protected $log = false;
76
77
	/**
78
	 * @var int
79
	 */
80
	protected $batch;
81
82
	/**
83
	 * Filename date prefix (Y_m_d_His)
84
	 * @var string
85
	 */
86
	protected $datePrefix;
87
88
	/**
89
	 * @var string
90
	 */
91
	protected $migrationName;
92
93
	/**
94
	 * @var string
95
	 */
96
	protected $method;
97
98
	/**
99
	 * @var string
100
	 */
101
	protected $table;
102
103
    /**
104
     * @var string|null
105
     */
106
    protected $connection = null;
107
108
    /**
109
	 * @param \Way\Generators\Generator  $generator
110
	 * @param \Way\Generators\Filesystem\Filesystem  $file
111
	 * @param \Way\Generators\Compilers\TemplateCompiler  $compiler
112
	 * @param \Illuminate\Database\Migrations\MigrationRepositoryInterface  $repository
113
	 * @param \Illuminate\Config\Repository  $config
114
	 */
115
	public function __construct(
116
		Generator $generator,
117
		Filesystem $file,
118
		TemplateCompiler $compiler,
119
		MigrationRepositoryInterface $repository,
120
		Config $config
121
	)
122
	{
123
		$this->file = $file;
124
		$this->compiler = $compiler;
125
		$this->repository = $repository;
126
		$this->config = $config;
127
128
		parent::__construct( $generator );
129
	}
130
131
	/**
132
	 * Execute the console command.
133
	 *
134
	 * @return void
135
	 */
136
	public function fire()
137
	{
138
		$this->info( 'Using connection: '. $this->option( 'connection' ) ."\n" );
139
        if ($this->option('connection') !== $this->config->get('database.default')) {
140
            $this->connection = $this->option('connection');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->option('connection') can also be of type array. However, the property $connection is declared as type string|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
141
        }
142
		$this->schemaGenerator = new SchemaGenerator(
143
			$this->option('connection'),
144
			$this->option('defaultIndexNames'),
145
			$this->option('defaultFKNames')
146
		);
147
148
		if ( $this->argument( 'tables' ) ) {
149
			$tables = explode( ',', $this->argument( 'tables' ) );
150
		} elseif ( $this->option('tables') ) {
151
			$tables = explode( ',', $this->option( 'tables' ) );
152
		} else {
153
			$tables = $this->schemaGenerator->getTables();
154
		}
155
156
		$tables = $this->removeExcludedTables($tables);
157
		$this->info( 'Generating migrations for: '. implode( ', ', $tables ) );
158
159
		if (!$this->option( 'no-interaction' )) {
160
			$this->log = $this->askYn('Do you want to log these migrations in the migrations table?');
161
		}
162
163
		if ( $this->log ) {
164
			$this->repository->setSource( $this->option( 'connection' ) );
165
			if ( ! $this->repository->repositoryExists() ) {
166
				$options = array('--database' => $this->option( 'connection' ) );
167
				$this->call('migrate:install', $options);
168
			}
169
			$batch = $this->repository->getNextBatchNumber();
170
			$this->batch = $this->askNumeric( 'Next Batch Number is: '. $batch .'. We recommend using Batch Number 0 so that it becomes the "first" migration', 0 );
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->askNumeric('Next ... "first" migration', 0) can also be of type double or string. However, the property $batch is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
171
		}
172
173
		$this->info( "Setting up Tables and Index Migrations" );
174
		$this->datePrefix = date( 'Y_m_d_His' );
175
		$this->generate( 'create', $tables );
176
		$this->info( "\nSetting up Foreign Key Migrations\n" );
177
		$this->datePrefix = date( 'Y_m_d_His', strtotime( '+1 second' ) );
178
		$this->generate( 'foreign_keys', $tables );
179
		$this->info( "\nFinished!\n" );
180
	}
181
182
	/**
183
	 * Ask for user input: Yes/No
184
	 * @param  string $question Question to ask
185
	 * @return boolean          Answer from user
186
	 */
187
	protected function askYn( $question ) {
188
		$answer = $this->ask( $question .' [Y/n] ');
189
		while ( ! in_array( strtolower( $answer ), [ 'y', 'n', 'yes', 'no' ] ) ) {
190
			$answer = $this->ask('Please choose either yes or no. ');
191
		}
192
		return in_array( strtolower( $answer ), [ 'y', 'yes' ] );
193
	}
194
195
	/**
196
	 * Ask user for a Numeric Value, or blank for default
197
	 * @param  string    $question Question to ask
198
	 * @param  int|float $default  Default Value (optional)
199
	 * @return int|float           Answer
200
	 */
201
	protected function askNumeric( $question, $default = null ) {
202
		$ask = 'Your answer needs to be a numeric value';
203
204
		if ( ! is_null( $default ) ) {
205
			$question .= ' [Default: '. $default .'] ';
206
			$ask .= ' or blank for default';
207
		}
208
209
		$answer = $this->ask( $question );
210
211
		while ( ! is_numeric( $answer ) and ! ( $answer == '' and ! is_null( $default ) ) ) {
212
			$answer = $this->ask( $ask .'. ');
213
		}
214
		if ( $answer == '' ) {
215
			$answer = $default;
216
		}
217
		return $answer;
218
	}
219
220
	/**
221
	 * Generate Migrations
222
	 *
223
	 * @param  string $method Create Tables or Foreign Keys ['create', 'foreign_keys']
224
	 * @param  array  $tables List of tables to create migrations for
225
	 * @throws MethodNotFoundException
226
	 * @return void
227
	 */
228
	protected function generate( $method, $tables )
229
	{
230
		if ( $method == 'create' ) {
231
			$function = 'getFields';
232
			$prefix = 'create';
233
		} elseif ( $method = 'foreign_keys' ) {
234
			$function = 'getForeignKeyConstraints';
235
			$prefix = 'add_foreign_keys_to';
236
			$method = 'table';
237
		} else {
238
			throw new MethodNotFoundException( $method );
239
		}
240
241
		foreach ( $tables as $table ) {
242
			$this->migrationName = $prefix .'_'. $table .'_table';
243
			$this->method = $method;
244
			$this->table = $table;
245
			$this->fields = $this->schemaGenerator->{$function}( $table );
246
			if ( $this->fields ) {
247
				parent::fire();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (fire() instead of generate()). Are you sure this is correct? If so, you might want to change this to $this->fire().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
248
				if ( $this->log ) {
249
					$file = $this->datePrefix . '_' . $this->migrationName;
250
					$this->repository->log($file, $this->batch);
251
				}
252
			}
253
		}
254
	}
255
256
	/**
257
	 * The path where the file will be created
258
	 *
259
	 * @return string
260
	 */
261
	protected function getFileGenerationPath()
262
	{
263
		$path = $this->getPathByOptionOrConfig( 'path', 'migration_target_path' );
264
		$migrationName = str_replace('/', '_', $this->migrationName);
265
		$fileName = $this->getDatePrefix() . '_' . $migrationName . '.php';
266
267
		return "{$path}/{$fileName}";
268
	}
269
270
	/**
271
	 * Get the date prefix for the migration.
272
	 *
273
	 * @return string
274
	 */
275
	protected function getDatePrefix()
276
	{
277
		return $this->datePrefix;
278
	}
279
280
	/**
281
	 * Fetch the template data
282
	 *
283
	 * @return array
284
	 */
285
	protected function getTemplateData()
286
	{
287
		if ( $this->method == 'create' ) {
288
			$up = (new AddToTable($this->file, $this->compiler))->run($this->fields, $this->table, $this->connection, 'create');
0 ignored issues
show
Bug introduced by
It seems like $this->connection can also be of type string; however, Xethron\MigrationsGenerator\Syntax\Table::run() does only seem to accept null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
289
			$down = (new DroppedTable)->drop($this->table, $this->connection);
0 ignored issues
show
Bug introduced by
It seems like $this->connection can also be of type string; however, Xethron\MigrationsGenera...ax\DroppedTable::drop() does only seem to accept null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
290
		} else {
291
			$up = (new AddForeignKeysToTable($this->file, $this->compiler))->run($this->fields,$this->table, $this->connection);
0 ignored issues
show
Bug introduced by
It seems like $this->connection can also be of type string; however, Xethron\MigrationsGenerator\Syntax\Table::run() does only seem to accept null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
292
			$down = (new RemoveForeignKeysFromTable($this->file, $this->compiler))->run($this->fields,$this->table, $this->connection);
0 ignored issues
show
Bug introduced by
It seems like $this->connection can also be of type string; however, Xethron\MigrationsGenerator\Syntax\Table::run() does only seem to accept null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
293
		}
294
295
		return [
296
			'CLASS' => ucwords(camel_case($this->migrationName)),
297
			'UP'    => $up,
298
			'DOWN'  => $down
299
		];
300
	}
301
302
	/**
303
	 * Get path to template for generator
304
	 *
305
	 * @return string
306
	 */
307
	protected function getTemplatePath()
308
	{
309
		return $this->getPathByOptionOrConfig( 'templatePath', 'migration_template_path' );
310
	}
311
312
	/**
313
	 * Get the console command arguments.
314
	 *
315
	 * @return array
316
	 */
317
	protected function getArguments()
318
	{
319
		return [
320
			['tables', InputArgument::OPTIONAL, 'A list of Tables you wish to Generate Migrations for separated by a comma: users,posts,comments'],
321
		];
322
	}
323
324
	/**
325
	 * Get the console command options.
326
	 *
327
	 * @return array
328
	 */
329
	protected function getOptions()
330
	{
331
		return [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(array('conn...ames for migrations')); (array<string|null>[]) is incompatible with the return type of the parent method Way\Generators\Commands\...atorCommand::getOptions of type array<string|null>[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
332
			['connection', 'c', InputOption::VALUE_OPTIONAL, 'The database connection to use.', $this->config->get( 'database.default' )],
333
			['tables', 't', InputOption::VALUE_OPTIONAL, 'A list of Tables you wish to Generate Migrations for separated by a comma: users,posts,comments'],
334
			['ignore', 'i', InputOption::VALUE_OPTIONAL, 'A list of Tables you wish to ignore, separated by a comma: users,posts,comments' ],
335
			['path', 'p', InputOption::VALUE_OPTIONAL, 'Where should the file be created?'],
336
			['templatePath', 'tp', InputOption::VALUE_OPTIONAL, 'The location of the template for this generator'],
337
			['defaultIndexNames', null, InputOption::VALUE_NONE, 'Don\'t use db index names for migrations'],
338
			['defaultFKNames', null, InputOption::VALUE_NONE, 'Don\'t use db foreign key names for migrations'],
339
		];
340
	}
341
342
	/**
343
	 * Remove all the tables to exclude from the array of tables
344
	 *
345
	 * @param $tables
346
	 *
347
	 * @return array
348
	 */
349
	protected function removeExcludedTables($tables)
350
	{
351
		$excludes = $this->getExcludedTables();
352
		$tables = array_diff($tables, $excludes);
353
354
		return $tables;
355
	}
356
357
	/**
358
	 * Get a list of tables to exclude
359
	 *
360
	 * @return array
361
	 */
362
	protected function getExcludedTables()
363
	{
364
		$excludes = ['migrations'];
365
		$ignore = $this->option('ignore');
366
		if ( ! empty($ignore)) {
367
			return array_merge($excludes, explode(',', $ignore));
368
		}
369
370
		return $excludes;
371
	}
372
373
}
374