Completed
Push — 4.2 ( 5e62fc...1584c5 )
by David
02:35
created
src/Mouf/Database/TDBM/OrderByAnalyzer.php 2 patches
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -12,122 +12,122 @@
 block discarded – undo
12 12
  */
13 13
 class OrderByAnalyzer
14 14
 {
15
-    /**
16
-     * The content of the cache variable.
17
-     *
18
-     * @var Cache
19
-     */
20
-    private $cache;
21
-
22
-    /**
23
-     * @var string
24
-     */
25
-    private $cachePrefix;
26
-
27
-    /**
28
-     * OrderByAnalyzer constructor.
29
-     *
30
-     * @param Cache       $cache
31
-     * @param string|null $cachePrefix
32
-     */
33
-    public function __construct(Cache $cache, $cachePrefix = null)
34
-    {
35
-        $this->cache = $cache;
36
-        $this->cachePrefix = $cachePrefix;
37
-    }
38
-
39
-    /**
40
-     * Returns an array for each sorted "column" in the form:.
41
-     *
42
-     * [
43
-     *      [
44
-     *          'type' => 'colref',
45
-     *          'table' => null,
46
-     *          'column' => 'a',
47
-     *          'direction' => 'ASC'
48
-     *      ],
49
-     *      [
50
-     *          'type' => 'expr',
51
-     *          'expr' => 'RAND()',
52
-     *          'direction' => 'DESC'
53
-     *      ]
54
-     * ]
55
-     *
56
-     * @param string $orderBy
57
-     *
58
-     * @return array
59
-     */
60
-    public function analyzeOrderBy(string $orderBy) : array
61
-    {
62
-        $key = $this->cachePrefix.'_order_by_analysis_'.$orderBy;
63
-        $results = $this->cache->fetch($key);
64
-        if ($results !== false) {
65
-            return $results;
66
-        }
67
-        $results = $this->analyzeOrderByNoCache($orderBy);
68
-        $this->cache->save($key, $results);
69
-
70
-        return $results;
71
-    }
72
-
73
-    private function analyzeOrderByNoCache(string $orderBy) : array
74
-    {
75
-        $sqlParser = new PHPSQLParser();
76
-        $sql = 'SELECT 1 FROM a ORDER BY '.$orderBy;
77
-        $parsed = $sqlParser->parse($sql, true);
78
-
79
-        $results = [];
80
-
81
-        for ($i = 0, $count = count($parsed['ORDER']); $i < $count; ++$i) {
82
-            $orderItem = $parsed['ORDER'][$i];
83
-            if ($orderItem['expr_type'] === 'colref') {
84
-                $parts = $orderItem['no_quotes']['parts'];
85
-                $columnName = array_pop($parts);
86
-                if (!empty($parts)) {
87
-                    $tableName = array_pop($parts);
88
-                } else {
89
-                    $tableName = null;
90
-                }
91
-
92
-                $results[] = [
93
-                    'type' => 'colref',
94
-                    'table' => $tableName,
95
-                    'column' => $columnName,
96
-                    'direction' => $orderItem['direction'],
97
-                ];
98
-            } else {
99
-                $position = $orderItem['position'];
100
-                if ($i + 1 < $count) {
101
-                    $nextPosition = $parsed['ORDER'][$i + 1]['position'];
102
-                    $str = substr($sql, $position, $nextPosition - $position);
103
-                } else {
104
-                    $str = substr($sql, $position);
105
-                }
106
-
107
-                $str = trim($str, " \t\r\n,");
108
-
109
-                $results[] = [
110
-                    'type' => 'expr',
111
-                    'expr' => $this->trimDirection($str),
112
-                    'direction' => $orderItem['direction'],
113
-                ];
114
-            }
115
-        }
116
-
117
-        return $results;
118
-    }
119
-
120
-    /**
121
-     * Trims the ASC/DESC direction at the end of the string.
122
-     *
123
-     * @param string $sql
124
-     *
125
-     * @return string
126
-     */
127
-    private function trimDirection(string $sql) : string
128
-    {
129
-        preg_match('/^(.*)(\s+(DESC|ASC|))*$/Ui', $sql, $matches);
130
-
131
-        return $matches[1];
132
-    }
15
+	/**
16
+	 * The content of the cache variable.
17
+	 *
18
+	 * @var Cache
19
+	 */
20
+	private $cache;
21
+
22
+	/**
23
+	 * @var string
24
+	 */
25
+	private $cachePrefix;
26
+
27
+	/**
28
+	 * OrderByAnalyzer constructor.
29
+	 *
30
+	 * @param Cache       $cache
31
+	 * @param string|null $cachePrefix
32
+	 */
33
+	public function __construct(Cache $cache, $cachePrefix = null)
34
+	{
35
+		$this->cache = $cache;
36
+		$this->cachePrefix = $cachePrefix;
37
+	}
38
+
39
+	/**
40
+	 * Returns an array for each sorted "column" in the form:.
41
+	 *
42
+	 * [
43
+	 *      [
44
+	 *          'type' => 'colref',
45
+	 *          'table' => null,
46
+	 *          'column' => 'a',
47
+	 *          'direction' => 'ASC'
48
+	 *      ],
49
+	 *      [
50
+	 *          'type' => 'expr',
51
+	 *          'expr' => 'RAND()',
52
+	 *          'direction' => 'DESC'
53
+	 *      ]
54
+	 * ]
55
+	 *
56
+	 * @param string $orderBy
57
+	 *
58
+	 * @return array
59
+	 */
60
+	public function analyzeOrderBy(string $orderBy) : array
61
+	{
62
+		$key = $this->cachePrefix.'_order_by_analysis_'.$orderBy;
63
+		$results = $this->cache->fetch($key);
64
+		if ($results !== false) {
65
+			return $results;
66
+		}
67
+		$results = $this->analyzeOrderByNoCache($orderBy);
68
+		$this->cache->save($key, $results);
69
+
70
+		return $results;
71
+	}
72
+
73
+	private function analyzeOrderByNoCache(string $orderBy) : array
74
+	{
75
+		$sqlParser = new PHPSQLParser();
76
+		$sql = 'SELECT 1 FROM a ORDER BY '.$orderBy;
77
+		$parsed = $sqlParser->parse($sql, true);
78
+
79
+		$results = [];
80
+
81
+		for ($i = 0, $count = count($parsed['ORDER']); $i < $count; ++$i) {
82
+			$orderItem = $parsed['ORDER'][$i];
83
+			if ($orderItem['expr_type'] === 'colref') {
84
+				$parts = $orderItem['no_quotes']['parts'];
85
+				$columnName = array_pop($parts);
86
+				if (!empty($parts)) {
87
+					$tableName = array_pop($parts);
88
+				} else {
89
+					$tableName = null;
90
+				}
91
+
92
+				$results[] = [
93
+					'type' => 'colref',
94
+					'table' => $tableName,
95
+					'column' => $columnName,
96
+					'direction' => $orderItem['direction'],
97
+				];
98
+			} else {
99
+				$position = $orderItem['position'];
100
+				if ($i + 1 < $count) {
101
+					$nextPosition = $parsed['ORDER'][$i + 1]['position'];
102
+					$str = substr($sql, $position, $nextPosition - $position);
103
+				} else {
104
+					$str = substr($sql, $position);
105
+				}
106
+
107
+				$str = trim($str, " \t\r\n,");
108
+
109
+				$results[] = [
110
+					'type' => 'expr',
111
+					'expr' => $this->trimDirection($str),
112
+					'direction' => $orderItem['direction'],
113
+				];
114
+			}
115
+		}
116
+
117
+		return $results;
118
+	}
119
+
120
+	/**
121
+	 * Trims the ASC/DESC direction at the end of the string.
122
+	 *
123
+	 * @param string $sql
124
+	 *
125
+	 * @return string
126
+	 */
127
+	private function trimDirection(string $sql) : string
128
+	{
129
+		preg_match('/^(.*)(\s+(DESC|ASC|))*$/Ui', $sql, $matches);
130
+
131
+		return $matches[1];
132
+	}
133 133
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 
79 79
         $results = [];
80 80
 
81
-        for ($i = 0, $count = count($parsed['ORDER']); $i < $count; ++$i) {
81
+        for ($i = 0, $count = count($parsed['ORDER']); $i<$count; ++$i) {
82 82
             $orderItem = $parsed['ORDER'][$i];
83 83
             if ($orderItem['expr_type'] === 'colref') {
84 84
                 $parts = $orderItem['no_quotes']['parts'];
@@ -97,9 +97,9 @@  discard block
 block discarded – undo
97 97
                 ];
98 98
             } else {
99 99
                 $position = $orderItem['position'];
100
-                if ($i + 1 < $count) {
101
-                    $nextPosition = $parsed['ORDER'][$i + 1]['position'];
102
-                    $str = substr($sql, $position, $nextPosition - $position);
100
+                if ($i+1<$count) {
101
+                    $nextPosition = $parsed['ORDER'][$i+1]['position'];
102
+                    $str = substr($sql, $position, $nextPosition-$position);
103 103
                 } else {
104 104
                     $str = substr($sql, $position);
105 105
                 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/UncheckedOrderBy.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -20,24 +20,24 @@
 block discarded – undo
20 20
  */
21 21
 class UncheckedOrderBy
22 22
 {
23
-    /**
24
-     * @var string
25
-     */
26
-    private $orderBy;
23
+	/**
24
+	 * @var string
25
+	 */
26
+	private $orderBy;
27 27
 
28
-    /**
29
-     * @param $orderBy
30
-     */
31
-    public function __construct(string $orderBy)
32
-    {
33
-        $this->orderBy = $orderBy;
34
-    }
28
+	/**
29
+	 * @param $orderBy
30
+	 */
31
+	public function __construct(string $orderBy)
32
+	{
33
+		$this->orderBy = $orderBy;
34
+	}
35 35
 
36
-    /**
37
-     * @return string
38
-     */
39
-    public function getOrderBy() : string
40
-    {
41
-        return $this->orderBy;
42
-    }
36
+	/**
37
+	 * @return string
38
+	 */
39
+	public function getOrderBy() : string
40
+	{
41
+		return $this->orderBy;
42
+	}
43 43
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/QueryFactory/FindObjectsQueryFactory.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@
 block discarded – undo
39 39
         $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$this->mainTable.')';
40 40
 
41 41
         $pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
42
-        $pkColumnNames = array_map(function ($pkColumn) {
42
+        $pkColumnNames = array_map(function($pkColumn) {
43 43
             return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
44 44
         }, $pkColumnNames);
45 45
 
Please login to merge, or discard this patch.
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -11,44 +11,44 @@
 block discarded – undo
11 11
  */
12 12
 class FindObjectsQueryFactory extends AbstractQueryFactory
13 13
 {
14
-    private $mainTable;
15
-    private $additionalTablesFetch;
16
-    private $filterString;
17
-
18
-    public function __construct(string $mainTable, array $additionalTablesFetch, $filterString, $orderBy, TDBMService $tdbmService, Schema $schema, OrderByAnalyzer $orderByAnalyzer)
19
-    {
20
-        parent::__construct($tdbmService, $schema, $orderByAnalyzer, $orderBy);
21
-        $this->mainTable = $mainTable;
22
-        $this->additionalTablesFetch = $additionalTablesFetch;
23
-        $this->filterString = $filterString;
24
-    }
25
-
26
-    protected function compute()
27
-    {
28
-        list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, $this->additionalTablesFetch, $this->orderBy);
29
-
30
-        $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$this->mainTable.')';
31
-
32
-        $pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
33
-        $pkColumnNames = array_map(function ($pkColumn) {
34
-            return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
35
-        }, $pkColumnNames);
36
-
37
-        $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$this->mainTable.')';
38
-
39
-        if (!empty($this->filterString)) {
40
-            $sql .= ' WHERE '.$this->filterString;
41
-            $countSql .= ' WHERE '.$this->filterString;
42
-        }
43
-
44
-        if (!empty($orderString)) {
45
-            $sql .= ' ORDER BY '.$orderString;
46
-        }
47
-
48
-        $this->magicSql = $sql;
49
-        $this->magicSqlCount = $countSql;
50
-        $this->columnDescList = $columnDescList;
51
-    }
14
+	private $mainTable;
15
+	private $additionalTablesFetch;
16
+	private $filterString;
17
+
18
+	public function __construct(string $mainTable, array $additionalTablesFetch, $filterString, $orderBy, TDBMService $tdbmService, Schema $schema, OrderByAnalyzer $orderByAnalyzer)
19
+	{
20
+		parent::__construct($tdbmService, $schema, $orderByAnalyzer, $orderBy);
21
+		$this->mainTable = $mainTable;
22
+		$this->additionalTablesFetch = $additionalTablesFetch;
23
+		$this->filterString = $filterString;
24
+	}
25
+
26
+	protected function compute()
27
+	{
28
+		list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, $this->additionalTablesFetch, $this->orderBy);
29
+
30
+		$sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$this->mainTable.')';
31
+
32
+		$pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
33
+		$pkColumnNames = array_map(function ($pkColumn) {
34
+			return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
35
+		}, $pkColumnNames);
36
+
37
+		$countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$this->mainTable.')';
38
+
39
+		if (!empty($this->filterString)) {
40
+			$sql .= ' WHERE '.$this->filterString;
41
+			$countSql .= ' WHERE '.$this->filterString;
42
+		}
43
+
44
+		if (!empty($orderString)) {
45
+			$sql .= ' ORDER BY '.$orderString;
46
+		}
47
+
48
+		$this->magicSql = $sql;
49
+		$this->magicSqlCount = $countSql;
50
+		$this->columnDescList = $columnDescList;
51
+	}
52 52
 
53 53
 
54 54
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/QueryFactory/QueryFactory.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -9,25 +9,25 @@
 block discarded – undo
9 9
  */
10 10
 interface QueryFactory
11 11
 {
12
-    /**
13
-     * Sets the ORDER BY directive executed in SQL.
14
-     *
15
-     * For instance:
16
-     *
17
-     *  $queryFactory->sort('label ASC, status DESC');
18
-     *
19
-     * **Important:** TDBM does its best to protect you from SQL injection. In particular, it will only allow column names in the "ORDER BY" clause. This means you are safe to pass input from the user directly in the ORDER BY parameter.
20
-     * If you want to pass an expression to the ORDER BY clause, you will need to tell TDBM to stop checking for SQL injections. You do this by passing a `UncheckedOrderBy` object as a parameter:
21
-     *
22
-     *  $queryFactory->sort(new UncheckedOrderBy('RAND()'))
23
-     *
24
-     * @param string|UncheckedOrderBy|null $orderBy
25
-     */
26
-    public function sort($orderBy);
12
+	/**
13
+	 * Sets the ORDER BY directive executed in SQL.
14
+	 *
15
+	 * For instance:
16
+	 *
17
+	 *  $queryFactory->sort('label ASC, status DESC');
18
+	 *
19
+	 * **Important:** TDBM does its best to protect you from SQL injection. In particular, it will only allow column names in the "ORDER BY" clause. This means you are safe to pass input from the user directly in the ORDER BY parameter.
20
+	 * If you want to pass an expression to the ORDER BY clause, you will need to tell TDBM to stop checking for SQL injections. You do this by passing a `UncheckedOrderBy` object as a parameter:
21
+	 *
22
+	 *  $queryFactory->sort(new UncheckedOrderBy('RAND()'))
23
+	 *
24
+	 * @param string|UncheckedOrderBy|null $orderBy
25
+	 */
26
+	public function sort($orderBy);
27 27
 
28
-    public function getMagicSql() : string;
28
+	public function getMagicSql() : string;
29 29
 
30
-    public function getMagicSqlCount() : string;
30
+	public function getMagicSqlCount() : string;
31 31
 
32
-    public function getColumnDescriptors() : array;
32
+	public function getColumnDescriptors() : array;
33 33
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/ScalarBeanPropertyDescriptor.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -11,125 +11,125 @@  discard block
 block discarded – undo
11 11
  */
12 12
 class ScalarBeanPropertyDescriptor extends AbstractBeanPropertyDescriptor
13 13
 {
14
-    /**
15
-     * @var Column
16
-     */
17
-    private $column;
18
-
19
-    public function __construct(Table $table, Column $column)
20
-    {
21
-        parent::__construct($table);
22
-        $this->table = $table;
23
-        $this->column = $column;
24
-    }
25
-
26
-    /**
27
-     * Returns the foreign-key the column is part of, if any. null otherwise.
28
-     *
29
-     * @return ForeignKeyConstraint|null
30
-     */
31
-    public function getForeignKey()
32
-    {
33
-        return false;
34
-    }
35
-
36
-    /**
37
-     * Returns the param annotation for this property (useful for constructor).
38
-     *
39
-     * @return string
40
-     */
41
-    public function getParamAnnotation()
42
-    {
43
-        $className = $this->getClassName();
44
-        $paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
45
-
46
-        $str = '     * @param %s %s';
47
-
48
-        return sprintf($str, $paramType, $this->getVariableName());
49
-    }
50
-
51
-    public function getUpperCamelCaseName()
52
-    {
53
-        return TDBMDaoGenerator::toCamelCase($this->column->getName());
54
-    }
55
-
56
-    /**
57
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
58
-     *
59
-     * @return null|string
60
-     */
61
-    public function getClassName()
62
-    {
63
-        return;
64
-    }
65
-
66
-    /**
67
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
68
-     *
69
-     * @return bool
70
-     */
71
-    public function isCompulsory()
72
-    {
73
-        return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
74
-    }
75
-
76
-    /**
77
-     * Returns true if the property has a default value.
78
-     *
79
-     * @return bool
80
-     */
81
-    public function hasDefault()
82
-    {
83
-        return $this->column->getDefault() !== null;
84
-    }
85
-
86
-    /**
87
-     * Returns the code that assigns a value to its default value.
88
-     *
89
-     * @return string
90
-     */
91
-    public function assignToDefaultCode()
92
-    {
93
-        $str = '        $this->%s(%s);';
94
-
95
-        $default = $this->column->getDefault();
96
-
97
-        if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
98
-            $defaultCode = 'new \DateTimeImmutable()';
99
-        } else {
100
-            $defaultCode = var_export($this->column->getDefault(), true);
101
-        }
102
-
103
-        return sprintf($str, $this->getSetterName(), $defaultCode);
104
-    }
105
-
106
-    /**
107
-     * Returns true if the property is the primary key.
108
-     *
109
-     * @return bool
110
-     */
111
-    public function isPrimaryKey()
112
-    {
113
-        return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
114
-    }
115
-
116
-    /**
117
-     * Returns the PHP code for getters and setters.
118
-     *
119
-     * @return string
120
-     */
121
-    public function getGetterSetterCode()
122
-    {
123
-        $type = $this->column->getType();
124
-        $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
125
-
126
-        $columnGetterName = $this->getGetterName();
127
-        $columnSetterName = $this->getSetterName();
128
-
129
-        // A column type can be forced if it is not nullable and not auto-incrmentable (for auto-increment columns, we can get "null" as long as the bean is not saved).
130
-        $canForceGetterReturnType = $this->column->getNotnull() && !$this->column->getAutoincrement();
131
-
132
-        $getterAndSetterCode = '    /**
14
+	/**
15
+	 * @var Column
16
+	 */
17
+	private $column;
18
+
19
+	public function __construct(Table $table, Column $column)
20
+	{
21
+		parent::__construct($table);
22
+		$this->table = $table;
23
+		$this->column = $column;
24
+	}
25
+
26
+	/**
27
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
28
+	 *
29
+	 * @return ForeignKeyConstraint|null
30
+	 */
31
+	public function getForeignKey()
32
+	{
33
+		return false;
34
+	}
35
+
36
+	/**
37
+	 * Returns the param annotation for this property (useful for constructor).
38
+	 *
39
+	 * @return string
40
+	 */
41
+	public function getParamAnnotation()
42
+	{
43
+		$className = $this->getClassName();
44
+		$paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
45
+
46
+		$str = '     * @param %s %s';
47
+
48
+		return sprintf($str, $paramType, $this->getVariableName());
49
+	}
50
+
51
+	public function getUpperCamelCaseName()
52
+	{
53
+		return TDBMDaoGenerator::toCamelCase($this->column->getName());
54
+	}
55
+
56
+	/**
57
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
58
+	 *
59
+	 * @return null|string
60
+	 */
61
+	public function getClassName()
62
+	{
63
+		return;
64
+	}
65
+
66
+	/**
67
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
68
+	 *
69
+	 * @return bool
70
+	 */
71
+	public function isCompulsory()
72
+	{
73
+		return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
74
+	}
75
+
76
+	/**
77
+	 * Returns true if the property has a default value.
78
+	 *
79
+	 * @return bool
80
+	 */
81
+	public function hasDefault()
82
+	{
83
+		return $this->column->getDefault() !== null;
84
+	}
85
+
86
+	/**
87
+	 * Returns the code that assigns a value to its default value.
88
+	 *
89
+	 * @return string
90
+	 */
91
+	public function assignToDefaultCode()
92
+	{
93
+		$str = '        $this->%s(%s);';
94
+
95
+		$default = $this->column->getDefault();
96
+
97
+		if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
98
+			$defaultCode = 'new \DateTimeImmutable()';
99
+		} else {
100
+			$defaultCode = var_export($this->column->getDefault(), true);
101
+		}
102
+
103
+		return sprintf($str, $this->getSetterName(), $defaultCode);
104
+	}
105
+
106
+	/**
107
+	 * Returns true if the property is the primary key.
108
+	 *
109
+	 * @return bool
110
+	 */
111
+	public function isPrimaryKey()
112
+	{
113
+		return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
114
+	}
115
+
116
+	/**
117
+	 * Returns the PHP code for getters and setters.
118
+	 *
119
+	 * @return string
120
+	 */
121
+	public function getGetterSetterCode()
122
+	{
123
+		$type = $this->column->getType();
124
+		$normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
125
+
126
+		$columnGetterName = $this->getGetterName();
127
+		$columnSetterName = $this->getSetterName();
128
+
129
+		// A column type can be forced if it is not nullable and not auto-incrmentable (for auto-increment columns, we can get "null" as long as the bean is not saved).
130
+		$canForceGetterReturnType = $this->column->getNotnull() && !$this->column->getAutoincrement();
131
+
132
+		$getterAndSetterCode = '    /**
133 133
      * The getter for the "%s" column.
134 134
      *
135 135
      * @return %s
@@ -151,52 +151,52 @@  discard block
 block discarded – undo
151 151
 
152 152
 ';
153 153
 
154
-        return sprintf($getterAndSetterCode,
155
-            // Getter
156
-            $this->column->getName(),
157
-            $normalizedType.($canForceGetterReturnType ? '' : '|null'),
158
-            $columnGetterName,
159
-            ($canForceGetterReturnType ? ' : '.$normalizedType : ''),
160
-            var_export($this->column->getName(), true),
161
-            var_export($this->table->getName(), true),
162
-            // Setter
163
-            $this->column->getName(),
164
-            $normalizedType,
165
-            $this->column->getName(),
166
-            $columnSetterName,
167
-            $normalizedType,
168
-            //$castTo,
169
-            $this->column->getName().($this->column->getNotnull() ? '' : ' = null'),
170
-            var_export($this->column->getName(), true),
171
-            $this->column->getName(),
172
-            var_export($this->table->getName(), true)
173
-        );
174
-    }
175
-
176
-    /**
177
-     * Returns the part of code useful when doing json serialization.
178
-     *
179
-     * @return string
180
-     */
181
-    public function getJsonSerializeCode()
182
-    {
183
-        $type = $this->column->getType();
184
-        $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
185
-
186
-        if ($normalizedType == '\\DateTimeInterface') {
187
-            return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null) ? null : $this->'.$this->getGetterName()."()->format('c');\n";
188
-        } else {
189
-            return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
190
-        }
191
-    }
192
-
193
-    /**
194
-     * Returns the column name.
195
-     *
196
-     * @return string
197
-     */
198
-    public function getColumnName()
199
-    {
200
-        return $this->column->getName();
201
-    }
154
+		return sprintf($getterAndSetterCode,
155
+			// Getter
156
+			$this->column->getName(),
157
+			$normalizedType.($canForceGetterReturnType ? '' : '|null'),
158
+			$columnGetterName,
159
+			($canForceGetterReturnType ? ' : '.$normalizedType : ''),
160
+			var_export($this->column->getName(), true),
161
+			var_export($this->table->getName(), true),
162
+			// Setter
163
+			$this->column->getName(),
164
+			$normalizedType,
165
+			$this->column->getName(),
166
+			$columnSetterName,
167
+			$normalizedType,
168
+			//$castTo,
169
+			$this->column->getName().($this->column->getNotnull() ? '' : ' = null'),
170
+			var_export($this->column->getName(), true),
171
+			$this->column->getName(),
172
+			var_export($this->table->getName(), true)
173
+		);
174
+	}
175
+
176
+	/**
177
+	 * Returns the part of code useful when doing json serialization.
178
+	 *
179
+	 * @return string
180
+	 */
181
+	public function getJsonSerializeCode()
182
+	{
183
+		$type = $this->column->getType();
184
+		$normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
185
+
186
+		if ($normalizedType == '\\DateTimeInterface') {
187
+			return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null) ? null : $this->'.$this->getGetterName()."()->format('c');\n";
188
+		} else {
189
+			return '        $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
190
+		}
191
+	}
192
+
193
+	/**
194
+	 * Returns the column name.
195
+	 *
196
+	 * @return string
197
+	 */
198
+	public function getColumnName()
199
+	{
200
+		return $this->column->getName();
201
+	}
202 202
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/QueryFactory/AbstractQueryFactory.php 1 patch
Indentation   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -10,214 +10,214 @@
 block discarded – undo
10 10
 
11 11
 abstract class AbstractQueryFactory implements QueryFactory
12 12
 {
13
-    /**
14
-     * @var TDBMService
15
-     */
16
-    protected $tdbmService;
17
-
18
-    /**
19
-     * @var Schema
20
-     */
21
-    protected $schema;
22
-
23
-    /**
24
-     * @var OrderByAnalyzer
25
-     */
26
-    protected $orderByAnalyzer;
27
-
28
-    /**
29
-     * @var string|UncheckedOrderBy|null
30
-     */
31
-    protected $orderBy;
32
-
33
-    protected $magicSql;
34
-    protected $magicSqlCount;
35
-    protected $columnDescList;
36
-
37
-    /**
38
-     * @param TDBMService $tdbmService
39
-     */
40
-    public function __construct(TDBMService $tdbmService, Schema $schema, OrderByAnalyzer $orderByAnalyzer, $orderBy)
41
-    {
42
-        $this->tdbmService = $tdbmService;
43
-        $this->schema = $schema;
44
-        $this->orderByAnalyzer = $orderByAnalyzer;
45
-        $this->orderBy = $orderBy;
46
-    }
47
-
48
-    /**
49
-     * Returns the column list that must be fetched for the SQL request.
50
-     *
51
-     * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
52
-     *
53
-     * @param string                       $mainTable
54
-     * @param array                        $additionalTablesFetch
55
-     * @param string|UncheckedOrderBy|null $orderBy
56
-     *
57
-     * @return array
58
-     *
59
-     * @throws \Doctrine\DBAL\Schema\SchemaException
60
-     */
61
-    protected function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), $orderBy = null)
62
-    {
63
-        // From the table name and the additional tables we want to fetch, let's build a list of all tables
64
-        // that must be part of the select columns.
65
-
66
-        $connection = $this->tdbmService->getConnection();
67
-
68
-        $tableGroups = [];
69
-        $allFetchedTables = $this->tdbmService->_getRelatedTablesByInheritance($mainTable);
70
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
71
-        foreach ($allFetchedTables as $table) {
72
-            $tableGroups[$table] = $tableGroupName;
73
-        }
74
-
75
-        $columnsList = [];
76
-        $columnDescList = [];
77
-        $sortColumn = 0;
78
-        $reconstructedOrderBy = null;
79
-
80
-        if (is_string($orderBy)) {
81
-            $orderBy = trim($orderBy);
82
-            if ($orderBy === '') {
83
-                $orderBy = null;
84
-            }
85
-        }
86
-
87
-        // Now, let's deal with "order by columns"
88
-        if ($orderBy !== null) {
89
-            if ($orderBy instanceof UncheckedOrderBy) {
90
-                $securedOrderBy = false;
91
-                $orderBy = $orderBy->getOrderBy();
92
-                $reconstructedOrderBy = $orderBy;
93
-            } else {
94
-                $securedOrderBy = true;
95
-                $reconstructedOrderBys = [];
96
-            }
97
-            $orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
98
-
99
-            // If we sort by a column, there is a high chance we will fetch the bean containing this column.
100
-            // Hence, we should add the table to the $additionalTablesFetch
101
-            foreach ($orderByColumns as $orderByColumn) {
102
-                if ($orderByColumn['type'] === 'colref') {
103
-                    if ($orderByColumn['table'] !== null) {
104
-                        $additionalTablesFetch[] = $orderByColumn['table'];
105
-                    }
106
-                    if ($securedOrderBy) {
107
-                        $reconstructedOrderBys[] = ($orderByColumn['table'] !== null ? $connection->quoteIdentifier($orderByColumn['table']).'.' : '').$connection->quoteIdentifier($orderByColumn['column']).' '.$orderByColumn['direction'];
108
-                    }
109
-                } elseif ($orderByColumn['type'] === 'expr') {
110
-                    $sortColumnName = 'sort_column_'.$sortColumn;
111
-                    $columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
112
-                    $columnDescList[] = [
113
-                        'tableGroup' => null,
114
-                    ];
115
-                    ++$sortColumn;
116
-
117
-                    if ($securedOrderBy) {
118
-                        throw new TDBMInvalidArgumentException('Invalid ORDER BY column: "'.$orderByColumn['expr'].'". If you want to use expression in your ORDER BY clause, you must wrap them in a UncheckedOrderBy object. For instance: new UncheckedOrderBy("col1 + col2 DESC")');
119
-                    }
120
-                }
121
-            }
122
-
123
-            if ($reconstructedOrderBy === null) {
124
-                $reconstructedOrderBy = implode(', ', $reconstructedOrderBys);
125
-            }
126
-        }
127
-
128
-        foreach ($additionalTablesFetch as $additionalTable) {
129
-            $relatedTables = $this->tdbmService->_getRelatedTablesByInheritance($additionalTable);
130
-            $tableGroupName = $this->getTableGroupName($relatedTables);
131
-            foreach ($relatedTables as $table) {
132
-                $tableGroups[$table] = $tableGroupName;
133
-            }
134
-            $allFetchedTables = array_merge($allFetchedTables, $relatedTables);
135
-        }
136
-
137
-        // Let's remove any duplicate
138
-        $allFetchedTables = array_flip(array_flip($allFetchedTables));
139
-
140
-        // Now, let's build the column list
141
-        foreach ($allFetchedTables as $table) {
142
-            foreach ($this->schema->getTable($table)->getColumns() as $column) {
143
-                $columnName = $column->getName();
144
-                $columnDescList[] = [
145
-                    'as' => $table.'____'.$columnName,
146
-                    'table' => $table,
147
-                    'column' => $columnName,
148
-                    'type' => $column->getType(),
149
-                    'tableGroup' => $tableGroups[$table],
150
-                ];
151
-                $columnsList[] = $connection->quoteIdentifier($table).'.'.$connection->quoteIdentifier($columnName).' as '.
152
-                    $connection->quoteIdentifier($table.'____'.$columnName);
153
-            }
154
-        }
155
-
156
-        return [$columnDescList, $columnsList, $reconstructedOrderBy];
157
-    }
158
-
159
-    abstract protected function compute();
160
-
161
-    /**
162
-     * Returns an identifier for the group of tables passed in parameter.
163
-     *
164
-     * @param string[] $relatedTables
165
-     *
166
-     * @return string
167
-     */
168
-    protected function getTableGroupName(array $relatedTables)
169
-    {
170
-        sort($relatedTables);
171
-
172
-        return implode('_``_', $relatedTables);
173
-    }
174
-
175
-    public function getMagicSql() : string
176
-    {
177
-        if ($this->magicSql === null) {
178
-            $this->compute();
179
-        }
180
-
181
-        return $this->magicSql;
182
-    }
183
-
184
-    public function getMagicSqlCount() : string
185
-    {
186
-        if ($this->magicSqlCount === null) {
187
-            $this->compute();
188
-        }
189
-
190
-        return $this->magicSqlCount;
191
-    }
192
-
193
-    public function getColumnDescriptors() : array
194
-    {
195
-        if ($this->columnDescList === null) {
196
-            $this->compute();
197
-        }
198
-
199
-        return $this->columnDescList;
200
-    }
201
-
202
-    /**
203
-     * Sets the ORDER BY directive executed in SQL.
204
-     *
205
-     * For instance:
206
-     *
207
-     *  $queryFactory->sort('label ASC, status DESC');
208
-     *
209
-     * **Important:** TDBM does its best to protect you from SQL injection. In particular, it will only allow column names in the "ORDER BY" clause. This means you are safe to pass input from the user directly in the ORDER BY parameter.
210
-     * If you want to pass an expression to the ORDER BY clause, you will need to tell TDBM to stop checking for SQL injections. You do this by passing a `UncheckedOrderBy` object as a parameter:
211
-     *
212
-     *  $queryFactory->sort(new UncheckedOrderBy('RAND()'))
213
-     *
214
-     * @param string|UncheckedOrderBy|null $orderBy
215
-     */
216
-    public function sort($orderBy)
217
-    {
218
-        $this->orderBy = $orderBy;
219
-        $this->magicSql = null;
220
-        $this->magicSqlCount = null;
221
-        $this->columnDescList = null;
222
-    }
13
+	/**
14
+	 * @var TDBMService
15
+	 */
16
+	protected $tdbmService;
17
+
18
+	/**
19
+	 * @var Schema
20
+	 */
21
+	protected $schema;
22
+
23
+	/**
24
+	 * @var OrderByAnalyzer
25
+	 */
26
+	protected $orderByAnalyzer;
27
+
28
+	/**
29
+	 * @var string|UncheckedOrderBy|null
30
+	 */
31
+	protected $orderBy;
32
+
33
+	protected $magicSql;
34
+	protected $magicSqlCount;
35
+	protected $columnDescList;
36
+
37
+	/**
38
+	 * @param TDBMService $tdbmService
39
+	 */
40
+	public function __construct(TDBMService $tdbmService, Schema $schema, OrderByAnalyzer $orderByAnalyzer, $orderBy)
41
+	{
42
+		$this->tdbmService = $tdbmService;
43
+		$this->schema = $schema;
44
+		$this->orderByAnalyzer = $orderByAnalyzer;
45
+		$this->orderBy = $orderBy;
46
+	}
47
+
48
+	/**
49
+	 * Returns the column list that must be fetched for the SQL request.
50
+	 *
51
+	 * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
52
+	 *
53
+	 * @param string                       $mainTable
54
+	 * @param array                        $additionalTablesFetch
55
+	 * @param string|UncheckedOrderBy|null $orderBy
56
+	 *
57
+	 * @return array
58
+	 *
59
+	 * @throws \Doctrine\DBAL\Schema\SchemaException
60
+	 */
61
+	protected function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), $orderBy = null)
62
+	{
63
+		// From the table name and the additional tables we want to fetch, let's build a list of all tables
64
+		// that must be part of the select columns.
65
+
66
+		$connection = $this->tdbmService->getConnection();
67
+
68
+		$tableGroups = [];
69
+		$allFetchedTables = $this->tdbmService->_getRelatedTablesByInheritance($mainTable);
70
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
71
+		foreach ($allFetchedTables as $table) {
72
+			$tableGroups[$table] = $tableGroupName;
73
+		}
74
+
75
+		$columnsList = [];
76
+		$columnDescList = [];
77
+		$sortColumn = 0;
78
+		$reconstructedOrderBy = null;
79
+
80
+		if (is_string($orderBy)) {
81
+			$orderBy = trim($orderBy);
82
+			if ($orderBy === '') {
83
+				$orderBy = null;
84
+			}
85
+		}
86
+
87
+		// Now, let's deal with "order by columns"
88
+		if ($orderBy !== null) {
89
+			if ($orderBy instanceof UncheckedOrderBy) {
90
+				$securedOrderBy = false;
91
+				$orderBy = $orderBy->getOrderBy();
92
+				$reconstructedOrderBy = $orderBy;
93
+			} else {
94
+				$securedOrderBy = true;
95
+				$reconstructedOrderBys = [];
96
+			}
97
+			$orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
98
+
99
+			// If we sort by a column, there is a high chance we will fetch the bean containing this column.
100
+			// Hence, we should add the table to the $additionalTablesFetch
101
+			foreach ($orderByColumns as $orderByColumn) {
102
+				if ($orderByColumn['type'] === 'colref') {
103
+					if ($orderByColumn['table'] !== null) {
104
+						$additionalTablesFetch[] = $orderByColumn['table'];
105
+					}
106
+					if ($securedOrderBy) {
107
+						$reconstructedOrderBys[] = ($orderByColumn['table'] !== null ? $connection->quoteIdentifier($orderByColumn['table']).'.' : '').$connection->quoteIdentifier($orderByColumn['column']).' '.$orderByColumn['direction'];
108
+					}
109
+				} elseif ($orderByColumn['type'] === 'expr') {
110
+					$sortColumnName = 'sort_column_'.$sortColumn;
111
+					$columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
112
+					$columnDescList[] = [
113
+						'tableGroup' => null,
114
+					];
115
+					++$sortColumn;
116
+
117
+					if ($securedOrderBy) {
118
+						throw new TDBMInvalidArgumentException('Invalid ORDER BY column: "'.$orderByColumn['expr'].'". If you want to use expression in your ORDER BY clause, you must wrap them in a UncheckedOrderBy object. For instance: new UncheckedOrderBy("col1 + col2 DESC")');
119
+					}
120
+				}
121
+			}
122
+
123
+			if ($reconstructedOrderBy === null) {
124
+				$reconstructedOrderBy = implode(', ', $reconstructedOrderBys);
125
+			}
126
+		}
127
+
128
+		foreach ($additionalTablesFetch as $additionalTable) {
129
+			$relatedTables = $this->tdbmService->_getRelatedTablesByInheritance($additionalTable);
130
+			$tableGroupName = $this->getTableGroupName($relatedTables);
131
+			foreach ($relatedTables as $table) {
132
+				$tableGroups[$table] = $tableGroupName;
133
+			}
134
+			$allFetchedTables = array_merge($allFetchedTables, $relatedTables);
135
+		}
136
+
137
+		// Let's remove any duplicate
138
+		$allFetchedTables = array_flip(array_flip($allFetchedTables));
139
+
140
+		// Now, let's build the column list
141
+		foreach ($allFetchedTables as $table) {
142
+			foreach ($this->schema->getTable($table)->getColumns() as $column) {
143
+				$columnName = $column->getName();
144
+				$columnDescList[] = [
145
+					'as' => $table.'____'.$columnName,
146
+					'table' => $table,
147
+					'column' => $columnName,
148
+					'type' => $column->getType(),
149
+					'tableGroup' => $tableGroups[$table],
150
+				];
151
+				$columnsList[] = $connection->quoteIdentifier($table).'.'.$connection->quoteIdentifier($columnName).' as '.
152
+					$connection->quoteIdentifier($table.'____'.$columnName);
153
+			}
154
+		}
155
+
156
+		return [$columnDescList, $columnsList, $reconstructedOrderBy];
157
+	}
158
+
159
+	abstract protected function compute();
160
+
161
+	/**
162
+	 * Returns an identifier for the group of tables passed in parameter.
163
+	 *
164
+	 * @param string[] $relatedTables
165
+	 *
166
+	 * @return string
167
+	 */
168
+	protected function getTableGroupName(array $relatedTables)
169
+	{
170
+		sort($relatedTables);
171
+
172
+		return implode('_``_', $relatedTables);
173
+	}
174
+
175
+	public function getMagicSql() : string
176
+	{
177
+		if ($this->magicSql === null) {
178
+			$this->compute();
179
+		}
180
+
181
+		return $this->magicSql;
182
+	}
183
+
184
+	public function getMagicSqlCount() : string
185
+	{
186
+		if ($this->magicSqlCount === null) {
187
+			$this->compute();
188
+		}
189
+
190
+		return $this->magicSqlCount;
191
+	}
192
+
193
+	public function getColumnDescriptors() : array
194
+	{
195
+		if ($this->columnDescList === null) {
196
+			$this->compute();
197
+		}
198
+
199
+		return $this->columnDescList;
200
+	}
201
+
202
+	/**
203
+	 * Sets the ORDER BY directive executed in SQL.
204
+	 *
205
+	 * For instance:
206
+	 *
207
+	 *  $queryFactory->sort('label ASC, status DESC');
208
+	 *
209
+	 * **Important:** TDBM does its best to protect you from SQL injection. In particular, it will only allow column names in the "ORDER BY" clause. This means you are safe to pass input from the user directly in the ORDER BY parameter.
210
+	 * If you want to pass an expression to the ORDER BY clause, you will need to tell TDBM to stop checking for SQL injections. You do this by passing a `UncheckedOrderBy` object as a parameter:
211
+	 *
212
+	 *  $queryFactory->sort(new UncheckedOrderBy('RAND()'))
213
+	 *
214
+	 * @param string|UncheckedOrderBy|null $orderBy
215
+	 */
216
+	public function sort($orderBy)
217
+	{
218
+		$this->orderBy = $orderBy;
219
+		$this->magicSql = null;
220
+		$this->magicSqlCount = null;
221
+		$this->columnDescList = null;
222
+	}
223 223
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/QueryFactory/FindObjectsFromSqlQueryFactory.php 2 patches
Indentation   +187 added lines, -187 removed lines patch added patch discarded remove patch
@@ -15,191 +15,191 @@
 block discarded – undo
15 15
  */
16 16
 class FindObjectsFromSqlQueryFactory extends AbstractQueryFactory
17 17
 {
18
-    private $mainTable;
19
-    private $from;
20
-    private $filterString;
21
-    private $cache;
22
-    private $cachePrefix;
23
-
24
-    public function __construct(string $mainTable, string $from, $filterString, $orderBy, TDBMService $tdbmService, Schema $schema, OrderByAnalyzer $orderByAnalyzer, SchemaAnalyzer $schemaAnalyzer, Cache $cache, string $cachePrefix)
25
-    {
26
-        parent::__construct($tdbmService, $schema, $orderByAnalyzer, $orderBy);
27
-        $this->mainTable = $mainTable;
28
-        $this->from = $from;
29
-        $this->filterString = $filterString;
30
-        $this->schemaAnalyzer = $schemaAnalyzer;
31
-        $this->cache = $cache;
32
-        $this->cachePrefix = $cachePrefix;
33
-    }
34
-
35
-    protected function compute()
36
-    {
37
-        $connection = $this->tdbmService->getConnection();
38
-
39
-        $columnsList = null;
40
-
41
-        $allFetchedTables = $this->tdbmService->_getRelatedTablesByInheritance($this->mainTable);
42
-
43
-        $columnDescList = [];
44
-
45
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
46
-
47
-        foreach ($this->schema->getTable($this->mainTable)->getColumns() as $column) {
48
-            $columnName = $column->getName();
49
-            $columnDescList[] = [
50
-                'as' => $columnName,
51
-                'table' => $this->mainTable,
52
-                'column' => $columnName,
53
-                'type' => $column->getType(),
54
-                'tableGroup' => $tableGroupName,
55
-            ];
56
-        }
57
-
58
-        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) {
59
-            return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($columnDesc['column']);
60
-        }, $columnDescList)).' FROM '.$this->from;
61
-
62
-        if (count($allFetchedTables) > 1) {
63
-            list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
64
-        } elseif ($this->orderBy) {
65
-            list(, , $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
66
-        }
67
-
68
-        // Let's compute the COUNT.
69
-        $pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
70
-        $pkColumnNames = array_map(function ($pkColumn) {
71
-            return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
72
-        }, $pkColumnNames);
73
-
74
-        $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$this->from;
75
-
76
-        if (!empty($this->filterString)) {
77
-            $sql .= ' WHERE '.$this->filterString;
78
-            $countSql .= ' WHERE '.$this->filterString;
79
-        }
80
-
81
-        if (!empty($orderString)) {
82
-            $sql .= ' ORDER BY '.$orderString;
83
-        }
84
-
85
-        if (stripos($countSql, 'GROUP BY') !== false) {
86
-            throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
87
-        }
88
-
89
-        if ($columnsList !== null) {
90
-            $joinSql = '';
91
-            $parentFks = $this->getParentRelationshipForeignKeys($this->mainTable);
92
-            foreach ($parentFks as $fk) {
93
-                $joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
94
-                    $connection->quoteIdentifier($fk->getForeignTableName()),
95
-                    $connection->quoteIdentifier($fk->getLocalTableName()),
96
-                    $connection->quoteIdentifier($fk->getLocalColumns()[0]),
97
-                    $connection->quoteIdentifier($fk->getForeignTableName()),
98
-                    $connection->quoteIdentifier($fk->getForeignColumns()[0])
99
-                );
100
-            }
101
-
102
-            $childrenFks = $this->getChildrenRelationshipForeignKeys($this->mainTable);
103
-            foreach ($childrenFks as $fk) {
104
-                $joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
105
-                    $connection->quoteIdentifier($fk->getLocalTableName()),
106
-                    $connection->quoteIdentifier($fk->getForeignTableName()),
107
-                    $connection->quoteIdentifier($fk->getForeignColumns()[0]),
108
-                    $connection->quoteIdentifier($fk->getLocalTableName()),
109
-                    $connection->quoteIdentifier($fk->getLocalColumns()[0])
110
-                );
111
-            }
112
-
113
-            $sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$this->mainTable.' '.$joinSql;
114
-            if (!empty($orderString)) {
115
-                $sql .= ' ORDER BY '.$orderString;
116
-            }
117
-        }
118
-
119
-        $this->magicSql = $sql;
120
-        $this->magicSqlCount = $countSql;
121
-        $this->columnDescList = $columnDescList;
122
-    }
123
-
124
-    /**
125
-     * @param string $tableName
126
-     *
127
-     * @return ForeignKeyConstraint[]
128
-     */
129
-    private function getParentRelationshipForeignKeys($tableName)
130
-    {
131
-        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
132
-            return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
133
-        });
134
-    }
135
-
136
-    /**
137
-     * @param string $tableName
138
-     *
139
-     * @return ForeignKeyConstraint[]
140
-     */
141
-    private function getParentRelationshipForeignKeysWithoutCache($tableName)
142
-    {
143
-        $parentFks = [];
144
-        $currentTable = $tableName;
145
-        while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
146
-            $currentTable = $currentFk->getForeignTableName();
147
-            $parentFks[] = $currentFk;
148
-        }
149
-
150
-        return $parentFks;
151
-    }
152
-
153
-    /**
154
-     * @param string $tableName
155
-     *
156
-     * @return ForeignKeyConstraint[]
157
-     */
158
-    private function getChildrenRelationshipForeignKeys(string $tableName) : array
159
-    {
160
-        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
161
-            return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
162
-        });
163
-    }
164
-
165
-    /**
166
-     * @param string $tableName
167
-     *
168
-     * @return ForeignKeyConstraint[]
169
-     */
170
-    private function getChildrenRelationshipForeignKeysWithoutCache(string $tableName) : array
171
-    {
172
-        $children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
173
-
174
-        if (!empty($children)) {
175
-            $fksTables = array_map(function (ForeignKeyConstraint $fk) {
176
-                return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
177
-            }, $children);
178
-
179
-            $fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
180
-
181
-            return $fks;
182
-        } else {
183
-            return [];
184
-        }
185
-    }
186
-
187
-    /**
188
-     * Returns an item from cache or computes it using $closure and puts it in cache.
189
-     *
190
-     * @param string   $key
191
-     * @param callable $closure
192
-     *
193
-     * @return mixed
194
-     */
195
-    protected function fromCache(string $key, callable $closure)
196
-    {
197
-        $item = $this->cache->fetch($key);
198
-        if ($item === false) {
199
-            $item = $closure();
200
-            $this->cache->save($key, $item);
201
-        }
202
-
203
-        return $item;
204
-    }
18
+	private $mainTable;
19
+	private $from;
20
+	private $filterString;
21
+	private $cache;
22
+	private $cachePrefix;
23
+
24
+	public function __construct(string $mainTable, string $from, $filterString, $orderBy, TDBMService $tdbmService, Schema $schema, OrderByAnalyzer $orderByAnalyzer, SchemaAnalyzer $schemaAnalyzer, Cache $cache, string $cachePrefix)
25
+	{
26
+		parent::__construct($tdbmService, $schema, $orderByAnalyzer, $orderBy);
27
+		$this->mainTable = $mainTable;
28
+		$this->from = $from;
29
+		$this->filterString = $filterString;
30
+		$this->schemaAnalyzer = $schemaAnalyzer;
31
+		$this->cache = $cache;
32
+		$this->cachePrefix = $cachePrefix;
33
+	}
34
+
35
+	protected function compute()
36
+	{
37
+		$connection = $this->tdbmService->getConnection();
38
+
39
+		$columnsList = null;
40
+
41
+		$allFetchedTables = $this->tdbmService->_getRelatedTablesByInheritance($this->mainTable);
42
+
43
+		$columnDescList = [];
44
+
45
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
46
+
47
+		foreach ($this->schema->getTable($this->mainTable)->getColumns() as $column) {
48
+			$columnName = $column->getName();
49
+			$columnDescList[] = [
50
+				'as' => $columnName,
51
+				'table' => $this->mainTable,
52
+				'column' => $columnName,
53
+				'type' => $column->getType(),
54
+				'tableGroup' => $tableGroupName,
55
+			];
56
+		}
57
+
58
+		$sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) {
59
+			return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($columnDesc['column']);
60
+		}, $columnDescList)).' FROM '.$this->from;
61
+
62
+		if (count($allFetchedTables) > 1) {
63
+			list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
64
+		} elseif ($this->orderBy) {
65
+			list(, , $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
66
+		}
67
+
68
+		// Let's compute the COUNT.
69
+		$pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
70
+		$pkColumnNames = array_map(function ($pkColumn) {
71
+			return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
72
+		}, $pkColumnNames);
73
+
74
+		$countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$this->from;
75
+
76
+		if (!empty($this->filterString)) {
77
+			$sql .= ' WHERE '.$this->filterString;
78
+			$countSql .= ' WHERE '.$this->filterString;
79
+		}
80
+
81
+		if (!empty($orderString)) {
82
+			$sql .= ' ORDER BY '.$orderString;
83
+		}
84
+
85
+		if (stripos($countSql, 'GROUP BY') !== false) {
86
+			throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
87
+		}
88
+
89
+		if ($columnsList !== null) {
90
+			$joinSql = '';
91
+			$parentFks = $this->getParentRelationshipForeignKeys($this->mainTable);
92
+			foreach ($parentFks as $fk) {
93
+				$joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
94
+					$connection->quoteIdentifier($fk->getForeignTableName()),
95
+					$connection->quoteIdentifier($fk->getLocalTableName()),
96
+					$connection->quoteIdentifier($fk->getLocalColumns()[0]),
97
+					$connection->quoteIdentifier($fk->getForeignTableName()),
98
+					$connection->quoteIdentifier($fk->getForeignColumns()[0])
99
+				);
100
+			}
101
+
102
+			$childrenFks = $this->getChildrenRelationshipForeignKeys($this->mainTable);
103
+			foreach ($childrenFks as $fk) {
104
+				$joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
105
+					$connection->quoteIdentifier($fk->getLocalTableName()),
106
+					$connection->quoteIdentifier($fk->getForeignTableName()),
107
+					$connection->quoteIdentifier($fk->getForeignColumns()[0]),
108
+					$connection->quoteIdentifier($fk->getLocalTableName()),
109
+					$connection->quoteIdentifier($fk->getLocalColumns()[0])
110
+				);
111
+			}
112
+
113
+			$sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$this->mainTable.' '.$joinSql;
114
+			if (!empty($orderString)) {
115
+				$sql .= ' ORDER BY '.$orderString;
116
+			}
117
+		}
118
+
119
+		$this->magicSql = $sql;
120
+		$this->magicSqlCount = $countSql;
121
+		$this->columnDescList = $columnDescList;
122
+	}
123
+
124
+	/**
125
+	 * @param string $tableName
126
+	 *
127
+	 * @return ForeignKeyConstraint[]
128
+	 */
129
+	private function getParentRelationshipForeignKeys($tableName)
130
+	{
131
+		return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
132
+			return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
133
+		});
134
+	}
135
+
136
+	/**
137
+	 * @param string $tableName
138
+	 *
139
+	 * @return ForeignKeyConstraint[]
140
+	 */
141
+	private function getParentRelationshipForeignKeysWithoutCache($tableName)
142
+	{
143
+		$parentFks = [];
144
+		$currentTable = $tableName;
145
+		while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
146
+			$currentTable = $currentFk->getForeignTableName();
147
+			$parentFks[] = $currentFk;
148
+		}
149
+
150
+		return $parentFks;
151
+	}
152
+
153
+	/**
154
+	 * @param string $tableName
155
+	 *
156
+	 * @return ForeignKeyConstraint[]
157
+	 */
158
+	private function getChildrenRelationshipForeignKeys(string $tableName) : array
159
+	{
160
+		return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
161
+			return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
162
+		});
163
+	}
164
+
165
+	/**
166
+	 * @param string $tableName
167
+	 *
168
+	 * @return ForeignKeyConstraint[]
169
+	 */
170
+	private function getChildrenRelationshipForeignKeysWithoutCache(string $tableName) : array
171
+	{
172
+		$children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
173
+
174
+		if (!empty($children)) {
175
+			$fksTables = array_map(function (ForeignKeyConstraint $fk) {
176
+				return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
177
+			}, $children);
178
+
179
+			$fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
180
+
181
+			return $fks;
182
+		} else {
183
+			return [];
184
+		}
185
+	}
186
+
187
+	/**
188
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
189
+	 *
190
+	 * @param string   $key
191
+	 * @param callable $closure
192
+	 *
193
+	 * @return mixed
194
+	 */
195
+	protected function fromCache(string $key, callable $closure)
196
+	{
197
+		$item = $this->cache->fetch($key);
198
+		if ($item === false) {
199
+			$item = $closure();
200
+			$this->cache->save($key, $item);
201
+		}
202
+
203
+		return $item;
204
+	}
205 205
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -55,19 +55,19 @@  discard block
 block discarded – undo
