Completed
Pull Request — 4.2 (#121)
by Marc
03:19
created
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -4,7 +4,6 @@
 block discarded – undo
4 4
 
5 5
 use Doctrine\Common\Inflector\Inflector;
6 6
 use Doctrine\DBAL\Driver\Connection;
7
-use Doctrine\DBAL\Schema\Column;
8 7
 use Doctrine\DBAL\Schema\Schema;
9 8
 use Doctrine\DBAL\Schema\Table;
10 9
 use Doctrine\DBAL\Types\Type;
Please login to merge, or discard this patch.
Indentation   +474 added lines, -474 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,10 +375,10 @@  discard block
 block discarded – undo
375 375
     }
376 376
     ";
377 377
 
378
-        if (count($primaryKeyColumns) === 1) {
379
-            $primaryKeyColumn = $primaryKeyColumns[0];
380
-            $primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
381
-            $str .= "
378
+		if (count($primaryKeyColumns) === 1) {
379
+			$primaryKeyColumn = $primaryKeyColumns[0];
380
+			$primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
381
+			$str .= "
382 382
     /**
383 383
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
384 384
      * If the primary key does not exist, an exception is thrown.
@@ -393,8 +393,8 @@  discard block
 block discarded – undo
393 393
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
394 394
     }
395 395
     ";
396
-        }
397
-        $str .= "
396
+		}
397
+		$str .= "
398 398
     /**
399 399
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
400 400
      *
@@ -493,33 +493,33 @@  discard block
 block discarded – undo
493 493
     }
494 494
 ";
495 495
 
496
-        $str .= $findByDaoCode;
497
-        $str .= '}
496
+		$str .= $findByDaoCode;
497
+		$str .= '}
498 498
 ';
499 499
 
500
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
501
-        if (empty($possibleBaseFileNames)) {
502
-            // @codeCoverageIgnoreStart
503
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
504
-            // @codeCoverageIgnoreEnd
505
-        }
506
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
507
-
508
-        $this->ensureDirectoryExist($possibleBaseFileName);
509
-        file_put_contents($possibleBaseFileName, $str);
510
-        @chmod($possibleBaseFileName, 0664);
511
-
512
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
513
-        if (empty($possibleFileNames)) {
514
-            // @codeCoverageIgnoreStart
515
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
516
-            // @codeCoverageIgnoreEnd
517
-        }
518
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
519
-
520
-        // Now, let's generate the "editable" class
521
-        if (!file_exists($possibleFileName)) {
522
-            $str = "<?php
500
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
501
+		if (empty($possibleBaseFileNames)) {
502
+			// @codeCoverageIgnoreStart
503
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
504
+			// @codeCoverageIgnoreEnd
505
+		}
506
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
507
+
508
+		$this->ensureDirectoryExist($possibleBaseFileName);
509
+		file_put_contents($possibleBaseFileName, $str);
510
+		@chmod($possibleBaseFileName, 0664);
511
+
512
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
513
+		if (empty($possibleFileNames)) {
514
+			// @codeCoverageIgnoreStart
515
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
516
+			// @codeCoverageIgnoreEnd
517
+		}
518
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
519
+
520
+		// Now, let's generate the "editable" class
521
+		if (!file_exists($possibleFileName)) {
522
+			$str = "<?php
523 523
 
524 524
 /*
525 525
  * This file has been automatically generated by TDBM.
@@ -538,22 +538,22 @@  discard block
 block discarded – undo
538 538
 
539 539
 }
540 540
 ";
541
-            $this->ensureDirectoryExist($possibleFileName);
542
-            file_put_contents($possibleFileName, $str);
543
-            @chmod($possibleFileName, 0664);
544
-        }
545
-    }
546
-
547
-    /**
548
-     * Generates the factory bean.
549
-     *
550
-     * @param Table[] $tableList
551
-     */
552
-    private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
553
-    {
554
-        // For each table, let's write a property.
555
-
556
-        $str = "<?php
541
+			$this->ensureDirectoryExist($possibleFileName);
542
+			file_put_contents($possibleFileName, $str);
543
+			@chmod($possibleFileName, 0664);
544
+		}
545
+	}
546
+
547
+	/**
548
+	 * Generates the factory bean.
549
+	 *
550
+	 * @param Table[] $tableList
551
+	 */
552
+	private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
553
+	{
554
+		// For each table, let's write a property.
555
+
556
+		$str = "<?php
557 557
 
558 558
 /*
559 559
  * This file has been automatically generated by TDBM.
@@ -562,13 +562,13 @@  discard block
 block discarded – undo
562 562
 
563 563
 namespace {$daoNamespace}\\Generated;
564 564
 ";
565
-        foreach ($tableList as $table) {
566
-            $tableName = $table->getName();
567
-            $daoClassName = $this->getDaoNameFromTableName($tableName);
568
-            $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
569
-        }
565
+		foreach ($tableList as $table) {
566
+			$tableName = $table->getName();
567
+			$daoClassName = $this->getDaoNameFromTableName($tableName);
568
+			$str .= "use {$daoNamespace}\\".$daoClassName.";\n";
569
+		}
570 570
 
571
-        $str .= "
571
+		$str .= "
572 572
 /**
573 573
  * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
574 574
  *
@@ -577,12 +577,12 @@  discard block
 block discarded – undo
577 577
 {
578 578
 ";
579 579
 
580
-        foreach ($tableList as $table) {
581
-            $tableName = $table->getName();
582
-            $daoClassName = $this->getDaoNameFromTableName($tableName);
583
-            $daoInstanceName = self::toVariableName($daoClassName);
580
+		foreach ($tableList as $table) {
581
+			$tableName = $table->getName();
582
+			$daoClassName = $this->getDaoNameFromTableName($tableName);
583
+			$daoInstanceName = self::toVariableName($daoClassName);
584 584
 
585
-            $str .= '    /**
585
+			$str .= '    /**
586 586
      * @var '.$daoClassName.'
587 587
      */
588 588
     private $'.$daoInstanceName.';
@@ -607,158 +607,158 @@  discard block
 block discarded – undo
607 607
     }
608 608
 
609 609
 ';
610
-        }
610
+		}
611 611
 
612
-        $str .= '
612
+		$str .= '
613 613
 }
614 614
 ';
615 615
 
616
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
617
-        if (empty($possibleFileNames)) {
618
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
619
-        }
620
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
621
-
622
-        $this->ensureDirectoryExist($possibleFileName);
623
-        file_put_contents($possibleFileName, $str);
624
-        @chmod($possibleFileName, 0664);
625
-    }
626
-
627
-    /**
628
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
629
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
630
-     *
631
-     * @param $str string
632
-     *
633
-     * @return string
634
-     */
635
-    public static function toCamelCase($str)
636
-    {
637
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
638
-        while (true) {
639
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
640
-                break;
641
-            }
642
-
643
-            $pos = strpos($str, '_');
644
-            if ($pos === false) {
645
-                $pos = strpos($str, ' ');
646
-            }
647
-            $before = substr($str, 0, $pos);
648
-            $after = substr($str, $pos + 1);
649
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
650
-        }
651
-
652
-        return $str;
653
-    }
654
-
655
-    /**
656
-     * Tries to put string to the singular form (if it is plural).
657
-     * We assume the table names are in english.
658
-     *
659
-     * @param $str string
660
-     *
661
-     * @return string
662
-     */
663
-    public static function toSingular($str)
664
-    {
665
-        return Inflector::singularize($str);
666
-    }
667
-
668
-    /**
669
-     * Put the first letter of the string in lower case.
670
-     * Very useful to transform a class name into a variable name.
671
-     *
672
-     * @param $str string
673
-     *
674
-     * @return string
675
-     */
676
-    public static function toVariableName($str)
677
-    {
678
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
679
-    }
680
-
681
-    /**
682
-     * Ensures the file passed in parameter can be written in its directory.
683
-     *
684
-     * @param string $fileName
685
-     *
686
-     * @throws TDBMException
687
-     */
688
-    private function ensureDirectoryExist($fileName)
689
-    {
690
-        $dirName = dirname($fileName);
691
-        if (!file_exists($dirName)) {
692
-            $old = umask(0);
693
-            $result = mkdir($dirName, 0775, true);
694
-            umask($old);
695
-            if ($result === false) {
696
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
697
-            }
698
-        }
699
-    }
700
-
701
-    /**
702
-     * Absolute path to composer json file.
703
-     *
704
-     * @param string $composerFile
705
-     */
706
-    public function setComposerFile($composerFile)
707
-    {
708
-        $this->rootPath = dirname($composerFile).'/';
709
-        $this->composerFile = basename($composerFile);
710
-    }
711
-
712
-    /**
713
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
714
-     *
715
-     * @param Type $type The DBAL type
716
-     *
717
-     * @return string The PHP type
718
-     */
719
-    public static function dbalTypeToPhpType(Type $type)
720
-    {
721
-        $map = [
722
-            Type::TARRAY => 'array',
723
-            Type::SIMPLE_ARRAY => 'array',
724
-            Type::JSON_ARRAY => 'array',
725
-            Type::BIGINT => 'string',
726
-            Type::BOOLEAN => 'bool',
727
-            Type::DATETIME => '\DateTimeInterface',
728
-            Type::DATETIMETZ => '\DateTimeInterface',
729
-            Type::DATE => '\DateTimeInterface',
730
-            Type::TIME => '\DateTimeInterface',
731
-            Type::DECIMAL => 'float',
732
-            Type::INTEGER => 'int',
733
-            Type::OBJECT => 'string',
734
-            Type::SMALLINT => 'int',
735
-            Type::STRING => 'string',
736
-            Type::TEXT => 'string',
737
-            Type::BINARY => 'string',
738
-            Type::BLOB => 'string',
739
-            Type::FLOAT => 'float',
740
-            Type::GUID => 'string',
741
-        ];
742
-
743
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
744
-    }
745
-
746
-    /**
747
-     * @param string $beanNamespace
748
-     *
749
-     * @return \string[] Returns a map mapping table name to beans name
750
-     */
751
-    public function buildTableToBeanMap($beanNamespace)
752
-    {
753
-        $tableToBeanMap = [];
754
-
755
-        $tables = $this->schema->getTables();
756
-
757
-        foreach ($tables as $table) {
758
-            $tableName = $table->getName();
759
-            $tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
760
-        }
761
-
762
-        return $tableToBeanMap;
763
-    }
616
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
617
+		if (empty($possibleFileNames)) {
618
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
619
+		}
620
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
621
+
622
+		$this->ensureDirectoryExist($possibleFileName);
623
+		file_put_contents($possibleFileName, $str);
624
+		@chmod($possibleFileName, 0664);
625
+	}
626
+
627
+	/**
628
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
629
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
630
+	 *
631
+	 * @param $str string
632
+	 *
633
+	 * @return string
634
+	 */
635
+	public static function toCamelCase($str)
636
+	{
637
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
638
+		while (true) {
639
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
640
+				break;
641
+			}
642
+
643
+			$pos = strpos($str, '_');
644
+			if ($pos === false) {
645
+				$pos = strpos($str, ' ');
646
+			}
647
+			$before = substr($str, 0, $pos);
648
+			$after = substr($str, $pos + 1);
649
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
650
+		}
651
+
652
+		return $str;
653
+	}
654
+
655
+	/**
656
+	 * Tries to put string to the singular form (if it is plural).
657
+	 * We assume the table names are in english.
658
+	 *
659
+	 * @param $str string
660
+	 *
661
+	 * @return string
662
+	 */
663
+	public static function toSingular($str)
664
+	{
665
+		return Inflector::singularize($str);
666
+	}
667
+
668
+	/**
669
+	 * Put the first letter of the string in lower case.
670
+	 * Very useful to transform a class name into a variable name.
671
+	 *
672
+	 * @param $str string
673
+	 *
674
+	 * @return string
675
+	 */
676
+	public static function toVariableName($str)
677
+	{
678
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
679
+	}
680
+
681
+	/**
682
+	 * Ensures the file passed in parameter can be written in its directory.
683
+	 *
684
+	 * @param string $fileName
685
+	 *
686
+	 * @throws TDBMException
687
+	 */
688
+	private function ensureDirectoryExist($fileName)
689
+	{
690
+		$dirName = dirname($fileName);
691
+		if (!file_exists($dirName)) {
692
+			$old = umask(0);
693
+			$result = mkdir($dirName, 0775, true);
694
+			umask($old);
695
+			if ($result === false) {
696
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
697
+			}
698
+		}
699
+	}
700
+
701
+	/**
702
+	 * Absolute path to composer json file.
703
+	 *
704
+	 * @param string $composerFile
705
+	 */
706
+	public function setComposerFile($composerFile)
707
+	{
708
+		$this->rootPath = dirname($composerFile).'/';
709
+		$this->composerFile = basename($composerFile);
710
+	}
711
+
712
+	/**
713
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
714
+	 *
715
+	 * @param Type $type The DBAL type
716
+	 *
717
+	 * @return string The PHP type
718
+	 */
719
+	public static function dbalTypeToPhpType(Type $type)
720
+	{
721
+		$map = [
722
+			Type::TARRAY => 'array',
723
+			Type::SIMPLE_ARRAY => 'array',
724
+			Type::JSON_ARRAY => 'array',
725
+			Type::BIGINT => 'string',
726
+			Type::BOOLEAN => 'bool',
727
+			Type::DATETIME => '\DateTimeInterface',
728
+			Type::DATETIMETZ => '\DateTimeInterface',
729
+			Type::DATE => '\DateTimeInterface',
730
+			Type::TIME => '\DateTimeInterface',
731
+			Type::DECIMAL => 'float',
732
+			Type::INTEGER => 'int',
733
+			Type::OBJECT => 'string',
734
+			Type::SMALLINT => 'int',
735
+			Type::STRING => 'string',
736
+			Type::TEXT => 'string',
737
+			Type::BINARY => 'string',
738
+			Type::BLOB => 'string',
739
+			Type::FLOAT => 'float',
740
+			Type::GUID => 'string',
741
+		];
742
+
743
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
744
+	}
745
+
746
+	/**
747
+	 * @param string $beanNamespace
748
+	 *
749
+	 * @return \string[] Returns a map mapping table name to beans name
750
+	 */
751
+	public function buildTableToBeanMap($beanNamespace)
752
+	{
753
+		$tableToBeanMap = [];
754
+
755
+		$tables = $this->schema->getTables();
756
+
757
+		foreach ($tables as $table) {
758
+			$tableName = $table->getName();
759
+			$tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
760
+		}
761
+
762
+		return $tableToBeanMap;
763
+	}
764 764
 }
Please login to merge, or discard this patch.
src/views/installStep2.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@
 block discarded – undo
8 8
 <input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" />
9 9
 
