ForeignKeyGenerator::getName()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 2
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