Completed
Pull Request — 4.1 (#107)
by David
03:26
created
src/Mouf/Database/TDBM/OrderByAnalyzer.php 2 patches
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -10,120 +10,120 @@
 block discarded – undo
10 10
  */
11 11
 class OrderByAnalyzer
12 12
 {
13
-    /**
14
-     * The content of the cache variable.
15
-     *
16
-     * @var Cache
17
-     */
18
-    private $cache;
13
+	/**
14
+	 * The content of the cache variable.
15
+	 *
16
+	 * @var Cache
17
+	 */
18
+	private $cache;
19 19
 
20
-    /**
21
-     * @var string
22
-     */
23
-    private $cachePrefix;
20
+	/**
21
+	 * @var string
22
+	 */
23
+	private $cachePrefix;
24 24
 
25
-    /**
26
-     * OrderByAnalyzer constructor.
27
-     * @param Cache $cache
28
-     * @param string|null $cachePrefix
29
-     */
30
-    public function __construct(Cache $cache, $cachePrefix = null)
31
-    {
32
-        $this->cache = $cache;
33
-        $this->cachePrefix = $cachePrefix;
34
-    }
25
+	/**
26
+	 * OrderByAnalyzer constructor.
27
+	 * @param Cache $cache
28
+	 * @param string|null $cachePrefix
29
+	 */
30
+	public function __construct(Cache $cache, $cachePrefix = null)
31
+	{
32
+		$this->cache = $cache;
33
+		$this->cachePrefix = $cachePrefix;
34
+	}
35 35
 
36
-    /**
37
-     * Returns an array for each sorted "column" in the form:
38
-     *
39
-     * [
40
-     *      [
41
-     *          'type' => 'colref',
42
-     *          'table' => null,
43
-     *          'column' => 'a',
44
-     *          'direction' => 'ASC'
45
-     *      ],
46
-     *      [
47
-     *          'type' => 'expr',
48
-     *          'expr' => 'RAND()',
49
-     *          'direction' => 'DESC'
50
-     *      ]
51
-     * ]
52
-     *
53
-     * @param string $orderBy
54
-     * @return array
55
-     */
56
-    public function analyzeOrderBy(string $orderBy) : array
57
-    {
58
-        $key = $this->cachePrefix.'_order_by_analysis_'.$orderBy;
59
-        $results = $this->cache->fetch($key);
60
-        if ($results !== false) {
61
-            return $results;
62
-        }
63
-        $results = $this->analyzeOrderByNoCache($orderBy);
64
-        $this->cache->save($key, $results);
65
-        return $results;
66
-    }
36
+	/**
37
+	 * Returns an array for each sorted "column" in the form:
38
+	 *
39
+	 * [
40
+	 *      [
41
+	 *          'type' => 'colref',
42
+	 *          'table' => null,
43
+	 *          'column' => 'a',
44
+	 *          'direction' => 'ASC'
45
+	 *      ],
46
+	 *      [
47
+	 *          'type' => 'expr',
48
+	 *          'expr' => 'RAND()',
49
+	 *          'direction' => 'DESC'
50
+	 *      ]
51
+	 * ]
52
+	 *
53
+	 * @param string $orderBy
54
+	 * @return array
55
+	 */
56
+	public function analyzeOrderBy(string $orderBy) : array
57
+	{
58
+		$key = $this->cachePrefix.'_order_by_analysis_'.$orderBy;
59
+		$results = $this->cache->fetch($key);
60
+		if ($results !== false) {
61
+			return $results;
62
+		}
63
+		$results = $this->analyzeOrderByNoCache($orderBy);
64
+		$this->cache->save($key, $results);
65
+		return $results;
66
+	}
67 67
 
68
-    private function analyzeOrderByNoCache(string $orderBy) : array
69
-    {
70
-        $sqlParser = new PHPSQLParser();
71
-        $sql = 'SELECT 1 FROM a ORDER BY '.$orderBy;
72
-        $parsed = $sqlParser->parse($sql, true);
68
+	private function analyzeOrderByNoCache(string $orderBy) : array
69
+	{
70
+		$sqlParser = new PHPSQLParser();
71
+		$sql = 'SELECT 1 FROM a ORDER BY '.$orderBy;
72
+		$parsed = $sqlParser->parse($sql, true);
73 73
 
74
-        $results = [];
74
+		$results = [];
75 75
 
76
-        for ($i = 0, $count = count($parsed['ORDER']); $i < $count; $i++) {
77
-            $orderItem = $parsed['ORDER'][$i];
78
-            if ($orderItem['expr_type'] === 'colref') {
79
-                $parts = $orderItem['no_quotes']['parts'];
80
-                $columnName = array_pop($parts);
81
-                if (!empty($parts)) {
82
-                    $tableName = array_pop($parts);
83
-                } else {
84
-                    $tableName = null;
85
-                }
76
+		for ($i = 0, $count = count($parsed['ORDER']); $i < $count; $i++) {
77
+			$orderItem = $parsed['ORDER'][$i];
78
+			if ($orderItem['expr_type'] === 'colref') {
79
+				$parts = $orderItem['no_quotes']['parts'];
80
+				$columnName = array_pop($parts);
81
+				if (!empty($parts)) {
82
+					$tableName = array_pop($parts);
83
+				} else {
84
+					$tableName = null;
85
+				}
86 86
 
87
-                $results[] = [
88
-                    'type' => 'colref',
89
-                    'table' => $tableName,
90
-                    'column' => $columnName,
91
-                    'direction' => $orderItem['direction']
92
-                ];
93
-            } else {
94
-                $position = $orderItem['position'];
95
-                if ($i+1 < $count) {
96
-                    $nextPosition = $parsed['ORDER'][$i+1]['position'];
97
-                    $str = substr($sql, $position, $nextPosition - $position);
98
-                } else {
99
-                    $str = substr($sql, $position);
100
-                }
87
+				$results[] = [
88
+					'type' => 'colref',
89
+					'table' => $tableName,
90
+					'column' => $columnName,
91
+					'direction' => $orderItem['direction']
92
+				];
93
+			} else {
94
+				$position = $orderItem['position'];
95
+				if ($i+1 < $count) {
96
+					$nextPosition = $parsed['ORDER'][$i+1]['position'];
97
+					$str = substr($sql, $position, $nextPosition - $position);
98
+				} else {
99
+					$str = substr($sql, $position);
100
+				}
101 101
 
102
-                $str = trim($str, " \t\r\n,");
102
+				$str = trim($str, " \t\r\n,");
103 103
 
104
-                $results[] = [
105
-                    'type' => 'expr',
106
-                    'expr' => $this->trimDirection($str),
107
-                    'direction' => $orderItem['direction']
108
-                ];
109
-            }
104
+				$results[] = [
105
+					'type' => 'expr',
106
+					'expr' => $this->trimDirection($str),
107
+					'direction' => $orderItem['direction']
108
+				];
109
+			}
110 110
 
111 111
 
112
-        }
112
+		}
113 113
 
114
-        return $results;
115
-    }
114
+		return $results;
115
+	}
116 116
 
117
-    /**
118
-     * Trims the ASC/DESC direction at the end of the string.
119
-     *
120
-     * @param string $sql
121
-     * @return string
122
-     */
123
-    private function trimDirection(string $sql) : string
124
-    {
125
-        preg_match('/^(.*)(\s+(DESC|ASC|))*$/Ui', $sql, $matches);
117
+	/**
118
+	 * Trims the ASC/DESC direction at the end of the string.
119
+	 *
120
+	 * @param string $sql
121
+	 * @return string
122
+	 */
123
+	private function trimDirection(string $sql) : string
124
+	{
125
+		preg_match('/^(.*)(\s+(DESC|ASC|))*$/Ui', $sql, $matches);
126 126
 
127
-        return $matches[1];
128
-    }
127
+		return $matches[1];
128
+	}
129 129
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 
74 74
         $results = [];
75 75
 
76
-        for ($i = 0, $count = count($parsed['ORDER']); $i < $count; $i++) {
76
+        for ($i = 0, $count = count($parsed['ORDER']); $i<$count; $i++) {
77 77
             $orderItem = $parsed['ORDER'][$i];
78 78
             if ($orderItem['expr_type'] === 'colref') {
79 79
                 $parts = $orderItem['no_quotes']['parts'];
@@ -92,9 +92,9 @@  discard block
 block discarded – undo
92 92
                 ];
93 93
             } else {
94 94
                 $position = $orderItem['position'];
95
-                if ($i+1 < $count) {
95
+                if ($i+1<$count) {
96 96
                     $nextPosition = $parsed['ORDER'][$i+1]['position'];
97
-                    $str = substr($sql, $position, $nextPosition - $position);
97
+                    $str = substr($sql, $position, $nextPosition-$position);
98 98
                 } else {
99 99
                     $str = substr($sql, $position);
100 100
                 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/InnerResultIterator.php 1 patch
Indentation   +263 added lines, -263 removed lines patch added patch discarded remove patch
@@ -29,267 +29,267 @@
 block discarded – undo
29 29
  */
30 30
 class InnerResultIterator implements \Iterator, \Countable, \ArrayAccess
31 31
 {
32
-    /**
33
-     * @var Statement
34
-     */
35
-    protected $statement;
36
-
37
-    protected $fetchStarted = false;
38
-    private $objectStorage;
39
-    private $className;
40
-
41
-    private $tdbmService;
42
-    private $magicSql;
43
-    private $parameters;
44
-    private $limit;
45
-    private $offset;
46
-    private $columnDescriptors;
47
-    private $magicQuery;
48
-
49
-    /**
50
-     * The key of the current retrieved object.
51
-     *
52
-     * @var int
53
-     */
54
-    protected $key = -1;
55
-
56
-    protected $current = null;
57
-
58
-    private $databasePlatform;
59
-
60
-    /**
61
-     * @var LoggerInterface
62
-     */
63
-    private $logger;
64
-
65
-    public function __construct($magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, LoggerInterface $logger)
66
-    {
67
-        $this->magicSql = $magicSql;
68
-        $this->objectStorage = $objectStorage;
69
-        $this->className = $className;
70
-        $this->tdbmService = $tdbmService;
71
-        $this->parameters = $parameters;
72
-        $this->limit = $limit;
73
-        $this->offset = $offset;
74
-        $this->columnDescriptors = $columnDescriptors;
75
-        $this->magicQuery = $magicQuery;
76
-        $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
77
-        $this->logger = $logger;
78
-    }
79
-
80
-    protected function executeQuery()
81
-    {
82
-        $sql = $this->magicQuery->build($this->magicSql, $this->parameters);
83
-        $sql = $this->tdbmService->getConnection()->getDatabasePlatform()->modifyLimitQuery($sql, $this->limit, $this->offset);
84
-
85
-        $this->logger->debug('Running SQL request: '.$sql);
86
-
87
-        $this->statement = $this->tdbmService->getConnection()->executeQuery($sql, $this->parameters);
88
-
89
-        $this->fetchStarted = true;
90
-    }
91
-
92
-    /**
93
-     * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
94
-     *
95
-     * @return int
96
-     */
97
-    public function count()
98
-    {
99
-        if (!$this->fetchStarted) {
100
-            $this->executeQuery();
101
-        }
102
-
103
-        return $this->statement->rowCount();
104
-    }
105
-
106
-    /**
107
-     * Fetches record at current cursor.
108
-     *
109
-     * @return AbstractTDBMObject|null
110
-     */
111
-    public function current()
112
-    {
113
-        return $this->current;
114
-    }
115
-
116
-    /**
117
-     * Returns the current result's key.
118
-     *
119
-     * @return int
120
-     */
121
-    public function key()
122
-    {
123
-        return $this->key;
124
-    }
125
-
126
-    /**
127
-     * Advances the cursor to the next result.
128
-     * Casts the database result into one (or several) beans.
129
-     */
130
-    public function next()
131
-    {
132
-        $row = $this->statement->fetch(\PDO::FETCH_NUM);
133
-        if ($row) {
134
-
135
-            // array<tablegroup, array<table, array<column, value>>>
136
-            $beansData = [];
137
-            foreach ($row as $i => $value) {
138
-                $columnDescriptor = $this->columnDescriptors[$i];
139
-
140
-                if ($columnDescriptor['tableGroup'] === null) {
141
-                    // A column can have no tableGroup (if it comes from an ORDER BY expression)
142
-                    continue;
143
-                }
144
-
145
-                // Let's cast the value according to its type
146
-                $value = $columnDescriptor['type']->convertToPHPValue($value, $this->databasePlatform);
147
-
148
-                $beansData[$columnDescriptor['tableGroup']][$columnDescriptor['table']][$columnDescriptor['column']] = $value;
149
-            }
150
-
151
-            $reflectionClassCache = [];
152
-            $firstBean = true;
153
-            foreach ($beansData as $beanData) {
154
-
155
-                // Let's find the bean class name associated to the bean.
156
-
157
-                list($actualClassName, $mainBeanTableName, $tablesUsed) = $this->tdbmService->_getClassNameFromBeanData($beanData);
158
-
159
-                if ($this->className !== null) {
160
-                    $actualClassName = $this->className;
161
-                }
162
-
163
-                // Let's filter out the beanData that is not used (because it belongs to a part of the hierarchy that is not fetched:
164
-                foreach ($beanData as $tableName => $descriptors) {
165
-                    if (!in_array($tableName, $tablesUsed)) {
166
-                        unset($beanData[$tableName]);
167
-                    }
168
-                }
169
-
170
-                // Must we create the bean? Let's see in the cache if we have a mapping DbRow?
171
-                // Let's get the first object mapping a row:
172
-                // We do this loop only for the first table
173
-
174
-                $primaryKeys = $this->tdbmService->_getPrimaryKeysFromObjectData($mainBeanTableName, $beanData[$mainBeanTableName]);
175
-                $hash = $this->tdbmService->getObjectHash($primaryKeys);
176
-
177
-                if ($this->objectStorage->has($mainBeanTableName, $hash)) {
178
-                    $dbRow = $this->objectStorage->get($mainBeanTableName, $hash);
179
-                    $bean = $dbRow->getTDBMObject();
180
-                } else {
181
-                    // Let's construct the bean
182
-                    if (!isset($reflectionClassCache[$actualClassName])) {
183
-                        $reflectionClassCache[$actualClassName] = new \ReflectionClass($actualClassName);
184
-                    }
185
-                    // Let's bypass the constructor when creating the bean!
186
-                    $bean = $reflectionClassCache[$actualClassName]->newInstanceWithoutConstructor();
187
-                    $bean->_constructFromData($beanData, $this->tdbmService);
188
-                }
189
-
190
-                // The first bean is the one containing the main table.
191
-                if ($firstBean) {
192
-                    $firstBean = false;
193
-                    $this->current = $bean;
194
-                }
195
-            }
196
-
197
-            ++$this->key;
198
-        } else {
199
-            $this->current = null;
200
-        }
201
-    }
202
-
203
-    /**
204
-     * Moves the cursor to the beginning of the result set.
205
-     */
206
-    public function rewind()
207
-    {
208
-        $this->executeQuery();
209
-        $this->key = -1;
210
-        $this->next();
211
-    }
212
-    /**
213
-     * Checks if the cursor is reading a valid result.
214
-     *
215
-     * @return bool
216
-     */
217
-    public function valid()
218
-    {
219
-        return $this->current !== null;
220
-    }
221
-
222
-    /**
223
-     * Whether a offset exists.
224
-     *
225
-     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
226
-     *
227
-     * @param mixed $offset <p>
228
-     *                      An offset to check for.
229
-     *                      </p>
230
-     *
231
-     * @return bool true on success or false on failure.
232
-     *              </p>
233
-     *              <p>
234
-     *              The return value will be casted to boolean if non-boolean was returned
235
-     *
236
-     * @since 5.0.0
237
-     */
238
-    public function offsetExists($offset)
239
-    {
240
-        throw new TDBMInvalidOperationException('You cannot access this result set via index because it was fetched in CURSOR mode. Use ARRAY_MODE instead.');
241
-    }
242
-
243
-    /**
244
-     * Offset to retrieve.
245
-     *
246
-     * @link http://php.net/manual/en/arrayaccess.offsetget.php
247
-     *
248
-     * @param mixed $offset <p>
249
-     *                      The offset to retrieve.
250
-     *                      </p>
251
-     *
252
-     * @return mixed Can return all value types
253
-     *
254
-     * @since 5.0.0
255
-     */
256
-    public function offsetGet($offset)
257
-    {
258
-        throw new TDBMInvalidOperationException('You cannot access this result set via index because it was fetched in CURSOR mode. Use ARRAY_MODE instead.');
259
-    }
260
-
261
-    /**
262
-     * Offset to set.
263
-     *
264
-     * @link http://php.net/manual/en/arrayaccess.offsetset.php
265
-     *
266
-     * @param mixed $offset <p>
267
-     *                      The offset to assign the value to.
268
-     *                      </p>
269
-     * @param mixed $value  <p>
270
-     *                      The value to set.
271
-     *                      </p>
272
-     *
273
-     * @since 5.0.0
274
-     */
275
-    public function offsetSet($offset, $value)
276
-    {
277
-        throw new TDBMInvalidOperationException('You can set values in a TDBM result set.');
278
-    }
279
-
280
-    /**
281
-     * Offset to unset.
282
-     *
283
-     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
284
-     *
285
-     * @param mixed $offset <p>
286
-     *                      The offset to unset.
287
-     *                      </p>
288
-     *
289
-     * @since 5.0.0
290
-     */
291
-    public function offsetUnset($offset)
292
-    {
293
-        throw new TDBMInvalidOperationException('You can unset values in a TDBM result set.');
294
-    }
32
+	/**
33
+	 * @var Statement
34
+	 */
35
+	protected $statement;
36
+
37
+	protected $fetchStarted = false;
38
+	private $objectStorage;
39
+	private $className;
40
+
41
+	private $tdbmService;
42
+	private $magicSql;
43
+	private $parameters;
44
+	private $limit;
45
+	private $offset;
46
+	private $columnDescriptors;
47
+	private $magicQuery;
48
+
49
+	/**
50
+	 * The key of the current retrieved object.
51
+	 *
52
+	 * @var int
53
+	 */
54
+	protected $key = -1;
55
+
56
+	protected $current = null;
57
+
58
+	private $databasePlatform;
59
+
60
+	/**
61
+	 * @var LoggerInterface
62
+	 */
63
+	private $logger;
64
+
65
+	public function __construct($magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, LoggerInterface $logger)
66
+	{
67
+		$this->magicSql = $magicSql;
68
+		$this->objectStorage = $objectStorage;
69
+		$this->className = $className;
70
+		$this->tdbmService = $tdbmService;
71
+		$this->parameters = $parameters;
72
+		$this->limit = $limit;
73
+		$this->offset = $offset;
74
+		$this->columnDescriptors = $columnDescriptors;
75
+		$this->magicQuery = $magicQuery;
76
+		$this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
77
+		$this->logger = $logger;
78
+	}
79
+
80
+	protected function executeQuery()
81
+	{
82
+		$sql = $this->magicQuery->build($this->magicSql, $this->parameters);
83
+		$sql = $this->tdbmService->getConnection()->getDatabasePlatform()->modifyLimitQuery($sql, $this->limit, $this->offset);
84
+
85
+		$this->logger->debug('Running SQL request: '.$sql);
86
+
87
+		$this->statement = $this->tdbmService->getConnection()->executeQuery($sql, $this->parameters);
88
+
89
+		$this->fetchStarted = true;
90
+	}
91
+
92
+	/**
93
+	 * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
94
+	 *
95
+	 * @return int
96
+	 */
97
+	public function count()
98
+	{
99
+		if (!$this->fetchStarted) {
100
+			$this->executeQuery();
101
+		}
102
+
103
+		return $this->statement->rowCount();
104
+	}
105
+
106
+	/**
107
+	 * Fetches record at current cursor.
108
+	 *
109
+	 * @return AbstractTDBMObject|null
110
+	 */
111
+	public function current()
112
+	{
113
+		return $this->current;
114
+	}
115
+
116
+	/**
117
+	 * Returns the current result's key.
118
+	 *
119
+	 * @return int
120
+	 */
121
+	public function key()
122
+	{
123
+		return $this->key;
124
+	}
125
+
126
+	/**
127
+	 * Advances the cursor to the next result.
128
+	 * Casts the database result into one (or several) beans.
129
+	 */
130
+	public function next()
131
+	{
132
+		$row = $this->statement->fetch(\PDO::FETCH_NUM);
133
+		if ($row) {
134
+
135
+			// array<tablegroup, array<table, array<column, value>>>
136
+			$beansData = [];
137
+			foreach ($row as $i => $value) {
138
+				$columnDescriptor = $this->columnDescriptors[$i];
139
+
140
+				if ($columnDescriptor['tableGroup'] === null) {
141
+					// A column can have no tableGroup (if it comes from an ORDER BY expression)
142
+					continue;
143
+				}
144
+
145
+				// Let's cast the value according to its type
146
+				$value = $columnDescriptor['type']->convertToPHPValue($value, $this->databasePlatform);
147
+
148
+				$beansData[$columnDescriptor['tableGroup']][$columnDescriptor['table']][$columnDescriptor['column']] = $value;
149
+			}
150
+
151
+			$reflectionClassCache = [];
152
+			$firstBean = true;
153
+			foreach ($beansData as $beanData) {
154
+
155
+				// Let's find the bean class name associated to the bean.
156
+
157
+				list($actualClassName, $mainBeanTableName, $tablesUsed) = $this->tdbmService->_getClassNameFromBeanData($beanData);
158
+
159
+				if ($this->className !== null) {
160
+					$actualClassName = $this->className;
161
+				}
162
+
163
+				// Let's filter out the beanData that is not used (because it belongs to a part of the hierarchy that is not fetched:
164
+				foreach ($beanData as $tableName => $descriptors) {
165
+					if (!in_array($tableName, $tablesUsed)) {
166
+						unset($beanData[$tableName]);
167
+					}
168
+				}
169
+
170
+				// Must we create the bean? Let's see in the cache if we have a mapping DbRow?
171
+				// Let's get the first object mapping a row:
172
+				// We do this loop only for the first table
173
+
174
+				$primaryKeys = $this->tdbmService->_getPrimaryKeysFromObjectData($mainBeanTableName, $beanData[$mainBeanTableName]);
175
+				$hash = $this->tdbmService->getObjectHash($primaryKeys);
176
+
177
+				if ($this->objectStorage->has($mainBeanTableName, $hash)) {
178
+					$dbRow = $this->objectStorage->get($mainBeanTableName, $hash);
179
+					$bean = $dbRow->getTDBMObject();
180
+				} else {
181
+					// Let's construct the bean
182
+					if (!isset($reflectionClassCache[$actualClassName])) {
183
+						$reflectionClassCache[$actualClassName] = new \ReflectionClass($actualClassName);
184
+					}
185
+					// Let's bypass the constructor when creating the bean!
186
+					$bean = $reflectionClassCache[$actualClassName]->newInstanceWithoutConstructor();
187
+					$bean->_constructFromData($beanData, $this->tdbmService);
188
+				}
189
+
190
+				// The first bean is the one containing the main table.
191
+				if ($firstBean) {
192
+					$firstBean = false;
193
+					$this->current = $bean;
194
+				}
195
+			}
196
+
197
+			++$this->key;
198
+		} else {
199
+			$this->current = null;
200
+		}
201
+	}
202
+
203
+	/**
204
+	 * Moves the cursor to the beginning of the result set.
205
+	 */
206
+	public function rewind()
207
+	{
208
+		$this->executeQuery();
209
+		$this->key = -1;
210
+		$this->next();
211
+	}
212
+	/**
213
+	 * Checks if the cursor is reading a valid result.
214
+	 *
215
+	 * @return bool
216
+	 */
217
+	public function valid()
218
+	{
219
+		return $this->current !== null;
220
+	}
221
+
222
+	/**
223
+	 * Whether a offset exists.
224
+	 *
225
+	 * @link http://php.net/manual/en/arrayaccess.offsetexists.php
226
+	 *
227
+	 * @param mixed $offset <p>
228
+	 *                      An offset to check for.
229
+	 *                      </p>
230
+	 *
231
+	 * @return bool true on success or false on failure.
232
+	 *              </p>
233
+	 *              <p>
234
+	 *              The return value will be casted to boolean if non-boolean was returned
235
+	 *
236
+	 * @since 5.0.0
237
+	 */
238
+	public function offsetExists($offset)
239
+	{
240
+		throw new TDBMInvalidOperationException('You cannot access this result set via index because it was fetched in CURSOR mode. Use ARRAY_MODE instead.');
241
+	}
242
+
243
+	/**
244
+	 * Offset to retrieve.
245
+	 *
246
+	 * @link http://php.net/manual/en/arrayaccess.offsetget.php
247
+	 *
248
+	 * @param mixed $offset <p>
249
+	 *                      The offset to retrieve.
250
+	 *                      </p>
251
+	 *
252
+	 * @return mixed Can return all value types
253
+	 *
254
+	 * @since 5.0.0
255
+	 */
256
+	public function offsetGet($offset)
257
+	{
258
+		throw new TDBMInvalidOperationException('You cannot access this result set via index because it was fetched in CURSOR mode. Use ARRAY_MODE instead.');
259
+	}
260
+
261
+	/**
262
+	 * Offset to set.
263
+	 *
264
+	 * @link http://php.net/manual/en/arrayaccess.offsetset.php
265
+	 *
266
+	 * @param mixed $offset <p>
267
+	 *                      The offset to assign the value to.
268
+	 *                      </p>
269
+	 * @param mixed $value  <p>
270
+	 *                      The value to set.
271
+	 *                      </p>
272
+	 *
273
+	 * @since 5.0.0
274
+	 */
275
+	public function offsetSet($offset, $value)
276
+	{
277
+		throw new TDBMInvalidOperationException('You can set values in a TDBM result set.');
278
+	}
279
+
280
+	/**
281
+	 * Offset to unset.
282
+	 *
283
+	 * @link http://php.net/manual/en/arrayaccess.offsetunset.php
284
+	 *
285
+	 * @param mixed $offset <p>
286
+	 *                      The offset to unset.
287
+	 *                      </p>
288
+	 *
289
+	 * @since 5.0.0
290
+	 */
291
+	public function offsetUnset($offset)
292
+	{
293
+		throw new TDBMInvalidOperationException('You can unset values in a TDBM result set.');
294
+	}
295 295
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMService.php 1 patch
Indentation   +1635 added lines, -1635 removed lines patch added patch discarded remove patch
@@ -45,236 +45,236 @@  discard block
 block discarded – undo
45 45
  */
46 46
 class TDBMService
47 47
 {
48
-    const MODE_CURSOR = 1;
49
-    const MODE_ARRAY = 2;
50
-
51
-    /**
52
-     * The database connection.
53
-     *
54
-     * @var Connection
55
-     */
56
-    private $connection;
57
-
58
-    /**
59
-     * @var SchemaAnalyzer
60
-     */
61
-    private $schemaAnalyzer;
62
-
63
-    /**
64
-     * @var MagicQuery
65
-     */
66
-    private $magicQuery;
67
-
68
-    /**
69
-     * @var TDBMSchemaAnalyzer
70
-     */
71
-    private $tdbmSchemaAnalyzer;
72
-
73
-    /**
74
-     * @var string
75
-     */
76
-    private $cachePrefix;
77
-
78
-    /**
79
-     * Cache of table of primary keys.
80
-     * Primary keys are stored by tables, as an array of column.
81
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
82
-     *
83
-     * @var string[]
84
-     */
85
-    private $primaryKeysColumns;
86
-
87
-    /**
88
-     * Service storing objects in memory.
89
-     * Access is done by table name and then by primary key.
90
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
91
-     *
92
-     * @var StandardObjectStorage|WeakrefObjectStorage
93
-     */
94
-    private $objectStorage;
95
-
96
-    /**
97
-     * The fetch mode of the result sets returned by `getObjects`.
98
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
99
-     *
100
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
101
-     * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
102
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
103
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
104
-     * You can access the array by key, or using foreach, several times.
105
-     *
106
-     * @var int
107
-     */
108
-    private $mode = self::MODE_ARRAY;
109
-
110
-    /**
111
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
112
-     *
113
-     * @var \SplObjectStorage of DbRow objects
114
-     */
115
-    private $toSaveObjects;
116
-
117
-    /**
118
-     * A cache service to be used.
119
-     *
120
-     * @var Cache|null
121
-     */
122
-    private $cache;
123
-
124
-    /**
125
-     * Map associating a table name to a fully qualified Bean class name.
126
-     *
127
-     * @var array
128
-     */
129
-    private $tableToBeanMap = [];
130
-
131
-    /**
132
-     * @var \ReflectionClass[]
133
-     */
134
-    private $reflectionClassCache = array();
135
-
136
-    /**
137
-     * @var LoggerInterface
138
-     */
139
-    private $rootLogger;
140
-
141
-    /**
142
-     * @var MinLogLevelFilter|NullLogger
143
-     */
144
-    private $logger;
145
-
146
-    /**
147
-     * @var OrderByAnalyzer
148
-     */
149
-    private $orderByAnalyzer;
150
-
151
-    /**
152
-     * @param Connection     $connection     The DBAL DB connection to use
153
-     * @param Cache|null     $cache          A cache service to be used
154
-     * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
155
-     *                                       Will be automatically created if not passed
156
-     */
157
-    public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
158
-    {
159
-        if (extension_loaded('weakref')) {
160
-            $this->objectStorage = new WeakrefObjectStorage();
161
-        } else {
162
-            $this->objectStorage = new StandardObjectStorage();
163
-        }
164
-        $this->connection = $connection;
165
-        if ($cache !== null) {
166
-            $this->cache = $cache;
167
-        } else {
168
-            $this->cache = new VoidCache();
169
-        }
170
-        if ($schemaAnalyzer) {
171
-            $this->schemaAnalyzer = $schemaAnalyzer;
172
-        } else {
173
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
174
-        }
175
-
176
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
177
-
178
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
179
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
180
-
181
-        $this->toSaveObjects = new \SplObjectStorage();
182
-        if ($logger === null) {
183
-            $this->logger = new NullLogger();
184
-            $this->rootLogger = new NullLogger();
185
-        } else {
186
-            $this->rootLogger = $logger;
187
-            $this->setLogLevel(LogLevel::WARNING);
188
-        }
189
-        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
190
-    }
191
-
192
-    /**
193
-     * Returns the object used to connect to the database.
194
-     *
195
-     * @return Connection
196
-     */
197
-    public function getConnection()
198
-    {
199
-        return $this->connection;
200
-    }
201
-
202
-    /**
203
-     * Creates a unique cache key for the current connection.
204
-     *
205
-     * @return string
206
-     */
207
-    private function getConnectionUniqueId()
208
-    {
209
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
210
-    }
211
-
212
-    /**
213
-     * Sets the default fetch mode of the result sets returned by `findObjects`.
214
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
215
-     *
216
-     * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
217
-     * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
218
-     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
219
-     *
220
-     * @param int $mode
221
-     *
222
-     * @return $this
223
-     *
224
-     * @throws TDBMException
225
-     */
226
-    public function setFetchMode($mode)
227
-    {
228
-        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
229
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
230
-        }
231
-        $this->mode = $mode;
232
-
233
-        return $this;
234
-    }
235
-
236
-    /**
237
-     * Returns a TDBMObject associated from table "$table_name".
238
-     * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
239
-     * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
240
-     *
241
-     * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
242
-     * 			$user = $tdbmService->getObject('users',1);
243
-     * 			echo $user->name;
244
-     * will return the name of the user whose user_id is one.
245
-     *
246
-     * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
247
-     * For instance:
248
-     * 			$group = $tdbmService->getObject('groups',array(1,2));
249
-     *
250
-     * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
251
-     * will be the same.
252
-     *
253
-     * For instance:
254
-     * 			$user1 = $tdbmService->getObject('users',1);
255
-     * 			$user2 = $tdbmService->getObject('users',1);
256
-     * 			$user1->name = 'John Doe';
257
-     * 			echo $user2->name;
258
-     * will return 'John Doe'.
259
-     *
260
-     * You can use filters instead of passing the primary key. For instance:
261
-     * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
262
-     * This will return the user whose login is 'jdoe'.
263
-     * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
264
-     *
265
-     * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
266
-     * For instance:
267
-     *  	$user = $tdbmService->getObject('users',1,'User');
268
-     * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
269
-     * Please be sure not to override any method or any property unless you perfectly know what you are doing!
270
-     *
271
-     * @param string $table_name   The name of the table we retrieve an object from
272
-     * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
273
-     * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
274
-     * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
275
-     *
276
-     * @return TDBMObject
277
-     */
48
+	const MODE_CURSOR = 1;
49
+	const MODE_ARRAY = 2;
50
+
51
+	/**
52
+	 * The database connection.
53
+	 *
54
+	 * @var Connection
55
+	 */
56
+	private $connection;
57
+
58
+	/**
59
+	 * @var SchemaAnalyzer
60
+	 */
61
+	private $schemaAnalyzer;
62
+
63
+	/**
64
+	 * @var MagicQuery
65
+	 */
66
+	private $magicQuery;
67
+
68
+	/**
69
+	 * @var TDBMSchemaAnalyzer
70
+	 */
71
+	private $tdbmSchemaAnalyzer;
72
+
73
+	/**
74
+	 * @var string
75
+	 */
76
+	private $cachePrefix;
77
+
78
+	/**
79
+	 * Cache of table of primary keys.
80
+	 * Primary keys are stored by tables, as an array of column.
81
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
82
+	 *
83
+	 * @var string[]
84
+	 */
85
+	private $primaryKeysColumns;
86
+
87
+	/**
88
+	 * Service storing objects in memory.
89
+	 * Access is done by table name and then by primary key.
90
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
91
+	 *
92
+	 * @var StandardObjectStorage|WeakrefObjectStorage
93
+	 */
94
+	private $objectStorage;
95
+
96
+	/**
97
+	 * The fetch mode of the result sets returned by `getObjects`.
98
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
99
+	 *
100
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
101
+	 * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
102
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
103
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
104
+	 * You can access the array by key, or using foreach, several times.
105
+	 *
106
+	 * @var int
107
+	 */
108
+	private $mode = self::MODE_ARRAY;
109
+
110
+	/**
111
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
112
+	 *
113
+	 * @var \SplObjectStorage of DbRow objects
114
+	 */
115
+	private $toSaveObjects;
116
+
117
+	/**
118
+	 * A cache service to be used.
119
+	 *
120
+	 * @var Cache|null
121
+	 */
122
+	private $cache;
123
+
124
+	/**
125
+	 * Map associating a table name to a fully qualified Bean class name.
126
+	 *
127
+	 * @var array
128
+	 */
129
+	private $tableToBeanMap = [];
130
+
131
+	/**
132
+	 * @var \ReflectionClass[]
133
+	 */
134
+	private $reflectionClassCache = array();
135
+
136
+	/**
137
+	 * @var LoggerInterface
138
+	 */
139
+	private $rootLogger;
140
+
141
+	/**
142
+	 * @var MinLogLevelFilter|NullLogger
143
+	 */
144
+	private $logger;
145
+
146
+	/**
147
+	 * @var OrderByAnalyzer
148
+	 */
149
+	private $orderByAnalyzer;
150
+
151
+	/**
152
+	 * @param Connection     $connection     The DBAL DB connection to use
153
+	 * @param Cache|null     $cache          A cache service to be used
154
+	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
155
+	 *                                       Will be automatically created if not passed
156
+	 */
157
+	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
158
+	{
159
+		if (extension_loaded('weakref')) {
160
+			$this->objectStorage = new WeakrefObjectStorage();
161
+		} else {
162
+			$this->objectStorage = new StandardObjectStorage();
163
+		}
164
+		$this->connection = $connection;
165
+		if ($cache !== null) {
166
+			$this->cache = $cache;
167
+		} else {
168
+			$this->cache = new VoidCache();
169
+		}
170
+		if ($schemaAnalyzer) {
171
+			$this->schemaAnalyzer = $schemaAnalyzer;
172
+		} else {
173
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
174
+		}
175
+
176
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
177
+
178
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
179
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
180
+
181
+		$this->toSaveObjects = new \SplObjectStorage();
182
+		if ($logger === null) {
183
+			$this->logger = new NullLogger();
184
+			$this->rootLogger = new NullLogger();
185
+		} else {
186
+			$this->rootLogger = $logger;
187
+			$this->setLogLevel(LogLevel::WARNING);
188
+		}
189
+		$this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
190
+	}
191
+
192
+	/**
193
+	 * Returns the object used to connect to the database.
194
+	 *
195
+	 * @return Connection
196
+	 */
197
+	public function getConnection()
198
+	{
199
+		return $this->connection;
200
+	}
201
+
202
+	/**
203
+	 * Creates a unique cache key for the current connection.
204
+	 *
205
+	 * @return string
206
+	 */
207
+	private function getConnectionUniqueId()
208
+	{
209
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
210
+	}
211
+
212
+	/**
213
+	 * Sets the default fetch mode of the result sets returned by `findObjects`.
214
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
215
+	 *
216
+	 * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
217
+	 * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
218
+	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
219
+	 *
220
+	 * @param int $mode
221
+	 *
222
+	 * @return $this
223
+	 *
224
+	 * @throws TDBMException
225
+	 */
226
+	public function setFetchMode($mode)
227
+	{
228
+		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
229
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
230
+		}
231
+		$this->mode = $mode;
232
+
233
+		return $this;
234
+	}
235
+
236
+	/**
237
+	 * Returns a TDBMObject associated from table "$table_name".
238
+	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
239
+	 * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
240
+	 *
241
+	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
242
+	 * 			$user = $tdbmService->getObject('users',1);
243
+	 * 			echo $user->name;
244
+	 * will return the name of the user whose user_id is one.
245
+	 *
246
+	 * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
247
+	 * For instance:
248
+	 * 			$group = $tdbmService->getObject('groups',array(1,2));
249
+	 *
250
+	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
251
+	 * will be the same.
252
+	 *
253
+	 * For instance:
254
+	 * 			$user1 = $tdbmService->getObject('users',1);
255
+	 * 			$user2 = $tdbmService->getObject('users',1);
256
+	 * 			$user1->name = 'John Doe';
257
+	 * 			echo $user2->name;
258
+	 * will return 'John Doe'.
259
+	 *
260
+	 * You can use filters instead of passing the primary key. For instance:
261
+	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
262
+	 * This will return the user whose login is 'jdoe'.
263
+	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
264
+	 *
265
+	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
266
+	 * For instance:
267
+	 *  	$user = $tdbmService->getObject('users',1,'User');
268
+	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
269
+	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
270
+	 *
271
+	 * @param string $table_name   The name of the table we retrieve an object from
272
+	 * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
273
+	 * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
274
+	 * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
275
+	 *
276
+	 * @return TDBMObject
277
+	 */
278 278
 /*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
279 279
 
280 280
         if (is_array($filters) || $filters instanceof FilterInterface) {
@@ -360,199 +360,199 @@  discard block
 block discarded – undo
360 360
         return $obj;
361 361
     }*/
362 362
 
363
-    /**
364
-     * Removes the given object from database.
365
-     * This cannot be called on an object that is not attached to this TDBMService
366
-     * (will throw a TDBMInvalidOperationException).
367
-     *
368
-     * @param AbstractTDBMObject $object the object to delete
369
-     *
370
-     * @throws TDBMException
371
-     * @throws TDBMInvalidOperationException
372
-     */
373
-    public function delete(AbstractTDBMObject $object)
374
-    {
375
-        switch ($object->_getStatus()) {
376
-            case TDBMObjectStateEnum::STATE_DELETED:
377
-                // Nothing to do, object already deleted.
378
-                return;
379
-            case TDBMObjectStateEnum::STATE_DETACHED:
380
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
381
-            case TDBMObjectStateEnum::STATE_NEW:
382
-                $this->deleteManyToManyRelationships($object);
383
-                foreach ($object->_getDbRows() as $dbRow) {
384
-                    $this->removeFromToSaveObjectList($dbRow);
385
-                }
386
-                break;
387
-            case TDBMObjectStateEnum::STATE_DIRTY:
388
-                foreach ($object->_getDbRows() as $dbRow) {
389
-                    $this->removeFromToSaveObjectList($dbRow);
390
-                }
391
-                // And continue deleting...
392
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
393
-            case TDBMObjectStateEnum::STATE_LOADED:
394
-                $this->deleteManyToManyRelationships($object);
395
-                // Let's delete db rows, in reverse order.
396
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
397
-                    $tableName = $dbRow->_getDbTableName();
398
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
399
-                    $this->connection->delete($tableName, $primaryKeys);
400
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
401
-                }
402
-                break;
403
-            // @codeCoverageIgnoreStart
404
-            default:
405
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
406
-            // @codeCoverageIgnoreEnd
407
-        }
408
-
409
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
410
-    }
411
-
412
-    /**
413
-     * Removes all many to many relationships for this object.
414
-     *
415
-     * @param AbstractTDBMObject $object
416
-     */
417
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
418
-    {
419
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
420
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
421
-            foreach ($pivotTables as $pivotTable) {
422
-                $remoteBeans = $object->_getRelationships($pivotTable);
423
-                foreach ($remoteBeans as $remoteBean) {
424
-                    $object->_removeRelationship($pivotTable, $remoteBean);
425
-                }
426
-            }
427
-        }
428
-        $this->persistManyToManyRelationships($object);
429
-    }
430
-
431
-    /**
432
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
433
-     * by parameter before all.
434
-     *
435
-     * Notice: if the object has a multiple primary key, the function will not work.
436
-     *
437
-     * @param AbstractTDBMObject $objToDelete
438
-     */
439
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
440
-    {
441
-        $this->deleteAllConstraintWithThisObject($objToDelete);
442
-        $this->delete($objToDelete);
443
-    }
444
-
445
-    /**
446
-     * This function is used only in TDBMService (private function)
447
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
448
-     *
449
-     * @param AbstractTDBMObject $obj
450
-     */
451
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
452
-    {
453
-        $dbRows = $obj->_getDbRows();
454
-        foreach ($dbRows as $dbRow) {
455
-            $tableName = $dbRow->_getDbTableName();
456
-            $pks = array_values($dbRow->_getPrimaryKeys());
457
-            if (!empty($pks)) {
458
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
459
-
460
-                foreach ($incomingFks as $incomingFk) {
461
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
462
-
463
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
464
-
465
-                    foreach ($results as $bean) {
466
-                        $this->deleteCascade($bean);
467
-                    }
468
-                }
469
-            }
470
-        }
471
-    }
472
-
473
-    /**
474
-     * This function performs a save() of all the objects that have been modified.
475
-     */
476
-    public function completeSave()
477
-    {
478
-        foreach ($this->toSaveObjects as $dbRow) {
479
-            $this->save($dbRow->getTDBMObject());
480
-        }
481
-    }
482
-
483
-    /**
484
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
485
-     * and gives back a proper Filter object.
486
-     *
487
-     * @param mixed $filter_bag
488
-     * @param int   $counter
489
-     *
490
-     * @return array First item: filter string, second item: parameters
491
-     *
492
-     * @throws TDBMException
493
-     */
494
-    public function buildFilterFromFilterBag($filter_bag, $counter = 1)
495
-    {
496
-        if ($filter_bag === null) {
497
-            return ['', []];
498
-        } elseif (is_string($filter_bag)) {
499
-            return [$filter_bag, []];
500
-        } elseif (is_array($filter_bag)) {
501
-            $sqlParts = [];
502
-            $parameters = [];
503
-            foreach ($filter_bag as $column => $value) {
504
-                if (is_int($column)) {
505
-                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
506
-                    $sqlParts[] = $subSqlPart;
507
-                    $parameters += $subParameters;
508
-                } else {
509
-                    $paramName = 'tdbmparam'.$counter;
510
-                    if (is_array($value)) {
511
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
512
-                    } else {
513
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
514
-                    }
515
-                    $parameters[$paramName] = $value;
516
-                    ++$counter;
517
-                }
518
-            }
519
-
520
-            return [implode(' AND ', $sqlParts), $parameters];
521
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
522
-            $sqlParts = [];
523
-            $parameters = [];
524
-            $dbRows = $filter_bag->_getDbRows();
525
-            $dbRow = reset($dbRows);
526
-            $primaryKeys = $dbRow->_getPrimaryKeys();
527
-
528
-            foreach ($primaryKeys as $column => $value) {
529
-                $paramName = 'tdbmparam'.$counter;
530
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
531
-                $parameters[$paramName] = $value;
532
-                ++$counter;
533
-            }
534
-
535
-            return [implode(' AND ', $sqlParts), $parameters];
536
-        } elseif ($filter_bag instanceof \Iterator) {
537
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
538
-        } else {
539
-            throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
540
-        }
541
-    }
542
-
543
-    /**
544
-     * @param string $table
545
-     *
546
-     * @return string[]
547
-     */
548
-    public function getPrimaryKeyColumns($table)
549
-    {
550
-        if (!isset($this->primaryKeysColumns[$table])) {
551
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
552
-
553
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
554
-
555
-            /*$arr = array();
363
+	/**
364
+	 * Removes the given object from database.
365
+	 * This cannot be called on an object that is not attached to this TDBMService
366
+	 * (will throw a TDBMInvalidOperationException).
367
+	 *
368
+	 * @param AbstractTDBMObject $object the object to delete
369
+	 *
370
+	 * @throws TDBMException
371
+	 * @throws TDBMInvalidOperationException
372
+	 */
373
+	public function delete(AbstractTDBMObject $object)
374
+	{
375
+		switch ($object->_getStatus()) {
376
+			case TDBMObjectStateEnum::STATE_DELETED:
377
+				// Nothing to do, object already deleted.
378
+				return;
379
+			case TDBMObjectStateEnum::STATE_DETACHED:
380
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
381
+			case TDBMObjectStateEnum::STATE_NEW:
382
+				$this->deleteManyToManyRelationships($object);
383
+				foreach ($object->_getDbRows() as $dbRow) {
384
+					$this->removeFromToSaveObjectList($dbRow);
385
+				}
386
+				break;
387
+			case TDBMObjectStateEnum::STATE_DIRTY:
388
+				foreach ($object->_getDbRows() as $dbRow) {
389
+					$this->removeFromToSaveObjectList($dbRow);
390
+				}
391
+				// And continue deleting...
392
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
393
+			case TDBMObjectStateEnum::STATE_LOADED:
394
+				$this->deleteManyToManyRelationships($object);
395
+				// Let's delete db rows, in reverse order.
396
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
397
+					$tableName = $dbRow->_getDbTableName();
398
+					$primaryKeys = $dbRow->_getPrimaryKeys();
399
+					$this->connection->delete($tableName, $primaryKeys);
400
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
401
+				}
402
+				break;
403
+			// @codeCoverageIgnoreStart
404
+			default:
405
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
406
+			// @codeCoverageIgnoreEnd
407
+		}
408
+
409
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
410
+	}
411
+
412
+	/**
413
+	 * Removes all many to many relationships for this object.
414
+	 *
415
+	 * @param AbstractTDBMObject $object
416
+	 */
417
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
418
+	{
419
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
420
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
421
+			foreach ($pivotTables as $pivotTable) {
422
+				$remoteBeans = $object->_getRelationships($pivotTable);
423
+				foreach ($remoteBeans as $remoteBean) {
424
+					$object->_removeRelationship($pivotTable, $remoteBean);
425
+				}
426
+			}
427
+		}
428
+		$this->persistManyToManyRelationships($object);
429
+	}
430
+
431
+	/**
432
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
433
+	 * by parameter before all.
434
+	 *
435
+	 * Notice: if the object has a multiple primary key, the function will not work.
436
+	 *
437
+	 * @param AbstractTDBMObject $objToDelete
438
+	 */
439
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
440
+	{
441
+		$this->deleteAllConstraintWithThisObject($objToDelete);
442
+		$this->delete($objToDelete);
443
+	}
444
+
445
+	/**
446
+	 * This function is used only in TDBMService (private function)
447
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
448
+	 *
449
+	 * @param AbstractTDBMObject $obj
450
+	 */
451
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
452
+	{
453
+		$dbRows = $obj->_getDbRows();
454
+		foreach ($dbRows as $dbRow) {
455
+			$tableName = $dbRow->_getDbTableName();
456
+			$pks = array_values($dbRow->_getPrimaryKeys());
457
+			if (!empty($pks)) {
458
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
459
+
460
+				foreach ($incomingFks as $incomingFk) {
461
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
462
+
463
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
464
+
465
+					foreach ($results as $bean) {
466
+						$this->deleteCascade($bean);
467
+					}
468
+				}
469
+			}
470
+		}
471
+	}
472
+
473
+	/**
474
+	 * This function performs a save() of all the objects that have been modified.
475
+	 */
476
+	public function completeSave()
477
+	{
478
+		foreach ($this->toSaveObjects as $dbRow) {
479
+			$this->save($dbRow->getTDBMObject());
480
+		}
481
+	}
482
+
483
+	/**
484
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
485
+	 * and gives back a proper Filter object.
486
+	 *
487
+	 * @param mixed $filter_bag
488
+	 * @param int   $counter
489
+	 *
490
+	 * @return array First item: filter string, second item: parameters
491
+	 *
492
+	 * @throws TDBMException
493
+	 */
494
+	public function buildFilterFromFilterBag($filter_bag, $counter = 1)
495
+	{
496
+		if ($filter_bag === null) {
497
+			return ['', []];
498
+		} elseif (is_string($filter_bag)) {
499
+			return [$filter_bag, []];
500
+		} elseif (is_array($filter_bag)) {
501
+			$sqlParts = [];
502
+			$parameters = [];
503
+			foreach ($filter_bag as $column => $value) {
504
+				if (is_int($column)) {
505
+					list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
506
+					$sqlParts[] = $subSqlPart;
507
+					$parameters += $subParameters;
508
+				} else {
509
+					$paramName = 'tdbmparam'.$counter;
510
+					if (is_array($value)) {
511
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
512
+					} else {
513
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
514
+					}
515
+					$parameters[$paramName] = $value;
516
+					++$counter;
517
+				}
518
+			}
519
+
520
+			return [implode(' AND ', $sqlParts), $parameters];
521
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
522
+			$sqlParts = [];
523
+			$parameters = [];
524
+			$dbRows = $filter_bag->_getDbRows();
525
+			$dbRow = reset($dbRows);
526
+			$primaryKeys = $dbRow->_getPrimaryKeys();
527
+
528
+			foreach ($primaryKeys as $column => $value) {
529
+				$paramName = 'tdbmparam'.$counter;
530
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
531
+				$parameters[$paramName] = $value;
532
+				++$counter;
533
+			}
534
+
535
+			return [implode(' AND ', $sqlParts), $parameters];
536
+		} elseif ($filter_bag instanceof \Iterator) {
537
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
538
+		} else {
539
+			throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
540
+		}
541
+	}
542
+
543
+	/**
544
+	 * @param string $table
545
+	 *
546
+	 * @return string[]
547
+	 */
548
+	public function getPrimaryKeyColumns($table)
549
+	{
550
+		if (!isset($this->primaryKeysColumns[$table])) {
551
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
552
+
553
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
554
+
555
+			/*$arr = array();
556 556
             foreach ($this->connection->getPrimaryKey($table) as $col) {
557 557
                 $arr[] = $col->name;
558 558
             }
@@ -573,141 +573,141 @@  discard block
 block discarded – undo
573 573
                     throw new TDBMException($str);
574 574
                 }
575 575
             }*/
576
-        }
577
-
578
-        return $this->primaryKeysColumns[$table];
579
-    }
580
-
581
-    /**
582
-     * This is an internal function, you should not use it in your application.
583
-     * This is used internally by TDBM to add an object to the object cache.
584
-     *
585
-     * @param DbRow $dbRow
586
-     */
587
-    public function _addToCache(DbRow $dbRow)
588
-    {
589
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
590
-        $hash = $this->getObjectHash($primaryKey);
591
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
592
-    }
593
-
594
-    /**
595
-     * This is an internal function, you should not use it in your application.
596
-     * This is used internally by TDBM to remove the object from the list of objects that have been
597
-     * created/updated but not saved yet.
598
-     *
599
-     * @param DbRow $myObject
600
-     */
601
-    private function removeFromToSaveObjectList(DbRow $myObject)
602
-    {
603
-        unset($this->toSaveObjects[$myObject]);
604
-    }
605
-
606
-    /**
607
-     * This is an internal function, you should not use it in your application.
608
-     * This is used internally by TDBM to add an object to the list of objects that have been
609
-     * created/updated but not saved yet.
610
-     *
611
-     * @param AbstractTDBMObject $myObject
612
-     */
613
-    public function _addToToSaveObjectList(DbRow $myObject)
614
-    {
615
-        $this->toSaveObjects[$myObject] = true;
616
-    }
617
-
618
-    /**
619
-     * Generates all the daos and beans.
620
-     *
621
-     * @param string $daoFactoryClassName The classe name of the DAO factory
622
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
623
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
624
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
625
-     * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
626
-     *
627
-     * @return \string[] the list of tables
628
-     */
629
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
630
-    {
631
-        // Purge cache before generating anything.
632
-        $this->cache->deleteAll();
633
-
634
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
635
-        if (null !== $composerFile) {
636
-            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
637
-        }
638
-
639
-        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
640
-    }
641
-
642
-    /**
643
-     * @param array<string, string> $tableToBeanMap
644
-     */
645
-    public function setTableToBeanMap(array $tableToBeanMap)
646
-    {
647
-        $this->tableToBeanMap = $tableToBeanMap;
648
-    }
649
-
650
-    /**
651
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
652
-     *
653
-     * @param AbstractTDBMObject $object
654
-     *
655
-     * @throws TDBMException
656
-     */
657
-    public function save(AbstractTDBMObject $object)
658
-    {
659
-        $status = $object->_getStatus();
660
-
661
-        if ($status === null) {
662
-            throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
663
-        }
664
-
665
-        // Let's attach this object if it is in detached state.
666
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
667
-            $object->_attach($this);
668
-            $status = $object->_getStatus();
669
-        }
670
-
671
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
672
-            $dbRows = $object->_getDbRows();
673
-
674
-            $unindexedPrimaryKeys = array();
675
-
676
-            foreach ($dbRows as $dbRow) {
677
-                $tableName = $dbRow->_getDbTableName();
678
-
679
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
680
-                $tableDescriptor = $schema->getTable($tableName);
681
-
682
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
683
-
684
-                if (empty($unindexedPrimaryKeys)) {
685
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
686
-                } else {
687
-                    // First insert, the children must have the same primary key as the parent.
688
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
689
-                    $dbRow->_setPrimaryKeys($primaryKeys);
690
-                }
691
-
692
-                $references = $dbRow->_getReferences();
693
-
694
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
695
-                foreach ($references as $fkName => $reference) {
696
-                    if ($reference !== null) {
697
-                        $refStatus = $reference->_getStatus();
698
-                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
699
-                            $this->save($reference);
700
-                        }
701
-                    }
702
-                }
703
-
704
-                $dbRowData = $dbRow->_getDbRow();
705
-
706
-                // Let's see if the columns for primary key have been set before inserting.
707
-                // We assume that if one of the value of the PK has been set, the PK is set.
708
-                $isPkSet = !empty($primaryKeys);
709
-
710
-                /*if (!$isPkSet) {
576
+		}
577
+
578
+		return $this->primaryKeysColumns[$table];
579
+	}
580
+
581
+	/**
582
+	 * This is an internal function, you should not use it in your application.
583
+	 * This is used internally by TDBM to add an object to the object cache.
584
+	 *
585
+	 * @param DbRow $dbRow
586
+	 */
587
+	public function _addToCache(DbRow $dbRow)
588
+	{
589
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
590
+		$hash = $this->getObjectHash($primaryKey);
591
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
592
+	}
593
+
594
+	/**
595
+	 * This is an internal function, you should not use it in your application.
596
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
597
+	 * created/updated but not saved yet.
598
+	 *
599
+	 * @param DbRow $myObject
600
+	 */
601
+	private function removeFromToSaveObjectList(DbRow $myObject)
602
+	{
603
+		unset($this->toSaveObjects[$myObject]);
604
+	}
605
+
606
+	/**
607
+	 * This is an internal function, you should not use it in your application.
608
+	 * This is used internally by TDBM to add an object to the list of objects that have been
609
+	 * created/updated but not saved yet.
610
+	 *
611
+	 * @param AbstractTDBMObject $myObject
612
+	 */
613
+	public function _addToToSaveObjectList(DbRow $myObject)
614
+	{
615
+		$this->toSaveObjects[$myObject] = true;
616
+	}
617
+
618
+	/**
619
+	 * Generates all the daos and beans.
620
+	 *
621
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
622
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
623
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
624
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
625
+	 * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
626
+	 *
627
+	 * @return \string[] the list of tables
628
+	 */
629
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
630
+	{
631
+		// Purge cache before generating anything.
632
+		$this->cache->deleteAll();
633
+
634
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
635
+		if (null !== $composerFile) {
636
+			$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
637
+		}
638
+
639
+		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
640
+	}
641
+
642
+	/**
643
+	 * @param array<string, string> $tableToBeanMap
644
+	 */
645
+	public function setTableToBeanMap(array $tableToBeanMap)
646
+	{
647
+		$this->tableToBeanMap = $tableToBeanMap;
648
+	}
649
+
650
+	/**
651
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
652
+	 *
653
+	 * @param AbstractTDBMObject $object
654
+	 *
655
+	 * @throws TDBMException
656
+	 */
657
+	public function save(AbstractTDBMObject $object)
658
+	{
659
+		$status = $object->_getStatus();
660
+
661
+		if ($status === null) {
662
+			throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
663
+		}
664
+
665
+		// Let's attach this object if it is in detached state.
666
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
667
+			$object->_attach($this);
668
+			$status = $object->_getStatus();
669
+		}
670
+
671
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
672
+			$dbRows = $object->_getDbRows();
673
+
674
+			$unindexedPrimaryKeys = array();
675
+
676
+			foreach ($dbRows as $dbRow) {
677
+				$tableName = $dbRow->_getDbTableName();
678
+
679
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
680
+				$tableDescriptor = $schema->getTable($tableName);
681
+
682
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
683
+
684
+				if (empty($unindexedPrimaryKeys)) {
685
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
686
+				} else {
687
+					// First insert, the children must have the same primary key as the parent.
688
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
689
+					$dbRow->_setPrimaryKeys($primaryKeys);
690
+				}
691
+
692
+				$references = $dbRow->_getReferences();
693
+
694
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
695
+				foreach ($references as $fkName => $reference) {
696
+					if ($reference !== null) {
697
+						$refStatus = $reference->_getStatus();
698
+						if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
699
+							$this->save($reference);
700
+						}
701
+					}
702
+				}
703
+
704
+				$dbRowData = $dbRow->_getDbRow();
705
+
706
+				// Let's see if the columns for primary key have been set before inserting.
707
+				// We assume that if one of the value of the PK has been set, the PK is set.
708
+				$isPkSet = !empty($primaryKeys);
709
+
710
+				/*if (!$isPkSet) {
711 711
                     // if there is no autoincrement and no pk set, let's go in error.
712 712
                     $isAutoIncrement = true;
713 713
 
@@ -725,27 +725,27 @@  discard block
 block discarded – undo
725 725
 
726 726
                 }*/
727 727
 
728
-                $types = [];
729
-                $escapedDbRowData = [];
728
+				$types = [];
729
+				$escapedDbRowData = [];
730 730
 
731
-                foreach ($dbRowData as $columnName => $value) {
732
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
733
-                    $types[] = $columnDescriptor->getType();
734
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
735
-                }
731
+				foreach ($dbRowData as $columnName => $value) {
732
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
733
+					$types[] = $columnDescriptor->getType();
734
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
735
+				}
736 736
 
737
-                $this->connection->insert($tableName, $escapedDbRowData, $types);
737
+				$this->connection->insert($tableName, $escapedDbRowData, $types);
738 738
 
739
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
740
-                    $id = $this->connection->lastInsertId();
741
-                    $primaryKeys[$primaryKeyColumns[0]] = $id;
742
-                }
739
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
740
+					$id = $this->connection->lastInsertId();
741
+					$primaryKeys[$primaryKeyColumns[0]] = $id;
742
+				}
743 743
 
744
-                // TODO: change this to some private magic accessor in future
745
-                $dbRow->_setPrimaryKeys($primaryKeys);
746
-                $unindexedPrimaryKeys = array_values($primaryKeys);
744
+				// TODO: change this to some private magic accessor in future
745
+				$dbRow->_setPrimaryKeys($primaryKeys);
746
+				$unindexedPrimaryKeys = array_values($primaryKeys);
747 747
 
748
-                /*
748
+				/*
749 749
                  * When attached, on "save", we check if the column updated is part of a primary key
750 750
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
751 751
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
                  *
756 756
                  */
757 757
 
758
-                /*try {
758
+				/*try {
759 759
                     $this->db_connection->exec($sql);
760 760
                 } catch (TDBMException $e) {
761 761
                     $this->db_onerror = true;
@@ -774,468 +774,468 @@  discard block
 block discarded – undo
774 774
                     }
775 775
                 }*/
776 776
 
777
-                // Let's remove this object from the $new_objects static table.
778
-                $this->removeFromToSaveObjectList($dbRow);
779
-
780
-                // TODO: change this behaviour to something more sensible performance-wise
781
-                // Maybe a setting to trigger this globally?
782
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
783
-                //$this->db_modified_state = false;
784
-                //$dbRow = array();
785
-
786
-                // Let's add this object to the list of objects in cache.
787
-                $this->_addToCache($dbRow);
788
-            }
789
-
790
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
791
-        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
792
-            $dbRows = $object->_getDbRows();
793
-
794
-            foreach ($dbRows as $dbRow) {
795
-                $references = $dbRow->_getReferences();
796
-
797
-                // Let's save all references in NEW state (we need their primary key)
798
-                foreach ($references as $fkName => $reference) {
799
-                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
800
-                        $this->save($reference);
801
-                    }
802
-                }
803
-
804
-                // Let's first get the primary keys
805
-                $tableName = $dbRow->_getDbTableName();
806
-                $dbRowData = $dbRow->_getDbRow();
807
-
808
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
809
-                $tableDescriptor = $schema->getTable($tableName);
810
-
811
-                $primaryKeys = $dbRow->_getPrimaryKeys();
812
-
813
-                $types = [];
814
-                $escapedDbRowData = [];
815
-                $escapedPrimaryKeys = [];
816
-
817
-                foreach ($dbRowData as $columnName => $value) {
818
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
819
-                    $types[] = $columnDescriptor->getType();
820
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
821
-                }
822
-                foreach ($primaryKeys as $columnName => $value) {
823
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
824
-                    $types[] = $columnDescriptor->getType();
825
-                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
826
-                }
827
-
828
-                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
829
-
830
-                // Let's check if the primary key has been updated...
831
-                $needsUpdatePk = false;
832
-                foreach ($primaryKeys as $column => $value) {
833
-                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
834
-                        $needsUpdatePk = true;
835
-                        break;
836
-                    }
837
-                }
838
-                if ($needsUpdatePk) {
839
-                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
840
-                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
841
-                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
842
-                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
843
-                }
844
-
845
-                // Let's remove this object from the list of objects to save.
846
-                $this->removeFromToSaveObjectList($dbRow);
847
-            }
848
-
849
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
850
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
851
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
852
-        }
853
-
854
-        // Finally, let's save all the many to many relationships to this bean.
855
-        $this->persistManyToManyRelationships($object);
856
-    }
857
-
858
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
859
-    {
860
-        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
861
-            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
862
-            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
863
-
864
-            $toRemoveFromStorage = [];
865
-
866
-            foreach ($storage as $remoteBean) {
867
-                /* @var $remoteBean AbstractTDBMObject */
868
-                $statusArr = $storage[$remoteBean];
869
-                $status = $statusArr['status'];
870
-                $reverse = $statusArr['reverse'];
871
-                if ($reverse) {
872
-                    continue;
873
-                }
874
-
875
-                if ($status === 'new') {
876
-                    $remoteBeanStatus = $remoteBean->_getStatus();
877
-                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
878
-                        // Let's save remote bean if needed.
879
-                        $this->save($remoteBean);
880
-                    }
881
-
882
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
883
-
884
-                    $types = [];
885
-                    $escapedFilters = [];
886
-
887
-                    foreach ($filters as $columnName => $value) {
888
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
889
-                        $types[] = $columnDescriptor->getType();
890
-                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
891
-                    }
892
-
893
-                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
894
-
895
-                    // Finally, let's mark relationships as saved.
896
-                    $statusArr['status'] = 'loaded';
897
-                    $storage[$remoteBean] = $statusArr;
898
-                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
899
-                    $remoteStatusArr = $remoteStorage[$object];
900
-                    $remoteStatusArr['status'] = 'loaded';
901
-                    $remoteStorage[$object] = $remoteStatusArr;
902
-                } elseif ($status === 'delete') {
903
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
904
-
905
-                    $types = [];
906
-
907
-                    foreach ($filters as $columnName => $value) {
908
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
909
-                        $types[] = $columnDescriptor->getType();
910
-                    }
911
-
912
-                    $this->connection->delete($pivotTableName, $filters, $types);
913
-
914
-                    // Finally, let's remove relationships completely from bean.
915
-                    $toRemoveFromStorage[] = $remoteBean;
916
-
917
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
918
-                }
919
-            }
920
-
921
-            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
922
-            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
923
-            foreach ($toRemoveFromStorage as $remoteBean) {
924
-                $storage->detach($remoteBean);
925
-            }
926
-        }
927
-    }
928
-
929
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
930
-    {
931
-        $localBeanPk = $this->getPrimaryKeyValues($localBean);
932
-        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
933
-        $localColumns = $localFk->getLocalColumns();
934
-        $remoteColumns = $remoteFk->getLocalColumns();
935
-
936
-        $localFilters = array_combine($localColumns, $localBeanPk);
937
-        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
938
-
939
-        return array_merge($localFilters, $remoteFilters);
940
-    }
941
-
942
-    /**
943
-     * Returns the "values" of the primary key.
944
-     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
945
-     *
946
-     * @param AbstractTDBMObject $bean
947
-     *
948
-     * @return array numerically indexed array of values
949
-     */
950
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
951
-    {
952
-        $dbRows = $bean->_getDbRows();
953
-        $dbRow = reset($dbRows);
954
-
955
-        return array_values($dbRow->_getPrimaryKeys());
956
-    }
957
-
958
-    /**
959
-     * Returns a unique hash used to store the object based on its primary key.
960
-     * If the array contains only one value, then the value is returned.
961
-     * Otherwise, a hash representing the array is returned.
962
-     *
963
-     * @param array $primaryKeys An array of columns => values forming the primary key
964
-     *
965
-     * @return string
966
-     */
967
-    public function getObjectHash(array $primaryKeys)
968
-    {
969
-        if (count($primaryKeys) === 1) {
970
-            return reset($primaryKeys);
971
-        } else {
972
-            ksort($primaryKeys);
973
-
974
-            return md5(json_encode($primaryKeys));
975
-        }
976
-    }
977
-
978
-    /**
979
-     * Returns an array of primary keys from the object.
980
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
981
-     * $primaryKeys variable of the object.
982
-     *
983
-     * @param DbRow $dbRow
984
-     *
985
-     * @return array Returns an array of column => value
986
-     */
987
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
988
-    {
989
-        $table = $dbRow->_getDbTableName();
990
-        $dbRowData = $dbRow->_getDbRow();
991
-
992
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
993
-    }
994
-
995
-    /**
996
-     * Returns an array of primary keys for the given row.
997
-     * The primary keys are extracted from the object columns.
998
-     *
999
-     * @param $table
1000
-     * @param array $columns
1001
-     *
1002
-     * @return array
1003
-     */
1004
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
1005
-    {
1006
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1007
-        $values = array();
1008
-        foreach ($primaryKeyColumns as $column) {
1009
-            if (isset($columns[$column])) {
1010
-                $values[$column] = $columns[$column];
1011
-            }
1012
-        }
1013
-
1014
-        return $values;
1015
-    }
1016
-
1017
-    /**
1018
-     * Attaches $object to this TDBMService.
1019
-     * The $object must be in DETACHED state and will pass in NEW state.
1020
-     *
1021
-     * @param AbstractTDBMObject $object
1022
-     *
1023
-     * @throws TDBMInvalidOperationException
1024
-     */
1025
-    public function attach(AbstractTDBMObject $object)
1026
-    {
1027
-        $object->_attach($this);
1028
-    }
1029
-
1030
-    /**
1031
-     * Returns an associative array (column => value) for the primary keys from the table name and an
1032
-     * indexed array of primary key values.
1033
-     *
1034
-     * @param string $tableName
1035
-     * @param array  $indexedPrimaryKeys
1036
-     */
1037
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1038
-    {
1039
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1040
-
1041
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1042
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
777
+				// Let's remove this object from the $new_objects static table.
778
+				$this->removeFromToSaveObjectList($dbRow);
779
+
780
+				// TODO: change this behaviour to something more sensible performance-wise
781
+				// Maybe a setting to trigger this globally?
782
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
783
+				//$this->db_modified_state = false;
784
+				//$dbRow = array();
785
+
786
+				// Let's add this object to the list of objects in cache.
787
+				$this->_addToCache($dbRow);
788
+			}
789
+
790
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
791
+		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
792
+			$dbRows = $object->_getDbRows();
793
+
794
+			foreach ($dbRows as $dbRow) {
795
+				$references = $dbRow->_getReferences();
796
+
797
+				// Let's save all references in NEW state (we need their primary key)
798
+				foreach ($references as $fkName => $reference) {
799
+					if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
800
+						$this->save($reference);
801
+					}
802
+				}
803
+
804
+				// Let's first get the primary keys
805
+				$tableName = $dbRow->_getDbTableName();
806
+				$dbRowData = $dbRow->_getDbRow();
807
+
808
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
809
+				$tableDescriptor = $schema->getTable($tableName);
810
+
811
+				$primaryKeys = $dbRow->_getPrimaryKeys();
812
+
813
+				$types = [];
814
+				$escapedDbRowData = [];
815
+				$escapedPrimaryKeys = [];
816
+
817
+				foreach ($dbRowData as $columnName => $value) {
818
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
819
+					$types[] = $columnDescriptor->getType();
820
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
821
+				}
822
+				foreach ($primaryKeys as $columnName => $value) {
823
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
824
+					$types[] = $columnDescriptor->getType();
825
+					$escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
826
+				}
827
+
828
+				$this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
829
+
830
+				// Let's check if the primary key has been updated...
831
+				$needsUpdatePk = false;
832
+				foreach ($primaryKeys as $column => $value) {
833
+					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
834
+						$needsUpdatePk = true;
835
+						break;
836
+					}
837
+				}
838
+				if ($needsUpdatePk) {
839
+					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
840
+					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
841
+					$dbRow->_setPrimaryKeys($newPrimaryKeys);
842
+					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
843
+				}
844
+
845
+				// Let's remove this object from the list of objects to save.
846
+				$this->removeFromToSaveObjectList($dbRow);
847
+			}
848
+
849
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
850
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
851
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
852
+		}
853
+
854
+		// Finally, let's save all the many to many relationships to this bean.
855
+		$this->persistManyToManyRelationships($object);
856
+	}
857
+
858
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
859
+	{
860
+		foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
861
+			$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
862
+			list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
863
+
864
+			$toRemoveFromStorage = [];
865
+
866
+			foreach ($storage as $remoteBean) {
867
+				/* @var $remoteBean AbstractTDBMObject */
868
+				$statusArr = $storage[$remoteBean];
869
+				$status = $statusArr['status'];
870
+				$reverse = $statusArr['reverse'];
871
+				if ($reverse) {
872
+					continue;
873
+				}
874
+
875
+				if ($status === 'new') {
876
+					$remoteBeanStatus = $remoteBean->_getStatus();
877
+					if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
878
+						// Let's save remote bean if needed.
879
+						$this->save($remoteBean);
880
+					}
881
+
882
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
883
+
884
+					$types = [];
885
+					$escapedFilters = [];
886
+
887
+					foreach ($filters as $columnName => $value) {
888
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
889
+						$types[] = $columnDescriptor->getType();
890
+						$escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
891
+					}
892
+
893
+					$this->connection->insert($pivotTableName, $escapedFilters, $types);
894
+
895
+					// Finally, let's mark relationships as saved.
896
+					$statusArr['status'] = 'loaded';
897
+					$storage[$remoteBean] = $statusArr;
898
+					$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
899
+					$remoteStatusArr = $remoteStorage[$object];
900
+					$remoteStatusArr['status'] = 'loaded';
901
+					$remoteStorage[$object] = $remoteStatusArr;
902
+				} elseif ($status === 'delete') {
903
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
904
+
905
+					$types = [];
906
+
907
+					foreach ($filters as $columnName => $value) {
908
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
909
+						$types[] = $columnDescriptor->getType();
910
+					}
911
+
912
+					$this->connection->delete($pivotTableName, $filters, $types);
913
+
914
+					// Finally, let's remove relationships completely from bean.
915
+					$toRemoveFromStorage[] = $remoteBean;
916
+
917
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
918
+				}
919
+			}
920
+
921
+			// Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
922
+			// Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
923
+			foreach ($toRemoveFromStorage as $remoteBean) {
924
+				$storage->detach($remoteBean);
925
+			}
926
+		}
927
+	}
928
+
929
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
930
+	{
931
+		$localBeanPk = $this->getPrimaryKeyValues($localBean);
932
+		$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
933
+		$localColumns = $localFk->getLocalColumns();
934
+		$remoteColumns = $remoteFk->getLocalColumns();
935
+
936
+		$localFilters = array_combine($localColumns, $localBeanPk);
937
+		$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
938
+
939
+		return array_merge($localFilters, $remoteFilters);
940
+	}
941
+
942
+	/**
943
+	 * Returns the "values" of the primary key.
944
+	 * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
945
+	 *
946
+	 * @param AbstractTDBMObject $bean
947
+	 *
948
+	 * @return array numerically indexed array of values
949
+	 */
950
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
951
+	{
952
+		$dbRows = $bean->_getDbRows();
953
+		$dbRow = reset($dbRows);
954
+
955
+		return array_values($dbRow->_getPrimaryKeys());
956
+	}
957
+
958
+	/**
959
+	 * Returns a unique hash used to store the object based on its primary key.
960
+	 * If the array contains only one value, then the value is returned.
961
+	 * Otherwise, a hash representing the array is returned.
962
+	 *
963
+	 * @param array $primaryKeys An array of columns => values forming the primary key
964
+	 *
965
+	 * @return string
966
+	 */
967
+	public function getObjectHash(array $primaryKeys)
968
+	{
969
+		if (count($primaryKeys) === 1) {
970
+			return reset($primaryKeys);
971
+		} else {
972
+			ksort($primaryKeys);
973
+
974
+			return md5(json_encode($primaryKeys));
975
+		}
976
+	}
977
+
978
+	/**
979
+	 * Returns an array of primary keys from the object.
980
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
981
+	 * $primaryKeys variable of the object.
982
+	 *
983
+	 * @param DbRow $dbRow
984
+	 *
985
+	 * @return array Returns an array of column => value
986
+	 */
987
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
988
+	{
989
+		$table = $dbRow->_getDbTableName();
990
+		$dbRowData = $dbRow->_getDbRow();
991
+
992
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
993
+	}
994
+
995
+	/**
996
+	 * Returns an array of primary keys for the given row.
997
+	 * The primary keys are extracted from the object columns.
998
+	 *
999
+	 * @param $table
1000
+	 * @param array $columns
1001
+	 *
1002
+	 * @return array
1003
+	 */
1004
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
1005
+	{
1006
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1007
+		$values = array();
1008
+		foreach ($primaryKeyColumns as $column) {
1009
+			if (isset($columns[$column])) {
1010
+				$values[$column] = $columns[$column];
1011
+			}
1012
+		}
1013
+
1014
+		return $values;
1015
+	}
1016
+
1017
+	/**
1018
+	 * Attaches $object to this TDBMService.
1019
+	 * The $object must be in DETACHED state and will pass in NEW state.
1020
+	 *
1021
+	 * @param AbstractTDBMObject $object
1022
+	 *
1023
+	 * @throws TDBMInvalidOperationException
1024
+	 */
1025
+	public function attach(AbstractTDBMObject $object)
1026
+	{
1027
+		$object->_attach($this);
1028
+	}
1029
+
1030
+	/**
1031
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
1032
+	 * indexed array of primary key values.
1033
+	 *
1034
+	 * @param string $tableName
1035
+	 * @param array  $indexedPrimaryKeys
1036
+	 */
1037
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1038
+	{
1039
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1040
+
1041
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1042
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1043 1043
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1044
-        }
1045
-
1046
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1047
-    }
1048
-
1049
-    /**
1050
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1051
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1052
-     *
1053
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1054
-     * we must be able to find all other tables.
1055
-     *
1056
-     * @param string[] $tables
1057
-     *
1058
-     * @return string[]
1059
-     */
1060
-    public function _getLinkBetweenInheritedTables(array $tables)
1061
-    {
1062
-        sort($tables);
1063
-
1064
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1065
-            function () use ($tables) {
1066
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1067
-            });
1068
-    }
1069
-
1070
-    /**
1071
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1072
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1073
-     *
1074
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1075
-     * we must be able to find all other tables.
1076
-     *
1077
-     * @param string[] $tables
1078
-     *
1079
-     * @return string[]
1080
-     */
1081
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1082
-    {
1083
-        $schemaAnalyzer = $this->schemaAnalyzer;
1084
-
1085
-        foreach ($tables as $currentTable) {
1086
-            $allParents = [$currentTable];
1087
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1088
-                $currentTable = $currentFk->getForeignTableName();
1089
-                $allParents[] = $currentTable;
1090
-            }
1091
-
1092
-            // Now, does the $allParents contain all the tables we want?
1093
-            $notFoundTables = array_diff($tables, $allParents);
1094
-            if (empty($notFoundTables)) {
1095
-                // We have a winner!
1096
-                return $allParents;
1097
-            }
1098
-        }
1099
-
1100
-        throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1101
-    }
1102
-
1103
-    /**
1104
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1105
-     *
1106
-     * @param string $table
1107
-     *
1108
-     * @return string[]
1109
-     */
1110
-    public function _getRelatedTablesByInheritance($table)
1111
-    {
1112
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1113
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1114
-        });
1115
-    }
1116
-
1117
-    /**
1118
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1119
-     *
1120
-     * @param string $table
1121
-     *
1122
-     * @return string[]
1123
-     */
1124
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1125
-    {
1126
-        $schemaAnalyzer = $this->schemaAnalyzer;
1127
-
1128
-        // Let's scan the parent tables
1129
-        $currentTable = $table;
1130
-
1131
-        $parentTables = [];
1132
-
1133
-        // Get parent relationship
1134
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1135
-            $currentTable = $currentFk->getForeignTableName();
1136
-            $parentTables[] = $currentTable;
1137
-        }
1138
-
1139
-        // Let's recurse in children
1140
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1141
-
1142
-        return array_merge(array_reverse($parentTables), $childrenTables);
1143
-    }
1144
-
1145
-    /**
1146
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1147
-     *
1148
-     * @param string $table
1149
-     *
1150
-     * @return string[]
1151
-     */
1152
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1153
-    {
1154
-        $tables = [$table];
1155
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1156
-
1157
-        foreach ($keys as $key) {
1158
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1159
-        }
1160
-
1161
-        return $tables;
1162
-    }
1163
-
1164
-    /**
1165
-     * @param string $tableName
1166
-     *
1167
-     * @return ForeignKeyConstraint[]
1168
-     */
1169
-    private function getParentRelationshipForeignKeys($tableName)
1170
-    {
1171
-        return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
1172
-            return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
1173
-        });
1174
-    }
1175
-
1176
-    /**
1177
-     * @param string $tableName
1178
-     *
1179
-     * @return ForeignKeyConstraint[]
1180
-     */
1181
-    private function getParentRelationshipForeignKeysWithoutCache($tableName)
1182
-    {
1183
-        $parentFks = [];
1184
-        $currentTable = $tableName;
1185
-        while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
1186
-            $currentTable = $currentFk->getForeignTableName();
1187
-            $parentFks[] = $currentFk;
1188
-        }
1189
-
1190
-        return $parentFks;
1191
-    }
1192
-
1193
-    /**
1194
-     * @param string $tableName
1195
-     *
1196
-     * @return ForeignKeyConstraint[]
1197
-     */
1198
-    private function getChildrenRelationshipForeignKeys($tableName)
1199
-    {
1200
-        return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
1201
-            return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
1202
-        });
1203
-    }
1204
-
1205
-    /**
1206
-     * @param string $tableName
1207
-     *
1208
-     * @return ForeignKeyConstraint[]
1209
-     */
1210
-    private function getChildrenRelationshipForeignKeysWithoutCache($tableName)
1211
-    {
1212
-        $children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
1213
-
1214
-        if (!empty($children)) {
1215
-            $fksTables = array_map(function (ForeignKeyConstraint $fk) {
1216
-                return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
1217
-            }, $children);
1218
-
1219
-            $fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
1220
-
1221
-            return $fks;
1222
-        } else {
1223
-            return [];
1224
-        }
1225
-    }
1226
-
1227
-    /**
1228
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1229
-     * The returned value does contain only one table. For instance:.
1230
-     *
1231
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1232
-     *
1233
-     * @param ForeignKeyConstraint $fk
1234
-     * @param bool                 $leftTableIsLocal
1235
-     *
1236
-     * @return string
1237
-     */
1238
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1044
+		}
1045
+
1046
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1047
+	}
1048
+
1049
+	/**
1050
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1051
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1052
+	 *
1053
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1054
+	 * we must be able to find all other tables.
1055
+	 *
1056
+	 * @param string[] $tables
1057
+	 *
1058
+	 * @return string[]
1059
+	 */
1060
+	public function _getLinkBetweenInheritedTables(array $tables)
1061
+	{
1062
+		sort($tables);
1063
+
1064
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1065
+			function () use ($tables) {
1066
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1067
+			});
1068
+	}
1069
+
1070
+	/**
1071
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1072
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1073
+	 *
1074
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1075
+	 * we must be able to find all other tables.
1076
+	 *
1077
+	 * @param string[] $tables
1078
+	 *
1079
+	 * @return string[]
1080
+	 */
1081
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1082
+	{
1083
+		$schemaAnalyzer = $this->schemaAnalyzer;
1084
+
1085
+		foreach ($tables as $currentTable) {
1086
+			$allParents = [$currentTable];
1087
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1088
+				$currentTable = $currentFk->getForeignTableName();
1089
+				$allParents[] = $currentTable;
1090
+			}
1091
+
1092
+			// Now, does the $allParents contain all the tables we want?
1093
+			$notFoundTables = array_diff($tables, $allParents);
1094
+			if (empty($notFoundTables)) {
1095
+				// We have a winner!
1096
+				return $allParents;
1097
+			}
1098
+		}
1099
+
1100
+		throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1101
+	}
1102
+
1103
+	/**
1104
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1105
+	 *
1106
+	 * @param string $table
1107
+	 *
1108
+	 * @return string[]
1109
+	 */
1110
+	public function _getRelatedTablesByInheritance($table)
1111
+	{
1112
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1113
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1114
+		});
1115
+	}
1116
+
1117
+	/**
1118
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1119
+	 *
1120
+	 * @param string $table
1121
+	 *
1122
+	 * @return string[]
1123
+	 */
1124
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1125
+	{
1126
+		$schemaAnalyzer = $this->schemaAnalyzer;
1127
+
1128
+		// Let's scan the parent tables
1129
+		$currentTable = $table;
1130
+
1131
+		$parentTables = [];
1132
+
1133
+		// Get parent relationship
1134
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1135
+			$currentTable = $currentFk->getForeignTableName();
1136
+			$parentTables[] = $currentTable;
1137
+		}
1138
+
1139
+		// Let's recurse in children
1140
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1141
+
1142
+		return array_merge(array_reverse($parentTables), $childrenTables);
1143
+	}
1144
+
1145
+	/**
1146
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1147
+	 *
1148
+	 * @param string $table
1149
+	 *
1150
+	 * @return string[]
1151
+	 */
1152
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1153
+	{
1154
+		$tables = [$table];
1155
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1156
+
1157
+		foreach ($keys as $key) {
1158
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1159
+		}
1160
+
1161
+		return $tables;
1162
+	}
1163
+
1164
+	/**
1165
+	 * @param string $tableName
1166
+	 *
1167
+	 * @return ForeignKeyConstraint[]
1168
+	 */
1169
+	private function getParentRelationshipForeignKeys($tableName)
1170
+	{
1171
+		return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
1172
+			return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
1173
+		});
1174
+	}
1175
+
1176
+	/**
1177
+	 * @param string $tableName
1178
+	 *
1179
+	 * @return ForeignKeyConstraint[]
1180
+	 */
1181
+	private function getParentRelationshipForeignKeysWithoutCache($tableName)
1182
+	{
1183
+		$parentFks = [];
1184
+		$currentTable = $tableName;
1185
+		while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
1186
+			$currentTable = $currentFk->getForeignTableName();
1187
+			$parentFks[] = $currentFk;
1188
+		}
1189
+
1190
+		return $parentFks;
1191
+	}
1192
+
1193
+	/**
1194
+	 * @param string $tableName
1195
+	 *
1196
+	 * @return ForeignKeyConstraint[]
1197
+	 */
1198
+	private function getChildrenRelationshipForeignKeys($tableName)
1199
+	{
1200
+		return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
1201
+			return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
1202
+		});
1203
+	}
1204
+
1205
+	/**
1206
+	 * @param string $tableName
1207
+	 *
1208
+	 * @return ForeignKeyConstraint[]
1209
+	 */
1210
+	private function getChildrenRelationshipForeignKeysWithoutCache($tableName)
1211
+	{
1212
+		$children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
1213
+
1214
+		if (!empty($children)) {
1215
+			$fksTables = array_map(function (ForeignKeyConstraint $fk) {
1216
+				return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
1217
+			}, $children);
1218
+
1219
+			$fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
1220
+
1221
+			return $fks;
1222
+		} else {
1223
+			return [];
1224
+		}
1225
+	}
1226
+
1227
+	/**
1228
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1229
+	 * The returned value does contain only one table. For instance:.
1230
+	 *
1231
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1232
+	 *
1233
+	 * @param ForeignKeyConstraint $fk
1234
+	 * @param bool                 $leftTableIsLocal
1235
+	 *
1236
+	 * @return string
1237
+	 */
1238
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1239 1239
         $onClauses = [];