55 55
             ];
56 56
         }
57 57
 
58
-        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) {
58
+        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function($columnDesc) {
59 59
             return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($columnDesc['column']);
60 60
         }, $columnDescList)).' FROM '.$this->from;
61 61
 
62
-        if (count($allFetchedTables) > 1) {
62
+        if (count($allFetchedTables)>1) {
63 63
             list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
64 64
         } elseif ($this->orderBy) {
65
-            list(, , $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
65
+            list(,, $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
66 66
         }
67 67
 
68 68
         // Let's compute the COUNT.
69 69
         $pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
70
-        $pkColumnNames = array_map(function ($pkColumn) {
70
+        $pkColumnNames = array_map(function($pkColumn) {
71 71
             return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
72 72
         }, $pkColumnNames);
73 73
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
      */
129 129
     private function getParentRelationshipForeignKeys($tableName)
130 130
     {
131
-        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
131
+        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function() use ($tableName) {
132 132
             return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
133 133
         });
134 134
     }
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
      */
158 158
     private function getChildrenRelationshipForeignKeys(string $tableName) : array
159 159
     {
160
-        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
160
+        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function() use ($tableName) {
161 161
             return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
162 162
         });
163 163
     }
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
         $children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
173 173
 
174 174
         if (!empty($children)) {
175
-            $fksTables = array_map(function (ForeignKeyConstraint $fk) {
175
+            $fksTables = array_map(function(ForeignKeyConstraint $fk) {
176 176
                 return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
177 177
             }, $children);
178 178
 
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/BeanDescriptor.php 2 patches
Indentation   +543 added lines, -543 removed lines patch added patch discarded remove patch
@@ -16,228 +16,228 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class BeanDescriptor
18 18
 {
19
-    /**
20
-     * @var Table
21
-     */
22
-    private $table;
23
-
24
-    /**
25
-     * @var SchemaAnalyzer
26
-     */
27
-    private $schemaAnalyzer;
28
-
29
-    /**
30
-     * @var Schema
31
-     */
32
-    private $schema;
33
-
34
-    /**
35
-     * @var AbstractBeanPropertyDescriptor[]
36
-     */
37
-    private $beanPropertyDescriptors = [];
38
-
39
-    /**
40
-     * @var TDBMSchemaAnalyzer
41
-     */
42
-    private $tdbmSchemaAnalyzer;
43
-
44
-    public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
-    {
46
-        $this->table = $table;
47
-        $this->schemaAnalyzer = $schemaAnalyzer;
48
-        $this->schema = $schema;
49
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
-        $this->initBeanPropertyDescriptors();
51
-    }
52
-
53
-    private function initBeanPropertyDescriptors()
54
-    {
55
-        $this->beanPropertyDescriptors = $this->getProperties($this->table);
56
-    }
57
-
58
-    /**
59
-     * Returns the foreign-key the column is part of, if any. null otherwise.
60
-     *
61
-     * @param Table  $table
62
-     * @param Column $column
63
-     *
64
-     * @return ForeignKeyConstraint|null
65
-     */
66
-    private function isPartOfForeignKey(Table $table, Column $column)
67
-    {
68
-        $localColumnName = $column->getName();
69
-        foreach ($table->getForeignKeys() as $foreignKey) {
70
-            foreach ($foreignKey->getColumns() as $columnName) {
71
-                if ($columnName === $localColumnName) {
72
-                    return $foreignKey;
73
-                }
74
-            }
75
-        }
76
-
77
-        return;
78
-    }
79
-
80
-    /**
81
-     * @return AbstractBeanPropertyDescriptor[]
82
-     */
83
-    public function getBeanPropertyDescriptors()
84
-    {
85
-        return $this->beanPropertyDescriptors;
86
-    }
87
-
88
-    /**
89
-     * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
-     *
91
-     * @return AbstractBeanPropertyDescriptor[]
92
-     */
93
-    public function getConstructorProperties()
94
-    {
95
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
-            return $property->isCompulsory();
97
-        });
98
-
99
-        return $constructorProperties;
100
-    }
101
-
102
-    /**
103
-     * Returns the list of columns that have default values for a given table.
104
-     *
105
-     * @return AbstractBeanPropertyDescriptor[]
106
-     */
107
-    public function getPropertiesWithDefault()
108
-    {
109
-        $properties = $this->getPropertiesForTable($this->table);
110
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
111
-            return $property->hasDefault();
112
-        });
113
-
114
-        return $defaultProperties;
115
-    }
116
-
117
-    /**
118
-     * Returns the list of properties exposed as getters and setters in this class.
119
-     *
120
-     * @return AbstractBeanPropertyDescriptor[]
121
-     */
122
-    public function getExposedProperties()
123
-    {
124
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
125
-            return $property->getTable()->getName() == $this->table->getName();
126
-        });
127
-
128
-        return $exposedProperties;
129
-    }
130
-
131
-    /**
132
-     * Returns the list of properties for this table (including parent tables).
133
-     *
134
-     * @param Table $table
135
-     *
136
-     * @return AbstractBeanPropertyDescriptor[]
137
-     */
138
-    private function getProperties(Table $table)
139
-    {
140
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
141
-        if ($parentRelationship) {
142
-            $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
143
-            $properties = $this->getProperties($parentTable);
144
-            // we merge properties by overriding property names.
145
-            $localProperties = $this->getPropertiesForTable($table);
146
-            foreach ($localProperties as $name => $property) {
147
-                // We do not override properties if this is a primary key!
148
-                if ($property->isPrimaryKey()) {
149
-                    continue;
150
-                }
151
-                $properties[$name] = $property;
152
-            }
153
-        } else {
154
-            $properties = $this->getPropertiesForTable($table);
155
-        }
156
-
157
-        return $properties;
158
-    }
159
-
160
-    /**
161
-     * Returns the list of properties for this table (ignoring parent tables).
162
-     *
163
-     * @param Table $table
164
-     *
165
-     * @return AbstractBeanPropertyDescriptor[]
166
-     */
167
-    private function getPropertiesForTable(Table $table)
168
-    {
169
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
170
-        if ($parentRelationship) {
171
-            $ignoreColumns = $parentRelationship->getLocalColumns();
172
-        } else {
173
-            $ignoreColumns = [];
174
-        }
175
-
176
-        $beanPropertyDescriptors = [];
177
-
178
-        foreach ($table->getColumns() as $column) {
179
-            if (array_search($column->getName(), $ignoreColumns) !== false) {
180
-                continue;
181
-            }
182
-
183
-            $fk = $this->isPartOfForeignKey($table, $column);
184
-            if ($fk !== null) {
185
-                // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
186
-                foreach ($beanPropertyDescriptors as $beanDescriptor) {
187
-                    if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
188
-                        continue 2;
189
-                    }
190
-                }
191
-                // Check that this property is not an inheritance relationship
192
-                $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
193
-                if ($parentRelationship === $fk) {
194
-                    continue;
195
-                }
196
-
197
-                $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
198
-            } else {
199
-                $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
200
-            }
201
-        }
202
-
203
-        // Now, let's get the name of all properties and let's check there is no duplicate.
204
-        /** @var $names AbstractBeanPropertyDescriptor[] */
205
-        $names = [];
206
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
207
-            $name = $beanDescriptor->getUpperCamelCaseName();
208
-            if (isset($names[$name])) {
209
-                $names[$name]->useAlternativeName();
210
-                $beanDescriptor->useAlternativeName();
211
-            } else {
212
-                $names[$name] = $beanDescriptor;
213
-            }
214
-        }
215
-
216
-        // Final check (throw exceptions if problem arises)
217
-        $names = [];
218
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
219
-            $name = $beanDescriptor->getUpperCamelCaseName();
220
-            if (isset($names[$name])) {
221
-                throw new TDBMException('Unsolvable name conflict while generating method name');
222
-            } else {
223
-                $names[$name] = $beanDescriptor;
224
-            }
225
-        }
226
-
227
-        // Last step, let's rebuild the list with a map:
228
-        $beanPropertyDescriptorsMap = [];
229
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
230
-            $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
231
-        }
232
-
233
-        return $beanPropertyDescriptorsMap;
234
-    }
235
-
236
-    public function generateBeanConstructor()
237
-    {
238
-        $constructorProperties = $this->getConstructorProperties();
239
-
240
-        $constructorCode = '    /**
19
+	/**
20
+	 * @var Table
21
+	 */
22
+	private $table;
23
+
24
+	/**
25
+	 * @var SchemaAnalyzer
26
+	 */
27
+	private $schemaAnalyzer;
28
+
29
+	/**
30
+	 * @var Schema
31
+	 */
32
+	private $schema;
33
+
34
+	/**
35
+	 * @var AbstractBeanPropertyDescriptor[]
36
+	 */
37
+	private $beanPropertyDescriptors = [];
38
+
39
+	/**
40
+	 * @var TDBMSchemaAnalyzer
41
+	 */
42
+	private $tdbmSchemaAnalyzer;
43
+
44
+	public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
+	{
46
+		$this->table = $table;
47
+		$this->schemaAnalyzer = $schemaAnalyzer;
48
+		$this->schema = $schema;
49
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
+		$this->initBeanPropertyDescriptors();
51
+	}
52
+
53
+	private function initBeanPropertyDescriptors()
54
+	{
55
+		$this->beanPropertyDescriptors = $this->getProperties($this->table);
56
+	}
57
+
58
+	/**
59
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
60
+	 *
61
+	 * @param Table  $table
62
+	 * @param Column $column
63
+	 *
64
+	 * @return ForeignKeyConstraint|null
65
+	 */
66
+	private function isPartOfForeignKey(Table $table, Column $column)
67
+	{
68
+		$localColumnName = $column->getName();
69
+		foreach ($table->getForeignKeys() as $foreignKey) {
70
+			foreach ($foreignKey->getColumns() as $columnName) {
71
+				if ($columnName === $localColumnName) {
72
+					return $foreignKey;
73
+				}
74
+			}
75
+		}
76
+
77
+		return;
78
+	}
79
+
80
+	/**
81
+	 * @return AbstractBeanPropertyDescriptor[]
82
+	 */
83
+	public function getBeanPropertyDescriptors()
84
+	{
85
+		return $this->beanPropertyDescriptors;
86
+	}
87
+
88
+	/**
89
+	 * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
+	 *
91
+	 * @return AbstractBeanPropertyDescriptor[]
92
+	 */
93
+	public function getConstructorProperties()
94
+	{
95
+		$constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
+			return $property->isCompulsory();
97
+		});
98
+
99
+		return $constructorProperties;
100
+	}
101
+
102
+	/**
103
+	 * Returns the list of columns that have default values for a given table.
104
+	 *
105
+	 * @return AbstractBeanPropertyDescriptor[]
106
+	 */
107
+	public function getPropertiesWithDefault()
108
+	{
109
+		$properties = $this->getPropertiesForTable($this->table);
110
+		$defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
111
+			return $property->hasDefault();
112
+		});
113
+
114
+		return $defaultProperties;
115
+	}
116
+
117
+	/**
118
+	 * Returns the list of properties exposed as getters and setters in this class.
119
+	 *
120
+	 * @return AbstractBeanPropertyDescriptor[]
121
+	 */
122
+	public function getExposedProperties()
123
+	{
124
+		$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
125
+			return $property->getTable()->getName() == $this->table->getName();
126
+		});
127
+
128
+		return $exposedProperties;
129
+	}
130
+
131
+	/**
132
+	 * Returns the list of properties for this table (including parent tables).
133
+	 *
134
+	 * @param Table $table
135
+	 *
136
+	 * @return AbstractBeanPropertyDescriptor[]
137
+	 */
138
+	private function getProperties(Table $table)
139
+	{
140
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
141
+		if ($parentRelationship) {
142
+			$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
143
+			$properties = $this->getProperties($parentTable);
144
+			// we merge properties by overriding property names.
145
+			$localProperties = $this->getPropertiesForTable($table);
146
+			foreach ($localProperties as $name => $property) {
147
+				// We do not override properties if this is a primary key!
148
+				if ($property->isPrimaryKey()) {
149
+					continue;
150
+				}
151
+				$properties[$name] = $property;
152
+			}
153
+		} else {
154
+			$properties = $this->getPropertiesForTable($table);
155
+		}
156
+
157
+		return $properties;
158
+	}
159
+
160
+	/**
161
+	 * Returns the list of properties for this table (ignoring parent tables).
162
+	 *
163
+	 * @param Table $table
164
+	 *
165
+	 * @return AbstractBeanPropertyDescriptor[]
166
+	 */
167
+	private function getPropertiesForTable(Table $table)
168
+	{
169
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
170
+		if ($parentRelationship) {
171
+			$ignoreColumns = $parentRelationship->getLocalColumns();
172
+		} else {
173
+			$ignoreColumns = [];
174
+		}
175
+
176
+		$beanPropertyDescriptors = [];
177
+
178
+		foreach ($table->getColumns() as $column) {
179
+			if (array_search($column->getName(), $ignoreColumns) !== false) {
180
+				continue;
181
+			}
182
+
183
+			$fk = $this->isPartOfForeignKey($table, $column);
184
+			if ($fk !== null) {
185
+				// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
186
+				foreach ($beanPropertyDescriptors as $beanDescriptor) {
187
+					if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
188
+						continue 2;
189
+					}
190
+				}
191
+				// Check that this property is not an inheritance relationship
192
+				$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
193
+				if ($parentRelationship === $fk) {
194
+					continue;
195
+				}
196
+
197
+				$beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
198
+			} else {
199
+				$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
200
+			}
201
+		}
202
+
203
+		// Now, let's get the name of all properties and let's check there is no duplicate.
204
+		/** @var $names AbstractBeanPropertyDescriptor[] */
205
+		$names = [];
206
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
207
+			$name = $beanDescriptor->getUpperCamelCaseName();
208
+			if (isset($names[$name])) {
209
+				$names[$name]->useAlternativeName();
210
+				$beanDescriptor->useAlternativeName();
211
+			} else {
212
+				$names[$name] = $beanDescriptor;
213
+			}
214
+		}
215
+
216
+		// Final check (throw exceptions if problem arises)
217
+		$names = [];
218
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
219
+			$name = $beanDescriptor->getUpperCamelCaseName();
220
+			if (isset($names[$name])) {
221
+				throw new TDBMException('Unsolvable name conflict while generating method name');
222
+			} else {
223
+				$names[$name] = $beanDescriptor;
224
+			}
225
+		}
226
+
227
+		// Last step, let's rebuild the list with a map:
228
+		$beanPropertyDescriptorsMap = [];
229
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
230
+			$beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
231
+		}
232
+
233
+		return $beanPropertyDescriptorsMap;
234
+	}
235
+
236
+	public function generateBeanConstructor()
237
+	{
238
+		$constructorProperties = $this->getConstructorProperties();
239
+
240
+		$constructorCode = '    /**
241 241
      * The constructor takes all compulsory arguments.
242 242
      *
243 243
 %s
@@ -248,110 +248,110 @@  discard block
 block discarded – undo
248 248
     }