10 10
 <?php if (!$this->autoloadDetected) {
11
-    ?>
11
+	?>
12 12
 <div class="alert">Warning! TDBM could not detect the autoload section of your composer.json file.
13 13
 Unless you are developing your own autoload system, you should configure <strong>composer.json</strong> to <a href="http://getcomposer.org/doc/01-basic-usage.md#autoloading" target="_blank">define a source directory and a root namespace using PSR-0</a>.</div>
14 14
 <?php 
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/WeakrefObjectStorage.php 1 patch
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -31,117 +31,117 @@
 block discarded – undo
31 31
  */
32 32
 class WeakrefObjectStorage
33 33
 {
34
-    /**
35
-     * An array of fetched object, accessible via table name and primary key.
36
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
37
-     *
38
-     * @var array<string, WeakMap<string, TDBMObject>>
39
-     */
40
-    private $objects = array();
34
+	/**
35
+	 * An array of fetched object, accessible via table name and primary key.
36
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
37
+	 *
38
+	 * @var array<string, WeakMap<string, TDBMObject>>
39
+	 */
40
+	private $objects = array();
41 41
 
42
-    /**
43
-     * Every 10000 set in the dataset, we perform a cleanup to ensure the WeakRef instances
44
-     * are removed if they are no more valid.
45
-     * This is to avoid having memory used by dangling WeakRef instances.
46
-     *
47
-     * @var int
48
-     */
49
-    private $garbageCollectorCount = 0;
42
+	/**
43
+	 * Every 10000 set in the dataset, we perform a cleanup to ensure the WeakRef instances
44
+	 * are removed if they are no more valid.
45
+	 * This is to avoid having memory used by dangling WeakRef instances.
46
+	 *
47
+	 * @var int
48
+	 */
49
+	private $garbageCollectorCount = 0;
50 50
 
51
-    /**
52
-     * Sets an object in the storage.
53
-     *
54
-     * @param string $tableName
55
-     * @param string $id
56
-     * @param DbRow  $dbRow
57
-     */
58
-    public function set($tableName, $id, DbRow $dbRow)
59
-    {
60
-        $this->objects[$tableName][$id] = new \WeakRef($dbRow);
61
-        ++$this->garbageCollectorCount;
62
-        if ($this->garbageCollectorCount == 10000) {
63
-            $this->garbageCollectorCount = 0;
64
-            $this->cleanupDanglingWeakRefs();
65
-        }
66
-    }
51
+	/**
52
+	 * Sets an object in the storage.
53
+	 *
54
+	 * @param string $tableName
55
+	 * @param string $id
56
+	 * @param DbRow  $dbRow
57
+	 */
58
+	public function set($tableName, $id, DbRow $dbRow)
59
+	{
60
+		$this->objects[$tableName][$id] = new \WeakRef($dbRow);
61
+		++$this->garbageCollectorCount;
62
+		if ($this->garbageCollectorCount == 10000) {
63
+			$this->garbageCollectorCount = 0;
64
+			$this->cleanupDanglingWeakRefs();
65
+		}
66
+	}
67 67
 
68
-    /**
69
-     * Checks if an object is in the storage.
70
-     *
71
-     * @param string $tableName
72
-     * @param string $id
73
-     *
74
-     * @return bool
75
-     */
76
-    public function has($tableName, $id)
77
-    {
78
-        if (isset($this->objects[$tableName][$id])) {
79
-            if ($this->objects[$tableName][$id]->valid()) {
80
-                return true;
81
-            } else {
82
-                unset($this->objects[$tableName][$id]);
83
-            }
84
-        }
68
+	/**
69
+	 * Checks if an object is in the storage.
70
+	 *
71
+	 * @param string $tableName
72
+	 * @param string $id
73
+	 *
74
+	 * @return bool
75
+	 */
76
+	public function has($tableName, $id)
77
+	{
78
+		if (isset($this->objects[$tableName][$id])) {
79
+			if ($this->objects[$tableName][$id]->valid()) {
80
+				return true;
81
+			} else {
82
+				unset($this->objects[$tableName][$id]);
83
+			}
84
+		}
85 85
 
86
-        return false;
87
-    }
86
+		return false;
87
+	}
88 88
 
89
-    /**
90
-     * Returns an object from the storage (or null if no object is set).
91
-     *
92
-     * @param string $tableName
93
-     * @param string $id
94
-     *
95
-     * @return DbRow
96
-     */
97
-    public function get($tableName, $id)
98
-    {
99
-        if (isset($this->objects[$tableName][$id])) {
100
-            if ($this->objects[$tableName][$id]->valid()) {
101
-                return $this->objects[$tableName][$id]->get();
102
-            }
103
-        } else {
104
-            return;
105
-        }
106
-    }
89
+	/**
90
+	 * Returns an object from the storage (or null if no object is set).
91
+	 *
92
+	 * @param string $tableName
93
+	 * @param string $id
94
+	 *
95
+	 * @return DbRow
96
+	 */
97
+	public function get($tableName, $id)
98
+	{
99
+		if (isset($this->objects[$tableName][$id])) {
100
+			if ($this->objects[$tableName][$id]->valid()) {
101
+				return $this->objects[$tableName][$id]->get();
102
+			}
103
+		} else {
104
+			return;
105
+		}
106
+	}
107 107
 
108
-    /**
109
-     * Removes an object from the storage.
110
-     *
111
-     * @param string $tableName
112
-     * @param string $id
113
-     */
114
-    public function remove($tableName, $id)
115
-    {
116
-        unset($this->objects[$tableName][$id]);
117
-    }
108
+	/**
109
+	 * Removes an object from the storage.
110
+	 *
111
+	 * @param string $tableName
112
+	 * @param string $id
113
+	 */
114
+	public function remove($tableName, $id)
115
+	{
116
+		unset($this->objects[$tableName][$id]);
117
+	}
118 118
 
119
-    /**
120
-     * Applies the callback to all objects.
121
-     *
122
-     * @param callable $callback
123
-     */
124
-    public function apply(callable $callback)
125
-    {
126
-        foreach ($this->objects as $tableName => $table) {
127
-            foreach ($table as $id => $obj) {
128
-                if ($obj->valid()) {
129
-                    $callback($obj->get(), $tableName, $id);
130
-                } else {
131
-                    unset($this->objects[$tableName][$id]);
132
-                }
133
-            }
134
-        }
135
-    }
119
+	/**
120
+	 * Applies the callback to all objects.
121
+	 *
122
+	 * @param callable $callback
123
+	 */
124
+	public function apply(callable $callback)
125
+	{
126
+		foreach ($this->objects as $tableName => $table) {
127
+			foreach ($table as $id => $obj) {
128
+				if ($obj->valid()) {
129
+					$callback($obj->get(), $tableName, $id);
130
+				} else {
131
+					unset($this->objects[$tableName][$id]);
132
+				}
133
+			}
134
+		}
135
+	}
136 136
 
137
-    private function cleanupDanglingWeakRefs()
138
-    {
139
-        foreach ($this->objects as $tableName => $table) {
140
-            foreach ($table as $id => $obj) {
141
-                if (!$obj->valid()) {
142
-                    unset($this->objects[$tableName][$id]);
143
-                }
144
-            }
145
-        }
146
-    }
137
+	private function cleanupDanglingWeakRefs()
138
+	{
139
+		foreach ($this->objects as $tableName => $table) {
140
+			foreach ($table as $id => $obj) {
141
+				if (!$obj->valid()) {
142
+					unset($this->objects[$tableName][$id]);
143
+				}
144
+			}
145
+		}
146
+	}
147 147
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMObjectStateEnum.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -27,10 +27,10 @@
 block discarded – undo
27 27
  */
28 28
 final class TDBMObjectStateEnum extends AbstractTDBMObject
29 29
 {
30
-    const STATE_DETACHED = 'detached';
31
-    const STATE_NEW = 'new';
32
-    const STATE_NOT_LOADED = 'not loaded';
33
-    const STATE_LOADED = 'loaded';
34
-    const STATE_DIRTY = 'dirty';
35
-    const STATE_DELETED = 'deleted';
30
+	const STATE_DETACHED = 'detached';
31
+	const STATE_NEW = 'new';
32
+	const STATE_NOT_LOADED = 'not loaded';
33
+	const STATE_LOADED = 'loaded';
34
+	const STATE_DIRTY = 'dirty';
35
+	const STATE_DELETED = 'deleted';
36 36
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/StandardObjectStorage.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -30,78 +30,78 @@
 block discarded – undo
30 30
  */
31 31
 class StandardObjectStorage
32 32
 {
33
-    /**
34
-     * An array of fetched object, accessible via table name and primary key.
35
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
36
-     *
37
-     * @var array<string, array<string, TDBMObject>>
38
-     */
39
-    private $objects = array();
33
+	/**
34
+	 * An array of fetched object, accessible via table name and primary key.
35
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
36
+	 *
37
+	 * @var array<string, array<string, TDBMObject>>
38
+	 */
39
+	private $objects = array();
40 40
 
41
-    /**
42
-     * Sets an object in the storage.
43
-     *
44
-     * @param string     $tableName
45
-     * @param string     $id
46
-     * @param TDBMObject $dbRow
47
-     */
48
-    public function set($tableName, $id, DbRow $dbRow)
49
-    {
50
-        $this->objects[$tableName][$id] = $dbRow;
51
-    }
41
+	/**
42
+	 * Sets an object in the storage.
43
+	 *
44
+	 * @param string     $tableName
45
+	 * @param string     $id
46
+	 * @param TDBMObject $dbRow
47
+	 */
48
+	public function set($tableName, $id, DbRow $dbRow)
49
+	{
50
+		$this->objects[$tableName][$id] = $dbRow;
51
+	}
52 52
 
53
-    /**
54
-     * Checks if an object is in the storage.
55
-     *
56
-     * @param string $tableName
57
-     * @param string $id
58
-     *
59
-     * @return bool
60
-     */
61
-    public function has($tableName, $id)
62
-    {
63
-        return isset($this->objects[$tableName][$id]);
64
-    }
53
+	/**
54
+	 * Checks if an object is in the storage.
55
+	 *
56
+	 * @param string $tableName
57
+	 * @param string $id
58
+	 *
59
+	 * @return bool
60
+	 */
61
+	public function has($tableName, $id)
62
+	{
63
+		return isset($this->objects[$tableName][$id]);
64
+	}
65 65
 
66
-    /**
67
-     * Returns an object from the storage (or null if no object is set).
68
-     *
69
-     * @param string $tableName
70
-     * @param string $id
71
-     *
72
-     * @return DbRow
73
-     */
74
-    public function get($tableName, $id)
75
-    {
76
-        if (isset($this->objects[$tableName][$id])) {
77
-            return $this->objects[$tableName][$id];
78
-        } else {
79
-            return;
80
-        }
81
-    }
66
+	/**
67
+	 * Returns an object from the storage (or null if no object is set).
68
+	 *
69
+	 * @param string $tableName
70
+	 * @param string $id
71
+	 *
72
+	 * @return DbRow
73
+	 */
74
+	public function get($tableName, $id)
75
+	{
76
+		if (isset($this->objects[$tableName][$id])) {
77
+			return $this->objects[$tableName][$id];
78
+		} else {
79
+			return;
80
+		}
81
+	}
82 82
 
83
-    /**
84
-     * Removes an object from the storage.
85
-     *
86
-     * @param string $tableName
87
-     * @param string $id
88
-     */
89
-    public function remove($tableName, $id)
90
-    {
91
-        unset($this->objects[$tableName][$id]);
92
-    }
83
+	/**
84
+	 * Removes an object from the storage.
85
+	 *
86
+	 * @param string $tableName
87
+	 * @param string $id
88
+	 */
89
+	public function remove($tableName, $id)
90
+	{
91
+		unset($this->objects[$tableName][$id]);
92
+	}
93 93
 
94
-    /**
95
-     * Applies the callback to all objects.
96
-     *
97
-     * @param callable $callback
98
-     */
99
-    public function apply(callable $callback)
100
-    {
101
-        foreach ($this->objects as $tableName => $table) {
102
-            foreach ($table as $id => $obj) {
103
-                $callback($obj, $tableName, $id);
104
-            }
105
-        }
106
-    }
94
+	/**
95
+	 * Applies the callback to all objects.
96
+	 *
97
+	 * @param callable $callback
98
+	 */
99
+	public function apply(callable $callback)
100
+	{
101
+		foreach ($this->objects as $tableName => $table) {
102
+			foreach ($table as $id => $obj) {
103
+				$callback($obj, $tableName, $id);
104
+			}
105
+		}
106
+	}
107 107
 }
Please login to merge, or discard this patch.
src/views/tdbmGenerate.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@
 block discarded – undo
8 8
 <input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" />
9 9
 
10 10
 <?php if (!$this->autoloadDetected) {
11
-    ?>
11
+	?>
12 12
 <div class="alert">Warning! TDBM could not detect the autoload section of your composer.json file.
13 13
 Unless you are developing your own autoload system, you should configure <strong>composer.json</strong> to <a href="http://getcomposer.org/doc/01-basic-usage.md#autoloading" target="_blank">define a source directory and a root namespace using PSR-0</a>.</div>
14 14
 <?php 
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmController.php 1 patch
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -18,148 +18,148 @@
 block discarded – undo
18 18
  */
19 19
 class TdbmController extends AbstractMoufInstanceController
20 20
 {
21
-    /**
22
-     * @var HtmlBlock
23
-     */
24
-    public $content;
25
-
26
-    protected $daoNamespace;
27
-    protected $beanNamespace;
28
-    protected $daoFactoryName;
29
-    protected $daoFactoryInstanceName;
30
-    protected $autoloadDetected;
31
-    protected $storeInUtc;
32
-    protected $useCustomComposer;
33
-
34
-    /**
35
-     * Admin page used to display the DAO generation form.
36
-     *
37
-     * @Action
38
-     */
39
-    public function defaultAction($name, $selfedit = 'false')
40
-    {
41
-        $this->initController($name, $selfedit);
42
-
43
-        // Fill variables
44
-        if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) {
45
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name);
46
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name);
47
-            $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name);
48
-            $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name);
49
-            $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name);
50
-            $this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer_'.$name);
51
-            $this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile_'.$name);
52
-        } else {
53
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace');
54
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace');
55
-            $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName');
56
-            $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName');
57
-            $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc');
58
-            $this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer');
59
-            $this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile');
60
-        }
61
-
62
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
63
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
64
-
65
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
66
-            if ($autoloadNamespaces) {
67
-                $this->autoloadDetected = true;
68
-                $rootNamespace = $autoloadNamespaces[0];
69
-                $this->daoNamespace = $rootNamespace.'Dao';
70
-                $this->beanNamespace = $rootNamespace.'Dao\\Bean';
71
-            } else {
72
-                $this->autoloadDetected = false;
73
-                $this->daoNamespace = 'YourApplication\\Dao';
74
-                $this->beanNamespace = 'YourApplication\\Dao\\Bean';
75
-            }
76
-        } else {
77
-            $this->autoloadDetected = true;
78
-        }
79
-
80
-        $this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
81
-        $this->template->toHtml();
82
-    }
83
-
84
-    /**
85
-     * This action generates the DAOs and Beans for the TDBM service passed in parameter.
86
-     *
87
-     * @Action
88
-     *
89
-     * @param string $name
90
-     * @param bool   $selfedit
91
-     */
92
-    public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
93
-    {
94
-        $this->initController($name, $selfedit);
95
-
96
-        self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc, $useCustomComposer, $composerFile);
97
-
98
-        // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
99
-        header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
100
-    }
101
-
102
-    /**
103
-     * This function generates the DAOs and Beans for the TDBM service passed in parameter.
104
-     *
105
-     * @param MoufManager $moufManager
106
-     * @param string      $name
107
-     * @param string      $daonamespace
108
-     * @param string      $beannamespace
109
-     * @param string      $daofactoryclassname
110
-     * @param string      $daofactoryinstancename
111
-     * @param string      $selfedit
112
-     * @param bool        $storeInUtc
113
-     *
114
-     * @throws \Mouf\MoufException
115
-     */
116
-    public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null, $useCustomComposer = null, $composerFile = null)
117
-    {
118
-        $moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace);
119
-        $moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace);
120
-        $moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname);
121
-        $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename);
122
-        $moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc);
123
-        $moufManager->setVariable('tdbmDefaultUseCustomComposer_'.$name, $useCustomComposer);
124
-        $moufManager->setVariable('tdbmDefaultComposerFile_'.$name, $composerFile);
125
-
126
-        // In case of instance renaming, let's use the last used settings
127
-        $moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace);
128
-        $moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace);
129
-        $moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname);
130
-        $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename);
131
-        $moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc);
132
-        $moufManager->setVariable('tdbmDefaultUseCustomComposer', $useCustomComposer);
133
-        $moufManager->setVariable('tdbmDefaultComposerFile', $composerFile);
134
-
135
-        // Remove first and last slash in namespace.
136
-        $daonamespace = trim($daonamespace, '\\');
137
-        $beannamespace = trim($beannamespace, '\\');
138
-
139
-        $tdbmService = new InstanceProxy($name);
140
-        /* @var $tdbmService TDBMService */
141
-        $tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc, ($useCustomComposer ? $composerFile : null));
142
-
143
-        $moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\Generated\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
144
-
145
-        $tableToBeanMap = [];
146
-
147
-        //$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService');
148
-
149
-        foreach ($tables as $table) {
150
-            $daoName = TDBMDaoGenerator::getDaoNameFromTableName($table);
151
-
152
-            $instanceName = TDBMDaoGenerator::toVariableName($daoName);
153
-            if (!$moufManager->instanceExists($instanceName)) {
154
-                $moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName);
155
-            }
156
-            $moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object');
157
-            $moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName);
158
-
159
-            $tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table);
160
-        }
161
-        $tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name);
162
-        $tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap);
163
-        $moufManager->rewriteMouf();
164
-    }
21
+	/**
22
+	 * @var HtmlBlock
23
+	 */
24
+	public $content;
25
+
26
+	protected $daoNamespace;
27
+	protected $beanNamespace;
28
+	protected $daoFactoryName;
29
+	protected $daoFactoryInstanceName;
30
+	protected $autoloadDetected;
31
+	protected $storeInUtc;
32
+	protected $useCustomComposer;
33
+
34
+	/**
35
+	 * Admin page used to display the DAO generation form.
36
+	 *
37
+	 * @Action
38
+	 */
39
+	public function defaultAction($name, $selfedit = 'false')
40
+	{
41
+		$this->initController($name, $selfedit);
42
+
43
+		// Fill variables
44
+		if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) {
45
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name);
46
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name);
47
+			$this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name);
48
+			$this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name);
49
+			$this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name);
50
+			$this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer_'.$name);
51
+			$this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile_'.$name);
52
+		} else {
53
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace');
54
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace');
55
+			$this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName');
56
+			$this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName');
57
+			$this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc');
58
+			$this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer');
59
+			$this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile');
60
+		}
61
+
62
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
63
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
64
+
65
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
66
+			if ($autoloadNamespaces) {
67
+				$this->autoloadDetected = true;
68
+				$rootNamespace = $autoloadNamespaces[0];
69
+				$this->daoNamespace = $rootNamespace.'Dao';
70
+				$this->beanNamespace = $rootNamespace.'Dao\\Bean';
71
+			} else {
72
+				$this->autoloadDetected = false;
73
+				$this->daoNamespace = 'YourApplication\\Dao';
74
+				$this->beanNamespace = 'YourApplication\\Dao\\Bean';
75
+			}
76
+		} else {
77
+			$this->autoloadDetected = true;
78
+		}
79
+
80
+		$this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
81
+		$this->template->toHtml();
82
+	}
83
+
84
+	/**
85
+	 * This action generates the DAOs and Beans for the TDBM service passed in parameter.
86
+	 *
87
+	 * @Action
88
+	 *
89
+	 * @param string $name
90
+	 * @param bool   $selfedit
91
+	 */
92
+	public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
93
+	{
94
+		$this->initController($name, $selfedit);
95
+
96
+		self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc, $useCustomComposer, $composerFile);
97
+
98
+		// TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
99
+		header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
100
+	}
101
+
102
+	/**
103
+	 * This function generates the DAOs and Beans for the TDBM service passed in parameter.
104
+	 *
105
+	 * @param MoufManager $moufManager
106
+	 * @param string      $name
107
+	 * @param string      $daonamespace
108
+	 * @param string      $beannamespace
109
+	 * @param string      $daofactoryclassname
110
+	 * @param string      $daofactoryinstancename
111
+	 * @param string      $selfedit
112
+	 * @param bool        $storeInUtc
113
+	 *
114
+	 * @throws \Mouf\MoufException
115
+	 */
116
+	public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null, $useCustomComposer = null, $composerFile = null)
117
+	{
118
+		$moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace);
119
+		$moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace);
120
+		$moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname);
121
+		$moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename);
122
+		$moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc);
123
+		$moufManager->setVariable('tdbmDefaultUseCustomComposer_'.$name, $useCustomComposer);
124
+		$moufManager->setVariable('tdbmDefaultComposerFile_'.$name, $composerFile);
125
+
126
+		// In case of instance renaming, let's use the last used settings
127
+		$moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace);
128
+		$moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace);
129
+		$moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname);
130
+		$moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename);
131
+		$moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc);
132
+		$moufManager->setVariable('tdbmDefaultUseCustomComposer', $useCustomComposer);
133
+		$moufManager->setVariable('tdbmDefaultComposerFile', $composerFile);
134
+
135
+		// Remove first and last slash in namespace.
136
+		$daonamespace = trim($daonamespace, '\\');
137
+		$beannamespace = trim($beannamespace, '\\');
138
+
139
+		$tdbmService = new InstanceProxy($name);
140
+		/* @var $tdbmService TDBMService */
141
+		$tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc, ($useCustomComposer ? $composerFile : null));
142
+
143
+		$moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\Generated\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
144
+
145
+		$tableToBeanMap = [];
146
+
147
+		//$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService');
148
+
149
+		foreach ($tables as $table) {
150
+			$daoName = TDBMDaoGenerator::getDaoNameFromTableName($table);
151
+
152
+			$instanceName = TDBMDaoGenerator::toVariableName($daoName);
153
+			if (!$moufManager->instanceExists($instanceName)) {
154
+				$moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName);
155
+			}
156
+			$moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object');
157
+			$moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName);
158
+
159
+			$tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table);
160
+		}
161
+		$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name);
162
+		$tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap);
163
+		$moufManager->rewriteMouf();
164
+	}
165 165
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMService.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,6 @@
 block discarded – undo
