Completed
Push — 4.0 ( 21f434...645c00 )
by David
08:33
created
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 1 patch
Indentation   +459 added lines, -459 removed lines patch added patch discarded remove patch
@@ -17,197 +17,197 @@  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
-     * @var TDBMSchemaAnalyzer
39
-     */
40
-    private $tdbmSchemaAnalyzer;
41
-
42
-    /**
43
-     * Constructor.
44
-     *
45
-     * @param SchemaAnalyzer     $schemaAnalyzer
46
-     * @param Schema             $schema
47
-     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
48
-     */
49
-    public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
50
-    {
51
-        $this->schemaAnalyzer = $schemaAnalyzer;
52
-        $this->schema = $schema;
53
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
54
-        $this->rootPath = __DIR__.'/../../../../../../../../';
55
-    }
56
-
57
-    /**
58
-     * Generates all the daos and beans.
59
-     *
60
-     * @param string $daoFactoryClassName The classe name of the DAO factory
61
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
62
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
63
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone.
64
-     *
65
-     * @return \string[] the list of tables
66
-     *
67
-     * @throws TDBMException
68
-     */
69
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc)
70
-    {
71
-        // TODO: extract ClassNameMapper in its own package!
72
-        $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.'composer.json');
73
-
74
-        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
75
-
76
-        $tableList = $this->schema->getTables();
77
-
78
-        // Remove all beans and daos from junction tables
79
-        $junctionTables = $this->schemaAnalyzer->detectJunctionTables();
80
-        $junctionTableNames = array_map(function (Table $table) {
81
-            return $table->getName();
82
-        }, $junctionTables);
83
-
84
-        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
85
-            return !in_array($table->getName(), $junctionTableNames);
86
-        });
87
-
88
-        foreach ($tableList as $table) {
89
-            $this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc);
90
-        }
91
-
92
-        $this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper);
93
-
94
-        // Ok, let's return the list of all tables.
95
-        // These will be used by the calling script to create Mouf instances.
96
-
97
-        return array_map(function (Table $table) { return $table->getName(); }, $tableList);
98
-    }
99
-
100
-    /**
101
-     * Generates in one method call the daos and the beans for one table.
102
-     *
103
-     * @param Table           $table
104
-     * @param string          $daonamespace
105
-     * @param string          $beannamespace
106
-     * @param ClassNameMapper $classNameMapper
107
-     * @param bool            $storeInUtc
108
-     *
109
-     * @throws TDBMException
110
-     */
111
-    public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
112
-    {
113
-        $tableName = $table->getName();
114
-        $daoName = $this->getDaoNameFromTableName($tableName);
115
-        $beanName = $this->getBeanNameFromTableName($tableName);
116
-        $baseBeanName = $this->getBaseBeanNameFromTableName($tableName);
117
-        $baseDaoName = $this->getBaseDaoNameFromTableName($tableName);
118
-
119
-        $beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer);
120
-
121
-        $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc);
122
-        $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper);
123
-    }
124
-
125
-    /**
126
-     * Returns the name of the bean class from the table name.
127
-     *
128
-     * @param $tableName
129
-     *
130
-     * @return string
131
-     */
132
-    public static function getBeanNameFromTableName($tableName)
133
-    {
134
-        return self::toSingular(self::toCamelCase($tableName)).'Bean';
135
-    }
136
-
137
-    /**
138
-     * Returns the name of the DAO class from the table name.
139
-     *
140
-     * @param $tableName
141
-     *
142
-     * @return string
143
-     */
144
-    public static function getDaoNameFromTableName($tableName)
145
-    {
146
-        return self::toSingular(self::toCamelCase($tableName)).'Dao';
147
-    }
148
-
149
-    /**
150
-     * Returns the name of the base bean class from the table name.
151
-     *
152
-     * @param $tableName
153
-     *
154
-     * @return string
155
-     */
156
-    public static function getBaseBeanNameFromTableName($tableName)
157
-    {
158
-        return self::toSingular(self::toCamelCase($tableName)).'BaseBean';
159
-    }
160
-
161
-    /**
162
-     * Returns the name of the base DAO class from the table name.
163
-     *
164
-     * @param $tableName
165
-     *
166
-     * @return string
167
-     */
168
-    public static function getBaseDaoNameFromTableName($tableName)
169
-    {
170
-        return self::toSingular(self::toCamelCase($tableName)).'BaseDao';
171
-    }
172
-
173
-    /**
174
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
175
-     *
176
-     * @param BeanDescriptor  $beanDescriptor
177
-     * @param string          $className       The name of the class
178
-     * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
179
-     * @param Table           $table           The table
180
-     * @param string          $beannamespace   The namespace of the bean
181
-     * @param ClassNameMapper $classNameMapper
182
-     *
183
-     * @throws TDBMException
184
-     */
185
-    public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
186
-    {
187
-        $str = $beanDescriptor->generatePhpCode($beannamespace);
188
-
189
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName);
190
-        if (empty($possibleBaseFileNames)) {
191
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
192
-        }
193
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
194
-
195
-        $this->ensureDirectoryExist($possibleBaseFileName);
196
-        file_put_contents($possibleBaseFileName, $str);
197
-        @chmod($possibleBaseFileName, 0664);
198
-
199
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
200
-        if (empty($possibleFileNames)) {
201
-            // @codeCoverageIgnoreStart
202
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
203
-            // @codeCoverageIgnoreEnd
204
-        }
205
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
206
-
207
-        if (!file_exists($possibleFileName)) {
208
-            $tableName = $table->getName();
209
-
210
-            $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
+	 * @var TDBMSchemaAnalyzer
39
+	 */
40
+	private $tdbmSchemaAnalyzer;
41
+
42
+	/**
43
+	 * Constructor.
44
+	 *
45
+	 * @param SchemaAnalyzer     $schemaAnalyzer
46
+	 * @param Schema             $schema
47
+	 * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
48
+	 */
49
+	public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
50
+	{
51
+		$this->schemaAnalyzer = $schemaAnalyzer;
52
+		$this->schema = $schema;
53
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
54
+		$this->rootPath = __DIR__.'/../../../../../../../../';
55
+	}
56
+
57
+	/**
58
+	 * Generates all the daos and beans.
59
+	 *
60
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
61
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
62
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
63
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone.
64
+	 *
65
+	 * @return \string[] the list of tables
66
+	 *
67
+	 * @throws TDBMException
68
+	 */
69
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc)
70
+	{
71
+		// TODO: extract ClassNameMapper in its own package!
72
+		$classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.'composer.json');
73
+
74
+		// TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
75
+
76
+		$tableList = $this->schema->getTables();
77
+
78
+		// Remove all beans and daos from junction tables
79
+		$junctionTables = $this->schemaAnalyzer->detectJunctionTables();
80
+		$junctionTableNames = array_map(function (Table $table) {
81
+			return $table->getName();
82
+		}, $junctionTables);
83
+
84
+		$tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
85
+			return !in_array($table->getName(), $junctionTableNames);
86
+		});
87
+
88
+		foreach ($tableList as $table) {
89
+			$this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc);
90
+		}
91
+
92
+		$this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper);
93
+
94
+		// Ok, let's return the list of all tables.
95
+		// These will be used by the calling script to create Mouf instances.
96
+
97
+		return array_map(function (Table $table) { return $table->getName(); }, $tableList);
98
+	}
99
+
100
+	/**
101
+	 * Generates in one method call the daos and the beans for one table.
102
+	 *
103
+	 * @param Table           $table
104
+	 * @param string          $daonamespace
105
+	 * @param string          $beannamespace
106
+	 * @param ClassNameMapper $classNameMapper
107
+	 * @param bool            $storeInUtc
108
+	 *
109
+	 * @throws TDBMException
110
+	 */
111
+	public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
112
+	{
113
+		$tableName = $table->getName();
114
+		$daoName = $this->getDaoNameFromTableName($tableName);
115
+		$beanName = $this->getBeanNameFromTableName($tableName);
116
+		$baseBeanName = $this->getBaseBeanNameFromTableName($tableName);
117
+		$baseDaoName = $this->getBaseDaoNameFromTableName($tableName);
118
+
119
+		$beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer);
120
+
121
+		$this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc);
122
+		$this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper);
123
+	}
124
+
125
+	/**
126
+	 * Returns the name of the bean class from the table name.
127
+	 *
128
+	 * @param $tableName
129
+	 *
130
+	 * @return string
131
+	 */
132
+	public static function getBeanNameFromTableName($tableName)
133
+	{
134
+		return self::toSingular(self::toCamelCase($tableName)).'Bean';
135
+	}
136
+
137
+	/**
138
+	 * Returns the name of the DAO class from the table name.
139
+	 *
140
+	 * @param $tableName
141
+	 *
142
+	 * @return string
143
+	 */
144
+	public static function getDaoNameFromTableName($tableName)
145
+	{
146
+		return self::toSingular(self::toCamelCase($tableName)).'Dao';
147
+	}
148
+
149
+	/**
150
+	 * Returns the name of the base bean class from the table name.
151
+	 *
152
+	 * @param $tableName
153
+	 *
154
+	 * @return string
155
+	 */
156
+	public static function getBaseBeanNameFromTableName($tableName)
157
+	{
158
+		return self::toSingular(self::toCamelCase($tableName)).'BaseBean';
159
+	}
160
+
161
+	/**
162
+	 * Returns the name of the base DAO class from the table name.
163
+	 *
164
+	 * @param $tableName
165
+	 *
166
+	 * @return string
167
+	 */
168
+	public static function getBaseDaoNameFromTableName($tableName)
169
+	{
170
+		return self::toSingular(self::toCamelCase($tableName)).'BaseDao';
171
+	}
172
+
173
+	/**
174
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
175
+	 *
176
+	 * @param BeanDescriptor  $beanDescriptor
177
+	 * @param string          $className       The name of the class
178
+	 * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
179
+	 * @param Table           $table           The table
180
+	 * @param string          $beannamespace   The namespace of the bean
181
+	 * @param ClassNameMapper $classNameMapper
182
+	 *
183
+	 * @throws TDBMException
184
+	 */
185
+	public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc)
186
+	{
187
+		$str = $beanDescriptor->generatePhpCode($beannamespace);
188
+
189
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName);
190
+		if (empty($possibleBaseFileNames)) {
191
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.');
192
+		}
193
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
194
+
195
+		$this->ensureDirectoryExist($possibleBaseFileName);
196
+		file_put_contents($possibleBaseFileName, $str);
197
+		@chmod($possibleBaseFileName, 0664);
198
+
199
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className);
200
+		if (empty($possibleFileNames)) {
201
+			// @codeCoverageIgnoreStart
202
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.');
203
+			// @codeCoverageIgnoreEnd
204
+		}
205
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
206
+
207
+		if (!file_exists($possibleFileName)) {
208
+			$tableName = $table->getName();
209
+
210
+			$str = "<?php
211 211
 /*
212 212
  * This file has been automatically generated by TDBM.
213 213
  * You can edit this file as it will not be overwritten.
@@ -222,76 +222,76 @@  discard block
 block discarded – undo
222 222
 {
223 223
 
224 224
 }";
225
-            $this->ensureDirectoryExist($possibleFileName);
226
-            file_put_contents($possibleFileName, $str);
227
-            @chmod($possibleFileName, 0664);
228
-        }
229
-    }
230
-
231
-    /**
232
-     * Tries to find a @defaultSort annotation in one of the columns.
233
-     *
234
-     * @param Table $table
235
-     *
236
-     * @return array First item: column name, Second item: column order (asc/desc)
237
-     */
238
-    private function getDefaultSortColumnFromAnnotation(Table $table)
239
-    {
240
-        $defaultSort = null;
241
-        $defaultSortDirection = null;
242
-        foreach ($table->getColumns() as $column) {
243
-            $comments = $column->getComment();
244
-            $matches = [];
245
-            if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
246
-                $defaultSort = $column->getName();
247
-                if (count($matches) === 3) {
248
-                    $defaultSortDirection = $matches[2];
249
-                } else {
250
-                    $defaultSortDirection = 'ASC';
251
-                }
252
-            }
253
-        }
254
-
255
-        return [$defaultSort, $defaultSortDirection];
256
-    }
257
-
258
-    /**
259
-     * Writes the PHP bean DAO with simple functions to create/get/save objects.
260
-     *
261
-     * @param BeanDescriptor  $beanDescriptor
262
-     * @param string          $className       The name of the class
263
-     * @param string          $baseClassName
264
-     * @param string          $beanClassName
265
-     * @param Table           $table
266
-     * @param string          $daonamespace
267
-     * @param string          $beannamespace
268
-     * @param ClassNameMapper $classNameMapper
269
-     *
270
-     * @throws TDBMException
271
-     */
272
-    public function generateDao(BeanDescriptor $beanDescriptor, $className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper)
273
-    {
274
-        $tableName = $table->getName();
275
-        $primaryKeyColumns = $table->getPrimaryKeyColumns();
276
-
277
-        list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
278
-
279
-        // FIXME: lowercase tables with _ in the name should work!
280
-        $tableCamel = self::toSingular(self::toCamelCase($tableName));
281
-
282
-        $beanClassWithoutNameSpace = $beanClassName;
283
-        $beanClassName = $beannamespace.'\\'.$beanClassName;
284
-
285
-        list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
286
-
287
-        $usedBeans[] = $beanClassName;
288
-        // Let's suppress duplicates in used beans (if any)
289
-        $usedBeans = array_flip(array_flip($usedBeans));
290
-        $useStatements = array_map(function ($usedBean) {
291
-            return "use $usedBean;\n";
292
-        }, $usedBeans);
293
-
294
-        $str = "<?php
225
+			$this->ensureDirectoryExist($possibleFileName);
226
+			file_put_contents($possibleFileName, $str);
227
+			@chmod($possibleFileName, 0664);
228
+		}
229
+	}
230
+
231
+	/**
232
+	 * Tries to find a @defaultSort annotation in one of the columns.
233
+	 *
234
+	 * @param Table $table
235
+	 *
236
+	 * @return array First item: column name, Second item: column order (asc/desc)
237
+	 */
238
+	private function getDefaultSortColumnFromAnnotation(Table $table)
239
+	{
240
+		$defaultSort = null;
241
+		$defaultSortDirection = null;
242
+		foreach ($table->getColumns() as $column) {
243
+			$comments = $column->getComment();
244
+			$matches = [];
245
+			if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
246
+				$defaultSort = $column->getName();
247
+				if (count($matches) === 3) {
248
+					$defaultSortDirection = $matches[2];
249
+				} else {
250
+					$defaultSortDirection = 'ASC';
251
+				}
252
+			}
253
+		}
254
+
255
+		return [$defaultSort, $defaultSortDirection];
256
+	}
257
+
258
+	/**
259
+	 * Writes the PHP bean DAO with simple functions to create/get/save objects.
260
+	 *
261
+	 * @param BeanDescriptor  $beanDescriptor
262
+	 * @param string          $className       The name of the class
263
+	 * @param string          $baseClassName
264
+	 * @param string          $beanClassName
265
+	 * @param Table           $table
266
+	 * @param string          $daonamespace
267
+	 * @param string          $beannamespace
268
+	 * @param ClassNameMapper $classNameMapper
269
+	 *
270
+	 * @throws TDBMException
271
+	 */
272
+	public function generateDao(BeanDescriptor $beanDescriptor, $className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper)
273
+	{
274
+		$tableName = $table->getName();
275
+		$primaryKeyColumns = $table->getPrimaryKeyColumns();
276
+
277
+		list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
278
+
279
+		// FIXME: lowercase tables with _ in the name should work!
280
+		$tableCamel = self::toSingular(self::toCamelCase($tableName));
281
+
282
+		$beanClassWithoutNameSpace = $beanClassName;
283
+		$beanClassName = $beannamespace.'\\'.$beanClassName;
284
+
285
+		list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
286
+
287
+		$usedBeans[] = $beanClassName;
288
+		// Let's suppress duplicates in used beans (if any)
289
+		$usedBeans = array_flip(array_flip($usedBeans));
290
+		$useStatements = array_map(function ($usedBean) {
291
+			return "use $usedBean;\n";
292
+		}, $usedBeans);
293
+
294
+		$str = "<?php
295 295
 
296 296
 /*
297 297
  * This file has been automatically generated by TDBM.
@@ -368,9 +368,9 @@  discard block
 block discarded – undo
368 368
     }
369 369
     ";
370 370
 
371
-        if (count($primaryKeyColumns) === 1) {
372
-            $primaryKeyColumn = $primaryKeyColumns[0];
373
-            $str .= "
371
+		if (count($primaryKeyColumns) === 1) {
372
+			$primaryKeyColumn = $primaryKeyColumns[0];
373
+			$str .= "
374 374
     /**
375 375
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
376 376
      * If the primary key does not exist, an exception is thrown.
@@ -385,8 +385,8 @@  discard block
 block discarded – undo
385 385
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
386 386
     }
387 387
     ";
388
-        }
389
-        $str .= "
388
+		}
389
+		$str .= "
390 390
     /**
391 391
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
392 392
      *
@@ -444,33 +444,33 @@  discard block
 block discarded – undo
444 444
     }
445 445
 ";
446 446
 
447
-        $str .= $findByDaoCode;
448
-        $str .= '}
447
+		$str .= $findByDaoCode;
448
+		$str .= '}
449 449
 ';
450 450
 
451
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName);
452
-        if (empty($possibleBaseFileNames)) {
453
-            // @codeCoverageIgnoreStart
454
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
455
-            // @codeCoverageIgnoreEnd
456
-        }
457
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
458
-
459
-        $this->ensureDirectoryExist($possibleBaseFileName);
460
-        file_put_contents($possibleBaseFileName, $str);
461
-        @chmod($possibleBaseFileName, 0664);
462
-
463
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
464
-        if (empty($possibleFileNames)) {
465
-            // @codeCoverageIgnoreStart
466
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
467
-            // @codeCoverageIgnoreEnd
468
-        }
469
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
470
-
471
-        // Now, let's generate the "editable" class
472
-        if (!file_exists($possibleFileName)) {
473
-            $str = "<?php
451
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName);
452
+		if (empty($possibleBaseFileNames)) {
453
+			// @codeCoverageIgnoreStart
454
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
455
+			// @codeCoverageIgnoreEnd
456
+		}
457
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
458
+
459
+		$this->ensureDirectoryExist($possibleBaseFileName);
460
+		file_put_contents($possibleBaseFileName, $str);
461
+		@chmod($possibleBaseFileName, 0664);
462
+
463
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
464
+		if (empty($possibleFileNames)) {
465
+			// @codeCoverageIgnoreStart
466
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
467
+			// @codeCoverageIgnoreEnd
468
+		}
469
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
470
+
471
+		// Now, let's generate the "editable" class
472
+		if (!file_exists($possibleFileName)) {
473
+			$str = "<?php
474 474
 
475 475
 /*
476 476
  * This file has been automatically generated by TDBM.
@@ -487,22 +487,22 @@  discard block
 block discarded – undo
487 487
 
488 488
 }
489 489
 ";
490
-            $this->ensureDirectoryExist($possibleFileName);
491
-            file_put_contents($possibleFileName, $str);
492
-            @chmod($possibleFileName, 0664);
493
-        }
494
-    }
495
-
496
-    /**
497
-     * Generates the factory bean.
498
-     *
499
-     * @param Table[] $tableList
500
-     */
501
-    private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
502
-    {
503
-        // For each table, let's write a property.
504
-
505
-        $str = "<?php
490
+			$this->ensureDirectoryExist($possibleFileName);
491
+			file_put_contents($possibleFileName, $str);
492
+			@chmod($possibleFileName, 0664);
493
+		}
494
+	}
495
+
496
+	/**
497
+	 * Generates the factory bean.
498
+	 *
499
+	 * @param Table[] $tableList
500
+	 */
501
+	private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
502
+	{
503
+		// For each table, let's write a property.
504
+
505
+		$str = "<?php
506 506
 
507 507
 /*
508 508
  * This file has been automatically generated by TDBM.
@@ -519,12 +519,12 @@  discard block
 block discarded – undo
519 519
 {
520 520
 ";
521 521
 
522
-        foreach ($tableList as $table) {
523
-            $tableName = $table->getName();
524
-            $daoClassName = $this->getDaoNameFromTableName($tableName);
525
-            $daoInstanceName = self::toVariableName($daoClassName);
522
+		foreach ($tableList as $table) {
523
+			$tableName = $table->getName();
524
+			$daoClassName = $this->getDaoNameFromTableName($tableName);
525
+			$daoInstanceName = self::toVariableName($daoClassName);
526 526
 
527
-            $str .= '    /**
527
+			$str .= '    /**
528 528
      * @var '.$daoClassName.'
529 529
      */
530 530
     private $'.$daoInstanceName.';
@@ -549,155 +549,155 @@  discard block
 block discarded – undo
549 549
     }