1240 1240
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1241 1241
         $foreignColumns = $fk->getForeignColumns();
@@ -1261,603 +1261,603 @@  discard block
 block discarded – undo
1261 1261
         }
1262 1262
     }*/
1263 1263
 
1264
-    /**
1265
-     * Returns an identifier for the group of tables passed in parameter.
1266
-     *
1267
-     * @param string[] $relatedTables
1268
-     *
1269
-     * @return string
1270
-     */
1271
-    private function getTableGroupName(array $relatedTables)
1272
-    {
1273
-        sort($relatedTables);
1274
-
1275
-        return implode('_``_', $relatedTables);
1276
-    }
1277
-
1278
-    /**
1279
-     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1280
-     *
1281
-     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1282
-     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1283
-     *
1284
-     * The findObjects method takes in parameter:
1285
-     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1286
-     * 			`$mainTable` parameter should be the name of an existing table in database.
1287
-     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1288
-     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1289
-     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1290
-     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1291
-     *          Instead, please consider passing parameters (see documentation for more details).
1292
-     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1293
-     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1294
-     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1295
-     *
1296
-     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1297
-     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1298
-     *
1299
-     * Finally, if filter_bag is null, the whole table is returned.
1300
-     *
1301
-     * @param string            $mainTable             The name of the table queried
1302
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1303
-     * @param array             $parameters
1304
-     * @param string|null       $orderString           The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1305
-     * @param array             $additionalTablesFetch
1306
-     * @param int               $mode
1307
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1308
-     *
1309
-     * @return ResultIterator An object representing an array of results
1310
-     *
1311
-     * @throws TDBMException
1312
-     */
1313
-    public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null)
1314
-    {
1315
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1316
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1317
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1318
-        }
1319
-
1320
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1321
-
1322
-        $parameters = array_merge($parameters, $additionalParameters);
1323
-
1324
-        list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, $additionalTablesFetch, $orderString);
1325
-
1326
-        $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')';
1327
-
1328
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1329
-        $pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1330
-        $pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1331
-            return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1332
-        }, $pkColumnNames);
1333
-
1334
-        $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$mainTable.')';
1335
-
1336
-        if (!empty($filterString)) {
1337
-            $sql .= ' WHERE '.$filterString;
1338
-            $countSql .= ' WHERE '.$filterString;
1339
-        }
1340
-
1341
-        if (!empty($orderString)) {
1342
-            $sql .= ' ORDER BY '.$orderString;
1343
-        }
1344
-
1345
-        if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1346
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1347
-        }
1348
-
1349
-        $mode = $mode ?: $this->mode;
1350
-
1351
-        return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1352
-    }
1353
-
1354
-    /**
1355
-     * @param string            $mainTable   The name of the table queried
1356
-     * @param string            $from        The from sql statement
1357
-     * @param string|array|null $filter      The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1358
-     * @param array             $parameters
1359
-     * @param string|null       $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1360
-     * @param int               $mode
1361
-     * @param string            $className   Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1362
-     *
1363
-     * @return ResultIterator An object representing an array of results
1364
-     *
1365
-     * @throws TDBMException
1366
-     */
1367
-    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), string $orderString = null, $mode = null, string $className = null)
1368
-    {
1369
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1370
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1371
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1372
-        }
1373
-
1374
-        $columnsList = null;
1375
-
1376
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1377
-
1378
-        $parameters = array_merge($parameters, $additionalParameters);
1379
-
1380
-        $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1381
-
1382
-        $columnDescList = [];
1383
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1384
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
1385
-
1386
-        foreach ($schema->getTable($mainTable)->getColumns() as $column) {
1387
-            $columnName = $column->getName();
1388
-            $columnDescList[] = [
1389
-                'as' => $columnName,
1390
-                'table' => $mainTable,
1391
-                'column' => $columnName,
1392
-                'type' => $column->getType(),
1393
-                'tableGroup' => $tableGroupName,
1394
-            ];
1395
-        }
1396
-
1397
-        $sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) use ($mainTable) {
1398
-            return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($columnDesc['column']);
1399
-        }, $columnDescList)).' FROM '.$from;
1400
-
1401
-        if (count($allFetchedTables) > 1) {
1402
-            list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, [], $orderString);
1403
-        }
1404
-
1405
-        // Let's compute the COUNT.
1406
-        $pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1407
-        $pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1408
-            return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1409
-        }, $pkColumnNames);
1410
-
1411
-        $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$from;
1412
-
1413
-        if (!empty($filterString)) {
1414
-            $sql .= ' WHERE '.$filterString;
1415
-            $countSql .= ' WHERE '.$filterString;
1416
-        }
1417
-
1418
-        if (!empty($orderString)) {
1419
-            $sql .= ' ORDER BY '.$orderString;
1420
-            $countSql .= ' ORDER BY '.$orderString;
1421
-        }
1422
-
1423
-        if (stripos($countSql, 'GROUP BY') !== false) {
1424
-            throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
1425
-        }
1426
-
1427
-        if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1428
-            throw new TDBMException("Unknown fetch mode: '".$mode."'");
1429
-        }
1430
-
1431
-        if ($columnsList !== null) {
1432
-            $joinSql = '';
1433
-            $parentFks = $this->getParentRelationshipForeignKeys($mainTable);
1434
-            foreach ($parentFks as $fk) {
1435
-                $joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
1436
-                    $this->connection->quoteIdentifier($fk->getForeignTableName()),
1437
-                    $this->connection->quoteIdentifier($fk->getLocalTableName()),
1438
-                    $this->connection->quoteIdentifier($fk->getLocalColumns()[0]),
1439
-                    $this->connection->quoteIdentifier($fk->getForeignTableName()),
1440
-                    $this->connection->quoteIdentifier($fk->getForeignColumns()[0])
1441
-                    );
1442
-            }
1443
-
1444
-            $childrenFks = $this->getChildrenRelationshipForeignKeys($mainTable);
1445
-            foreach ($childrenFks as $fk) {
1446
-                $joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
1447
-                    $this->connection->quoteIdentifier($fk->getLocalTableName()),
1448
-                    $this->connection->quoteIdentifier($fk->getForeignTableName()),
1449
-                    $this->connection->quoteIdentifier($fk->getForeignColumns()[0]),
1450
-                    $this->connection->quoteIdentifier($fk->getLocalTableName()),
1451
-                    $this->connection->quoteIdentifier($fk->getLocalColumns()[0])
1452
-                );
1453
-            }
1454
-
1455
-            $sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$mainTable.' '.$joinSql;
1456
-        }
1457
-
1458
-        $mode = $mode ?: $this->mode;
1459
-
1460
-        return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1461
-    }
1462
-
1463
-    /**
1464
-     * Returns the column list that must be fetched for the SQL request.
1465
-     *
1466
-     * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
1467
-     *
1468
-     * @param string $mainTable
1469
-     * @param array  $additionalTablesFetch
1470
-     * @param string|null $orderBy
1471
-     *
1472
-     * @return array
1473
-     *
1474
-     * @throws \Doctrine\DBAL\Schema\SchemaException
1475
-     */
1476
-    private function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), string $orderBy = null)
1477
-    {
1478
-        // From the table name and the additional tables we want to fetch, let's build a list of all tables
1479
-        // that must be part of the select columns.
1480
-
1481
-        $tableGroups = [];
1482
-        $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1483
-        $tableGroupName = $this->getTableGroupName($allFetchedTables);
1484
-        foreach ($allFetchedTables as $table) {
1485
-            $tableGroups[$table] = $tableGroupName;
1486
-        }
1487
-
1488
-        $columnsList = [];
1489
-        $columnDescList = [];
1490
-        $sortColumn = 0;
1491
-
1492
-        // Now, let's deal with "order by columns"
1493
-        if ($orderBy !== null) {
1494
-            $orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
1495
-
1496
-            // If we sort by a column, there is a high chance we will fetch the bean containing this column.
1497
-            // Hence, we should add the table to the $additionalTablesFetch
1498
-            foreach ($orderByColumns as $orderByColumn) {
1499
-                if ($orderByColumn['type'] === 'colref' && $orderByColumn['table'] !== null) {
1500
-                    $additionalTablesFetch[] = $orderByColumn['table'];
1501
-                } elseif ($orderByColumn['type'] === 'expr') {
1502
-                    $sortColumnName = 'sort_column_'.$sortColumn;
1503
-                    $columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
1504
-                    $columnDescList[] = [
1505
-                        'tableGroup' => null
1506
-                    ];
1507
-                    $sortColumn++;
1508
-                }
1509
-            }
1510
-        }
1511
-
1512
-
1513
-        foreach ($additionalTablesFetch as $additionalTable) {
1514
-            $relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1515
-            $tableGroupName = $this->getTableGroupName($relatedTables);
1516
-            foreach ($relatedTables as $table) {
1517
-                $tableGroups[$table] = $tableGroupName;
1518
-            }
1519
-            $allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1520
-        }
1521
-
1522
-        // Let's remove any duplicate
1523
-        $allFetchedTables = array_flip(array_flip($allFetchedTables));
1524
-
1525
-        $schema = $this->tdbmSchemaAnalyzer->getSchema();
1526
-
1527
-        // Now, let's build the column list
1528
-        foreach ($allFetchedTables as $table) {
1529
-            foreach ($schema->getTable($table)->getColumns() as $column) {
1530
-                $columnName = $column->getName();
1531
-                $columnDescList[] = [
1532
-                    'as' => $table.'____'.$columnName,
1533
-                    'table' => $table,
1534
-                    'column' => $columnName,
1535
-                    'type' => $column->getType(),
1536
-                    'tableGroup' => $tableGroups[$table],
1537
-                ];
1538
-                $columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1539
-                    $this->connection->quoteIdentifier($table.'____'.$columnName);
1540
-            }
1541
-        }
1542
-
1543
-        return [$columnDescList, $columnsList];
1544
-    }
1545
-
1546
-    /**
1547
-     * @param $table
1548
-     * @param array  $primaryKeys
1549
-     * @param array  $additionalTablesFetch
1550
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1551
-     * @param string $className
1552
-     *
1553
-     * @return AbstractTDBMObject
1554
-     *
1555
-     * @throws TDBMException
1556
-     */
1557
-    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1558
-    {
1559
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1560
-        $hash = $this->getObjectHash($primaryKeys);
1561
-
1562
-        if ($this->objectStorage->has($table, $hash)) {
1563
-            $dbRow = $this->objectStorage->get($table, $hash);
1564
-            $bean = $dbRow->getTDBMObject();
1565
-            if ($className !== null && !is_a($bean, $className)) {
1566
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1567
-            }
1568
-
1569
-            return $bean;
1570
-        }
1571
-
1572
-        // Are we performing lazy fetching?
1573
-        if ($lazy === true) {
1574
-            // Can we perform lazy fetching?
1575
-            $tables = $this->_getRelatedTablesByInheritance($table);
1576
-            // Only allowed if no inheritance.
1577
-            if (count($tables) === 1) {
1578
-                if ($className === null) {
1579
-                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1580
-                }
1581
-
1582
-                // Let's construct the bean
1583
-                if (!isset($this->reflectionClassCache[$className])) {
1584
-                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1585
-                }
1586
-                // Let's bypass the constructor when creating the bean!
1587
-                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1588
-                /* @var $bean AbstractTDBMObject */
1589
-                $bean->_constructLazy($table, $primaryKeys, $this);
1590
-
1591
-                return $bean;
1592
-            }
1593
-        }
1594
-
1595
-        // Did not find the object in cache? Let's query it!
1596
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1597
-    }
1598
-
1599
-    /**
1600
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1601
-     *
1602
-     * @param string            $mainTable             The name of the table queried
1603
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1604
-     * @param array             $parameters
1605
-     * @param array             $additionalTablesFetch
1606
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1607
-     *
1608
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1609
-     *
1610
-     * @throws TDBMException
1611
-     */
1612
-    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1613
-    {
1614
-        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1615
-        $page = $objects->take(0, 2);
1616
-        $count = $page->count();
1617
-        if ($count > 1) {
1618
-            throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1619
-        } elseif ($count === 0) {
1620
-            return;
1621
-        }
1622
-
1623
-        return $page[0];
1624
-    }
1625
-
1626
-    /**
1627
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1628
-     *
1629
-     * @param string            $mainTable  The name of the table queried
1630
-     * @param string            $from       The from sql statement
1631
-     * @param string|array|null $filter     The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1632
-     * @param array             $parameters
1633
-     * @param string            $className  Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1634
-     *
1635
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1636
-     *
1637
-     * @throws TDBMException
1638
-     */
1639
-    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1640
-    {
1641
-        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1642
-        $page = $objects->take(0, 2);
1643
-        $count = $page->count();
1644
-        if ($count > 1) {
1645
-            throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1646
-        } elseif ($count === 0) {
1647
-            return;
1648
-        }
1649
-
1650
-        return $page[0];
1651
-    }
1652
-
1653
-    /**
1654
-     * Returns a unique bean according to the filters passed in parameter.
1655
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1656
-     *
1657
-     * @param string            $mainTable             The name of the table queried
1658
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1659
-     * @param array             $parameters
1660
-     * @param array             $additionalTablesFetch
1661
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1662
-     *
1663
-     * @return AbstractTDBMObject The object we want
1664
-     *
1665
-     * @throws TDBMException
1666
-     */
1667
-    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1668
-    {
1669
-        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1670
-        if ($bean === null) {
1671
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1672
-        }
1673
-
1674
-        return $bean;
1675
-    }
1676
-
1677
-    /**
1678
-     * @param array $beanData An array of data: array<table, array<column, value>>
1679
-     *
1680
-     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1681
-     */
1682
-    public function _getClassNameFromBeanData(array $beanData)
1683
-    {
1684
-        if (count($beanData) === 1) {
1685
-            $tableName = array_keys($beanData)[0];
1686
-            $allTables = [$tableName];
1687
-        } else {
1688
-            $tables = [];
1689
-            foreach ($beanData as $table => $row) {
1690
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1691
-                $pkSet = false;
1692
-                foreach ($primaryKeyColumns as $columnName) {
1693
-                    if ($row[$columnName] !== null) {
1694
-                        $pkSet = true;
1695
-                        break;
1696
-                    }
1697
-                }
1698
-                if ($pkSet) {
1699
-                    $tables[] = $table;
1700
-                }
1701
-            }
1702
-
1703
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1704
-            $allTables = $this->_getLinkBetweenInheritedTables($tables);
1705
-            $tableName = $allTables[0];
1706
-        }
1707
-
1708
-        // Only one table in this bean. Life is sweat, let's look at its type:
1709
-        if (isset($this->tableToBeanMap[$tableName])) {
1710
-            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1711
-        } else {
1712
-            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1713
-        }
1714
-    }
1715
-
1716
-    /**
1717
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1718
-     *
1719
-     * @param string   $key
1720
-     * @param callable $closure
1721
-     *
1722
-     * @return mixed
1723
-     */
1724
-    private function fromCache(string $key, callable $closure)
1725
-    {
1726
-        $item = $this->cache->fetch($key);
1727
-        if ($item === false) {
1728
-            $item = $closure();
1729
-            $this->cache->save($key, $item);
1730
-        }
1731
-
1732
-        return $item;
1733
-    }
1734
-
1735
-    /**
1736
-     * Returns the foreign key object.
1737
-     *
1738
-     * @param string $table
1739
-     * @param string $fkName
1740
-     *
1741
-     * @return ForeignKeyConstraint
1742
-     */
1743
-    public function _getForeignKeyByName(string $table, string $fkName)
1744
-    {
1745
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1746
-    }
1747
-
1748
-    /**
1749
-     * @param $pivotTableName
1750
-     * @param AbstractTDBMObject $bean
1751
-     *
1752
-     * @return AbstractTDBMObject[]
1753
-     */
1754
-    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1755
-    {
1756
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1757
-        /* @var $localFk ForeignKeyConstraint */
1758
-        /* @var $remoteFk ForeignKeyConstraint */
1759
-        $remoteTable = $remoteFk->getForeignTableName();
1760
-
1761
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1762
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1763
-            return $pivotTableName.'.'.$name;
1764
-        }, $localFk->getLocalColumns());
1765
-
1766
-        $filter = array_combine($columnNames, $primaryKeys);
1767
-
1768
-        return $this->findObjects($remoteTable, $filter);
1769
-    }
1770
-
1771
-    /**
1772
-     * @param $pivotTableName
1773
-     * @param AbstractTDBMObject $bean The LOCAL bean
1774
-     *
1775
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1776
-     *
1777
-     * @throws TDBMException
1778
-     */
1779
-    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1780
-    {
1781
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1782
-        $table1 = $fks[0]->getForeignTableName();
1783
-        $table2 = $fks[1]->getForeignTableName();
1784
-
1785
-        $beanTables = array_map(function (DbRow $dbRow) {
1786
-            return $dbRow->_getDbTableName();
1787
-        }, $bean->_getDbRows());
1788
-
1789
-        if (in_array($table1, $beanTables)) {
1790
-            return [$fks[0], $fks[1]];
1791
-        } elseif (in_array($table2, $beanTables)) {
1792
-            return [$fks[1], $fks[0]];
1793
-        } else {
1794
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1795
-        }
1796
-    }
1797
-
1798
-    /**
1799
-     * Returns a list of pivot tables linked to $bean.
1800
-     *
1801
-     * @param AbstractTDBMObject $bean
1802
-     *
1803
-     * @return string[]
1804
-     */
1805
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1806
-    {
1807
-        $junctionTables = [];
1808
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1809
-        foreach ($bean->_getDbRows() as $dbRow) {
1810
-            foreach ($allJunctionTables as $table) {
1811
-                // There are exactly 2 FKs since this is a pivot table.
1812
-                $fks = array_values($table->getForeignKeys());
1813
-
1814
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1815
-                    $junctionTables[] = $table->getName();
1816
-                }
1817
-            }
1818
-        }
1819
-
1820
-        return $junctionTables;
1821
-    }
1822
-
1823
-    /**
1824
-     * Array of types for tables.
1825
-     * Key: table name
1826
-     * Value: array of types indexed by column.
1827
-     *
1828
-     * @var array[]
1829
-     */
1830
-    private $typesForTable = [];
1831
-
1832
-    /**
1833
-     * @internal
1834
-     *
1835
-     * @param string $tableName
1836
-     *
1837
-     * @return Type[]
1838
-     */
1839
-    public function _getColumnTypesForTable(string $tableName)
1840
-    {
1841
-        if (!isset($typesForTable[$tableName])) {
1842
-            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1843
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1844
-                return $column->getType();
1845
-            }, $columns);
1846
-        }
1847
-
1848
-        return $typesForTable[$tableName];
1849
-    }
1850
-
1851
-    /**
1852
-     * Sets the minimum log level.
1853
-     * $level must be one of Psr\Log\LogLevel::xxx.
1854
-     *
1855
-     * Defaults to LogLevel::WARNING
1856
-     *
1857
-     * @param string $level
1858
-     */
1859
-    public function setLogLevel(string $level)
1860
-    {
1861
-        $this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1862
-    }
1264
+	/**
1265
+	 * Returns an identifier for the group of tables passed in parameter.
1266
+	 *
1267
+	 * @param string[] $relatedTables
1268
+	 *
1269
+	 * @return string
1270
+	 */
1271
+	private function getTableGroupName(array $relatedTables)
1272
+	{
1273
+		sort($relatedTables);
1274
+
1275
+		return implode('_``_', $relatedTables);
1276
+	}
1277
+
1278
+	/**
1279
+	 * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1280
+	 *
1281
+	 * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1282
+	 * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1283
+	 *
1284
+	 * The findObjects method takes in parameter:
1285
+	 * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1286
+	 * 			`$mainTable` parameter should be the name of an existing table in database.
1287
+	 *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1288
+	 *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1289
+	 *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1290
+	 *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1291
+	 *          Instead, please consider passing parameters (see documentation for more details).
1292
+	 *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1293
+	 *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1294
+	 *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1295
+	 *
1296
+	 * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1297
+	 * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1298
+	 *
1299
+	 * Finally, if filter_bag is null, the whole table is returned.
1300
+	 *
1301
+	 * @param string            $mainTable             The name of the table queried
1302
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1303
+	 * @param array             $parameters
1304
+	 * @param string|null       $orderString           The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1305
+	 * @param array             $additionalTablesFetch
1306
+	 * @param int               $mode
1307
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1308
+	 *
1309
+	 * @return ResultIterator An object representing an array of results
1310
+	 *
1311
+	 * @throws TDBMException
1312
+	 */
1313
+	public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null)
1314
+	{
1315
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1316
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1317
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1318
+		}
1319
+
1320
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1321
+
1322
+		$parameters = array_merge($parameters, $additionalParameters);
1323
+
1324
+		list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, $additionalTablesFetch, $orderString);
1325
+
1326
+		$sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')';
1327
+
1328
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1329
+		$pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1330
+		$pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1331
+			return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1332
+		}, $pkColumnNames);
1333
+
1334
+		$countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$mainTable.')';
1335
+
1336
+		if (!empty($filterString)) {
1337
+			$sql .= ' WHERE '.$filterString;
1338
+			$countSql .= ' WHERE '.$filterString;
1339
+		}
1340
+
1341
+		if (!empty($orderString)) {
1342
+			$sql .= ' ORDER BY '.$orderString;
1343
+		}
1344
+
1345
+		if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1346
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
1347
+		}
1348
+
1349
+		$mode = $mode ?: $this->mode;
1350
+
1351
+		return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1352
+	}
1353
+
1354
+	/**
1355
+	 * @param string            $mainTable   The name of the table queried
1356
+	 * @param string            $from        The from sql statement
1357
+	 * @param string|array|null $filter      The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1358
+	 * @param array             $parameters
1359
+	 * @param string|null       $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1360
+	 * @param int               $mode
1361
+	 * @param string            $className   Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1362
+	 *
1363
+	 * @return ResultIterator An object representing an array of results
1364
+	 *
1365
+	 * @throws TDBMException
1366
+	 */
1367
+	public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), string $orderString = null, $mode = null, string $className = null)
1368
+	{
1369
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1370
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1371
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1372
+		}
1373
+
1374
+		$columnsList = null;
1375
+
1376
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1377
+
1378
+		$parameters = array_merge($parameters, $additionalParameters);
1379
+
1380
+		$allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1381
+
1382
+		$columnDescList = [];
1383
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1384
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
1385
+
1386
+		foreach ($schema->getTable($mainTable)->getColumns() as $column) {
1387
+			$columnName = $column->getName();
1388
+			$columnDescList[] = [
1389
+				'as' => $columnName,
1390
+				'table' => $mainTable,
1391
+				'column' => $columnName,
1392
+				'type' => $column->getType(),
1393
+				'tableGroup' => $tableGroupName,
1394
+			];
1395
+		}
1396
+
1397
+		$sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) use ($mainTable) {
1398
+			return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($columnDesc['column']);
1399
+		}, $columnDescList)).' FROM '.$from;
1400
+
1401
+		if (count($allFetchedTables) > 1) {
1402
+			list($columnDescList, $columnsList) = $this->getColumnsList($mainTable, [], $orderString);
1403
+		}
1404
+
1405
+		// Let's compute the COUNT.
1406
+		$pkColumnNames = $schema->getTable($mainTable)->getPrimaryKeyColumns();
1407
+		$pkColumnNames = array_map(function ($pkColumn) use ($mainTable) {
1408
+			return $this->connection->quoteIdentifier($mainTable).'.'.$this->connection->quoteIdentifier($pkColumn);
1409
+		}, $pkColumnNames);
1410
+
1411
+		$countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$from;
1412
+
1413
+		if (!empty($filterString)) {
1414
+			$sql .= ' WHERE '.$filterString;
1415
+			$countSql .= ' WHERE '.$filterString;
1416
+		}
1417
+
1418
+		if (!empty($orderString)) {
1419
+			$sql .= ' ORDER BY '.$orderString;
1420
+			$countSql .= ' ORDER BY '.$orderString;
1421
+		}
1422
+
1423
+		if (stripos($countSql, 'GROUP BY') !== false) {
1424
+			throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
1425
+		}
1426
+
1427
+		if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
1428
+			throw new TDBMException("Unknown fetch mode: '".$mode."'");
1429
+		}
1430
+
1431
+		if ($columnsList !== null) {
1432
+			$joinSql = '';
1433
+			$parentFks = $this->getParentRelationshipForeignKeys($mainTable);
1434
+			foreach ($parentFks as $fk) {
1435
+				$joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
1436
+					$this->connection->quoteIdentifier($fk->getForeignTableName()),
1437
+					$this->connection->quoteIdentifier($fk->getLocalTableName()),
1438
+					$this->connection->quoteIdentifier($fk->getLocalColumns()[0]),
1439
+					$this->connection->quoteIdentifier($fk->getForeignTableName()),
1440
+					$this->connection->quoteIdentifier($fk->getForeignColumns()[0])
1441
+					);
1442
+			}
1443
+
1444
+			$childrenFks = $this->getChildrenRelationshipForeignKeys($mainTable);
1445
+			foreach ($childrenFks as $fk) {
1446
+				$joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
1447
+					$this->connection->quoteIdentifier($fk->getLocalTableName()),
1448
+					$this->connection->quoteIdentifier($fk->getForeignTableName()),
1449
+					$this->connection->quoteIdentifier($fk->getForeignColumns()[0]),
1450
+					$this->connection->quoteIdentifier($fk->getLocalTableName()),
1451
+					$this->connection->quoteIdentifier($fk->getLocalColumns()[0])
1452
+				);
1453
+			}
1454
+
1455
+			$sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$mainTable.' '.$joinSql;
1456
+		}
1457
+
1458
+		$mode = $mode ?: $this->mode;
1459
+
1460
+		return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1461
+	}
1462
+
1463
+	/**
1464
+	 * Returns the column list that must be fetched for the SQL request.
1465
+	 *
1466
+	 * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
1467
+	 *
1468
+	 * @param string $mainTable
1469
+	 * @param array  $additionalTablesFetch
1470
+	 * @param string|null $orderBy
1471
+	 *
1472
+	 * @return array
1473
+	 *
1474
+	 * @throws \Doctrine\DBAL\Schema\SchemaException
1475
+	 */
1476
+	private function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), string $orderBy = null)
1477
+	{
1478
+		// From the table name and the additional tables we want to fetch, let's build a list of all tables
1479
+		// that must be part of the select columns.
1480
+
1481
+		$tableGroups = [];
1482
+		$allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable);
1483
+		$tableGroupName = $this->getTableGroupName($allFetchedTables);
1484
+		foreach ($allFetchedTables as $table) {
1485
+			$tableGroups[$table] = $tableGroupName;
1486
+		}
1487
+
1488
+		$columnsList = [];
1489
+		$columnDescList = [];
1490
+		$sortColumn = 0;
1491
+
1492
+		// Now, let's deal with "order by columns"
1493
+		if ($orderBy !== null) {
1494
+			$orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
1495
+
1496
+			// If we sort by a column, there is a high chance we will fetch the bean containing this column.
1497
+			// Hence, we should add the table to the $additionalTablesFetch
1498
+			foreach ($orderByColumns as $orderByColumn) {
1499
+				if ($orderByColumn['type'] === 'colref' && $orderByColumn['table'] !== null) {
1500
+					$additionalTablesFetch[] = $orderByColumn['table'];
1501
+				} elseif ($orderByColumn['type'] === 'expr') {
1502
+					$sortColumnName = 'sort_column_'.$sortColumn;
1503
+					$columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
1504
+					$columnDescList[] = [
1505
+						'tableGroup' => null
1506
+					];
1507
+					$sortColumn++;
1508
+				}
1509
+			}
1510
+		}
1511
+
1512
+
1513
+		foreach ($additionalTablesFetch as $additionalTable) {
1514
+			$relatedTables = $this->_getRelatedTablesByInheritance($additionalTable);
1515
+			$tableGroupName = $this->getTableGroupName($relatedTables);
1516
+			foreach ($relatedTables as $table) {
1517
+				$tableGroups[$table] = $tableGroupName;
1518
+			}
1519
+			$allFetchedTables = array_merge($allFetchedTables, $relatedTables);
1520
+		}
1521
+
1522
+		// Let's remove any duplicate
1523
+		$allFetchedTables = array_flip(array_flip($allFetchedTables));
1524
+
1525
+		$schema = $this->tdbmSchemaAnalyzer->getSchema();
1526
+
1527
+		// Now, let's build the column list
1528
+		foreach ($allFetchedTables as $table) {
1529
+			foreach ($schema->getTable($table)->getColumns() as $column) {
1530
+				$columnName = $column->getName();
1531
+				$columnDescList[] = [
1532
+					'as' => $table.'____'.$columnName,
1533
+					'table' => $table,
1534
+					'column' => $columnName,
1535
+					'type' => $column->getType(),
1536
+					'tableGroup' => $tableGroups[$table],
1537
+				];
1538
+				$columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '.
1539
+					$this->connection->quoteIdentifier($table.'____'.$columnName);
1540
+			}
1541
+		}
1542
+
1543
+		return [$columnDescList, $columnsList];
1544
+	}
1545
+
1546
+	/**
1547
+	 * @param $table
1548
+	 * @param array  $primaryKeys
1549
+	 * @param array  $additionalTablesFetch
1550
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1551
+	 * @param string $className
1552
+	 *
1553
+	 * @return AbstractTDBMObject
1554
+	 *
1555
+	 * @throws TDBMException
1556
+	 */
1557
+	public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1558
+	{
1559
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1560
+		$hash = $this->getObjectHash($primaryKeys);
1561
+
1562
+		if ($this->objectStorage->has($table, $hash)) {
1563
+			$dbRow = $this->objectStorage->get($table, $hash);
1564
+			$bean = $dbRow->getTDBMObject();
1565
+			if ($className !== null && !is_a($bean, $className)) {
1566
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1567
+			}
1568
+
1569
+			return $bean;
1570
+		}
1571
+
1572
+		// Are we performing lazy fetching?
1573
+		if ($lazy === true) {
1574
+			// Can we perform lazy fetching?
1575
+			$tables = $this->_getRelatedTablesByInheritance($table);
1576
+			// Only allowed if no inheritance.
1577
+			if (count($tables) === 1) {
1578
+				if ($className === null) {
1579
+					$className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1580
+				}
1581
+
1582
+				// Let's construct the bean
1583
+				if (!isset($this->reflectionClassCache[$className])) {
1584
+					$this->reflectionClassCache[$className] = new \ReflectionClass($className);
1585
+				}
1586
+				// Let's bypass the constructor when creating the bean!
1587
+				$bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1588
+				/* @var $bean AbstractTDBMObject */
1589
+				$bean->_constructLazy($table, $primaryKeys, $this);
1590
+
1591
+				return $bean;
1592
+			}
1593
+		}
1594
+
1595
+		// Did not find the object in cache? Let's query it!
1596
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1597
+	}
1598
+
1599
+	/**
1600
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1601
+	 *
1602
+	 * @param string            $mainTable             The name of the table queried
1603
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1604
+	 * @param array             $parameters
1605
+	 * @param array             $additionalTablesFetch
1606
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1607
+	 *
1608
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1609
+	 *
1610
+	 * @throws TDBMException
1611
+	 */
1612
+	public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1613
+	{
1614
+		$objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1615
+		$page = $objects->take(0, 2);
1616
+		$count = $page->count();
1617
+		if ($count > 1) {
1618
+			throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1619
+		} elseif ($count === 0) {
1620
+			return;
1621
+		}
1622
+
1623
+		return $page[0];
1624
+	}
1625
+
1626
+	/**
1627
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1628
+	 *
1629
+	 * @param string            $mainTable  The name of the table queried
1630
+	 * @param string            $from       The from sql statement
1631
+	 * @param string|array|null $filter     The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1632
+	 * @param array             $parameters
1633
+	 * @param string            $className  Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1634
+	 *
1635
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1636
+	 *
1637
+	 * @throws TDBMException
1638
+	 */
1639
+	public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1640
+	{
1641
+		$objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1642
+		$page = $objects->take(0, 2);
1643
+		$count = $page->count();
1644
+		if ($count > 1) {
1645
+			throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1646
+		} elseif ($count === 0) {
1647
+			return;
1648
+		}
1649
+
1650
+		return $page[0];
1651
+	}
1652
+
1653
+	/**
1654
+	 * Returns a unique bean according to the filters passed in parameter.
1655
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1656
+	 *
1657
+	 * @param string            $mainTable             The name of the table queried
1658
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1659
+	 * @param array             $parameters
1660
+	 * @param array             $additionalTablesFetch
1661
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1662
+	 *
1663
+	 * @return AbstractTDBMObject The object we want
1664
+	 *
1665
+	 * @throws TDBMException
1666
+	 */
1667
+	public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1668
+	{
1669
+		$bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1670
+		if ($bean === null) {
1671
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1672
+		}
1673
+
1674
+		return $bean;
1675
+	}
1676
+
1677
+	/**
1678
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1679
+	 *
1680
+	 * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1681
+	 */
1682
+	public function _getClassNameFromBeanData(array $beanData)
1683
+	{
1684
+		if (count($beanData) === 1) {
1685
+			$tableName = array_keys($beanData)[0];
1686
+			$allTables = [$tableName];
1687
+		} else {
1688
+			$tables = [];
1689
+			foreach ($beanData as $table => $row) {
1690
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1691
+				$pkSet = false;
1692
+				foreach ($primaryKeyColumns as $columnName) {
1693
+					if ($row[$columnName] !== null) {
1694
+						$pkSet = true;
1695
+						break;
1696
+					}
1697
+				}
1698
+				if ($pkSet) {
1699
+					$tables[] = $table;
1700
+				}
1701
+			}
1702
+
1703
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1704
+			$allTables = $this->_getLinkBetweenInheritedTables($tables);
1705
+			$tableName = $allTables[0];
1706
+		}
1707
+
1708
+		// Only one table in this bean. Life is sweat, let's look at its type:
1709
+		if (isset($this->tableToBeanMap[$tableName])) {
1710
+			return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1711
+		} else {
1712
+			return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1713
+		}
1714
+	}
1715
+
1716
+	/**
1717
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1718
+	 *
1719
+	 * @param string   $key
1720
+	 * @param callable $closure
1721
+	 *
1722
+	 * @return mixed
1723
+	 */
1724
+	private function fromCache(string $key, callable $closure)
1725
+	{
1726
+		$item = $this->cache->fetch($key);
1727
+		if ($item === false) {
1728
+			$item = $closure();
1729
+			$this->cache->save($key, $item);
1730
+		}
1731
+
1732
+		return $item;
1733
+	}
1734
+
1735
+	/**
1736
+	 * Returns the foreign key object.
1737
+	 *
1738
+	 * @param string $table
1739
+	 * @param string $fkName
1740
+	 *
1741
+	 * @return ForeignKeyConstraint
1742
+	 */
1743
+	public function _getForeignKeyByName(string $table, string $fkName)
1744
+	{
1745
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1746
+	}
1747
+
1748
+	/**
1749
+	 * @param $pivotTableName
1750
+	 * @param AbstractTDBMObject $bean
1751
+	 *
1752
+	 * @return AbstractTDBMObject[]
1753
+	 */
1754
+	public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1755
+	{
1756
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1757
+		/* @var $localFk ForeignKeyConstraint */
1758
+		/* @var $remoteFk ForeignKeyConstraint */
1759
+		$remoteTable = $remoteFk->getForeignTableName();
1760
+
1761
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1762
+		$columnNames = array_map(function ($name) use ($pivotTableName) {
1763
+			return $pivotTableName.'.'.$name;
1764
+		}, $localFk->getLocalColumns());
1765
+
1766
+		$filter = array_combine($columnNames, $primaryKeys);
1767
+
1768
+		return $this->findObjects($remoteTable, $filter);
1769
+	}
1770
+
1771
+	/**
1772
+	 * @param $pivotTableName
1773
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1774
+	 *
1775
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1776
+	 *
1777
+	 * @throws TDBMException
1778
+	 */
1779
+	private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1780
+	{
1781
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1782
+		$table1 = $fks[0]->getForeignTableName();
1783
+		$table2 = $fks[1]->getForeignTableName();
1784
+
1785
+		$beanTables = array_map(function (DbRow $dbRow) {
1786
+			return $dbRow->_getDbTableName();
1787
+		}, $bean->_getDbRows());
1788
+
1789
+		if (in_array($table1, $beanTables)) {
1790
+			return [$fks[0], $fks[1]];
1791
+		} elseif (in_array($table2, $beanTables)) {
1792
+			return [$fks[1], $fks[0]];
1793
+		} else {
1794
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1795
+		}
1796
+	}
1797
+
1798
+	/**
1799
+	 * Returns a list of pivot tables linked to $bean.
1800
+	 *
1801
+	 * @param AbstractTDBMObject $bean
1802
+	 *
1803
+	 * @return string[]
1804
+	 */
1805
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1806
+	{
1807
+		$junctionTables = [];
1808
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1809
+		foreach ($bean->_getDbRows() as $dbRow) {
1810
+			foreach ($allJunctionTables as $table) {
1811
+				// There are exactly 2 FKs since this is a pivot table.
1812
+				$fks = array_values($table->getForeignKeys());
1813
+
1814
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1815
+					$junctionTables[] = $table->getName();
1816
+				}
1817
+			}
1818
+		}
1819
+
1820
+		return $junctionTables;
1821
+	}
1822
+
1823
+	/**
1824
+	 * Array of types for tables.
1825
+	 * Key: table name
1826
+	 * Value: array of types indexed by column.
1827
+	 *
1828
+	 * @var array[]
1829
+	 */
1830
+	private $typesForTable = [];
1831
+
1832
+	/**
1833
+	 * @internal
1834
+	 *
1835
+	 * @param string $tableName
1836
+	 *
1837
+	 * @return Type[]
1838
+	 */
1839
+	public function _getColumnTypesForTable(string $tableName)
1840
+	{
1841
+		if (!isset($typesForTable[$tableName])) {
1842
+			$columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1843
+			$typesForTable[$tableName] = array_map(function (Column $column) {
1844
+				return $column->getType();
1845
+			}, $columns);
1846
+		}
1847
+
1848
+		return $typesForTable[$tableName];
1849
+	}
1850
+
1851
+	/**
1852
+	 * Sets the minimum log level.
1853
+	 * $level must be one of Psr\Log\LogLevel::xxx.
1854
+	 *
1855
+	 * Defaults to LogLevel::WARNING
1856
+	 *
1857
+	 * @param string $level
1858
+	 */
1859
+	public function setLogLevel(string $level)
1860
+	{
1861
+		$this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1862
+	}
1863 1863
 }
Please login to merge, or discard this patch.