25 25
 use Doctrine\DBAL\Connection;
26 26
 use Doctrine\DBAL\Schema\Column;
27 27
 use Doctrine\DBAL\Schema\ForeignKeyConstraint;
28
-use Doctrine\DBAL\Schema\Schema;
29 28
 use Doctrine\DBAL\Schema\Table;
30 29
 use Doctrine\DBAL\Types\Type;
31 30
 use Mouf\Database\MagicQuery;
Please login to merge, or discard this patch.
Indentation   +1390 added lines, -1390 removed lines patch added patch discarded remove patch
@@ -47,236 +47,236 @@  discard block
 block discarded – undo
47 47
  */
48 48
 class TDBMService
49 49
 {
50
-    const MODE_CURSOR = 1;
51
-    const MODE_ARRAY = 2;
52
-
53
-    /**
54
-     * The database connection.
55
-     *
56
-     * @var Connection
57
-     */
58
-    private $connection;
59
-
60
-    /**
61
-     * @var SchemaAnalyzer
62
-     */
63
-    private $schemaAnalyzer;
64
-
65
-    /**
66
-     * @var MagicQuery
67
-     */
68
-    private $magicQuery;
69
-
70
-    /**
71
-     * @var TDBMSchemaAnalyzer
72
-     */
73
-    private $tdbmSchemaAnalyzer;
74
-
75
-    /**
76
-     * @var string
77
-     */
78
-    private $cachePrefix;
79
-
80
-    /**
81
-     * Cache of table of primary keys.
82
-     * Primary keys are stored by tables, as an array of column.
83
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
84
-     *
85
-     * @var string[]
86
-     */
87
-    private $primaryKeysColumns;
88
-
89
-    /**
90
-     * Service storing objects in memory.
91
-     * Access is done by table name and then by primary key.
92
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
93
-     *
94
-     * @var StandardObjectStorage|WeakrefObjectStorage
95
-     */
96
-    private $objectStorage;
97
-
98
-    /**
99
-     * The fetch mode of the result sets returned by `getObjects`.
100
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
101
-     *
102
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
103
-     * 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,
104
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
105
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
106
-     * You can access the array by key, or using foreach, several times.
107
-     *
108
-     * @var int
109
-     */
110
-    private $mode = self::MODE_ARRAY;
111
-
112
-    /**
113
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
114
-     *
115
-     * @var \SplObjectStorage of DbRow objects
116
-     */
117
-    private $toSaveObjects;
118
-
119
-    /**
120
-     * A cache service to be used.
121
-     *
122
-     * @var Cache|null
123
-     */
124
-    private $cache;
125
-
126
-    /**
127
-     * Map associating a table name to a fully qualified Bean class name.
128
-     *
129
-     * @var array
130
-     */
131
-    private $tableToBeanMap = [];
132
-
133
-    /**
134
-     * @var \ReflectionClass[]
135
-     */
136
-    private $reflectionClassCache = array();
137
-
138
-    /**
139
-     * @var LoggerInterface
140
-     */
141
-    private $rootLogger;
142
-
143
-    /**
144
-     * @var MinLogLevelFilter|NullLogger
145
-     */
146
-    private $logger;
147
-
148
-    /**
149
-     * @var OrderByAnalyzer
150
-     */
151
-    private $orderByAnalyzer;
152
-
153
-    /**
154
-     * @param Connection     $connection     The DBAL DB connection to use
155
-     * @param Cache|null     $cache          A cache service to be used
156
-     * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
157
-     *                                       Will be automatically created if not passed
158
-     */
159
-    public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
160
-    {
161
-        if (extension_loaded('weakref')) {
162
-            $this->objectStorage = new WeakrefObjectStorage();
163
-        } else {
164
-            $this->objectStorage = new StandardObjectStorage();
165
-        }
166
-        $this->connection = $connection;
167
-        if ($cache !== null) {
168
-            $this->cache = $cache;
169
-        } else {
170
-            $this->cache = new VoidCache();
171
-        }
172
-        if ($schemaAnalyzer) {
173
-            $this->schemaAnalyzer = $schemaAnalyzer;
174
-        } else {
175
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
176
-        }
177
-
178
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
179
-
180
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
181
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
182
-
183
-        $this->toSaveObjects = new \SplObjectStorage();
184
-        if ($logger === null) {
185
-            $this->logger = new NullLogger();
186
-            $this->rootLogger = new NullLogger();
187
-        } else {
188
-            $this->rootLogger = $logger;
189
-            $this->setLogLevel(LogLevel::WARNING);
190
-        }
191
-        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
192
-    }
193
-
194
-    /**
195
-     * Returns the object used to connect to the database.
196
-     *
197
-     * @return Connection
198
-     */
199
-    public function getConnection()
200
-    {
201
-        return $this->connection;
202
-    }
203
-
204
-    /**
205
-     * Creates a unique cache key for the current connection.
206
-     *
207
-     * @return string
208
-     */
209
-    private function getConnectionUniqueId()
210
-    {
211
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
212
-    }
213
-
214
-    /**
215
-     * Sets the default fetch mode of the result sets returned by `findObjects`.
216
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
217
-     *
218
-     * 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).
219
-     * 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
220
-     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
221
-     *
222
-     * @param int $mode
223
-     *
224
-     * @return $this
225
-     *
226
-     * @throws TDBMException
227
-     */
228
-    public function setFetchMode($mode)
229
-    {
230
-        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
231
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
232
-        }
233
-        $this->mode = $mode;
234
-
235
-        return $this;
236
-    }
237
-
238
-    /**
239
-     * Returns a TDBMObject associated from table "$table_name".
240
-     * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
241
-     * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
242
-     *
243
-     * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
244
-     * 			$user = $tdbmService->getObject('users',1);
245
-     * 			echo $user->name;
246
-     * will return the name of the user whose user_id is one.
247
-     *
248
-     * 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.
249
-     * For instance:
250
-     * 			$group = $tdbmService->getObject('groups',array(1,2));
251
-     *
252
-     * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
253
-     * will be the same.
254
-     *
255
-     * For instance:
256
-     * 			$user1 = $tdbmService->getObject('users',1);
257
-     * 			$user2 = $tdbmService->getObject('users',1);
258
-     * 			$user1->name = 'John Doe';
259
-     * 			echo $user2->name;
260
-     * will return 'John Doe'.
261
-     *
262
-     * You can use filters instead of passing the primary key. For instance:
263
-     * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
264
-     * This will return the user whose login is 'jdoe'.
265
-     * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
266
-     *
267
-     * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
268
-     * For instance:
269
-     *  	$user = $tdbmService->getObject('users',1,'User');
270
-     * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
271
-     * Please be sure not to override any method or any property unless you perfectly know what you are doing!
272
-     *
273
-     * @param string $table_name   The name of the table we retrieve an object from
274
-     * @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)
275
-     * @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
276
-     * @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
277
-     *
278
-     * @return TDBMObject
279
-     */
50
+	const MODE_CURSOR = 1;
51
+	const MODE_ARRAY = 2;
52
+
53
+	/**
54
+	 * The database connection.
55
+	 *
56
+	 * @var Connection
57
+	 */
58
+	private $connection;
59
+
60
+	/**
61
+	 * @var SchemaAnalyzer
62
+	 */
63
+	private $schemaAnalyzer;
64
+
65
+	/**
66
+	 * @var MagicQuery
67
+	 */
68
+	private $magicQuery;
69
+
70
+	/**
71
+	 * @var TDBMSchemaAnalyzer
72
+	 */
73
+	private $tdbmSchemaAnalyzer;
74
+
75
+	/**
76
+	 * @var string
77
+	 */
78
+	private $cachePrefix;
79
+
80
+	/**
81
+	 * Cache of table of primary keys.
82
+	 * Primary keys are stored by tables, as an array of column.
83
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
84
+	 *
85
+	 * @var string[]
86
+	 */
87
+	private $primaryKeysColumns;
88
+
89
+	/**
90
+	 * Service storing objects in memory.
91
+	 * Access is done by table name and then by primary key.
92
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
93
+	 *
94
+	 * @var StandardObjectStorage|WeakrefObjectStorage
95
+	 */
96
+	private $objectStorage;
97
+
98
+	/**
99
+	 * The fetch mode of the result sets returned by `getObjects`.
100
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
101
+	 *
102
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
103
+	 * 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,
104
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
105
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
106
+	 * You can access the array by key, or using foreach, several times.
107
+	 *
108
+	 * @var int
109
+	 */
110
+	private $mode = self::MODE_ARRAY;
111
+
112
+	/**
113
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
114
+	 *
115
+	 * @var \SplObjectStorage of DbRow objects
116
+	 */
117
+	private $toSaveObjects;
118
+
119
+	/**
120
+	 * A cache service to be used.
121
+	 *
122
+	 * @var Cache|null
123
+	 */
124
+	private $cache;
125
+
126
+	/**
127
+	 * Map associating a table name to a fully qualified Bean class name.
128
+	 *
129
+	 * @var array
130
+	 */
131
+	private $tableToBeanMap = [];
132
+
133
+	/**
134
+	 * @var \ReflectionClass[]
135
+	 */
136
+	private $reflectionClassCache = array();
137
+
138
+	/**
139
+	 * @var LoggerInterface
140
+	 */
141
+	private $rootLogger;
142
+
143
+	/**
144
+	 * @var MinLogLevelFilter|NullLogger
145
+	 */
146
+	private $logger;
147
+
148
+	/**
149
+	 * @var OrderByAnalyzer
150
+	 */
151
+	private $orderByAnalyzer;
152
+
153
+	/**
154
+	 * @param Connection     $connection     The DBAL DB connection to use
155
+	 * @param Cache|null     $cache          A cache service to be used
156
+	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
157
+	 *                                       Will be automatically created if not passed
158
+	 */
159
+	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
160
+	{
161
+		if (extension_loaded('weakref')) {
162
+			$this->objectStorage = new WeakrefObjectStorage();
163
+		} else {
164
+			$this->objectStorage = new StandardObjectStorage();
165
+		}
166
+		$this->connection = $connection;
167
+		if ($cache !== null) {
168
+			$this->cache = $cache;
169
+		} else {
170
+			$this->cache = new VoidCache();
171
+		}
172
+		if ($schemaAnalyzer) {
173
+			$this->schemaAnalyzer = $schemaAnalyzer;
174
+		} else {
175
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
176
+		}
177
+
178
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
179
+
180
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
181
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
182
+
183
+		$this->toSaveObjects = new \SplObjectStorage();
184
+		if ($logger === null) {
185
+			$this->logger = new NullLogger();
186
+			$this->rootLogger = new NullLogger();
187
+		} else {
188
+			$this->rootLogger = $logger;
189
+			$this->setLogLevel(LogLevel::WARNING);
190
+		}
191
+		$this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
192
+	}
193
+
194
+	/**
195
+	 * Returns the object used to connect to the database.
196
+	 *
197
+	 * @return Connection
198
+	 */
199
+	public function getConnection()
200
+	{
201
+		return $this->connection;
202
+	}
203
+
204
+	/**
205
+	 * Creates a unique cache key for the current connection.
206
+	 *
207
+	 * @return string
208
+	 */
209
+	private function getConnectionUniqueId()
210
+	{
211
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
212
+	}
213
+
214
+	/**
215
+	 * Sets the default fetch mode of the result sets returned by `findObjects`.
216
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
217
+	 *
218
+	 * 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).
219
+	 * 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
220
+	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
221
+	 *
222
+	 * @param int $mode
223
+	 *
224
+	 * @return $this
225
+	 *
226
+	 * @throws TDBMException
227
+	 */
228
+	public function setFetchMode($mode)
229
+	{
230
+		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
231
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
232
+		}
233
+		$this->mode = $mode;
234
+
235
+		return $this;
236
+	}
237
+
238
+	/**
239
+	 * Returns a TDBMObject associated from table "$table_name".
240
+	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
241
+	 * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
242
+	 *
243
+	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
244
+	 * 			$user = $tdbmService->getObject('users',1);
245
+	 * 			echo $user->name;
246
+	 * will return the name of the user whose user_id is one.
247
+	 *
248
+	 * 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.
249
+	 * For instance:
250
+	 * 			$group = $tdbmService->getObject('groups',array(1,2));
251
+	 *
252
+	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
253
+	 * will be the same.
254
+	 *
255
+	 * For instance:
256
+	 * 			$user1 = $tdbmService->getObject('users',1);
257
+	 * 			$user2 = $tdbmService->getObject('users',1);
258
+	 * 			$user1->name = 'John Doe';
259
+	 * 			echo $user2->name;
260
+	 * will return 'John Doe'.
261
+	 *
262
+	 * You can use filters instead of passing the primary key. For instance:
263
+	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
264
+	 * This will return the user whose login is 'jdoe'.
265
+	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
266
+	 *
267
+	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
268
+	 * For instance:
269
+	 *  	$user = $tdbmService->getObject('users',1,'User');
270
+	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
271
+	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
272
+	 *
273
+	 * @param string $table_name   The name of the table we retrieve an object from
274
+	 * @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)
275
+	 * @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
276
+	 * @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
277
+	 *
278
+	 * @return TDBMObject
279
+	 */
280 280
 /*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
281 281
 
282 282
         if (is_array($filters) || $filters instanceof FilterInterface) {
@@ -362,199 +362,199 @@  discard block
 block discarded – undo
362 362
         return $obj;
363 363
     }*/