550 550
 
551 551
 ';
552
-        }
552
+		}
553 553
 
554
-        $str .= '
554
+		$str .= '
555 555
 }
556 556
 ';
557 557
 
558
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\'.$daoFactoryClassName);
559
-        if (empty($possibleFileNames)) {
560
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
561
-        }
562
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
563
-
564
-        $this->ensureDirectoryExist($possibleFileName);
565
-        file_put_contents($possibleFileName, $str);
566
-        @chmod($possibleFileName, 0664);
567
-    }
568
-
569
-    /**
570
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
571
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
572
-     *
573
-     * @param $str string
574
-     *
575
-     * @return string
576
-     */
577
-    public static function toCamelCase($str)
578
-    {
579
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
580
-        while (true) {
581
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
582
-                break;
583
-            }
584
-
585
-            $pos = strpos($str, '_');
586
-            if ($pos === false) {
587
-                $pos = strpos($str, ' ');
588
-            }
589
-            $before = substr($str, 0, $pos);
590
-            $after = substr($str, $pos + 1);
591
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
592
-        }
593
-
594
-        return $str;
595
-    }
596
-
597
-    /**
598
-     * Tries to put string to the singular form (if it is plural).
599
-     * We assume the table names are in english.
600
-     *
601
-     * @param $str string
602
-     *
603
-     * @return string
604
-     */
605
-    public static function toSingular($str)
606
-    {
607
-        return Inflector::singularize($str);
608
-    }
609
-
610
-    /**
611
-     * Put the first letter of the string in lower case.
612
-     * Very useful to transform a class name into a variable name.
613
-     *
614
-     * @param $str string
615
-     *
616
-     * @return string
617
-     */
618
-    public static function toVariableName($str)
619
-    {
620
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
621
-    }
622
-
623
-    /**
624
-     * Ensures the file passed in parameter can be written in its directory.
625
-     *
626
-     * @param string $fileName
627
-     *
628
-     * @throws TDBMException
629
-     */
630
-    private function ensureDirectoryExist($fileName)
631
-    {
632
-        $dirName = dirname($fileName);
633
-        if (!file_exists($dirName)) {
634
-            $old = umask(0);
635
-            $result = mkdir($dirName, 0775, true);
636
-            umask($old);
637
-            if ($result === false) {
638
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
639
-            }
640
-        }
641
-    }
642
-
643
-    /**
644
-     * @param string $rootPath
645
-     */
646
-    public function setRootPath($rootPath)
647
-    {
648
-        $this->rootPath = $rootPath;
649
-    }
650
-
651
-    /**
652
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
653
-     *
654
-     * @param Type $type The DBAL type
655
-     *
656
-     * @return string The PHP type
657
-     */
658
-    public static function dbalTypeToPhpType(Type $type)
659
-    {
660
-        $map = [
661
-            Type::TARRAY => 'array',
662
-            Type::SIMPLE_ARRAY => 'array',
663
-            Type::JSON_ARRAY => 'array',
664
-            Type::BIGINT => 'string',
665
-            Type::BOOLEAN => 'bool',
666
-            Type::DATETIME => '\DateTimeInterface',
667
-            Type::DATETIMETZ => '\DateTimeInterface',
668
-            Type::DATE => '\DateTimeInterface',
669
-            Type::TIME => '\DateTimeInterface',
670
-            Type::DECIMAL => 'float',
671
-            Type::INTEGER => 'int',
672
-            Type::OBJECT => 'string',
673
-            Type::SMALLINT => 'int',
674
-            Type::STRING => 'string',
675
-            Type::TEXT => 'string',
676
-            Type::BINARY => 'string',
677
-            Type::BLOB => 'string',
678
-            Type::FLOAT => 'float',
679
-            Type::GUID => 'string',
680
-        ];
681
-
682
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
683
-    }
684
-
685
-    /**
686
-     * @param string $beanNamespace
687
-     *
688
-     * @return \string[] Returns a map mapping table name to beans name
689
-     */
690
-    public function buildTableToBeanMap($beanNamespace)
691
-    {
692
-        $tableToBeanMap = [];
693
-
694
-        $tables = $this->schema->getTables();
695
-
696
-        foreach ($tables as $table) {
697
-            $tableName = $table->getName();
698
-            $tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
699
-        }
700
-
701
-        return $tableToBeanMap;
702
-    }
558
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\'.$daoFactoryClassName);
559
+		if (empty($possibleFileNames)) {
560
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
561
+		}
562
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
563
+
564
+		$this->ensureDirectoryExist($possibleFileName);
565
+		file_put_contents($possibleFileName, $str);
566
+		@chmod($possibleFileName, 0664);
567
+	}
568
+
569
+	/**
570
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
571
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
572
+	 *
573
+	 * @param $str string
574
+	 *
575
+	 * @return string
576
+	 */
577
+	public static function toCamelCase($str)
578
+	{
579
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
580
+		while (true) {
581
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
582
+				break;
583
+			}
584
+
585
+			$pos = strpos($str, '_');
586
+			if ($pos === false) {
587
+				$pos = strpos($str, ' ');
588
+			}
589
+			$before = substr($str, 0, $pos);
590
+			$after = substr($str, $pos + 1);
591
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
592
+		}
593
+
594
+		return $str;
595
+	}
596
+
597
+	/**
598
+	 * Tries to put string to the singular form (if it is plural).
599
+	 * We assume the table names are in english.
600
+	 *
601
+	 * @param $str string
602
+	 *
603
+	 * @return string
604
+	 */
605
+	public static function toSingular($str)
606
+	{
607
+		return Inflector::singularize($str);
608
+	}
609
+
610
+	/**
611
+	 * Put the first letter of the string in lower case.
612
+	 * Very useful to transform a class name into a variable name.
613
+	 *
614
+	 * @param $str string
615
+	 *
616
+	 * @return string
617
+	 */
618
+	public static function toVariableName($str)
619
+	{
620
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
621
+	}
622
+
623
+	/**
624
+	 * Ensures the file passed in parameter can be written in its directory.
625
+	 *
626
+	 * @param string $fileName
627
+	 *
628
+	 * @throws TDBMException
629
+	 */
630
+	private function ensureDirectoryExist($fileName)
631
+	{
632
+		$dirName = dirname($fileName);
633
+		if (!file_exists($dirName)) {
634
+			$old = umask(0);
635
+			$result = mkdir($dirName, 0775, true);
636
+			umask($old);
637
+			if ($result === false) {
638
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
639
+			}
640
+		}
641
+	}
642
+
643
+	/**
644
+	 * @param string $rootPath
645
+	 */
646
+	public function setRootPath($rootPath)
647
+	{
648
+		$this->rootPath = $rootPath;
649
+	}
650
+
651
+	/**
652
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
653
+	 *
654
+	 * @param Type $type The DBAL type
655
+	 *
656
+	 * @return string The PHP type
657
+	 */
658
+	public static function dbalTypeToPhpType(Type $type)
659
+	{
660
+		$map = [
661
+			Type::TARRAY => 'array',
662
+			Type::SIMPLE_ARRAY => 'array',
663
+			Type::JSON_ARRAY => 'array',
664
+			Type::BIGINT => 'string',
665
+			Type::BOOLEAN => 'bool',
666
+			Type::DATETIME => '\DateTimeInterface',
667
+			Type::DATETIMETZ => '\DateTimeInterface',
668
+			Type::DATE => '\DateTimeInterface',
669
+			Type::TIME => '\DateTimeInterface',
670
+			Type::DECIMAL => 'float',
671
+			Type::INTEGER => 'int',
672
+			Type::OBJECT => 'string',
673
+			Type::SMALLINT => 'int',
674
+			Type::STRING => 'string',
675
+			Type::TEXT => 'string',
676
+			Type::BINARY => 'string',
677
+			Type::BLOB => 'string',
678
+			Type::FLOAT => 'float',
679
+			Type::GUID => 'string',
680
+		];
681
+
682
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
683
+	}
684
+
685
+	/**
686
+	 * @param string $beanNamespace
687
+	 *
688
+	 * @return \string[] Returns a map mapping table name to beans name
689
+	 */
690
+	public function buildTableToBeanMap($beanNamespace)
691
+	{
692
+		$tableToBeanMap = [];
693
+
694
+		$tables = $this->schema->getTables();
695
+
696
+		foreach ($tables as $table) {
697
+			$tableName = $table->getName();
698
+			$tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
699
+		}
700
+
701
+		return $tableToBeanMap;
702
+	}
703 703
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/BeanDescriptor.php 1 patch
Indentation   +539 added lines, -539 removed lines patch added patch discarded remove patch
@@ -16,213 +16,213 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class BeanDescriptor
18 18
 {
19
-    /**
20
-     * @var Table
21
-     */
22
-    private $table;
23
-
24
-    /**
25
-     * @var SchemaAnalyzer
26
-     */
27
-    private $schemaAnalyzer;
28
-
29
-    /**
30
-     * @var Schema
31
-     */
32
-    private $schema;
33
-
34
-    /**
35
-     * @var AbstractBeanPropertyDescriptor[]
36
-     */
37
-    private $beanPropertyDescriptors = [];
38
-
39
-    /**
40
-     * @var TDBMSchemaAnalyzer
41
-     */
42
-    private $tdbmSchemaAnalyzer;
43
-
44
-    public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
-    {
46
-        $this->table = $table;
47
-        $this->schemaAnalyzer = $schemaAnalyzer;
48
-        $this->schema = $schema;
49
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
-        $this->initBeanPropertyDescriptors();
51
-    }
52
-
53
-    private function initBeanPropertyDescriptors()
54
-    {
55
-        $this->beanPropertyDescriptors = $this->getProperties($this->table);
56
-    }
57
-
58
-    /**
59
-     * Returns the foreign-key the column is part of, if any. null otherwise.
60
-     *
61
-     * @param Table  $table
62
-     * @param Column $column
63
-     *
64
-     * @return ForeignKeyConstraint|null
65
-     */
66
-    private function isPartOfForeignKey(Table $table, Column $column)
67
-    {
68
-        $localColumnName = $column->getName();
69
-        foreach ($table->getForeignKeys() as $foreignKey) {
70
-            foreach ($foreignKey->getColumns() as $columnName) {
71
-                if ($columnName === $localColumnName) {
72
-                    return $foreignKey;
73
-                }
74
-            }
75
-        }
76
-
77
-        return;
78
-    }
79
-
80
-    /**
81
-     * @return AbstractBeanPropertyDescriptor[]
82
-     */
83
-    public function getBeanPropertyDescriptors()
84
-    {
85
-        return $this->beanPropertyDescriptors;
86
-    }
87
-
88
-    /**
89
-     * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
-     *
91
-     * @return AbstractBeanPropertyDescriptor[]
92
-     */
93
-    public function getConstructorProperties()
94
-    {
95
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
-           return $property->isCompulsory();
97
-        });
98
-
99
-        return $constructorProperties;
100
-    }
101
-
102
-    /**
103
-     * Returns the list of properties exposed as getters and setters in this class.
104
-     *
105
-     * @return AbstractBeanPropertyDescriptor[]
106
-     */
107
-    public function getExposedProperties()
108
-    {
109
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
110
-            return $property->getTable()->getName() == $this->table->getName();
111
-        });
112
-
113
-        return $exposedProperties;
114
-    }
115
-
116
-    /**
117
-     * Returns the list of properties for this table (including parent tables).
118
-     *
119
-     * @param Table $table
120
-     *
121
-     * @return AbstractBeanPropertyDescriptor[]
122
-     */
123
-    private function getProperties(Table $table)
124
-    {
125
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
126
-        if ($parentRelationship) {
127
-            $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
128
-            $properties = $this->getProperties($parentTable);
129
-            // we merge properties by overriding property names.
130
-            $localProperties = $this->getPropertiesForTable($table);
131
-            foreach ($localProperties as $name => $property) {
132
-                // We do not override properties if this is a primary key!
133
-                if ($property->isPrimaryKey()) {
134
-                    continue;
135
-                }
136
-                $properties[$name] = $property;
137
-            }
138
-        } else {
139
-            $properties = $this->getPropertiesForTable($table);
140
-        }
141
-
142
-        return $properties;
143
-    }
144
-
145
-    /**
146
-     * Returns the list of properties for this table (ignoring parent tables).
147
-     *
148
-     * @param Table $table
149
-     *
150
-     * @return AbstractBeanPropertyDescriptor[]
151
-     */
152
-    private function getPropertiesForTable(Table $table)
153
-    {
154
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
155
-        if ($parentRelationship) {
156
-            $ignoreColumns = $parentRelationship->getLocalColumns();
157
-        } else {
158
-            $ignoreColumns = [];
159
-        }
160
-
161
-        $beanPropertyDescriptors = [];
162
-
163
-        foreach ($table->getColumns() as $column) {
164
-            if (array_search($column->getName(), $ignoreColumns) !== false) {
165
-                continue;
166
-            }
167
-
168
-            $fk = $this->isPartOfForeignKey($table, $column);
169
-            if ($fk !== null) {
170
-                // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
171
-                foreach ($beanPropertyDescriptors as $beanDescriptor) {
172
-                    if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
173
-                        continue 2;
174
-                    }
175
-                }
176
-                // Check that this property is not an inheritance relationship
177
-                $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
178
-                if ($parentRelationship === $fk) {
179
-                    continue;
180
-                }
181
-
182
-                $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
183
-            } else {
184
-                $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
185
-            }
186
-        }
187
-
188
-        // Now, let's get the name of all properties and let's check there is no duplicate.
189
-        /** @var $names AbstractBeanPropertyDescriptor[] */
190
-        $names = [];
191
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
192
-            $name = $beanDescriptor->getUpperCamelCaseName();
193
-            if (isset($names[$name])) {
194
-                $names[$name]->useAlternativeName();
195
-                $beanDescriptor->useAlternativeName();
196
-            } else {
197
-                $names[$name] = $beanDescriptor;
198
-            }
199
-        }
200
-
201
-        // Final check (throw exceptions if problem arises)
202
-        $names = [];
203
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
204
-            $name = $beanDescriptor->getUpperCamelCaseName();
205
-            if (isset($names[$name])) {
206
-                throw new TDBMException('Unsolvable name conflict while generating method name');
207
-            } else {
208
-                $names[$name] = $beanDescriptor;
209
-            }
210
-        }
211
-
212
-        // Last step, let's rebuild the list with a map:
213
-        $beanPropertyDescriptorsMap = [];
214
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
215
-            $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
216
-        }
217
-
218
-        return $beanPropertyDescriptorsMap;
219
-    }
220
-
221
-    public function generateBeanConstructor()
222
-    {
223
-        $constructorProperties = $this->getConstructorProperties();
224
-
225
-        $constructorCode = '    /**
19
+	/**
20
+	 * @var Table
21
+	 */
22
+	private $table;
23
+
24
+	/**
25
+	 * @var SchemaAnalyzer
26
+	 */
27
+	private $schemaAnalyzer;
28
+
29
+	/**
30
+	 * @var Schema
31
+	 */
32
+	private $schema;
33
+
34
+	/**
35
+	 * @var AbstractBeanPropertyDescriptor[]
36
+	 */
37
+	private $beanPropertyDescriptors = [];
38
+
39
+	/**
40
+	 * @var TDBMSchemaAnalyzer
41
+	 */
42
+	private $tdbmSchemaAnalyzer;
43
+
44
+	public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
+	{
46
+		$this->table = $table;
47
+		$this->schemaAnalyzer = $schemaAnalyzer;
48
+		$this->schema = $schema;
49
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
+		$this->initBeanPropertyDescriptors();
51
+	}
52
+
53
+	private function initBeanPropertyDescriptors()
54
+	{
55
+		$this->beanPropertyDescriptors = $this->getProperties($this->table);
56
+	}
57
+
58
+	/**
59
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
60
+	 *
61
+	 * @param Table  $table
62
+	 * @param Column $column
63
+	 *
64
+	 * @return ForeignKeyConstraint|null
65
+	 */
66
+	private function isPartOfForeignKey(Table $table, Column $column)
67
+	{
68
+		$localColumnName = $column->getName();
69
+		foreach ($table->getForeignKeys() as $foreignKey) {
70
+			foreach ($foreignKey->getColumns() as $columnName) {
71
+				if ($columnName === $localColumnName) {
72
+					return $foreignKey;
73
+				}
74
+			}
75
+		}
76
+
77
+		return;
78
+	}
79
+
80
+	/**
81
+	 * @return AbstractBeanPropertyDescriptor[]
82
+	 */
83
+	public function getBeanPropertyDescriptors()
84
+	{
85
+		return $this->beanPropertyDescriptors;
86
+	}
87
+
88
+	/**
89
+	 * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
+	 *
91
+	 * @return AbstractBeanPropertyDescriptor[]
92
+	 */
93
+	public function getConstructorProperties()
94
+	{
95
+		$constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
+		   return $property->isCompulsory();
97
+		});
98
+
99
+		return $constructorProperties;
100
+	}
101
+
102
+	/**
103
+	 * Returns the list of properties exposed as getters and setters in this class.
104
+	 *
105
+	 * @return AbstractBeanPropertyDescriptor[]
106
+	 */
107
+	public function getExposedProperties()
108
+	{
109
+		$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
110
+			return $property->getTable()->getName() == $this->table->getName();
111
+		});
112
+
113
+		return $exposedProperties;
114
+	}
115
+
116
+	/**
117
+	 * Returns the list of properties for this table (including parent tables).
118
+	 *
119
+	 * @param Table $table
120
+	 *
121
+	 * @return AbstractBeanPropertyDescriptor[]
122
+	 */
123
+	private function getProperties(Table $table)
124
+	{
125
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
126
+		if ($parentRelationship) {
127
+			$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
128
+			$properties = $this->getProperties($parentTable);
129
+			// we merge properties by overriding property names.
130
+			$localProperties = $this->getPropertiesForTable($table);
131
+			foreach ($localProperties as $name => $property) {
132
+				// We do not override properties if this is a primary key!
133
+				if ($property->isPrimaryKey()) {
134
+					continue;
135
+				}
136
+				$properties[$name] = $property;
137
+			}
138
+		} else {
139
+			$properties = $this->getPropertiesForTable($table);
140
+		}
141
+
142
+		return $properties;
143
+	}
144
+
145
+	/**
146
+	 * Returns the list of properties for this table (ignoring parent tables).
147
+	 *
148
+	 * @param Table $table
149
+	 *
150
+	 * @return AbstractBeanPropertyDescriptor[]
151
+	 */
152
+	private function getPropertiesForTable(Table $table)
153
+	{
154
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
155
+		if ($parentRelationship) {
156
+			$ignoreColumns = $parentRelationship->getLocalColumns();
157
+		} else {
158
+			$ignoreColumns = [];
159
+		}
160
+
161
+		$beanPropertyDescriptors = [];
162
+
163
+		foreach ($table->getColumns() as $column) {
164
+			if (array_search($column->getName(), $ignoreColumns) !== false) {
165
+				continue;
166
+			}
167
+
168
+			$fk = $this->isPartOfForeignKey($table, $column);
169
+			if ($fk !== null) {
170
+				// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
171
+				foreach ($beanPropertyDescriptors as $beanDescriptor) {
172
+					if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
173
+						continue 2;
174
+					}
175
+				}
176
+				// Check that this property is not an inheritance relationship
177
+				$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
178
+				if ($parentRelationship === $fk) {
179
+					continue;
180
+				}
181
+
182
+				$beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
183
+			} else {
184
+				$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
185
+			}
186
+		}
187
+
188
+		// Now, let's get the name of all properties and let's check there is no duplicate.
189
+		/** @var $names AbstractBeanPropertyDescriptor[] */
190
+		$names = [];
191
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
192
+			$name = $beanDescriptor->getUpperCamelCaseName();
193
+			if (isset($names[$name])) {
194
+				$names[$name]->useAlternativeName();
195
+				$beanDescriptor->useAlternativeName();
196
+			} else {
197
+				$names[$name] = $beanDescriptor;
198
+			}
199
+		}
200
+
201
+		// Final check (throw exceptions if problem arises)
202
+		$names = [];
203
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
204
+			$name = $beanDescriptor->getUpperCamelCaseName();
205
+			if (isset($names[$name])) {
206
+				throw new TDBMException('Unsolvable name conflict while generating method name');
207
+			} else {
208
+				$names[$name] = $beanDescriptor;
209
+			}
210
+		}
211
+
212
+		// Last step, let's rebuild the list with a map:
213
+		$beanPropertyDescriptorsMap = [];
214
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
215
+			$beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
216
+		}
217
+
218
+		return $beanPropertyDescriptorsMap;
219
+	}
220
+
221
+	public function generateBeanConstructor()
222
+	{
223
+		$constructorProperties = $this->getConstructorProperties();
224
+
225
+		$constructorCode = '    /**
226 226
      * The constructor takes all compulsory arguments.
227 227
      *
228 228
 %s
@@ -232,65 +232,65 @@  discard block
 block discarded – undo
232 232
     }
