Completed
Push — master ( 6fb5fb...b26681 )
by David
11s
created

DefaultNamingStrategy::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
4
namespace TheCodingMachine\FluidSchema;
5
6
use Doctrine\Common\Inflector\Inflector;
7
use Doctrine\DBAL\Platforms\AbstractPlatform;
8
9
class DefaultNamingStrategy implements NamingStrategyInterface
10
{
11
    /**
12
     * @var AbstractPlatform
13
     */
14
    private $platform;
15
16
    public function __construct(AbstractPlatform $platform = null)
17
    {
18
        $this->platform = $platform;
19
    }
20
21
    /**
22
     * Returns the name of the jointure table from the name of the joined tables.
23
     *
24
     * @param string $table1
25
     * @param string $table2
26
     * @return string
27
     */
28
    public function getJointureTableName(string $table1, string $table2): string
29
    {
30
        return $table1.'_'.$table2;
31
    }
32
33
    /**
34
     * Returns the name of a foreign key column based on the name of the targeted table.
35
     *
36
     * @param string $targetTable
37
     * @return string
38
     */
39
    public function getForeignKeyColumnName(string $targetTable): string
40
    {
41
        return $this->toSingular($targetTable).'_id';
42
    }
43
44
    /**
45
     * Put all the words of a string separated by underscores on singular.
46
     * Assumes the words are in English and in their plural form.
47
     *
48
     * @param $plural
49
     * @return string
50
     */
51
    private function toSingular($plural): string
52
    {
53
        $tokens = preg_split("/[_ ]+/", $plural);
54
55
        $strs = [];
56
        foreach ($tokens as $token) {
57
            $strs[] = Inflector::singularize($token);
58
        }
59
60
        return implode('_', $strs);
61
    }
62
63
    /**
64
     * Let's quote if a database platform has been provided to us!
65
     *
66
     * @param string $identifier
67
     * @return string
68
     */
69
    public function quoteIdentifier(string $identifier): string
70
    {
71
        return ($this->platform !== null) ? $this->platform->quoteIdentifier($identifier) : $identifier;
72
    }
73
}
74