364 364
 
365
-    /**
366
-     * Removes the given object from database.
367
-     * This cannot be called on an object that is not attached to this TDBMService
368
-     * (will throw a TDBMInvalidOperationException).
369
-     *
370
-     * @param AbstractTDBMObject $object the object to delete
371
-     *
372
-     * @throws TDBMException
373
-     * @throws TDBMInvalidOperationException
374
-     */
375
-    public function delete(AbstractTDBMObject $object)
376
-    {
377
-        switch ($object->_getStatus()) {
378
-            case TDBMObjectStateEnum::STATE_DELETED:
379
-                // Nothing to do, object already deleted.
380
-                return;
381
-            case TDBMObjectStateEnum::STATE_DETACHED:
382
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
-            case TDBMObjectStateEnum::STATE_NEW:
384
-                $this->deleteManyToManyRelationships($object);
385
-                foreach ($object->_getDbRows() as $dbRow) {
386
-                    $this->removeFromToSaveObjectList($dbRow);
387
-                }
388
-                break;
389
-            case TDBMObjectStateEnum::STATE_DIRTY:
390
-                foreach ($object->_getDbRows() as $dbRow) {
391
-                    $this->removeFromToSaveObjectList($dbRow);
392
-                }
393
-                // And continue deleting...
394
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
395
-            case TDBMObjectStateEnum::STATE_LOADED:
396
-                $this->deleteManyToManyRelationships($object);
397
-                // Let's delete db rows, in reverse order.
398
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
399
-                    $tableName = $dbRow->_getDbTableName();
400
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
401
-                    $this->connection->delete($tableName, $primaryKeys);
402
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
403
-                }
404
-                break;
405
-            // @codeCoverageIgnoreStart
406
-            default:
407
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
408
-            // @codeCoverageIgnoreEnd
409
-        }
410
-
411
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
412
-    }
413
-
414
-    /**
415
-     * Removes all many to many relationships for this object.
416
-     *
417
-     * @param AbstractTDBMObject $object
418
-     */
419
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
420
-    {
421
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
422
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
423
-            foreach ($pivotTables as $pivotTable) {
424
-                $remoteBeans = $object->_getRelationships($pivotTable);
425
-                foreach ($remoteBeans as $remoteBean) {
426
-                    $object->_removeRelationship($pivotTable, $remoteBean);
427
-                }
428
-            }
429
-        }
430
-        $this->persistManyToManyRelationships($object);
431
-    }
432
-
433
-    /**
434
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
435
-     * by parameter before all.
436
-     *
437
-     * Notice: if the object has a multiple primary key, the function will not work.
438
-     *
439
-     * @param AbstractTDBMObject $objToDelete
440
-     */
441
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
442
-    {
443
-        $this->deleteAllConstraintWithThisObject($objToDelete);
444
-        $this->delete($objToDelete);
445
-    }
446
-
447
-    /**
448
-     * This function is used only in TDBMService (private function)
449
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
450
-     *
451
-     * @param AbstractTDBMObject $obj
452
-     */
453
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
454
-    {
455
-        $dbRows = $obj->_getDbRows();
456
-        foreach ($dbRows as $dbRow) {
457
-            $tableName = $dbRow->_getDbTableName();
458
-            $pks = array_values($dbRow->_getPrimaryKeys());
459
-            if (!empty($pks)) {
460
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
461
-
462
-                foreach ($incomingFks as $incomingFk) {
463
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
464
-
465
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
466
-
467
-                    foreach ($results as $bean) {
468
-                        $this->deleteCascade($bean);
469
-                    }
470
-                }
471
-            }
472
-        }
473
-    }
474
-
475
-    /**
476
-     * This function performs a save() of all the objects that have been modified.
477
-     */
478
-    public function completeSave()
479
-    {
480
-        foreach ($this->toSaveObjects as $dbRow) {
481
-            $this->save($dbRow->getTDBMObject());
482
-        }
483
-    }
484
-
485
-    /**
486
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
487
-     * and gives back a proper Filter object.
488
-     *
489
-     * @param mixed $filter_bag
490
-     * @param int   $counter
491
-     *
492
-     * @return array First item: filter string, second item: parameters
493
-     *
494
-     * @throws TDBMException
495
-     */
496
-    public function buildFilterFromFilterBag($filter_bag, $counter = 1)
497
-    {
498
-        if ($filter_bag === null) {
499
-            return ['', []];
500
-        } elseif (is_string($filter_bag)) {
501
-            return [$filter_bag, []];
502
-        } elseif (is_array($filter_bag)) {
503
-            $sqlParts = [];
504
-            $parameters = [];
505
-            foreach ($filter_bag as $column => $value) {
506
-                if (is_int($column)) {
507
-                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
508
-                    $sqlParts[] = $subSqlPart;
509
-                    $parameters += $subParameters;
510
-                } else {
511
-                    $paramName = 'tdbmparam'.$counter;
512
-                    if (is_array($value)) {
513
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
514
-                    } else {
515
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
516
-                    }
517
-                    $parameters[$paramName] = $value;
518
-                    ++$counter;
519
-                }
520
-            }
521
-
522
-            return [implode(' AND ', $sqlParts), $parameters];
523
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
524
-            $sqlParts = [];
525
-            $parameters = [];
526
-            $dbRows = $filter_bag->_getDbRows();
527
-            $dbRow = reset($dbRows);
528
-            $primaryKeys = $dbRow->_getPrimaryKeys();
529
-
530
-            foreach ($primaryKeys as $column => $value) {
531
-                $paramName = 'tdbmparam'.$counter;
532
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
533
-                $parameters[$paramName] = $value;
534
-                ++$counter;
535
-            }
536
-
537
-            return [implode(' AND ', $sqlParts), $parameters];
538
-        } elseif ($filter_bag instanceof \Iterator) {
539
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
540
-        } else {
541
-            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.');
542
-        }
543
-    }
544
-
545
-    /**
546
-     * @param string $table
547
-     *
548
-     * @return string[]
549
-     */
550
-    public function getPrimaryKeyColumns($table)
551
-    {
552
-        if (!isset($this->primaryKeysColumns[$table])) {
553
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
554
-
555
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
556
-
557
-            /*$arr = array();
365
+	/**
366
+	 * Removes the given object from database.
367
+	 * This cannot be called on an object that is not attached to this TDBMService
368
+	 * (will throw a TDBMInvalidOperationException).
369
+	 *
370
+	 * @param AbstractTDBMObject $object the object to delete
371
+	 *
372
+	 * @throws TDBMException
373
+	 * @throws TDBMInvalidOperationException
374
+	 */
375
+	public function delete(AbstractTDBMObject $object)
376
+	{
377
+		switch ($object->_getStatus()) {
378
+			case TDBMObjectStateEnum::STATE_DELETED:
379
+				// Nothing to do, object already deleted.
380
+				return;
381
+			case TDBMObjectStateEnum::STATE_DETACHED:
382
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
+			case TDBMObjectStateEnum::STATE_NEW:
384
+				$this->deleteManyToManyRelationships($object);
385
+				foreach ($object->_getDbRows() as $dbRow) {
386
+					$this->removeFromToSaveObjectList($dbRow);
387
+				}
388
+				break;
389
+			case TDBMObjectStateEnum::STATE_DIRTY:
390
+				foreach ($object->_getDbRows() as $dbRow) {
391
+					$this->removeFromToSaveObjectList($dbRow);
392
+				}
393
+				// And continue deleting...
394
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
395
+			case TDBMObjectStateEnum::STATE_LOADED:
396
+				$this->deleteManyToManyRelationships($object);
397
+				// Let's delete db rows, in reverse order.
398
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
399
+					$tableName = $dbRow->_getDbTableName();
400
+					$primaryKeys = $dbRow->_getPrimaryKeys();
401
+					$this->connection->delete($tableName, $primaryKeys);
402
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
403
+				}
404
+				break;
405
+			// @codeCoverageIgnoreStart
406
+			default:
407
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
408
+			// @codeCoverageIgnoreEnd
409
+		}
410
+
411
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
412
+	}
413
+
414
+	/**
415
+	 * Removes all many to many relationships for this object.
416
+	 *
417
+	 * @param AbstractTDBMObject $object
418
+	 */
419
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
420
+	{
421
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
422
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
423
+			foreach ($pivotTables as $pivotTable) {
424
+				$remoteBeans = $object->_getRelationships($pivotTable);
425
+				foreach ($remoteBeans as $remoteBean) {
426
+					$object->_removeRelationship($pivotTable, $remoteBean);
427
+				}
428
+			}
429
+		}
430
+		$this->persistManyToManyRelationships($object);
431
+	}
432
+
433
+	/**
434
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
435
+	 * by parameter before all.
436
+	 *
437
+	 * Notice: if the object has a multiple primary key, the function will not work.
438
+	 *
439
+	 * @param AbstractTDBMObject $objToDelete
440
+	 */
441
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
442
+	{
443
+		$this->deleteAllConstraintWithThisObject($objToDelete);
444
+		$this->delete($objToDelete);
445
+	}
446
+
447
+	/**
448
+	 * This function is used only in TDBMService (private function)
449
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
450
+	 *
451
+	 * @param AbstractTDBMObject $obj
452
+	 */
453
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
454
+	{
455
+		$dbRows = $obj->_getDbRows();
456
+		foreach ($dbRows as $dbRow) {
457
+			$tableName = $dbRow->_getDbTableName();
458
+			$pks = array_values($dbRow->_getPrimaryKeys());
459
+			if (!empty($pks)) {
460
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
461
+
462
+				foreach ($incomingFks as $incomingFk) {
463
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
464
+
465
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
466
+
467
+					foreach ($results as $bean) {
468
+						$this->deleteCascade($bean);
469
+					}
470
+				}
471
+			}
472
+		}
473
+	}
474
+
475
+	/**
476
+	 * This function performs a save() of all the objects that have been modified.
477
+	 */
478
+	public function completeSave()
479
+	{
480
+		foreach ($this->toSaveObjects as $dbRow) {
481
+			$this->save($dbRow->getTDBMObject());
482
+		}
483
+	}
484
+
485
+	/**
486
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
487
+	 * and gives back a proper Filter object.
488
+	 *
489
+	 * @param mixed $filter_bag
490
+	 * @param int   $counter
491
+	 *
492
+	 * @return array First item: filter string, second item: parameters
493
+	 *
494
+	 * @throws TDBMException
495
+	 */
496
+	public function buildFilterFromFilterBag($filter_bag, $counter = 1)
497
+	{
498
+		if ($filter_bag === null) {
499
+			return ['', []];
500
+		} elseif (is_string($filter_bag)) {
501
+			return [$filter_bag, []];
502
+		} elseif (is_array($filter_bag)) {
503
+			$sqlParts = [];
504
+			$parameters = [];
505
+			foreach ($filter_bag as $column => $value) {
506
+				if (is_int($column)) {
507
+					list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
508
+					$sqlParts[] = $subSqlPart;
509
+					$parameters += $subParameters;
510
+				} else {
511
+					$paramName = 'tdbmparam'.$counter;
512
+					if (is_array($value)) {
513
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
514
+					} else {
515
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
516
+					}
517
+					$parameters[$paramName] = $value;
518
+					++$counter;
519
+				}
520
+			}
521
+
522
+			return [implode(' AND ', $sqlParts), $parameters];
523
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
524
+			$sqlParts = [];
525
+			$parameters = [];
526
+			$dbRows = $filter_bag->_getDbRows();
527
+			$dbRow = reset($dbRows);
528
+			$primaryKeys = $dbRow->_getPrimaryKeys();
529
+
530
+			foreach ($primaryKeys as $column => $value) {
531
+				$paramName = 'tdbmparam'.$counter;
532
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
533
+				$parameters[$paramName] = $value;
534
+				++$counter;
535
+			}
536
+
537
+			return [implode(' AND ', $sqlParts), $parameters];
538
+		} elseif ($filter_bag instanceof \Iterator) {
539
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
540
+		} else {
541
+			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.');
542
+		}
543
+	}
544
+
545
+	/**
546
+	 * @param string $table
547
+	 *
548
+	 * @return string[]
549
+	 */
550
+	public function getPrimaryKeyColumns($table)
551
+	{
552
+		if (!isset($this->primaryKeysColumns[$table])) {
553
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
554
+
555
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
556
+
557
+			/*$arr = array();
558 558
             foreach ($this->connection->getPrimaryKey($table) as $col) {
559 559
                 $arr[] = $col->name;
560 560
             }
@@ -575,157 +575,157 @@  discard block
 block discarded – undo
575 575
                     throw new TDBMException($str);
576 576
                 }
577 577
             }*/
578
-        }
579
-
580
-        return $this->primaryKeysColumns[$table];
581
-    }
582
-
583
-    /**
584
-     * This is an internal function, you should not use it in your application.
585
-     * This is used internally by TDBM to add an object to the object cache.
586
-     *
587
-     * @param DbRow $dbRow
588
-     */
589
-    public function _addToCache(DbRow $dbRow)
590
-    {
591
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
592
-        $hash = $this->getObjectHash($primaryKey);
593
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
594
-    }
595
-
596
-    /**
597
-     * This is an internal function, you should not use it in your application.
598
-     * This is used internally by TDBM to remove the object from the list of objects that have been
599
-     * created/updated but not saved yet.
600
-     *
601
-     * @param DbRow $myObject
602
-     */
603
-    private function removeFromToSaveObjectList(DbRow $myObject)
604
-    {
605
-        unset($this->toSaveObjects[$myObject]);
606
-    }
607
-
608
-    /**
609
-     * This is an internal function, you should not use it in your application.
610
-     * This is used internally by TDBM to add an object to the list of objects that have been
611
-     * created/updated but not saved yet.
612
-     *
613
-     * @param AbstractTDBMObject $myObject
614
-     */
615
-    public function _addToToSaveObjectList(DbRow $myObject)
616
-    {
617
-        $this->toSaveObjects[$myObject] = true;
618
-    }
619
-
620
-    /**
621
-     * Generates all the daos and beans.
622
-     *
623
-     * @param string $daoFactoryClassName The classe name of the DAO factory
624
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
625
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
626
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
627
-     * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
628
-     *
629
-     * @return \string[] the list of tables
630
-     */
631
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
632
-    {
633
-        // Purge cache before generating anything.
634
-        $this->cache->deleteAll();
635
-
636
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
-        if (null !== $composerFile) {
638
-            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
-        }
640
-
641
-        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
-    }
643
-
644
-    /**
645
-     * @param array<string, string> $tableToBeanMap
646
-     */
647
-    public function setTableToBeanMap(array $tableToBeanMap)
648
-    {
649
-        $this->tableToBeanMap = $tableToBeanMap;
650
-    }
651
-
652
-    /**
653
-     * Returns the fully qualified class name of the bean associated with table $tableName.
654
-     *
655
-     *
656
-     * @param string $tableName
657
-     * @return string
658
-     */
659
-    public function getBeanClassName(string $tableName) : string
660
-    {
661
-        if (isset($this->tableToBeanMap[$tableName])) {
662
-            return $this->tableToBeanMap[$tableName];
663
-        } else {
664
-            throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
665
-        }
666
-    }
667
-
668
-    /**
669
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
670
-     *
671
-     * @param AbstractTDBMObject $object
672
-     *
673
-     * @throws TDBMException
674
-     */
675
-    public function save(AbstractTDBMObject $object)
676
-    {
677
-        $status = $object->_getStatus();
678
-
679
-        if ($status === null) {
680
-            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)));
681
-        }
682
-
683
-        // Let's attach this object if it is in detached state.
684
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
685
-            $object->_attach($this);
686
-            $status = $object->_getStatus();
687
-        }
688
-
689
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
690
-            $dbRows = $object->_getDbRows();
691
-
692
-            $unindexedPrimaryKeys = array();
693
-
694
-            foreach ($dbRows as $dbRow) {
695
-                $tableName = $dbRow->_getDbTableName();
696
-
697
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
698
-                $tableDescriptor = $schema->getTable($tableName);
699
-
700
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
701
-
702
-                if (empty($unindexedPrimaryKeys)) {
703
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
704
-                } else {
705
-                    // First insert, the children must have the same primary key as the parent.
706
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
707
-                    $dbRow->_setPrimaryKeys($primaryKeys);
708
-                }
709
-
710
-                $references = $dbRow->_getReferences();
711
-
712
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
713
-                foreach ($references as $fkName => $reference) {
714
-                    if ($reference !== null) {
715
-                        $refStatus = $reference->_getStatus();
716
-                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
717
-                            $this->save($reference);
718
-                        }
719
-                    }
720
-                }
721
-
722
-                $dbRowData = $dbRow->_getDbRow();
723
-
724
-                // Let's see if the columns for primary key have been set before inserting.
725
-                // We assume that if one of the value of the PK has been set, the PK is set.
726
-                $isPkSet = !empty($primaryKeys);
727
-
728
-                /*if (!$isPkSet) {
578
+		}
579
+
580
+		return $this->primaryKeysColumns[$table];
581
+	}
582
+
583
+	/**
584
+	 * This is an internal function, you should not use it in your application.
585
+	 * This is used internally by TDBM to add an object to the object cache.
586
+	 *
587
+	 * @param DbRow $dbRow
588
+	 */
589
+	public function _addToCache(DbRow $dbRow)
590
+	{
591
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
592
+		$hash = $this->getObjectHash($primaryKey);
593
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
594
+	}
595
+
596
+	/**
597
+	 * This is an internal function, you should not use it in your application.
598
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
599
+	 * created/updated but not saved yet.
600
+	 *
601
+	 * @param DbRow $myObject
602
+	 */
603
+	private function removeFromToSaveObjectList(DbRow $myObject)
604
+	{
605
+		unset($this->toSaveObjects[$myObject]);
606
+	}
607
+
608
+	/**
609
+	 * This is an internal function, you should not use it in your application.
610
+	 * This is used internally by TDBM to add an object to the list of objects that have been
611
+	 * created/updated but not saved yet.
612
+	 *
613
+	 * @param AbstractTDBMObject $myObject
614
+	 */
615
+	public function _addToToSaveObjectList(DbRow $myObject)
616
+	{
617
+		$this->toSaveObjects[$myObject] = true;
618
+	}
619
+
620
+	/**
621
+	 * Generates all the daos and beans.
622
+	 *
623
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
624
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
625
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
626
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
627
+	 * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
628
+	 *
629
+	 * @return \string[] the list of tables
630
+	 */
631
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
632
+	{
633
+		// Purge cache before generating anything.
634
+		$this->cache->deleteAll();
635
+
636
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
+		if (null !== $composerFile) {
638
+			$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
+		}
640
+
641
+		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
+	}
643
+
644
+	/**
645
+	 * @param array<string, string> $tableToBeanMap
646
+	 */
647
+	public function setTableToBeanMap(array $tableToBeanMap)
648
+	{
649
+		$this->tableToBeanMap = $tableToBeanMap;
650
+	}
651
+
652
+	/**
653
+	 * Returns the fully qualified class name of the bean associated with table $tableName.
654
+	 *
655
+	 *
656
+	 * @param string $tableName
657
+	 * @return string
658
+	 */
659
+	public function getBeanClassName(string $tableName) : string
660
+	{
661
+		if (isset($this->tableToBeanMap[$tableName])) {
662
+			return $this->tableToBeanMap[$tableName];
663
+		} else {
664
+			throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
665
+		}
666
+	}
667
+
668
+	/**
669
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
670
+	 *
671
+	 * @param AbstractTDBMObject $object
672
+	 *
673
+	 * @throws TDBMException
674
+	 */
675
+	public function save(AbstractTDBMObject $object)
676
+	{
677
+		$status = $object->_getStatus();
678
+
679
+		if ($status === null) {
680
+			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)));
681
+		}
682
+
683
+		// Let's attach this object if it is in detached state.
684
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
685
+			$object->_attach($this);
686
+			$status = $object->_getStatus();
687
+		}
688
+
689
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
690
+			$dbRows = $object->_getDbRows();
691
+
692
+			$unindexedPrimaryKeys = array();
693
+
694
+			foreach ($dbRows as $dbRow) {
695
+				$tableName = $dbRow->_getDbTableName();
696
+
697
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
698
+				$tableDescriptor = $schema->getTable($tableName);
699
+
700
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
701
+
702
+				if (empty($unindexedPrimaryKeys)) {
703
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
704
+				} else {
705
+					// First insert, the children must have the same primary key as the parent.
706
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
707
+					$dbRow->_setPrimaryKeys($primaryKeys);
708
+				}
709
+
710
+				$references = $dbRow->_getReferences();
711
+
712
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
713
+				foreach ($references as $fkName => $reference) {
714
+					if ($reference !== null) {
715
+						$refStatus = $reference->_getStatus();
716
+						if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
717
+							$this->save($reference);
718
+						}
719
+					}
720
+				}
721
+
722
+				$dbRowData = $dbRow->_getDbRow();
723
+
724
+				// Let's see if the columns for primary key have been set before inserting.
725
+				// We assume that if one of the value of the PK has been set, the PK is set.
726
+				$isPkSet = !empty($primaryKeys);
727
+
728
+				/*if (!$isPkSet) {
729 729
                     // if there is no autoincrement and no pk set, let's go in error.
730 730
                     $isAutoIncrement = true;
731 731
 
@@ -743,27 +743,27 @@  discard block
 block discarded – undo
743 743
 
744 744
                 }*/