233 233
     ';
234 234
 
235
-        $paramAnnotations = [];
236
-        $arguments = [];
237
-        $assigns = [];
238
-        $parentConstructorArguments = [];
239
-
240
-        foreach ($constructorProperties as $property) {
241
-            $className = $property->getClassName();
242
-            if ($className) {
243
-                $arguments[] = $className.' '.$property->getVariableName();
244
-            } else {
245
-                $arguments[] = $property->getVariableName();
246
-            }
247
-            $paramAnnotations[] = $property->getParamAnnotation();
248
-            if ($property->getTable()->getName() === $this->table->getName()) {
249
-                $assigns[] = $property->getConstructorAssignCode();
250
-            } else {
251
-                $parentConstructorArguments[] = $property->getVariableName();
252
-            }
253
-        }
254
-
255
-        $parentConstrutorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
256
-
257
-        return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstrutorCode, implode("\n", $assigns));
258
-    }
259
-
260
-    public function generateDirectForeignKeysCode()
261
-    {
262
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
263
-
264
-        $fksByTable = [];
265
-
266
-        foreach ($fks as $fk) {
267
-            $fksByTable[$fk->getLocalTableName()][] = $fk;
268
-        }
269
-
270
-        /* @var $fksByMethodName ForeignKeyConstraint[] */
271
-        $fksByMethodName = [];
272
-
273
-        foreach ($fksByTable as $tableName => $fksForTable) {
274
-            if (count($fksForTable) > 1) {
275
-                foreach ($fksForTable as $fk) {
276
-                    $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
277
-
278
-                    $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $fk->getLocalColumns());
279
-
280
-                    $methodName .= implode('And', $camelizedColumns);
281
-
282
-                    $fksByMethodName[$methodName] = $fk;
283
-                }
284
-            } else {
285
-                $methodName = 'get'.TDBMDaoGenerator::toCamelCase($fksForTable[0]->getLocalTableName());
286
-                $fksByMethodName[$methodName] = $fksForTable[0];
287
-            }
288
-        }
289
-
290
-        $code = '';
291
-
292
-        foreach ($fksByMethodName as $methodName => $fk) {
293
-            $getterCode = '    /**
235
+		$paramAnnotations = [];
236
+		$arguments = [];
237
+		$assigns = [];
238
+		$parentConstructorArguments = [];
239
+
240
+		foreach ($constructorProperties as $property) {
241
+			$className = $property->getClassName();
242
+			if ($className) {
243
+				$arguments[] = $className.' '.$property->getVariableName();
244
+			} else {
245
+				$arguments[] = $property->getVariableName();
246
+			}
247
+			$paramAnnotations[] = $property->getParamAnnotation();
248
+			if ($property->getTable()->getName() === $this->table->getName()) {
249
+				$assigns[] = $property->getConstructorAssignCode();
250
+			} else {
251
+				$parentConstructorArguments[] = $property->getVariableName();
252
+			}
253
+		}
254
+
255
+		$parentConstrutorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
256
+
257
+		return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstrutorCode, implode("\n", $assigns));
258
+	}
259
+
260
+	public function generateDirectForeignKeysCode()
261
+	{
262
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
263
+
264
+		$fksByTable = [];
265
+
266
+		foreach ($fks as $fk) {
267
+			$fksByTable[$fk->getLocalTableName()][] = $fk;
268
+		}
269
+
270
+		/* @var $fksByMethodName ForeignKeyConstraint[] */
271
+		$fksByMethodName = [];
272
+
273
+		foreach ($fksByTable as $tableName => $fksForTable) {
274
+			if (count($fksForTable) > 1) {
275
+				foreach ($fksForTable as $fk) {
276
+					$methodName = 'get'.TDBMDaoGenerator::toCamelCase($fk->getLocalTableName()).'By';
277
+
278
+					$camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $fk->getLocalColumns());
279
+
280
+					$methodName .= implode('And', $camelizedColumns);
281
+
282
+					$fksByMethodName[$methodName] = $fk;
283
+				}
284
+			} else {
285
+				$methodName = 'get'.TDBMDaoGenerator::toCamelCase($fksForTable[0]->getLocalTableName());
286
+				$fksByMethodName[$methodName] = $fksForTable[0];
287
+			}
288
+		}
289
+
290
+		$code = '';
291
+
292
+		foreach ($fksByMethodName as $methodName => $fk) {
293
+			$getterCode = '    /**
294 294
      * Returns the list of %s pointing to this bean via the %s column.
295 295
      *
296 296
      * @return %s[]|ResultIterator
@@ -302,111 +302,111 @@  discard block
 block discarded – undo
302 302
 
303 303
 ';
304 304
 
305
-            list($sql, $parametersCode) = $this->getFilters($fk);
306
-
307
-            $beanClass = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
308
-            $code .= sprintf($getterCode,
309
-                $beanClass,
310
-                implode(', ', $fk->getColumns()),
311
-                $beanClass,
312
-                $methodName,
313
-                var_export($fk->getLocalTableName(), true),
314
-                $sql,
315
-                $parametersCode
316
-            );
317
-        }
318
-
319
-        return $code;
320
-    }
321
-
322
-    private function getFilters(ForeignKeyConstraint $fk)
323
-    {
324
-        $sqlParts = [];
325
-        $counter = 0;
326
-        $parameters = [];
327
-
328
-        $pkColumns = $this->table->getPrimaryKeyColumns();
329
-
330
-        foreach ($fk->getLocalColumns() as $columnName) {
331
-            $paramName = 'tdbmparam'.$counter;
332
-            $sqlParts[] = $fk->getLocalTableName().'.'.$columnName.' = :'.$paramName;
333
-
334
-            $pkColumn = $pkColumns[$counter];
335
-            $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($paramName, true), var_export($pkColumn, true), var_export($this->table->getName(), true));
336
-            ++$counter;
337
-        }
338
-        $sql = "'".implode(' AND ', $sqlParts)."'";
339
-        $parametersCode = '[ '.implode(', ', $parameters).' ]';
340
-
341
-        return [$sql, $parametersCode];
342
-    }
343
-
344
-    /**
345
-     * Generate code section about pivot tables.
346
-     *
347
-     * @return string
348
-     */
349
-    public function generatePivotTableCode()
350
-    {
351
-        $finalDescs = $this->getPivotTableDescriptors();
352
-
353
-        $code = '';
354
-
355
-        foreach ($finalDescs as $desc) {
356
-            $code .= $this->getPivotTableCode($desc['name'], $desc['table'], $desc['localFK'], $desc['remoteFK']);
357
-        }
358
-
359
-        return $code;
360
-    }
361
-
362
-    private function getPivotTableDescriptors()
363
-    {
364
-        $descs = [];
365
-        foreach ($this->schemaAnalyzer->detectJunctionTables() as $table) {
366
-            // There are exactly 2 FKs since this is a pivot table.
367
-            $fks = array_values($table->getForeignKeys());
368
-
369
-            if ($fks[0]->getForeignTableName() === $this->table->getName()) {
370
-                $localFK = $fks[0];
371
-                $remoteFK = $fks[1];
372
-            } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
373
-                $localFK = $fks[1];
374
-                $remoteFK = $fks[0];
375
-            } else {
376
-                continue;
377
-            }
378
-
379
-            $descs[$remoteFK->getForeignTableName()][] = [
380
-                'table' => $table,
381
-                'localFK' => $localFK,
382
-                'remoteFK' => $remoteFK,
383
-            ];
384
-        }
385
-
386
-        $finalDescs = [];
387
-        foreach ($descs as $descArray) {
388
-            if (count($descArray) > 1) {
389
-                foreach ($descArray as $desc) {
390
-                    $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
391
-                    $finalDescs[] = $desc;
392
-                }
393
-            } else {
394
-                $desc = $descArray[0];
395
-                $desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName());
396
-                $finalDescs[] = $desc;
397
-            }
398
-        }
399
-
400
-        return $finalDescs;
401
-    }
402
-
403
-    public function getPivotTableCode($name, Table $table, ForeignKeyConstraint $localFK, ForeignKeyConstraint $remoteFK)
404
-    {
405
-        $singularName = TDBMDaoGenerator::toSingular($name);
406
-        $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
407
-        $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
408
-
409
-        $str = '    /**
305
+			list($sql, $parametersCode) = $this->getFilters($fk);
306
+
307
+			$beanClass = TDBMDaoGenerator::getBeanNameFromTableName($fk->getLocalTableName());
308
+			$code .= sprintf($getterCode,
309
+				$beanClass,
310
+				implode(', ', $fk->getColumns()),
311
+				$beanClass,
312
+				$methodName,
313
+				var_export($fk->getLocalTableName(), true),
314
+				$sql,
315
+				$parametersCode
316
+			);
317
+		}
318
+
319
+		return $code;
320
+	}
321
+
322
+	private function getFilters(ForeignKeyConstraint $fk)
323
+	{
324
+		$sqlParts = [];
325
+		$counter = 0;
326
+		$parameters = [];
327
+
328
+		$pkColumns = $this->table->getPrimaryKeyColumns();
329
+
330
+		foreach ($fk->getLocalColumns() as $columnName) {
331
+			$paramName = 'tdbmparam'.$counter;
332
+			$sqlParts[] = $fk->getLocalTableName().'.'.$columnName.' = :'.$paramName;
333
+
334
+			$pkColumn = $pkColumns[$counter];
335
+			$parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($paramName, true), var_export($pkColumn, true), var_export($this->table->getName(), true));
336
+			++$counter;
337
+		}
338
+		$sql = "'".implode(' AND ', $sqlParts)."'";
339
+		$parametersCode = '[ '.implode(', ', $parameters).' ]';
340
+
341
+		return [$sql, $parametersCode];
342
+	}
343
+
344
+	/**
345
+	 * Generate code section about pivot tables.
346
+	 *
347
+	 * @return string
348
+	 */
349
+	public function generatePivotTableCode()
350
+	{
351
+		$finalDescs = $this->getPivotTableDescriptors();
352
+
353
+		$code = '';
354
+
355
+		foreach ($finalDescs as $desc) {
356
+			$code .= $this->getPivotTableCode($desc['name'], $desc['table'], $desc['localFK'], $desc['remoteFK']);
357
+		}
358
+
359
+		return $code;
360
+	}
361
+
362
+	private function getPivotTableDescriptors()
363
+	{
364
+		$descs = [];
365
+		foreach ($this->schemaAnalyzer->detectJunctionTables() as $table) {
366
+			// There are exactly 2 FKs since this is a pivot table.
367
+			$fks = array_values($table->getForeignKeys());
368
+
369
+			if ($fks[0]->getForeignTableName() === $this->table->getName()) {
370
+				$localFK = $fks[0];
371
+				$remoteFK = $fks[1];
372
+			} elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
373
+				$localFK = $fks[1];
374
+				$remoteFK = $fks[0];
375
+			} else {
376
+				continue;
377
+			}
378
+
379
+			$descs[$remoteFK->getForeignTableName()][] = [
380
+				'table' => $table,
381
+				'localFK' => $localFK,
382
+				'remoteFK' => $remoteFK,
383
+			];
384
+		}
385
+
386
+		$finalDescs = [];
387
+		foreach ($descs as $descArray) {
388
+			if (count($descArray) > 1) {
389
+				foreach ($descArray as $desc) {
390
+					$desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($desc['table']->getName());
391
+					$finalDescs[] = $desc;
392
+				}
393
+			} else {
394
+				$desc = $descArray[0];
395
+				$desc['name'] = TDBMDaoGenerator::toCamelCase($desc['remoteFK']->getForeignTableName());
396
+				$finalDescs[] = $desc;
397
+			}
398
+		}
399
+
400
+		return $finalDescs;
401
+	}
402
+
403
+	public function getPivotTableCode($name, Table $table, ForeignKeyConstraint $localFK, ForeignKeyConstraint $remoteFK)
404
+	{
405
+		$singularName = TDBMDaoGenerator::toSingular($name);
406
+		$remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
407
+		$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
408
+
409
+		$str = '    /**
410 410
      * Returns the list of %s associated to this bean via the %s pivot table.
411 411
      *
412 412
      * @return %s[]
@@ -416,9 +416,9 @@  discard block
 block discarded – undo
416 416
     }