249 249
     ';
250 250
 
251
-        $paramAnnotations = [];
252
-        $arguments = [];
253
-        $assigns = [];
254
-        $parentConstructorArguments = [];
255
-
256
-        foreach ($constructorProperties as $property) {
257
-            $className = $property->getClassName();
258
-            if ($className) {
259
-                $arguments[] = $className.' '.$property->getVariableName();
260
-            } else {
261
-                $arguments[] = $property->getVariableName();
262
-            }
263
-            $paramAnnotations[] = $property->getParamAnnotation();
264
-            if ($property->getTable()->getName() === $this->table->getName()) {
265
-                $assigns[] = $property->getConstructorAssignCode();
266
-            } else {
267
-                $parentConstructorArguments[] = $property->getVariableName();
268
-            }
269
-        }
270
-
271
-        $parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
272
-
273
-        foreach ($this->getPropertiesWithDefault() as $property) {
274
-            $assigns[] = $property->assignToDefaultCode();
275
-        }
276
-
277
-        return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode("\n", $assigns));
278
-    }
279
-
280
-    public function getDirectForeignKeysDescriptors()
281
-    {
282
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
283
-
284
-        $descriptors = [];
285
-
286
-        foreach ($fks as $fk) {
287
-            $descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table);
288
-        }
289
-
290
-        return $descriptors;
291
-    }
292
-
293
-    private function getPivotTableDescriptors()
294
-    {
295
-        $descs = [];
296
-        foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
297
-            // There are exactly 2 FKs since this is a pivot table.
298
-            $fks = array_values($table->getForeignKeys());
299
-
300
-            if ($fks[0]->getForeignTableName() === $this->table->getName()) {
301
-                list($localFk, $remoteFk) = $fks;
302
-            } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
303
-                list($remoteFk, $localFk) = $fks;
304
-            } else {
305
-                continue;
306
-            }
307
-
308
-            $descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk);
309
-        }
310
-
311
-        return $descs;
312
-    }
313
-
314
-    /**
315
-     * Returns the list of method descriptors (and applies the alternative name if needed).
316
-     *
317
-     * @return MethodDescriptorInterface[]
318
-     */
319
-    private function getMethodDescriptors()
320
-    {
321
-        $directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
322
-        $pivotTableDescriptors = $this->getPivotTableDescriptors();
323
-
324
-        $descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
325
-
326
-        // Descriptors by method names
327
-        $descriptorsByMethodName = [];
328
-
329
-        foreach ($descriptors as $descriptor) {
330
-            $descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
331
-        }
332
-
333
-        foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
334
-            if (count($descriptorsForMethodName) > 1) {
335
-                foreach ($descriptorsForMethodName as $descriptor) {
336
-                    $descriptor->useAlternativeName();
337
-                }
338
-            }
339
-        }
340
-
341
-        return $descriptors;
342
-    }
343
-
344
-    public function generateJsonSerialize()
345
-    {
346
-        $tableName = $this->table->getName();
347
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
348
-        if ($parentFk !== null) {
349
-            $initializer = '$array = parent::jsonSerialize($stopRecursion);';
350
-        } else {
351
-            $initializer = '$array = [];';
352
-        }
353
-
354
-        $str = '
251
+		$paramAnnotations = [];
252
+		$arguments = [];
253
+		$assigns = [];
254
+		$parentConstructorArguments = [];
255
+
256
+		foreach ($constructorProperties as $property) {
257
+			$className = $property->getClassName();
258
+			if ($className) {
259
+				$arguments[] = $className.' '.$property->getVariableName();
260
+			} else {
261
+				$arguments[] = $property->getVariableName();
262
+			}
263
+			$paramAnnotations[] = $property->getParamAnnotation();
264
+			if ($property->getTable()->getName() === $this->table->getName()) {
265
+				$assigns[] = $property->getConstructorAssignCode();
266
+			} else {
267
+				$parentConstructorArguments[] = $property->getVariableName();
268
+			}
269
+		}
270
+
271
+		$parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
272
+
273
+		foreach ($this->getPropertiesWithDefault() as $property) {
274
+			$assigns[] = $property->assignToDefaultCode();
275
+		}
276
+
277
+		return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode("\n", $assigns));
278
+	}
279
+
280
+	public function getDirectForeignKeysDescriptors()
281
+	{
282
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
283
+
284
+		$descriptors = [];
285
+
286
+		foreach ($fks as $fk) {
287
+			$descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table);
288
+		}
289
+
290
+		return $descriptors;
291
+	}
292
+
293
+	private function getPivotTableDescriptors()
294
+	{
295
+		$descs = [];
296
+		foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
297
+			// There are exactly 2 FKs since this is a pivot table.
298
+			$fks = array_values($table->getForeignKeys());
299
+
300
+			if ($fks[0]->getForeignTableName() === $this->table->getName()) {
301
+				list($localFk, $remoteFk) = $fks;
302
+			} elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
303
+				list($remoteFk, $localFk) = $fks;
304
+			} else {
305
+				continue;
306
+			}
307
+
308
+			$descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk);
309
+		}
310
+
311
+		return $descs;
312
+	}
313
+
314
+	/**
315
+	 * Returns the list of method descriptors (and applies the alternative name if needed).
316
+	 *
317
+	 * @return MethodDescriptorInterface[]
318
+	 */
319
+	private function getMethodDescriptors()
320
+	{
321
+		$directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
322
+		$pivotTableDescriptors = $this->getPivotTableDescriptors();
323
+
324
+		$descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
325
+
326
+		// Descriptors by method names
327
+		$descriptorsByMethodName = [];
328
+
329
+		foreach ($descriptors as $descriptor) {
330
+			$descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
331
+		}
332
+
333
+		foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
334
+			if (count($descriptorsForMethodName) > 1) {
335
+				foreach ($descriptorsForMethodName as $descriptor) {
336
+					$descriptor->useAlternativeName();
337
+				}
338
+			}
339
+		}
340
+
341
+		return $descriptors;
342
+	}
343
+
344
+	public function generateJsonSerialize()
345
+	{
346
+		$tableName = $this->table->getName();
347
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
348
+		if ($parentFk !== null) {
349
+			$initializer = '$array = parent::jsonSerialize($stopRecursion);';
350
+		} else {
351
+			$initializer = '$array = [];';
352
+		}
353
+
354
+		$str = '
355 355
     /**
356 356
      * Serializes the object for JSON encoding.
357 357
      *
@@ -367,76 +367,76 @@  discard block
 block discarded – undo
367 367
     }
368 368
 ';
369 369
 
370
-        $propertiesCode = '';
371
-        foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
372
-            $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
373
-        }
374
-
375
-        // Many2many relationships
376
-        $methodsCode = '';
377
-        foreach ($this->getMethodDescriptors() as $methodDescriptor) {
378
-            $methodsCode .= $methodDescriptor->getJsonSerializeCode();
379
-        }
380
-
381
-        return sprintf($str, $initializer, $propertiesCode, $methodsCode);
382
-    }
383
-
384
-    /**
385
-     * Returns as an array the class we need to extend from and the list of use statements.
386
-     *
387
-     * @return array
388
-     */
389
-    private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
390
-    {
391
-        $classes = [];
392
-        if ($parentFk !== null) {
393
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
394
-            $classes[] = $extends;
395
-        }
396
-
397
-        foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
398
-            $className = $beanPropertyDescriptor->getClassName();
399
-            if (null !== $className) {
400
-                $classes[] = $beanPropertyDescriptor->getClassName();
401
-            }
402
-        }
403
-
404
-        foreach ($this->getMethodDescriptors() as $descriptor) {
405
-            $classes = array_merge($classes, $descriptor->getUsedClasses());
406
-        }
407
-
408
-        $classes = array_unique($classes);
409
-
410
-        return $classes;
411
-    }
412
-
413
-    /**
414
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
415
-     *
416
-     * @param string $beannamespace The namespace of the bean
417
-     */
418
-    public function generatePhpCode($beannamespace)
419
-    {
420
-        $tableName = $this->table->getName();
421
-        $baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
422
-        $className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
423
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
424
-
425
-        $classes = $this->generateExtendsAndUseStatements($parentFk);
426
-
427
-        $uses = array_map(function ($className) use ($beannamespace) {
428
-            return 'use '.$beannamespace.'\\'.$className.";\n";
429
-        }, $classes);
430
-        $use = implode('', $uses);
431
-
432
-        if ($parentFk !== null) {
433
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
434
-        } else {
435
-            $extends = 'AbstractTDBMObject';
436
-            $use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
437
-        }
438
-
439
-        $str = "<?php
370
+		$propertiesCode = '';
371
+		foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
372
+			$propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
373
+		}
374
+
375
+		// Many2many relationships
376
+		$methodsCode = '';
377
+		foreach ($this->getMethodDescriptors() as $methodDescriptor) {
378
+			$methodsCode .= $methodDescriptor->getJsonSerializeCode();
379
+		}
380
+
381
+		return sprintf($str, $initializer, $propertiesCode, $methodsCode);
382
+	}
383
+
384
+	/**
385
+	 * Returns as an array the class we need to extend from and the list of use statements.
386
+	 *
387
+	 * @return array
388
+	 */
389
+	private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
390
+	{
391
+		$classes = [];
392
+		if ($parentFk !== null) {
393
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
394
+			$classes[] = $extends;
395
+		}
396
+
397
+		foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
398
+			$className = $beanPropertyDescriptor->getClassName();
399
+			if (null !== $className) {
400
+				$classes[] = $beanPropertyDescriptor->getClassName();
401
+			}
402
+		}
403
+
404
+		foreach ($this->getMethodDescriptors() as $descriptor) {
405
+			$classes = array_merge($classes, $descriptor->getUsedClasses());
406
+		}
407
+
408
+		$classes = array_unique($classes);
409
+
410
+		return $classes;
411
+	}
412
+
413
+	/**
414
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
415
+	 *
416
+	 * @param string $beannamespace The namespace of the bean
417
+	 */
418
+	public function generatePhpCode($beannamespace)
419
+	{
420
+		$tableName = $this->table->getName();
421
+		$baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
422
+		$className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
423
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
424
+
425
+		$classes = $this->generateExtendsAndUseStatements($parentFk);
426
+
427
+		$uses = array_map(function ($className) use ($beannamespace) {
428
+			return 'use '.$beannamespace.'\\'.$className.";\n";
429
+		}, $classes);
430
+		$use = implode('', $uses);
431
+
432
+		if ($parentFk !== null) {
433
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
434
+		} else {
435
+			$extends = 'AbstractTDBMObject';
436
+			$use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
437
+		}
438
+
439
+		$str = "<?php
440 440
 namespace {$beannamespace}\\Generated;
441 441
 
442 442
 use Mouf\\Database\\TDBM\\ResultIterator;
@@ -456,129 +456,129 @@  discard block
 block discarded – undo
456 456
 {
457 457
 ";
458 458
 
459
-        $str .= $this->generateBeanConstructor();
459
+		$str .= $this->generateBeanConstructor();
460 460
 
461
-        foreach ($this->getExposedProperties() as $property) {
462
-            $str .= $property->getGetterSetterCode();
463
-        }
461
+		foreach ($this->getExposedProperties() as $property) {
462
+			$str .= $property->getGetterSetterCode();
463
+		}
464 464
 
465
-        foreach ($this->getMethodDescriptors() as $methodDescriptor) {
466
-            $str .= $methodDescriptor->getCode();
467
-        }
468
-        $str .= $this->generateJsonSerialize();
465
+		foreach ($this->getMethodDescriptors() as $methodDescriptor) {
466
+			$str .= $methodDescriptor->getCode();
467
+		}
468
+		$str .= $this->generateJsonSerialize();
469 469
 
470
-        $str .= $this->generateGetUsedTablesCode();
470
+		$str .= $this->generateGetUsedTablesCode();
471 471
 
472
-        $str .= $this->generateOnDeleteCode();
472
+		$str .= $this->generateOnDeleteCode();
473 473
 
474
-        $str .= '}
474
+		$str .= '}
475 475
 ';
476 476
 
477
-        return $str;
478
-    }
479
-
480
-    /**
481
-     * @param string $beanNamespace
482
-     * @param string $beanClassName
483
-     *
484
-     * @return array first element: list of used beans, second item: PHP code as a string
485
-     */
486
-    public function generateFindByDaoCode($beanNamespace, $beanClassName)
487
-    {
488
-        $code = '';
489
-        $usedBeans = [];
490
-        foreach ($this->table->getIndexes() as $index) {
491
-            if (!$index->isPrimary()) {
492
-                list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
493
-                $code .= $codeForIndex;
494
-                $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
495
-            }
496
-        }
497
-
498
-        return [$usedBeans, $code];
499
-    }
500
-
501
-    /**
502
-     * @param Index  $index
503
-     * @param string $beanNamespace
504
-     * @param string $beanClassName
505
-     *
506
-     * @return array first element: list of used beans, second item: PHP code as a string
507
-     */
508
-    private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
509
-    {
510
-        $columns = $index->getColumns();
511
-        $usedBeans = [];
512
-
513
-        /*
477
+		return $str;
478
+	}
479
+
480
+	/**
481
+	 * @param string $beanNamespace
482
+	 * @param string $beanClassName
483
+	 *
484
+	 * @return array first element: list of used beans, second item: PHP code as a string
485
+	 */
486
+	public function generateFindByDaoCode($beanNamespace, $beanClassName)
487
+	{
488
+		$code = '';
489
+		$usedBeans = [];
490
+		foreach ($this->table->getIndexes() as $index) {
491
+			if (!$index->isPrimary()) {
492
+				list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
493
+				$code .= $codeForIndex;
494
+				$usedBeans = array_merge($usedBeans, $usedBeansForIndex);
495
+			}
496
+		}
497
+
498
+		return [$usedBeans, $code];
499
+	}
500
+
501
+	/**
502
+	 * @param Index  $index
503
+	 * @param string $beanNamespace
504
+	 * @param string $beanClassName
505
+	 *
506
+	 * @return array first element: list of used beans, second item: PHP code as a string
507
+	 */
508
+	private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
509
+	{
510
+		$columns = $index->getColumns();
511
+		$usedBeans = [];
512
+
513
+		/*
514 514
          * The list of elements building this index (expressed as columns or foreign keys)
515 515
          * @var AbstractBeanPropertyDescriptor[]
516 516
          */
517
-        $elements = [];
518
-
519
-        foreach ($columns as $column) {
520
-            $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
521
-            if ($fk !== null) {
522
-                if (!in_array($fk, $elements)) {
523
-                    $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
524
-                }
525
-            } else {
526
-                $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
527
-            }
528
-        }
529
-
530
-        // If the index is actually only a foreign key, let's bypass it entirely.
531
-        if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
532
-            return [[], ''];
533
-        }
534
-
535
-        $methodNameComponent = [];
536
-        $functionParameters = [];
537
-        $first = true;
538
-        foreach ($elements as $element) {
539
-            $methodNameComponent[] = $element->getUpperCamelCaseName();
540
-            $functionParameter = $element->getClassName();
541
-            if ($functionParameter) {
542
-                $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
543
-                $functionParameter .= ' ';
544
-            }
545
-            $functionParameter .= $element->getVariableName();
546
-            if ($first) {
547
-                $first = false;
548
-            } else {
549
-                $functionParameter .= ' = null';
550
-            }
551
-            $functionParameters[] = $functionParameter;
552
-        }
553
-        if ($index->isUnique()) {
554
-            $methodName = 'findOneBy'.implode('And', $methodNameComponent);
555
-            $calledMethod = 'findOne';
556
-            $returnType = "{$beanClassName}";
557
-        } else {
558
-            $methodName = 'findBy'.implode('And', $methodNameComponent);
559
-            $returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
560
-            $calledMethod = 'find';
561
-        }
562
-        $functionParametersString = implode(', ', $functionParameters);
563
-
564
-        $count = 0;
565
-
566
-        $params = [];
567
-        $filterArrayCode = '';
568
-        $commentArguments = [];
569
-        foreach ($elements as $element) {
570
-            $params[] = $element->getParamAnnotation();
571
-            if ($element instanceof ScalarBeanPropertyDescriptor) {
572
-                $filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
573
-            } else {
574
-                ++$count;
575
-                $filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
576
-            }
577
-            $commentArguments[] = substr($element->getVariableName(), 1);
578
-        }
579
-        $paramsString = implode("\n", $params);
580
-
581
-        $code = "
517
+		$elements = [];
518
+
519
+		foreach ($columns as $column) {
520
+			$fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
521
+			if ($fk !== null) {
522
+				if (!in_array($fk, $elements)) {
523
+					$elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
524
+				}
525
+			} else {
526
+				$elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
527
+			}
528
+		}
529
+
530
+		// If the index is actually only a foreign key, let's bypass it entirely.
531
+		if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
532
+			return [[], ''];
533
+		}
534
+
535
+		$methodNameComponent = [];
536
+		$functionParameters = [];
537
+		$first = true;
538
+		foreach ($elements as $element) {
539
+			$methodNameComponent[] = $element->getUpperCamelCaseName();
540
+			$functionParameter = $element->getClassName();
541
+			if ($functionParameter) {
542
+				$usedBeans[] = $beanNamespace.'\\'.$functionParameter;
543
+				$functionParameter .= ' ';
544
+			}
545
+			$functionParameter .= $element->getVariableName();
546
+			if ($first) {
547
+				$first = false;
548
+			} else {
549
+				$functionParameter .= ' = null';
550
+			}
551
+			$functionParameters[] = $functionParameter;
552
+		}
553
+		if ($index->isUnique()) {
554
+			$methodName = 'findOneBy'.implode('And', $methodNameComponent);
555
+			$calledMethod = 'findOne';
556
+			$returnType = "{$beanClassName}";
557
+		} else {
558
+			$methodName = 'findBy'.implode('And', $methodNameComponent);
559
+			$returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
560
+			$calledMethod = 'find';
561
+		}
562
+		$functionParametersString = implode(', ', $functionParameters);
563
+
564
+		$count = 0;
565
+
566
+		$params = [];
567
+		$filterArrayCode = '';
568
+		$commentArguments = [];
569
+		foreach ($elements as $element) {
570
+			$params[] = $element->getParamAnnotation();
571
+			if ($element instanceof ScalarBeanPropertyDescriptor) {
572
+				$filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
573
+			} else {
574
+				++$count;
575
+				$filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
576
+			}
577
+			$commentArguments[] = substr($element->getVariableName(), 1);
578
+		}
579
+		$paramsString = implode("\n", $params);
580
+
581
+		$code = "
582 582
     /**
583 583
      * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
584 584
      *
@@ -596,27 +596,27 @@  discard block
 block discarded – undo
596 596
     }
597 597
 ";
598 598
 
599
-        return [$usedBeans, $code];
600
-    }
601
-
602
-    /**
603
-     * Generates the code for the getUsedTable protected method.
604
-     *
605
-     * @return string
606
-     */
607
-    private function generateGetUsedTablesCode()
608
-    {
609
-        $hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
610
-        if ($hasParentRelationship) {
611
-            $code = sprintf('        $tables = parent::getUsedTables();
599
+		return [$usedBeans, $code];
600
+	}
601
+
602
+	/**
603
+	 * Generates the code for the getUsedTable protected method.
604
+	 *
605
+	 * @return string
606
+	 */
607
+	private function generateGetUsedTablesCode()
608
+	{
609
+		$hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
610
+		if ($hasParentRelationship) {
611
+			$code = sprintf('        $tables = parent::getUsedTables();
612 612
         $tables[] = %s;
613 613
         
614 614
         return $tables;', var_export($this->table->getName(), true));
615
-        } else {
616
-            $code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
617
-        }
615
+		} else {
616
+			$code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
617
+		}
618 618
 
619
-        return sprintf('
619
+		return sprintf('
620 620
     /**
621 621
      * Returns an array of used tables by this bean (from parent to child relationship).
622 622
      *
@@ -627,20 +627,20 @@  discard block
 block discarded – undo
627 627
 %s    
628 628
     }
629 629
 ', $code);
630
-    }
631
-
632
-    private function generateOnDeleteCode()
633
-    {
634
-        $code = '';
635
-        $relationships = $this->getPropertiesForTable($this->table);
636
-        foreach ($relationships as $relationship) {
637
-            if ($relationship instanceof ObjectBeanPropertyDescriptor) {
638
-                $code .= sprintf('        $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
639
-            }
640
-        }
641
-
642
-        if ($code) {
643
-            return sprintf('
630
+	}
631
+
632
+	private function generateOnDeleteCode()
633
+	{
634
+		$code = '';
635
+		$relationships = $this->getPropertiesForTable($this->table);
636
+		foreach ($relationships as $relationship) {
637
+			if ($relationship instanceof ObjectBeanPropertyDescriptor) {
638
+				$code .= sprintf('        $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
639
+			}
640
+		}
641
+
642
+		if ($code) {
643
+			return sprintf('
644 644
     /**
645 645
      * Method called when the bean is removed from database.
646 646
      *
@@ -651,8 +651,8 @@  discard block
 block discarded – undo
651 651
 %s
652 652
     }
653 653
 ', $code);
654
-        }
654
+		}
655 655
 
656
-        return '';
657
-    }
656
+		return '';
657
+	}
658 658
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
      */
93 93
     public function getConstructorProperties()
94 94
     {
95
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
95
+        $constructorProperties = array_filter($this->beanPropertyDescriptors, function(AbstractBeanPropertyDescriptor $property) {
96 96
             return $property->isCompulsory();
97 97
         });
98 98
 
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
     public function getPropertiesWithDefault()
108 108
     {
109 109
         $properties = $this->getPropertiesForTable($this->table);
110
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
110
+        $defaultProperties = array_filter($properties, function(AbstractBeanPropertyDescriptor $property) {
111 111
             return $property->hasDefault();
112 112
         });
113 113
 
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
      */
122 122
     public function getExposedProperties()
123 123
     {
124
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
124
+        $exposedProperties = array_filter($this->beanPropertyDescriptors, function(AbstractBeanPropertyDescriptor $property) {
125 125
             return $property->getTable()->getName() == $this->table->getName();
126 126
         });
127 127
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
         }
332 332
 
333 333
         foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
334
-            if (count($descriptorsForMethodName) > 1) {
334
+            if (count($descriptorsForMethodName)>1) {
335 335
                 foreach ($descriptorsForMethodName as $descriptor) {
336 336
                     $descriptor->useAlternativeName();
337 337
                 }
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
 
425 425
         $classes = $this->generateExtendsAndUseStatements($parentFk);
426 426
 
427
-        $uses = array_map(function ($className) use ($beannamespace) {
427
+        $uses = array_map(function($className) use ($beannamespace) {
428 428
             return 'use '.$beannamespace.'\\'.$className.";\n";
429 429
         }, $classes);
430 430
         $use = implode('', $uses);
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/MethodDescriptorInterface.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -4,36 +4,36 @@
 block discarded – undo
4 4
 
5 5
 interface MethodDescriptorInterface
6 6
 {
7
-    /**
8
-     * Returns the name of the method to be generated.
9
-     *
10
-     * @return string
11
-     */
12
-    public function getName() : string;
7
+	/**
8
+	 * Returns the name of the method to be generated.
9
+	 *
10
+	 * @return string
11
+	 */
12
+	public function getName() : string;
13 13
 
14
-    /**
15
-     * Requests the use of an alternative name for this method.
16
-     */
17
-    public function useAlternativeName();
14
+	/**
15
+	 * Requests the use of an alternative name for this method.
16
+	 */
17
+	public function useAlternativeName();
18 18
 
19
-    /**
20
-     * Returns the code of the method.
21
-     *
22
-     * @return string
23
-     */
24
-    public function getCode() : string;
19
+	/**
20
+	 * Returns the code of the method.
21
+	 *
22
+	 * @return string
23
+	 */
24
+	public function getCode() : string;
25 25
 
26
-    /**
27
-     * Returns an array of classes that needs a "use" for this method.
28
-     *
29
-     * @return string[]
30
-     */
31
-    public function getUsedClasses() : array;
26
+	/**
27
+	 * Returns an array of classes that needs a "use" for this method.
28
+	 *
29
+	 * @return string[]
30
+	 */
31
+	public function getUsedClasses() : array;
32 32
 
33
-    /**
34
-     * Returns the code to past in jsonSerialize.
35
-     *
36
-     * @return string
37
-     */
38
-    public function getJsonSerializeCode() : string;
33
+	/**
34
+	 * Returns the code to past in jsonSerialize.
35
+	 *
36
+	 * @return string
37
+	 */
38
+	public function getJsonSerializeCode() : string;
39 39
 }
Please login to merge, or discard this patch.