745 745
 
746
-                $types = [];
747
-                $escapedDbRowData = [];
746
+				$types = [];
747
+				$escapedDbRowData = [];
748 748
 
749
-                foreach ($dbRowData as $columnName => $value) {
750
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
751
-                    $types[] = $columnDescriptor->getType();
752
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
753
-                }
749
+				foreach ($dbRowData as $columnName => $value) {
750
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
751
+					$types[] = $columnDescriptor->getType();
752
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
753
+				}
754 754
 
755
-                $this->connection->insert($tableName, $escapedDbRowData, $types);
755
+				$this->connection->insert($tableName, $escapedDbRowData, $types);
756 756
 
757
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
758
-                    $id = $this->connection->lastInsertId();
759
-                    $primaryKeys[$primaryKeyColumns[0]] = $id;
760
-                }
757
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
758
+					$id = $this->connection->lastInsertId();
759
+					$primaryKeys[$primaryKeyColumns[0]] = $id;
760
+				}
761 761
 
762
-                // TODO: change this to some private magic accessor in future
763
-                $dbRow->_setPrimaryKeys($primaryKeys);
764
-                $unindexedPrimaryKeys = array_values($primaryKeys);
762
+				// TODO: change this to some private magic accessor in future
763
+				$dbRow->_setPrimaryKeys($primaryKeys);
764
+				$unindexedPrimaryKeys = array_values($primaryKeys);
765 765
 
766
-                /*
766
+				/*
767 767
                  * When attached, on "save", we check if the column updated is part of a primary key
768 768
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
769 769
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
                  *
774 774
                  */
775 775
 
776
-                /*try {
776
+				/*try {
777 777
                     $this->db_connection->exec($sql);
778 778
                 } catch (TDBMException $e) {
779 779
                     $this->db_onerror = true;
@@ -792,405 +792,405 @@  discard block
 block discarded – undo
792 792
                     }
793 793
                 }*/
794 794
 