417 417
 ';
418 418
 
419
-        $getterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $name, var_export($remoteFK->getLocalTableName(), true));
419
+		$getterCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $name, var_export($remoteFK->getLocalTableName(), true));
420 420
 
421
-        $str = '    /**
421
+		$str = '    /**
422 422
      * Adds a relationship with %s associated to this bean via the %s pivot table.
423 423
      *
424 424
      * @param %s %s
@@ -428,9 +428,9 @@  discard block
 block discarded – undo
428 428
     }
429 429
 ';
430 430
 
431
-        $adderCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
431
+		$adderCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
432 432
 
433
-        $str = '    /**
433
+		$str = '    /**
434 434
      * Deletes the relationship with %s associated to this bean via the %s pivot table.
435 435
      *
436 436
      * @param %s %s
@@ -440,9 +440,9 @@  discard block
 block discarded – undo
440 440
     }
441 441
 ';
442 442
 
443
-        $removerCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
443
+		$removerCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
444 444
 
445
-        $str = '    /**
445
+		$str = '    /**
446 446
      * Returns whether this bean is associated with %s via the %s pivot table.
447 447
      *
448 448
      * @param %s %s
@@ -453,24 +453,24 @@  discard block
 block discarded – undo
453 453
     }
454 454
 ';
455 455
 
