ForeignKeyGenerator   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 73
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 6 3
A isDefaultName() 0 3 1
A createIndexName() 0 6 1
B generate() 0 21 5
1
<?php namespace Xethron\MigrationsGenerator\Generators;
2
3
class ForeignKeyGenerator {
4
5
	/**
6
	 * @var string
7
	 */
8
	protected $table;
9
10
	/**
11
	 * Get array of foreign keys
12
	 *
13
	 * @param string                                      $table Table Name
14
	 * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema
15
	 * @param                                             $ignoreForeignKeyNames
16
	 *
17
	 * @return array
18
	 */
19
	public function generate($table, $schema, $ignoreForeignKeyNames)
20
	{
21
		$this->table = $table;
22
		$fields = [];
23
24
		$foreignKeys = $schema->listTableForeignKeys($table);
25
26
		if ( empty( $foreignKeys ) ) return array();
27
28
		foreach ( $foreignKeys as $foreignKey ) {
29
			$fields[] = [
30
				'name' => $this->getName($foreignKey, $ignoreForeignKeyNames),
31
				'field' => $foreignKey->getLocalColumns()[0],
32
				'references' => $foreignKey->getForeignColumns()[0],
33
				'on' => $foreignKey->getForeignTableName(),
34
				'onUpdate' => $foreignKey->hasOption('onUpdate') ? $foreignKey->getOption('onUpdate') : 'RESTRICT',
35
				'onDelete' => $foreignKey->hasOption('onDelete') ? $foreignKey->getOption('onDelete') : 'RESTRICT',
36
			];
37
		}
38
		return $fields;
39
	}
40
41
	/**
42
	 * @param      $foreignKey
43
	 * @param bool $ignoreForeignKeyNames
44
	 *
45
	 * @return null
46
	 */
47
	private function getName($foreignKey, $ignoreForeignKeyNames) {
48
		if ($ignoreForeignKeyNames or $this->isDefaultName($foreignKey)) {
49
			return null;
50
		}
51
		return $foreignKey->getName();
52
	}
53
54
	/**
55
	 * @param $foreignKey
56
	 *
57
	 * @return bool
58
	 */
59
	private function isDefaultName($foreignKey) {
60
		return $foreignKey->getName() === $this->createIndexName($foreignKey->getLocalColumns()[0]);
61
	}
62
63
	/**
64
	 * Create a default index name for the table.
65
	 *
66
	 * @param  string  $column
67
	 * @return string
68
	 */
69
	protected function createIndexName($column)
70
	{
71
		$index = strtolower($this->table.'_'.$column.'_foreign');
72
73
		return str_replace(array('-', '.'), '_', $index);
74
	}
75
}
76