795
-                // Let's remove this object from the $new_objects static table.
796
-                $this->removeFromToSaveObjectList($dbRow);
797
-
798
-                // TODO: change this behaviour to something more sensible performance-wise
799
-                // Maybe a setting to trigger this globally?
800
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
801
-                //$this->db_modified_state = false;
802
-                //$dbRow = array();
803
-
804
-                // Let's add this object to the list of objects in cache.
805
-                $this->_addToCache($dbRow);
806
-            }
807
-
808
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
809
-        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
810
-            $dbRows = $object->_getDbRows();
811
-
812
-            foreach ($dbRows as $dbRow) {
813
-                $references = $dbRow->_getReferences();
814
-
815
-                // Let's save all references in NEW state (we need their primary key)
816
-                foreach ($references as $fkName => $reference) {
817
-                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
818
-                        $this->save($reference);
819
-                    }
820
-                }
821
-
822
-                // Let's first get the primary keys
823
-                $tableName = $dbRow->_getDbTableName();
824
-                $dbRowData = $dbRow->_getDbRow();
825
-
826
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
827
-                $tableDescriptor = $schema->getTable($tableName);
828
-
829
-                $primaryKeys = $dbRow->_getPrimaryKeys();
830
-
831
-                $types = [];
832
-                $escapedDbRowData = [];
833
-                $escapedPrimaryKeys = [];
834
-
835
-                foreach ($dbRowData as $columnName => $value) {
836
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
837
-                    $types[] = $columnDescriptor->getType();
838
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
839
-                }
840
-                foreach ($primaryKeys as $columnName => $value) {
841
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
842
-                    $types[] = $columnDescriptor->getType();
843
-                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
844
-                }
845
-
846
-                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
847
-
848
-                // Let's check if the primary key has been updated...
849
-                $needsUpdatePk = false;
850
-                foreach ($primaryKeys as $column => $value) {
851
-                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
852
-                        $needsUpdatePk = true;
853
-                        break;
854
-                    }
855
-                }
856
-                if ($needsUpdatePk) {
857
-                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
858
-                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
859
-                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
860
-                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
861
-                }
862
-
863
-                // Let's remove this object from the list of objects to save.
864
-                $this->removeFromToSaveObjectList($dbRow);
865
-            }
866
-
867
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
868
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
869
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
870
-        }
871
-
872
-        // Finally, let's save all the many to many relationships to this bean.
873
-        $this->persistManyToManyRelationships($object);
874
-    }
875
-
876
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
877
-    {
878
-        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
879
-            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
880
-            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
881
-
882
-            $toRemoveFromStorage = [];
883
-
884
-            foreach ($storage as $remoteBean) {
885
-                /* @var $remoteBean AbstractTDBMObject */
886
-                $statusArr = $storage[$remoteBean];
887
-                $status = $statusArr['status'];
888
-                $reverse = $statusArr['reverse'];
889
-                if ($reverse) {
890
-                    continue;
891
-                }
892
-
893
-                if ($status === 'new') {
894
-                    $remoteBeanStatus = $remoteBean->_getStatus();
895
-                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
896
-                        // Let's save remote bean if needed.
897
-                        $this->save($remoteBean);
898
-                    }
899
-
900
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
901
-
902
-                    $types = [];
903
-                    $escapedFilters = [];
904
-
905
-                    foreach ($filters as $columnName => $value) {
906
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
907
-                        $types[] = $columnDescriptor->getType();
908
-                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
909
-                    }
910
-
911
-                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
912
-
913
-                    // Finally, let's mark relationships as saved.
914
-                    $statusArr['status'] = 'loaded';
915
-                    $storage[$remoteBean] = $statusArr;
916
-                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
917
-                    $remoteStatusArr = $remoteStorage[$object];
918
-                    $remoteStatusArr['status'] = 'loaded';
919
-                    $remoteStorage[$object] = $remoteStatusArr;
920
-                } elseif ($status === 'delete') {
921
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
922
-
923
-                    $types = [];
924
-
925
-                    foreach ($filters as $columnName => $value) {
926
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
927
-                        $types[] = $columnDescriptor->getType();
928
-                    }
929
-
930
-                    $this->connection->delete($pivotTableName, $filters, $types);
931
-
932
-                    // Finally, let's remove relationships completely from bean.
933
-                    $toRemoveFromStorage[] = $remoteBean;
934
-
935
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
936
-                }
937
-            }
938
-
939
-            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
940
-            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
941
-            foreach ($toRemoveFromStorage as $remoteBean) {
942
-                $storage->detach($remoteBean);
943
-            }
944
-        }
945
-    }
946
-
947
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
948
-    {
949
-        $localBeanPk = $this->getPrimaryKeyValues($localBean);
950
-        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
951
-        $localColumns = $localFk->getLocalColumns();
952
-        $remoteColumns = $remoteFk->getLocalColumns();
953
-
954
-        $localFilters = array_combine($localColumns, $localBeanPk);
955
-        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
956
-
957
-        return array_merge($localFilters, $remoteFilters);
958
-    }
959
-
960
-    /**
961
-     * Returns the "values" of the primary key.
962
-     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
963
-     *
964
-     * @param AbstractTDBMObject $bean
965
-     *
966
-     * @return array numerically indexed array of values
967
-     */
968
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
969
-    {
970
-        $dbRows = $bean->_getDbRows();
971
-        $dbRow = reset($dbRows);
972
-
973
-        return array_values($dbRow->_getPrimaryKeys());
974
-    }
975
-
976
-    /**
977
-     * Returns a unique hash used to store the object based on its primary key.
978
-     * If the array contains only one value, then the value is returned.
979
-     * Otherwise, a hash representing the array is returned.
980
-     *
981
-     * @param array $primaryKeys An array of columns => values forming the primary key
982
-     *
983
-     * @return string
984
-     */
985
-    public function getObjectHash(array $primaryKeys)
986
-    {
987
-        if (count($primaryKeys) === 1) {
988
-            return reset($primaryKeys);
989
-        } else {
990
-            ksort($primaryKeys);
991
-
992
-            return md5(json_encode($primaryKeys));
993
-        }
994
-    }
995
-
996
-    /**
997
-     * Returns an array of primary keys from the object.
998
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
999
-     * $primaryKeys variable of the object.
1000
-     *
1001
-     * @param DbRow $dbRow
1002
-     *
1003
-     * @return array Returns an array of column => value
1004
-     */
1005
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1006
-    {
1007
-        $table = $dbRow->_getDbTableName();
1008
-        $dbRowData = $dbRow->_getDbRow();
1009
-
1010
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1011
-    }
1012
-
1013
-    /**
1014
-     * Returns an array of primary keys for the given row.
1015
-     * The primary keys are extracted from the object columns.
1016
-     *
1017
-     * @param $table
1018
-     * @param array $columns
1019
-     *
1020
-     * @return array
1021
-     */
1022
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
1023
-    {
1024
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1025
-        $values = array();
1026
-        foreach ($primaryKeyColumns as $column) {
1027
-            if (isset($columns[$column])) {
1028
-                $values[$column] = $columns[$column];
1029
-            }
1030
-        }
1031
-
1032
-        return $values;
1033
-    }
1034
-
1035
-    /**
1036
-     * Attaches $object to this TDBMService.
1037
-     * The $object must be in DETACHED state and will pass in NEW state.
1038
-     *
1039
-     * @param AbstractTDBMObject $object
1040
-     *
1041
-     * @throws TDBMInvalidOperationException
1042
-     */
1043
-    public function attach(AbstractTDBMObject $object)
1044
-    {
1045
-        $object->_attach($this);
1046
-    }
1047
-
1048
-    /**
1049
-     * Returns an associative array (column => value) for the primary keys from the table name and an
1050
-     * indexed array of primary key values.
1051
-     *
1052
-     * @param string $tableName
1053
-     * @param array  $indexedPrimaryKeys
1054
-     */
1055
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1056
-    {
1057
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1058
-
1059
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1060
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
795
+				// Let's remove this object from the $new_objects static table.
796
+				$this->removeFromToSaveObjectList($dbRow);
797
+
798
+				// TODO: change this behaviour to something more sensible performance-wise
799
+				// Maybe a setting to trigger this globally?
800
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
801
+				//$this->db_modified_state = false;
802
+				//$dbRow = array();
803
+
804
+				// Let's add this object to the list of objects in cache.
805
+				$this->_addToCache($dbRow);
806
+			}
807
+
808
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
809
+		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
810
+			$dbRows = $object->_getDbRows();
811
+
812
+			foreach ($dbRows as $dbRow) {
813
+				$references = $dbRow->_getReferences();
814
+
815
+				// Let's save all references in NEW state (we need their primary key)
816
+				foreach ($references as $fkName => $reference) {
817
+					if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
818
+						$this->save($reference);
819
+					}
820
+				}
821
+
822
+				// Let's first get the primary keys
823
+				$tableName = $dbRow->_getDbTableName();
824
+				$dbRowData = $dbRow->_getDbRow();
825
+
826
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
827
+				$tableDescriptor = $schema->getTable($tableName);
828
+
829
+				$primaryKeys = $dbRow->_getPrimaryKeys();
830
+
831
+				$types = [];
832
+				$escapedDbRowData = [];
833
+				$escapedPrimaryKeys = [];
834
+
835
+				foreach ($dbRowData as $columnName => $value) {
836
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
837
+					$types[] = $columnDescriptor->getType();
838
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
839
+				}
840
+				foreach ($primaryKeys as $columnName => $value) {
841
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
842
+					$types[] = $columnDescriptor->getType();
843
+					$escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
844
+				}
845
+
846
+				$this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
847
+
848
+				// Let's check if the primary key has been updated...
849
+				$needsUpdatePk = false;
850
+				foreach ($primaryKeys as $column => $value) {
851
+					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
852
+						$needsUpdatePk = true;
853
+						break;
854
+					}
855
+				}
856
+				if ($needsUpdatePk) {
857
+					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
858
+					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
859
+					$dbRow->_setPrimaryKeys($newPrimaryKeys);
860
+					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
861
+				}
862
+
863
+				// Let's remove this object from the list of objects to save.
864
+				$this->removeFromToSaveObjectList($dbRow);
865
+			}
866
+
867
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
868
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
869
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
870
+		}
871
+
872
+		// Finally, let's save all the many to many relationships to this bean.
873
+		$this->persistManyToManyRelationships($object);
874
+	}
875
+
876
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
877
+	{
878
+		foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
879
+			$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
880
+			list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
881
+
882
+			$toRemoveFromStorage = [];
883
+
884
+			foreach ($storage as $remoteBean) {
885
+				/* @var $remoteBean AbstractTDBMObject */
886
+				$statusArr = $storage[$remoteBean];
887
+				$status = $statusArr['status'];
888
+				$reverse = $statusArr['reverse'];
889
+				if ($reverse) {
890
+					continue;
891
+				}
892
+
893
+				if ($status === 'new') {
894
+					$remoteBeanStatus = $remoteBean->_getStatus();
895
+					if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
896
+						// Let's save remote bean if needed.
897
+						$this->save($remoteBean);
898
+					}
899
+
900
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
901
+
902
+					$types = [];
903
+					$escapedFilters = [];
904
+
905
+					foreach ($filters as $columnName => $value) {
906
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
907
+						$types[] = $columnDescriptor->getType();
908
+						$escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
909
+					}
910
+
911
+					$this->connection->insert($pivotTableName, $escapedFilters, $types);
912
+
913
+					// Finally, let's mark relationships as saved.
914
+					$statusArr['status'] = 'loaded';
915
+					$storage[$remoteBean] = $statusArr;
916
+					$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
917
+					$remoteStatusArr = $remoteStorage[$object];
918
+					$remoteStatusArr['status'] = 'loaded';
919
+					$remoteStorage[$object] = $remoteStatusArr;
920
+				} elseif ($status === 'delete') {
921
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
922
+
923
+					$types = [];
924
+
925
+					foreach ($filters as $columnName => $value) {
926
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
927
+						$types[] = $columnDescriptor->getType();
928
+					}
929
+
930
+					$this->connection->delete($pivotTableName, $filters, $types);
931
+
932
+					// Finally, let's remove relationships completely from bean.
933
+					$toRemoveFromStorage[] = $remoteBean;
934
+
935
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
936
+				}
937
+			}
938
+
939
+			// Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
940
+			// Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
941
+			foreach ($toRemoveFromStorage as $remoteBean) {
942
+				$storage->detach($remoteBean);
943
+			}
944
+		}
945
+	}
946
+
947
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
948
+	{
949
+		$localBeanPk = $this->getPrimaryKeyValues($localBean);
950
+		$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
951
+		$localColumns = $localFk->getLocalColumns();
952
+		$remoteColumns = $remoteFk->getLocalColumns();
953
+
954
+		$localFilters = array_combine($localColumns, $localBeanPk);
955
+		$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
956
+
957
+		return array_merge($localFilters, $remoteFilters);
958
+	}
959
+
960
+	/**
961
+	 * Returns the "values" of the primary key.
962
+	 * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
963
+	 *
964
+	 * @param AbstractTDBMObject $bean
965
+	 *
966
+	 * @return array numerically indexed array of values
967
+	 */
968
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
969
+	{
970
+		$dbRows = $bean->_getDbRows();
971
+		$dbRow = reset($dbRows);
972
+
973
+		return array_values($dbRow->_getPrimaryKeys());
974
+	}
975
+
976
+	/**
977
+	 * Returns a unique hash used to store the object based on its primary key.
978
+	 * If the array contains only one value, then the value is returned.
979
+	 * Otherwise, a hash representing the array is returned.
980
+	 *
981
+	 * @param array $primaryKeys An array of columns => values forming the primary key
982
+	 *
983
+	 * @return string
984
+	 */
985
+	public function getObjectHash(array $primaryKeys)
986
+	{
987
+		if (count($primaryKeys) === 1) {
988
+			return reset($primaryKeys);
989
+		} else {
990
+			ksort($primaryKeys);
991
+
992
+			return md5(json_encode($primaryKeys));
993
+		}
994
+	}
995
+
996
+	/**
997
+	 * Returns an array of primary keys from the object.
998
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
999
+	 * $primaryKeys variable of the object.
1000
+	 *
1001
+	 * @param DbRow $dbRow
1002
+	 *
1003
+	 * @return array Returns an array of column => value
1004
+	 */
1005
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1006
+	{
1007
+		$table = $dbRow->_getDbTableName();
1008
+		$dbRowData = $dbRow->_getDbRow();
1009
+
1010
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1011
+	}
1012
+
1013
+	/**
1014
+	 * Returns an array of primary keys for the given row.
1015
+	 * The primary keys are extracted from the object columns.
1016
+	 *
1017
+	 * @param $table
1018
+	 * @param array $columns
1019
+	 *
1020
+	 * @return array
1021
+	 */
1022
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
1023
+	{
1024
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1025
+		$values = array();
1026
+		foreach ($primaryKeyColumns as $column) {
1027
+			if (isset($columns[$column])) {
1028
+				$values[$column] = $columns[$column];
1029
+			}
1030
+		}
1031
+
1032
+		return $values;
1033
+	}
1034
+
1035
+	/**
1036
+	 * Attaches $object to this TDBMService.
1037
+	 * The $object must be in DETACHED state and will pass in NEW state.
1038
+	 *
1039
+	 * @param AbstractTDBMObject $object
1040
+	 *
1041
+	 * @throws TDBMInvalidOperationException
1042
+	 */
1043
+	public function attach(AbstractTDBMObject $object)
1044
+	{
1045
+		$object->_attach($this);
1046
+	}
1047
+
1048
+	/**
1049
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
1050
+	 * indexed array of primary key values.
1051
+	 *
1052
+	 * @param string $tableName
1053
+	 * @param array  $indexedPrimaryKeys
1054
+	 */
1055
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1056
+	{
1057
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1058
+
1059
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1060
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1061 1061
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1062
-        }
1063
-
1064
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1065
-    }
1066
-
1067
-    /**
1068
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1069
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1070
-     *
1071
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1072
-     * we must be able to find all other tables.
1073
-     *
1074
-     * @param string[] $tables
1075
-     *
1076
-     * @return string[]
1077
-     */
1078
-    public function _getLinkBetweenInheritedTables(array $tables)
1079
-    {
1080
-        sort($tables);
1081
-
1082
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1083
-            function () use ($tables) {
1084
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1085
-            });
1086
-    }
1087
-
1088
-    /**
1089
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1090
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1091
-     *
1092
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1093
-     * we must be able to find all other tables.
1094
-     *
1095
-     * @param string[] $tables
1096
-     *
1097
-     * @return string[]
1098
-     */
1099
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1100
-    {
1101
-        $schemaAnalyzer = $this->schemaAnalyzer;
1102
-
1103
-        foreach ($tables as $currentTable) {
1104
-            $allParents = [$currentTable];
1105
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1106
-                $currentTable = $currentFk->getForeignTableName();
1107
-                $allParents[] = $currentTable;
1108
-            }
1109
-
1110
-            // Now, does the $allParents contain all the tables we want?
1111
-            $notFoundTables = array_diff($tables, $allParents);
1112
-            if (empty($notFoundTables)) {
1113
-                // We have a winner!
1114
-                return $allParents;
1115
-            }
1116
-        }
1117
-
1118
-        throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1119
-    }
1120
-
1121
-    /**
1122
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1123
-     *
1124
-     * @param string $table
1125
-     *
1126
-     * @return string[]
1127
-     */
1128
-    public function _getRelatedTablesByInheritance($table)
1129
-    {
1130
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1131
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1132
-        });
1133
-    }
1134
-
1135
-    /**
1136
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1137
-     *
1138
-     * @param string $table
1139
-     *
1140
-     * @return string[]
1141
-     */
1142
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1143
-    {
1144
-        $schemaAnalyzer = $this->schemaAnalyzer;
1145
-
1146
-        // Let's scan the parent tables
1147
-        $currentTable = $table;
1148
-
1149
-        $parentTables = [];
1150
-
1151
-        // Get parent relationship
1152
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1153
-            $currentTable = $currentFk->getForeignTableName();
1154
-            $parentTables[] = $currentTable;
1155
-        }
1156
-
1157
-        // Let's recurse in children
1158
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1159
-
1160
-        return array_merge(array_reverse($parentTables), $childrenTables);
1161
-    }
1162
-
1163
-    /**
1164
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1165
-     *
1166
-     * @param string $table
1167
-     *
1168
-     * @return string[]
1169
-     */
1170
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1171
-    {
1172
-        $tables = [$table];
1173
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1174
-
1175
-        foreach ($keys as $key) {
1176
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1177
-        }
1178
-
1179
-        return $tables;
1180
-    }
1181
-
1182
-    /**
1183
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1184
-     * The returned value does contain only one table. For instance:.
1185
-     *
1186
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1187
-     *
1188
-     * @param ForeignKeyConstraint $fk
1189
-     * @param bool                 $leftTableIsLocal
1190
-     *
1191
-     * @return string
1192
-     */
1193
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1062
+		}
1063
+
1064
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1065
+	}
1066
+
1067
+	/**
1068
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1069
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1070
+	 *
1071
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1072
+	 * we must be able to find all other tables.
1073
+	 *
1074
+	 * @param string[] $tables
1075
+	 *
1076
+	 * @return string[]
1077
+	 */
1078
+	public function _getLinkBetweenInheritedTables(array $tables)
1079
+	{
1080
+		sort($tables);
1081
+
1082
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1083
+			function () use ($tables) {
1084
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1085
+			});
1086
+	}
1087
+
1088
+	/**
1089
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1090
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1091
+	 *
1092
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1093
+	 * we must be able to find all other tables.
1094
+	 *
1095
+	 * @param string[] $tables
1096
+	 *
1097
+	 * @return string[]
1098
+	 */
1099
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1100
+	{
1101
+		$schemaAnalyzer = $this->schemaAnalyzer;
1102
+
1103
+		foreach ($tables as $currentTable) {
1104
+			$allParents = [$currentTable];
1105
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1106
+				$currentTable = $currentFk->getForeignTableName();
1107
+				$allParents[] = $currentTable;
1108
+			}
1109
+
1110
+			// Now, does the $allParents contain all the tables we want?
1111
+			$notFoundTables = array_diff($tables, $allParents);
1112
+			if (empty($notFoundTables)) {
1113
+				// We have a winner!
1114
+				return $allParents;
1115
+			}
1116
+		}
1117
+
1118
+		throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables)));
1119
+	}
1120
+
1121
+	/**
1122
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1123
+	 *
1124
+	 * @param string $table
1125
+	 *
1126
+	 * @return string[]
1127
+	 */
1128
+	public function _getRelatedTablesByInheritance($table)
1129
+	{
1130
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1131
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1132
+		});
1133
+	}
1134
+
1135
+	/**
1136
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1137
+	 *
1138
+	 * @param string $table
1139
+	 *
1140
+	 * @return string[]
1141
+	 */
1142
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1143
+	{
1144
+		$schemaAnalyzer = $this->schemaAnalyzer;
1145
+
1146
+		// Let's scan the parent tables
1147
+		$currentTable = $table;
1148
+
1149
+		$parentTables = [];
1150
+
1151
+		// Get parent relationship
1152
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1153
+			$currentTable = $currentFk->getForeignTableName();
1154
+			$parentTables[] = $currentTable;
1155
+		}
1156
+
1157
+		// Let's recurse in children
1158
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1159
+
1160
+		return array_merge(array_reverse($parentTables), $childrenTables);
1161
+	}
1162
+
1163
+	/**
1164
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1165
+	 *
1166
+	 * @param string $table
1167
+	 *
1168
+	 * @return string[]
1169
+	 */
1170
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1171
+	{
1172
+		$tables = [$table];
1173
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1174
+
1175
+		foreach ($keys as $key) {
1176
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1177
+		}
1178
+
1179
+		return $tables;
1180
+	}
1181
+
1182
+	/**
1183
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1184
+	 * The returned value does contain only one table. For instance:.
1185
+	 *
1186
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1187
+	 *
1188
+	 * @param ForeignKeyConstraint $fk
1189
+	 * @param bool                 $leftTableIsLocal
1190
+	 *
1191
+	 * @return string
1192
+	 */
1193
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1194 1194
         $onClauses = [];