456
-        $hasCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
456
+		$hasCode = sprintf($str, $remoteBeanName, $table->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($remoteFK->getLocalTableName(), true), $variableName);
457 457
 
458
-        $code = $getterCode.$adderCode.$removerCode.$hasCode;
458
+		$code = $getterCode.$adderCode.$removerCode.$hasCode;
459 459
 
460
-        return $code;
461
-    }
460
+		return $code;
461
+	}
462 462
 
463
-    public function generateJsonSerialize()
464
-    {
465
-        $tableName = $this->table->getName();
466
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
467
-        if ($parentFk !== null) {
468
-            $initializer = '$array = parent::jsonSerialize();';
469
-        } else {
470
-            $initializer = '$array = [];';
471
-        }
463
+	public function generateJsonSerialize()
464
+	{
465
+		$tableName = $this->table->getName();
466
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
467
+		if ($parentFk !== null) {
468
+			$initializer = '$array = parent::jsonSerialize();';
469
+		} else {
470
+			$initializer = '$array = [];';
471
+		}
472 472
 
473
-        $str = '
473
+		$str = '
474 474
     /**
475 475
      * Serializes the object for JSON encoding
476 476
      *
@@ -486,54 +486,54 @@  discard block
 block discarded – undo
486 486
     }
487 487
 ';
488 488
 
489
-        $propertiesCode = '';
490
-        foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
491
-            $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
492
-        }
489
+		$propertiesCode = '';
490
+		foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
491
+			$propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
492
+		}
493 493
 
494
-        // Many to many relationships:
494
+		// Many to many relationships:
495 495
 
496
-        $descs = $this->getPivotTableDescriptors();
496
+		$descs = $this->getPivotTableDescriptors();
497 497
 
498
-        $many2manyCode = '';
498
+		$many2manyCode = '';
499 499
 
500
-        foreach ($descs as $desc) {
501
-            $remoteFK = $desc['remoteFK'];
502
-            $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
503
-            $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
500
+		foreach ($descs as $desc) {
501
+			$remoteFK = $desc['remoteFK'];
502
+			$remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($remoteFK->getForeignTableName());
503
+			$variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
504 504
 
505
-            $many2manyCode .= '        if (!$stopRecursion) {
505
+			$many2manyCode .= '        if (!$stopRecursion) {
506 506
             $array[\''.lcfirst($desc['name']).'\'] = array_map(function('.$remoteBeanName.' '.$variableName.') {
507 507
                 return '.$variableName.'->jsonSerialize(true);
508 508
             }, $this->get'.$desc['name'].'());
509 509
         }
510 510
         ';
511
-        }
512
-
513
-        return sprintf($str, $initializer, $propertiesCode, $many2manyCode);
514
-    }
515
-
516
-    /**
517
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
518
-     *
519
-     * @param string $beannamespace The namespace of the bean
520
-     */
521
-    public function generatePhpCode($beannamespace)
522
-    {
523
-        $baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($this->table->getName());
524
-        $className = TDBMDaoGenerator::getBeanNameFromTableName($this->table->getName());
525
-        $tableName = $this->table->getName();
526
-
527
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
528
-        if ($parentFk !== null) {
529
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
530
-            $use = '';
531
-        } else {
532
-            $extends = 'AbstractTDBMObject';
533
-            $use = "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n\n";
534
-        }
535
-
536
-        $str = "<?php
511
+		}
512
+
513
+		return sprintf($str, $initializer, $propertiesCode, $many2manyCode);
514
+	}
515
+
516
+	/**
517
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
518
+	 *
519
+	 * @param string $beannamespace The namespace of the bean
520
+	 */
521
+	public function generatePhpCode($beannamespace)
522
+	{
523
+		$baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($this->table->getName());
524
+		$className = TDBMDaoGenerator::getBeanNameFromTableName($this->table->getName());
525
+		$tableName = $this->table->getName();
526
+
527
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
528
+		if ($parentFk !== null) {
529
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
530
+			$use = '';
531
+		} else {
532
+			$extends = 'AbstractTDBMObject';
533
+			$use = "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n\n";
534
+		}
535
+
536
+		$str = "<?php
537 537
 namespace {$beannamespace};
538 538
 
539 539
 use Mouf\\Database\\TDBM\\ResultIterator;
@@ -551,122 +551,122 @@  discard block
 block discarded – undo
551 551
 {
552 552
 ";
553 553
 
554
-        $str .= $this->generateBeanConstructor();
554
+		$str .= $this->generateBeanConstructor();
555 555
 
556
-        foreach ($this->getExposedProperties() as $property) {
557
-            $str .= $property->getGetterSetterCode();
558
-        }
556
+		foreach ($this->getExposedProperties() as $property) {
557
+			$str .= $property->getGetterSetterCode();
558
+		}
559 559
 
560
-        $str .= $this->generateDirectForeignKeysCode();
561
-        $str .= $this->generatePivotTableCode();
562
-        $str .= $this->generateJsonSerialize();
560
+		$str .= $this->generateDirectForeignKeysCode();
561
+		$str .= $this->generatePivotTableCode();
562
+		$str .= $this->generateJsonSerialize();
563 563
 
564
-        $str .= '}
564
+		$str .= '}
565 565
 ';
566 566
 
567
-        return $str;
568
-    }
569
-
570
-    /**
571
-     * @param string $beanNamespace
572
-     * @param string $beanClassName
573
-     *
574
-     * @return array first element: list of used beans, second item: PHP code as a string
575
-     */
576
-    public function generateFindByDaoCode($beanNamespace, $beanClassName)
577
-    {
578
-        $code = '';
579
-        $usedBeans = [];
580
-        foreach ($this->table->getIndexes() as $index) {
581
-            if (!$index->isPrimary()) {
582
-                list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
583
-                $code .= $codeForIndex;
584
-                $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
585
-            }
586
-        }
587
-
588
-        return [$usedBeans, $code];
589
-    }
590
-
591
-    /**
592
-     * @param Index  $index
593
-     * @param string $beanNamespace
594
-     * @param string $beanClassName
595
-     *
596
-     * @return array first element: list of used beans, second item: PHP code as a string
597
-     */
598
-    private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
599
-    {
600
-        $columns = $index->getColumns();
601
-        $usedBeans = [];
602
-
603
-        /*
567
+		return $str;
568
+	}
569
+
570
+	/**
571
+	 * @param string $beanNamespace
572
+	 * @param string $beanClassName
573
+	 *
574
+	 * @return array first element: list of used beans, second item: PHP code as a string
575
+	 */
576
+	public function generateFindByDaoCode($beanNamespace, $beanClassName)
577
+	{
578
+		$code = '';
579
+		$usedBeans = [];
580
+		foreach ($this->table->getIndexes() as $index) {
581
+			if (!$index->isPrimary()) {
582
+				list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
583
+				$code .= $codeForIndex;
584
+				$usedBeans = array_merge($usedBeans, $usedBeansForIndex);
585
+			}
586
+		}
587
+
588
+		return [$usedBeans, $code];
589
+	}
590
+
591
+	/**
592
+	 * @param Index  $index
593
+	 * @param string $beanNamespace
594
+	 * @param string $beanClassName
595
+	 *
596
+	 * @return array first element: list of used beans, second item: PHP code as a string
597
+	 */
598
+	private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
599
+	{
600
+		$columns = $index->getColumns();
601
+		$usedBeans = [];
602
+
603
+		/*
604 604
          * The list of elements building this index (expressed as columns or foreign keys)
605 605
          * @var AbstractBeanPropertyDescriptor[]
606 606
          */
607
-        $elements = [];
608
-
609
-        foreach ($columns as $column) {
610
-            $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
611
-            if ($fk !== null) {
612
-                if (!in_array($fk, $elements)) {
613
-                    $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
614
-                }
615
-            } else {
616
-                $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
617
-            }
618
-        }
619
-
620
-        // If the index is actually only a foreign key, let's bypass it entirely.
621
-        if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
622
-            return [[], ''];
623
-        }
624
-
625
-        $methodNameComponent = [];
626
-        $functionParameters = [];
627
-        $first = true;
628
-        foreach ($elements as $element) {
629
-            $methodNameComponent[] = $element->getUpperCamelCaseName();
630
-            $functionParameter = $element->getClassName();
631
-            if ($functionParameter) {
632
-                $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
633
-                $functionParameter .= ' ';
634
-            }
635
-            $functionParameter .= $element->getVariableName();
636
-            if ($first) {
637
-                $first = false;
638
-            } else {
639
-                $functionParameter .= ' = null';
640
-            }
641
-            $functionParameters[] = $functionParameter;
642
-        }
643
-        if ($index->isUnique()) {
644
-            $methodName = 'findOneBy'.implode('And', $methodNameComponent);
645
-            $calledMethod = 'findOne';
646
-        } else {
647
-            $methodName = 'findBy'.implode('And', $methodNameComponent);
648
-            $calledMethod = 'find';
649
-        }
650
-        $functionParametersString = implode(', ', $functionParameters);
651
-
652
-        $count = 0;
653
-
654
-        $params = [];
655
-        $filterArrayCode = '';
656
-        $commentArguments = [];
657
-        foreach ($elements as $element) {
658
-            $params[] = $element->getParamAnnotation();
659
-            if ($element instanceof ScalarBeanPropertyDescriptor) {
660
-                $filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
661
-            } else {
662
-                ++$count;
663
-                $filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
664
-            }
665
-            $commentArguments[] = substr($element->getVariableName(), 1);
666
-        }
667
-        $paramsString = implode("\n", $params);
668
-
669
-        $code = "
607
+		$elements = [];
608
+
609
+		foreach ($columns as $column) {
610
+			$fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
611
+			if ($fk !== null) {
612
+				if (!in_array($fk, $elements)) {
613
+					$elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
614
+				}
615
+			} else {
616
+				$elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
617
+			}
618
+		}
619
+
620
+		// If the index is actually only a foreign key, let's bypass it entirely.
621
+		if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
622
+			return [[], ''];
623
+		}
624
+
625
+		$methodNameComponent = [];
626
+		$functionParameters = [];
627
+		$first = true;
628
+		foreach ($elements as $element) {
629
+			$methodNameComponent[] = $element->getUpperCamelCaseName();
630
+			$functionParameter = $element->getClassName();
631
+			if ($functionParameter) {
632
+				$usedBeans[] = $beanNamespace.'\\'.$functionParameter;
633
+				$functionParameter .= ' ';
634
+			}
635
+			$functionParameter .= $element->getVariableName();
636
+			if ($first) {
637
+				$first = false;
638
+			} else {
639
+				$functionParameter .= ' = null';
640
+			}
641
+			$functionParameters[] = $functionParameter;
642
+		}
643
+		if ($index->isUnique()) {
644
+			$methodName = 'findOneBy'.implode('And', $methodNameComponent);
645
+			$calledMethod = 'findOne';
646
+		} else {
647
+			$methodName = 'findBy'.implode('And', $methodNameComponent);
648
+			$calledMethod = 'find';
649
+		}
650
+		$functionParametersString = implode(', ', $functionParameters);
651
+
652
+		$count = 0;
653
+
654
+		$params = [];
655
+		$filterArrayCode = '';
656
+		$commentArguments = [];
657
+		foreach ($elements as $element) {
658
+			$params[] = $element->getParamAnnotation();
659
+			if ($element instanceof ScalarBeanPropertyDescriptor) {
660
+				$filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
661
+			} else {
662
+				++$count;
663
+				$filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
664
+			}
665
+			$commentArguments[] = substr($element->getVariableName(), 1);
666
+		}
667
+		$paramsString = implode("\n", $params);
668
+
669
+		$code = "
670 670
     /**
671 671
      * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
672 672
      *
@@ -684,6 +684,6 @@  discard block
 block discarded – undo
684 684
     }
685 685
 ";
686 686
 
687
-        return [$usedBeans, $code];
688
-    }
687
+		return [$usedBeans, $code];
688
+	}
689 689
 }
Please login to merge, or discard this patch.