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