1195 1195
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1196 1196
         $foreignColumns = $fk->getForeignColumns();
@@ -1216,405 +1216,405 @@  discard block
 block discarded – undo
1216 1216
         }
1217 1217
     }*/
1218 1218
 
1219
-    /**
1220
-     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1221
-     *
1222
-     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1223
-     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1224
-     *
1225
-     * The findObjects method takes in parameter:
1226
-     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1227
-     * 			`$mainTable` parameter should be the name of an existing table in database.
1228
-     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1229
-     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1230
-     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1231
-     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1232
-     *          Instead, please consider passing parameters (see documentation for more details).
1233
-     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1234
-     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1235
-     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1236
-     *
1237
-     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1238
-     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1239
-     *
1240
-     * Finally, if filter_bag is null, the whole table is returned.
1241
-     *
1242
-     * @param string                       $mainTable             The name of the table queried
1243
-     * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1244
-     * @param array                        $parameters
1245
-     * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1246
-     * @param array                        $additionalTablesFetch
1247
-     * @param int                          $mode
1248
-     * @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
1249
-     *
1250
-     * @return ResultIterator An object representing an array of results
1251
-     *
1252
-     * @throws TDBMException
1253
-     */
1254
-    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1255
-    {
1256
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1257
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1258
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1259
-        }
1260
-
1261
-        $mode = $mode ?: $this->mode;
1262
-
1263
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1264
-
1265
-        $parameters = array_merge($parameters, $additionalParameters);
1266
-
1267
-        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1268
-
1269
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1270
-    }
1271
-
1272
-    /**
1273
-     * @param string                       $mainTable   The name of the table queried
1274
-     * @param string                       $from        The from sql statement
1275
-     * @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)
1276
-     * @param array                        $parameters
1277
-     * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1278
-     * @param int                          $mode
1279
-     * @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
1280
-     *
1281
-     * @return ResultIterator An object representing an array of results
1282
-     *
1283
-     * @throws TDBMException
1284
-     */
1285
-    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1286
-    {
1287
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1288
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1289
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1290
-        }
1291
-
1292
-        $mode = $mode ?: $this->mode;
1293
-
1294
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1295
-
1296
-        $parameters = array_merge($parameters, $additionalParameters);
1297
-
1298
-        $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1299
-
1300
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1301
-    }
1302
-
1303
-    /**
1304
-     * @param $table
1305
-     * @param array  $primaryKeys
1306
-     * @param array  $additionalTablesFetch
1307
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1308
-     * @param string $className
1309
-     *
1310
-     * @return AbstractTDBMObject
1311
-     *
1312
-     * @throws TDBMException
1313
-     */
1314
-    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1315
-    {
1316
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1317
-        $hash = $this->getObjectHash($primaryKeys);
1318
-
1319
-        if ($this->objectStorage->has($table, $hash)) {
1320
-            $dbRow = $this->objectStorage->get($table, $hash);
1321
-            $bean = $dbRow->getTDBMObject();
1322
-            if ($className !== null && !is_a($bean, $className)) {
1323
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1324
-            }
1325
-
1326
-            return $bean;
1327
-        }
1328
-
1329
-        // Are we performing lazy fetching?
1330
-        if ($lazy === true) {
1331
-            // Can we perform lazy fetching?
1332
-            $tables = $this->_getRelatedTablesByInheritance($table);
1333
-            // Only allowed if no inheritance.
1334
-            if (count($tables) === 1) {
1335
-                if ($className === null) {
1336
-                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1337
-                }
1338
-
1339
-                // Let's construct the bean
1340
-                if (!isset($this->reflectionClassCache[$className])) {
1341
-                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1342
-                }
1343
-                // Let's bypass the constructor when creating the bean!
1344
-                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1345
-                /* @var $bean AbstractTDBMObject */
1346
-                $bean->_constructLazy($table, $primaryKeys, $this);
1347
-
1348
-                return $bean;
1349
-            }
1350
-        }
1351
-
1352
-        // Did not find the object in cache? Let's query it!
1353
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1354
-    }
1355
-
1356
-    /**
1357
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1358
-     *
1359
-     * @param string            $mainTable             The name of the table queried
1360
-     * @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)
1361
-     * @param array             $parameters
1362
-     * @param array             $additionalTablesFetch
1363
-     * @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
1364
-     *
1365
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1366
-     *
1367
-     * @throws TDBMException
1368
-     */
1369
-    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1370
-    {
1371
-        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1372
-        $page = $objects->take(0, 2);
1373
-        $count = $page->count();
1374
-        if ($count > 1) {
1375
-            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.");
1376
-        } elseif ($count === 0) {
1377
-            return;
1378
-        }
1379
-
1380
-        return $page[0];
1381
-    }
1382
-
1383
-    /**
1384
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1385
-     *
1386
-     * @param string            $mainTable  The name of the table queried
1387
-     * @param string            $from       The from sql statement
1388
-     * @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)
1389
-     * @param array             $parameters
1390
-     * @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
1391
-     *
1392
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1393
-     *
1394
-     * @throws TDBMException
1395
-     */
1396
-    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1397
-    {
1398
-        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1399
-        $page = $objects->take(0, 2);
1400
-        $count = $page->count();
1401
-        if ($count > 1) {
1402
-            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.");
1403
-        } elseif ($count === 0) {
1404
-            return;
1405
-        }
1406
-
1407
-        return $page[0];
1408
-    }
1409
-
1410
-    /**
1411
-     * Returns a unique bean according to the filters passed in parameter.
1412
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1413
-     *
1414
-     * @param string            $mainTable             The name of the table queried
1415
-     * @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)
1416
-     * @param array             $parameters
1417
-     * @param array             $additionalTablesFetch
1418
-     * @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
1419
-     *
1420
-     * @return AbstractTDBMObject The object we want
1421
-     *
1422
-     * @throws TDBMException
1423
-     */
1424
-    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1425
-    {
1426
-        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1427
-        if ($bean === null) {
1428
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1429
-        }
1430
-
1431
-        return $bean;
1432
-    }
1433
-
1434
-    /**
1435
-     * @param array $beanData An array of data: array<table, array<column, value>>
1436
-     *
1437
-     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1438
-     */
1439
-    public function _getClassNameFromBeanData(array $beanData)
1440
-    {
1441
-        if (count($beanData) === 1) {
1442
-            $tableName = array_keys($beanData)[0];
1443
-            $allTables = [$tableName];
1444
-        } else {
1445
-            $tables = [];
1446
-            foreach ($beanData as $table => $row) {
1447
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1448
-                $pkSet = false;
1449
-                foreach ($primaryKeyColumns as $columnName) {
1450
-                    if ($row[$columnName] !== null) {
1451
-                        $pkSet = true;
1452
-                        break;
1453
-                    }
1454
-                }
1455
-                if ($pkSet) {
1456
-                    $tables[] = $table;
1457
-                }
1458
-            }
1459
-
1460
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1461
-            $allTables = $this->_getLinkBetweenInheritedTables($tables);
1462
-            $tableName = $allTables[0];
1463
-        }
1464
-
1465
-        // Only one table in this bean. Life is sweat, let's look at its type:
1466
-        if (isset($this->tableToBeanMap[$tableName])) {
1467
-            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1468
-        } else {
1469
-            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1470
-        }
1471
-    }
1472
-
1473
-    /**
1474
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1475
-     *
1476
-     * @param string   $key
1477
-     * @param callable $closure
1478
-     *
1479
-     * @return mixed
1480
-     */
1481
-    private function fromCache(string $key, callable $closure)
1482
-    {
1483
-        $item = $this->cache->fetch($key);
1484
-        if ($item === false) {
1485
-            $item = $closure();
1486
-            $this->cache->save($key, $item);
1487
-        }
1488
-
1489
-        return $item;
1490
-    }
1491
-
1492
-    /**
1493
-     * Returns the foreign key object.
1494
-     *
1495
-     * @param string $table
1496
-     * @param string $fkName
1497
-     *
1498
-     * @return ForeignKeyConstraint
1499
-     */
1500
-    public function _getForeignKeyByName(string $table, string $fkName)
1501
-    {
1502
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1503
-    }
1504
-
1505
-    /**
1506
-     * @param $pivotTableName
1507
-     * @param AbstractTDBMObject $bean
1508
-     *
1509
-     * @return AbstractTDBMObject[]
1510
-     */
1511
-    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1512
-    {
1513
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1514
-        /* @var $localFk ForeignKeyConstraint */
1515
-        /* @var $remoteFk ForeignKeyConstraint */
1516
-        $remoteTable = $remoteFk->getForeignTableName();
1517
-
1518
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1519
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1520
-            return $pivotTableName.'.'.$name;
1521
-        }, $localFk->getLocalColumns());
1522
-
1523
-        $filter = array_combine($columnNames, $primaryKeys);
1524
-
1525
-        return $this->findObjects($remoteTable, $filter);
1526
-    }
1527
-
1528
-    /**
1529
-     * @param $pivotTableName
1530
-     * @param AbstractTDBMObject $bean The LOCAL bean
1531
-     *
1532
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1533
-     *
1534
-     * @throws TDBMException
1535
-     */
1536
-    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1537
-    {
1538
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1539
-        $table1 = $fks[0]->getForeignTableName();
1540
-        $table2 = $fks[1]->getForeignTableName();
1541
-
1542
-        $beanTables = array_map(function (DbRow $dbRow) {
1543
-            return $dbRow->_getDbTableName();
1544
-        }, $bean->_getDbRows());
1545
-
1546
-        if (in_array($table1, $beanTables)) {
1547
-            return [$fks[0], $fks[1]];
1548
-        } elseif (in_array($table2, $beanTables)) {
1549
-            return [$fks[1], $fks[0]];
1550
-        } else {
1551
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1552
-        }
1553
-    }
1554
-
1555
-    /**
1556
-     * Returns a list of pivot tables linked to $bean.
1557
-     *
1558
-     * @param AbstractTDBMObject $bean
1559
-     *
1560
-     * @return string[]
1561
-     */
1562
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1563
-    {
1564
-        $junctionTables = [];
1565
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1566
-        foreach ($bean->_getDbRows() as $dbRow) {
1567
-            foreach ($allJunctionTables as $table) {
1568
-                // There are exactly 2 FKs since this is a pivot table.
1569
-                $fks = array_values($table->getForeignKeys());
1570
-
1571
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1572
-                    $junctionTables[] = $table->getName();
1573
-                }
1574
-            }
1575
-        }
1576
-
1577
-        return $junctionTables;
1578
-    }
1579
-
1580
-    /**
1581
-     * Array of types for tables.
1582
-     * Key: table name
1583
-     * Value: array of types indexed by column.
1584
-     *
1585
-     * @var array[]
1586
-     */
1587
-    private $typesForTable = [];
1588
-
1589
-    /**
1590
-     * @internal
1591
-     *
1592
-     * @param string $tableName
1593
-     *
1594
-     * @return Type[]
1595
-     */
1596
-    public function _getColumnTypesForTable(string $tableName)
1597
-    {
1598
-        if (!isset($typesForTable[$tableName])) {
1599
-            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1600
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1601
-                return $column->getType();
1602
-            }, $columns);
1603
-        }
1604
-
1605
-        return $typesForTable[$tableName];
1606
-    }
1607
-
1608
-    /**
1609
-     * Sets the minimum log level.
1610
-     * $level must be one of Psr\Log\LogLevel::xxx.
1611
-     *
1612
-     * Defaults to LogLevel::WARNING
1613
-     *
1614
-     * @param string $level
1615
-     */
1616
-    public function setLogLevel(string $level)
1617
-    {
1618
-        $this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1619
-    }
1219
+	/**
1220
+	 * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1221
+	 *
1222
+	 * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1223
+	 * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1224
+	 *
1225
+	 * The findObjects method takes in parameter:
1226
+	 * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1227
+	 * 			`$mainTable` parameter should be the name of an existing table in database.
1228
+	 *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1229
+	 *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1230
+	 *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1231
+	 *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1232
+	 *          Instead, please consider passing parameters (see documentation for more details).
1233
+	 *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1234
+	 *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1235
+	 *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1236
+	 *
1237
+	 * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1238
+	 * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1239
+	 *
1240
+	 * Finally, if filter_bag is null, the whole table is returned.
1241
+	 *
1242
+	 * @param string                       $mainTable             The name of the table queried
1243
+	 * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1244
+	 * @param array                        $parameters
1245
+	 * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1246
+	 * @param array                        $additionalTablesFetch
1247
+	 * @param int                          $mode
1248
+	 * @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
1249
+	 *
1250
+	 * @return ResultIterator An object representing an array of results
1251
+	 *
1252
+	 * @throws TDBMException
1253
+	 */
1254
+	public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1255
+	{
1256
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1257
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1258
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1259
+		}
1260
+
1261
+		$mode = $mode ?: $this->mode;
1262
+
1263
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1264
+
1265
+		$parameters = array_merge($parameters, $additionalParameters);
1266
+
1267
+		$queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1268
+
1269
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1270
+	}
1271
+
1272
+	/**
1273
+	 * @param string                       $mainTable   The name of the table queried
1274
+	 * @param string                       $from        The from sql statement
1275
+	 * @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)
1276
+	 * @param array                        $parameters
1277
+	 * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1278
+	 * @param int                          $mode
1279
+	 * @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
1280
+	 *
1281
+	 * @return ResultIterator An object representing an array of results
1282
+	 *
1283
+	 * @throws TDBMException
1284
+	 */
1285
+	public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1286
+	{
1287
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1288
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1289
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1290
+		}
1291
+
1292
+		$mode = $mode ?: $this->mode;
1293
+
1294
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1295
+
1296
+		$parameters = array_merge($parameters, $additionalParameters);
1297
+
1298
+		$queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1299
+
1300
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1301
+	}
1302
+
1303
+	/**
1304
+	 * @param $table
1305
+	 * @param array  $primaryKeys
1306
+	 * @param array  $additionalTablesFetch
1307
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1308
+	 * @param string $className
1309
+	 *
1310
+	 * @return AbstractTDBMObject
1311
+	 *
1312
+	 * @throws TDBMException
1313
+	 */
1314
+	public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1315
+	{
1316
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1317
+		$hash = $this->getObjectHash($primaryKeys);
1318
+
1319
+		if ($this->objectStorage->has($table, $hash)) {
1320
+			$dbRow = $this->objectStorage->get($table, $hash);
1321
+			$bean = $dbRow->getTDBMObject();
1322
+			if ($className !== null && !is_a($bean, $className)) {
1323
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1324
+			}
1325
+
1326
+			return $bean;
1327
+		}
1328
+
1329
+		// Are we performing lazy fetching?
1330
+		if ($lazy === true) {
1331
+			// Can we perform lazy fetching?
1332
+			$tables = $this->_getRelatedTablesByInheritance($table);
1333
+			// Only allowed if no inheritance.
1334
+			if (count($tables) === 1) {
1335
+				if ($className === null) {
1336
+					$className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1337
+				}
1338
+
1339
+				// Let's construct the bean
1340
+				if (!isset($this->reflectionClassCache[$className])) {
1341
+					$this->reflectionClassCache[$className] = new \ReflectionClass($className);
1342
+				}
1343
+				// Let's bypass the constructor when creating the bean!
1344
+				$bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1345
+				/* @var $bean AbstractTDBMObject */
1346
+				$bean->_constructLazy($table, $primaryKeys, $this);
1347
+
1348
+				return $bean;
1349
+			}
1350
+		}
1351
+
1352
+		// Did not find the object in cache? Let's query it!
1353
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1354
+	}
1355
+
1356
+	/**
1357
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1358
+	 *
1359
+	 * @param string            $mainTable             The name of the table queried
1360
+	 * @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)
1361
+	 * @param array             $parameters
1362
+	 * @param array             $additionalTablesFetch
1363
+	 * @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
1364
+	 *
1365
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1366
+	 *
1367
+	 * @throws TDBMException
1368
+	 */
1369
+	public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1370
+	{
1371
+		$objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1372
+		$page = $objects->take(0, 2);
1373
+		$count = $page->count();
1374
+		if ($count > 1) {
1375
+			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.");
1376
+		} elseif ($count === 0) {
1377
+			return;
1378
+		}
1379
+
1380
+		return $page[0];
1381
+	}
1382
+
1383
+	/**
1384
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1385
+	 *
1386
+	 * @param string            $mainTable  The name of the table queried
1387
+	 * @param string            $from       The from sql statement
1388
+	 * @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)
1389
+	 * @param array             $parameters
1390
+	 * @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
1391
+	 *
1392
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1393
+	 *
1394
+	 * @throws TDBMException
1395
+	 */
1396
+	public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1397
+	{
1398
+		$objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1399
+		$page = $objects->take(0, 2);
1400
+		$count = $page->count();
1401
+		if ($count > 1) {
1402
+			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.");
1403
+		} elseif ($count === 0) {
1404
+			return;
1405
+		}
1406
+
1407
+		return $page[0];
1408
+	}
1409
+
1410
+	/**
1411
+	 * Returns a unique bean according to the filters passed in parameter.
1412
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1413
+	 *
1414
+	 * @param string            $mainTable             The name of the table queried
1415
+	 * @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)
1416
+	 * @param array             $parameters
1417
+	 * @param array             $additionalTablesFetch
1418
+	 * @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
1419
+	 *
1420
+	 * @return AbstractTDBMObject The object we want
1421
+	 *
1422
+	 * @throws TDBMException
1423
+	 */
1424
+	public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1425
+	{
1426
+		$bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1427
+		if ($bean === null) {
1428
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1429
+		}
1430
+
1431
+		return $bean;
1432
+	}
1433
+
1434
+	/**
1435
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1436
+	 *
1437
+	 * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1438
+	 */
1439
+	public function _getClassNameFromBeanData(array $beanData)
1440
+	{
1441
+		if (count($beanData) === 1) {
1442
+			$tableName = array_keys($beanData)[0];
1443
+			$allTables = [$tableName];
1444
+		} else {
1445
+			$tables = [];
1446
+			foreach ($beanData as $table => $row) {
1447
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1448
+				$pkSet = false;
1449
+				foreach ($primaryKeyColumns as $columnName) {
1450
+					if ($row[$columnName] !== null) {
1451
+						$pkSet = true;
1452
+						break;
1453
+					}
1454
+				}
1455
+				if ($pkSet) {
1456
+					$tables[] = $table;
1457
+				}
1458
+			}
1459
+
1460
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1461
+			$allTables = $this->_getLinkBetweenInheritedTables($tables);
1462
+			$tableName = $allTables[0];
1463
+		}
1464
+
1465
+		// Only one table in this bean. Life is sweat, let's look at its type:
1466
+		if (isset($this->tableToBeanMap[$tableName])) {
1467
+			return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1468
+		} else {
1469
+			return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1470
+		}
1471
+	}
1472
+
1473
+	/**
1474
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1475
+	 *
1476
+	 * @param string   $key
1477
+	 * @param callable $closure
1478
+	 *
1479
+	 * @return mixed
1480
+	 */
1481
+	private function fromCache(string $key, callable $closure)
1482
+	{
1483
+		$item = $this->cache->fetch($key);
1484
+		if ($item === false) {
1485
+			$item = $closure();
1486
+			$this->cache->save($key, $item);
1487
+		}
1488
+
1489
+		return $item;
1490
+	}
1491
+
1492
+	/**
1493
+	 * Returns the foreign key object.
1494
+	 *
1495
+	 * @param string $table
1496
+	 * @param string $fkName
1497
+	 *
1498
+	 * @return ForeignKeyConstraint
1499
+	 */
1500
+	public function _getForeignKeyByName(string $table, string $fkName)
1501
+	{
1502
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1503
+	}
1504
+
1505
+	/**
1506
+	 * @param $pivotTableName
1507
+	 * @param AbstractTDBMObject $bean
1508
+	 *
1509
+	 * @return AbstractTDBMObject[]
1510
+	 */
1511
+	public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1512
+	{
1513
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1514
+		/* @var $localFk ForeignKeyConstraint */
1515
+		/* @var $remoteFk ForeignKeyConstraint */
1516
+		$remoteTable = $remoteFk->getForeignTableName();
1517
+
1518
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1519
+		$columnNames = array_map(function ($name) use ($pivotTableName) {
1520
+			return $pivotTableName.'.'.$name;
1521
+		}, $localFk->getLocalColumns());
1522
+
1523
+		$filter = array_combine($columnNames, $primaryKeys);
1524
+
1525
+		return $this->findObjects($remoteTable, $filter);
1526
+	}
1527
+
1528
+	/**
1529
+	 * @param $pivotTableName
1530
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1531
+	 *
1532
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1533
+	 *
1534
+	 * @throws TDBMException
1535
+	 */
1536
+	private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1537
+	{
1538
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1539
+		$table1 = $fks[0]->getForeignTableName();
1540
+		$table2 = $fks[1]->getForeignTableName();
1541
+
1542
+		$beanTables = array_map(function (DbRow $dbRow) {
1543
+			return $dbRow->_getDbTableName();
1544
+		}, $bean->_getDbRows());
1545
+
1546
+		if (in_array($table1, $beanTables)) {
1547
+			return [$fks[0], $fks[1]];
1548
+		} elseif (in_array($table2, $beanTables)) {
1549
+			return [$fks[1], $fks[0]];
1550
+		} else {
1551
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1552
+		}
1553
+	}
1554
+
1555
+	/**
1556
+	 * Returns a list of pivot tables linked to $bean.
1557
+	 *
1558
+	 * @param AbstractTDBMObject $bean
1559
+	 *
1560
+	 * @return string[]
1561
+	 */
1562
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1563
+	{
1564
+		$junctionTables = [];
1565
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1566
+		foreach ($bean->_getDbRows() as $dbRow) {
1567
+			foreach ($allJunctionTables as $table) {
1568
+				// There are exactly 2 FKs since this is a pivot table.
1569
+				$fks = array_values($table->getForeignKeys());
1570
+
1571
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1572
+					$junctionTables[] = $table->getName();
1573
+				}
1574
+			}
1575
+		}
1576
+
1577
+		return $junctionTables;
1578
+	}
1579
+
1580
+	/**
1581
+	 * Array of types for tables.
1582
+	 * Key: table name
1583
+	 * Value: array of types indexed by column.
1584
+	 *
1585
+	 * @var array[]
1586
+	 */
1587
+	private $typesForTable = [];
1588
+
1589
+	/**
1590
+	 * @internal
1591
+	 *
1592
+	 * @param string $tableName
1593
+	 *
1594
+	 * @return Type[]
1595
+	 */
1596
+	public function _getColumnTypesForTable(string $tableName)
1597
+	{
1598
+		if (!isset($typesForTable[$tableName])) {
1599
+			$columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1600
+			$typesForTable[$tableName] = array_map(function (Column $column) {
1601
+				return $column->getType();
1602
+			}, $columns);
1603
+		}
1604
+
1605
+		return $typesForTable[$tableName];
1606
+	}
1607
+
1608
+	/**
1609
+	 * Sets the minimum log level.
1610
+	 * $level must be one of Psr\Log\LogLevel::xxx.
1611
+	 *
1612
+	 * Defaults to LogLevel::WARNING
1613
+	 *
1614
+	 * @param string $level
1615
+	 */
1616
+	public function setLogLevel(string $level)
1617
+	{
1618
+		$this->logger = new MinLogLevelFilter($this->rootLogger, $level);
1619
+	}
1620 1620
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/AbstractBeanPropertyDescriptor.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -9,131 +9,131 @@
 block discarded – undo
9 9
  */
10 10
 abstract class AbstractBeanPropertyDescriptor
11 11
 {
12
-    /**
13
-     * @var Table
14
-     */
15
-    protected $table;
16
-
17
-    /**
18
-     * Whether to use the more complex name in case of conflict.
19
-     *
20
-     * @var bool
21
-     */
22
-    protected $alternativeName = false;
23
-
24
-    /**
25
-     * @param Table $table
26
-     */
27
-    public function __construct(Table $table)
28
-    {
29
-        $this->table = $table;
30
-    }
31
-
32
-    /**
33
-     * Use the more complex name in case of conflict.
34
-     */
35
-    public function useAlternativeName()
36
-    {
37
-        $this->alternativeName = true;
38
-    }
39
-
40
-    /**
41
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
42
-     *
43
-     * @return null|string
44
-     */
45
-    abstract public function getClassName();
46
-
47
-    /**
48
-     * Returns the param annotation for this property (useful for constructor).
49
-     *
50
-     * @return string
51
-     */
52
-    abstract public function getParamAnnotation();
53
-
54
-    public function getVariableName()
55
-    {
56
-        return '$'.$this->getLowerCamelCaseName();
57
-    }
58
-
59
-    public function getLowerCamelCaseName()
60
-    {
61
-        return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
62
-    }
63
-
64
-    abstract public function getUpperCamelCaseName();
65
-
66
-    public function getSetterName()
67
-    {
68
-        return 'set'.$this->getUpperCamelCaseName();
69
-    }
70
-
71
-    public function getGetterName()
72
-    {
73
-        return 'get'.$this->getUpperCamelCaseName();
74
-    }
75
-
76
-    /**
77
-     * Returns the PHP code used in the ben constructor for this property.
78
-     *
79
-     * @return string
80
-     */
81
-    public function getConstructorAssignCode()
82
-    {
83
-        $str = '        $this->%s(%s);';
84
-
85
-        return sprintf($str, $this->getSetterName(), $this->getVariableName());
86
-    }
87
-
88
-    /**
89
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
90
-     *
91
-     * @return bool
92
-     */
93
-    abstract public function isCompulsory();
94
-
95
-    /**
96
-     * Returns true if the property has a default value.
97
-     *
98
-     * @return bool
99
-     */
100
-    abstract public function hasDefault();
101
-
102
-    /**
103
-     * Returns the code that assigns a value to its default value.
104
-     *
105
-     * @return string
106
-     *
107
-     * @throws \TDBMException
108
-     */
109
-    abstract public function assignToDefaultCode();
110
-
111
-    /**
112
-     * Returns true if the property is the primary key.
113
-     *
114
-     * @return bool
115
-     */
116
-    abstract public function isPrimaryKey();
117
-
118
-    /**
119
-     * @return Table
120
-     */
121
-    public function getTable()
122
-    {
123
-        return $this->table;
124
-    }
125
-
126
-    /**
127
-     * Returns the PHP code for getters and setters.
128
-     *
129
-     * @return string
130
-     */
131
-    abstract public function getGetterSetterCode();
132
-
133
-    /**
134
-     * Returns the part of code useful when doing json serialization.
135
-     *
136
-     * @return string
137
-     */
138
-    abstract public function getJsonSerializeCode();
12
+	/**
13
+	 * @var Table
14
+	 */
15
+	protected $table;
16
+
17
+	/**
18
+	 * Whether to use the more complex name in case of conflict.
19
+	 *
20
+	 * @var bool
21
+	 */
22
+	protected $alternativeName = false;
23
+
24
+	/**
25
+	 * @param Table $table
26
+	 */
27
+	public function __construct(Table $table)
28
+	{
29
+		$this->table = $table;
30
+	}
31
+
32
+	/**
33
+	 * Use the more complex name in case of conflict.
34
+	 */
35
+	public function useAlternativeName()
36
+	{
37
+		$this->alternativeName = true;
38
+	}
39
+
40
+	/**
41
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
42
+	 *
43
+	 * @return null|string
44
+	 */
45
+	abstract public function getClassName();
46
+
47
+	/**
48
+	 * Returns the param annotation for this property (useful for constructor).
49
+	 *
50
+	 * @return string
51
+	 */
52
+	abstract public function getParamAnnotation();
53
+
54
+	public function getVariableName()
55
+	{
56
+		return '$'.$this->getLowerCamelCaseName();
57
+	}
58
+
59
+	public function getLowerCamelCaseName()
60
+	{
61
+		return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
62
+	}
63
+
64
+	abstract public function getUpperCamelCaseName();
65
+
66
+	public function getSetterName()
67
+	{
68
+		return 'set'.$this->getUpperCamelCaseName();
69
+	}
70
+
71
+	public function getGetterName()
72
+	{
73
+		return 'get'.$this->getUpperCamelCaseName();
74
+	}
75
+
76
+	/**
77
+	 * Returns the PHP code used in the ben constructor for this property.
78
+	 *
79
+	 * @return string
80
+	 */
81
+	public function getConstructorAssignCode()
82
+	{
83
+		$str = '        $this->%s(%s);';
84
+
85
+		return sprintf($str, $this->getSetterName(), $this->getVariableName());
86
+	}
87
+
88
+	/**
89
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
90
+	 *
91
+	 * @return bool
92
+	 */
93
+	abstract public function isCompulsory();
94
+
95
+	/**
96
+	 * Returns true if the property has a default value.
97
+	 *
98
+	 * @return bool
99
+	 */
100
+	abstract public function hasDefault();
101
+
102
+	/**
103
+	 * Returns the code that assigns a value to its default value.
104
+	 *
105
+	 * @return string
106
+	 *
107
+	 * @throws \TDBMException
108
+	 */
109
+	abstract public function assignToDefaultCode();
110
+
111
+	/**
112
+	 * Returns true if the property is the primary key.
113
+	 *
114
+	 * @return bool
115
+	 */
116
+	abstract public function isPrimaryKey();
117
+
118
+	/**
119
+	 * @return Table
120
+	 */
121
+	public function getTable()
122
+	{
123
+		return $this->table;
124
+	}
125
+
126
+	/**
127
+	 * Returns the PHP code for getters and setters.
128
+	 *
129
+	 * @return string
130
+	 */
131
+	abstract public function getGetterSetterCode();
132
+
133
+	/**
134
+	 * Returns the part of code useful when doing json serialization.
135
+	 *
136
+	 * @return string
137
+	 */
138
+	abstract public function getJsonSerializeCode();
139 139
 }
Please login to merge, or discard this patch.