Completed
Push — 4.3 ( 28cdbc )
by David
21:20 queued 01:32
created
src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php 1 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.
@@ -374,10 +374,10 @@  discard block
 block discarded – undo
374 374
     }
375 375
     ";
376 376
 
377
-        if (count($primaryKeyColumns) === 1) {
378
-            $primaryKeyColumn = $primaryKeyColumns[0];
379
-            $primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
380
-            $str .= "
377
+		if (count($primaryKeyColumns) === 1) {
378
+			$primaryKeyColumn = $primaryKeyColumns[0];
379
+			$primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
380
+			$str .= "
381 381
     /**
382 382
      * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
383 383
      * If the primary key does not exist, an exception is thrown.
@@ -392,8 +392,8 @@  discard block
 block discarded – undo
392 392
         return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
393 393
     }
394 394
     ";
395
-        }
396
-        $str .= "
395
+		}
396
+		$str .= "
397 397
     /**
398 398
      * Deletes the $beanClassWithoutNameSpace passed in parameter.
399 399
      *
@@ -492,33 +492,33 @@  discard block
 block discarded – undo
492 492
     }
493 493
 ";
494 494
 
495
-        $str .= $findByDaoCode;
496
-        $str .= '}
495
+		$str .= $findByDaoCode;
496
+		$str .= '}
497 497
 ';
498 498
 
499
-        $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
500
-        if (empty($possibleBaseFileNames)) {
501
-            // @codeCoverageIgnoreStart
502
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
503
-            // @codeCoverageIgnoreEnd
504
-        }
505
-        $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
506
-
507
-        $this->ensureDirectoryExist($possibleBaseFileName);
508
-        file_put_contents($possibleBaseFileName, $str);
509
-        @chmod($possibleBaseFileName, 0664);
510
-
511
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
512
-        if (empty($possibleFileNames)) {
513
-            // @codeCoverageIgnoreStart
514
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
515
-            // @codeCoverageIgnoreEnd
516
-        }
517
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
518
-
519
-        // Now, let's generate the "editable" class
520
-        if (!file_exists($possibleFileName)) {
521
-            $str = "<?php
499
+		$possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\Generated\\'.$baseClassName);
500
+		if (empty($possibleBaseFileNames)) {
501
+			// @codeCoverageIgnoreStart
502
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.');
503
+			// @codeCoverageIgnoreEnd
504
+		}
505
+		$possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0];
506
+
507
+		$this->ensureDirectoryExist($possibleBaseFileName);
508
+		file_put_contents($possibleBaseFileName, $str);
509
+		@chmod($possibleBaseFileName, 0664);
510
+
511
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className);
512
+		if (empty($possibleFileNames)) {
513
+			// @codeCoverageIgnoreStart
514
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.');
515
+			// @codeCoverageIgnoreEnd
516
+		}
517
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
518
+
519
+		// Now, let's generate the "editable" class
520
+		if (!file_exists($possibleFileName)) {
521
+			$str = "<?php
522 522
 
523 523
 /*
524 524
  * This file has been automatically generated by TDBM.
@@ -536,22 +536,22 @@  discard block
 block discarded – undo
536 536
 {
537 537
 }
538 538
 ";
539
-            $this->ensureDirectoryExist($possibleFileName);
540
-            file_put_contents($possibleFileName, $str);
541
-            @chmod($possibleFileName, 0664);
542
-        }
543
-    }
544
-
545
-    /**
546
-     * Generates the factory bean.
547
-     *
548
-     * @param Table[] $tableList
549
-     */
550
-    private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
551
-    {
552
-        // For each table, let's write a property.
553
-
554
-        $str = "<?php
539
+			$this->ensureDirectoryExist($possibleFileName);
540
+			file_put_contents($possibleFileName, $str);
541
+			@chmod($possibleFileName, 0664);
542
+		}
543
+	}
544
+
545
+	/**
546
+	 * Generates the factory bean.
547
+	 *
548
+	 * @param Table[] $tableList
549
+	 */
550
+	private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper)
551
+	{
552
+		// For each table, let's write a property.
553
+
554
+		$str = "<?php
555 555
 
556 556
 /*
557 557
  * This file has been automatically generated by TDBM.
@@ -561,13 +561,13 @@  discard block
 block discarded – undo
561 561
 namespace {$daoNamespace}\\Generated;
562 562
 
563 563
 ";
564
-        foreach ($tableList as $table) {
565
-            $tableName = $table->getName();
566
-            $daoClassName = $this->getDaoNameFromTableName($tableName);
567
-            $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
568
-        }
564
+		foreach ($tableList as $table) {
565
+			$tableName = $table->getName();
566
+			$daoClassName = $this->getDaoNameFromTableName($tableName);
567
+			$str .= "use {$daoNamespace}\\".$daoClassName.";\n";
568
+		}
569 569
 
570
-        $str .= "
570
+		$str .= "
571 571
 /**
572 572
  * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
573 573
  *
@@ -576,12 +576,12 @@  discard block
 block discarded – undo
576 576
 {
577 577
 ";
578 578
 
579
-        foreach ($tableList as $table) {
580
-            $tableName = $table->getName();
581
-            $daoClassName = $this->getDaoNameFromTableName($tableName);
582
-            $daoInstanceName = self::toVariableName($daoClassName);
579
+		foreach ($tableList as $table) {
580
+			$tableName = $table->getName();
581
+			$daoClassName = $this->getDaoNameFromTableName($tableName);
582
+			$daoInstanceName = self::toVariableName($daoClassName);
583 583
 
584
-            $str .= '    /**
584
+			$str .= '    /**
585 585
      * @var '.$daoClassName.'
586 586
      */
587 587
     private $'.$daoInstanceName.';
@@ -605,158 +605,158 @@  discard block
 block discarded – undo
605 605
     {
606 606
         $this->'.$daoInstanceName.' = $'.$daoInstanceName.';
607 607
     }';
608
-        }
608
+		}
609 609
 
610
-        $str .= '
610
+		$str .= '
611 611
 }
612 612
 ';
613 613
 
614
-        $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
615
-        if (empty($possibleFileNames)) {
616
-            throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
617
-        }
618
-        $possibleFileName = $this->rootPath.$possibleFileNames[0];
619
-
620
-        $this->ensureDirectoryExist($possibleFileName);
621
-        file_put_contents($possibleFileName, $str);
622
-        @chmod($possibleFileName, 0664);
623
-    }
624
-
625
-    /**
626
-     * Transforms a string to camelCase (except the first letter will be uppercase too).
627
-     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
628
-     *
629
-     * @param $str string
630
-     *
631
-     * @return string
632
-     */
633
-    public static function toCamelCase($str)
634
-    {
635
-        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
636
-        while (true) {
637
-            if (strpos($str, '_') === false && strpos($str, ' ') === false) {
638
-                break;
639
-            }
640
-
641
-            $pos = strpos($str, '_');
642
-            if ($pos === false) {
643
-                $pos = strpos($str, ' ');
644
-            }
645
-            $before = substr($str, 0, $pos);
646
-            $after = substr($str, $pos + 1);
647
-            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
648
-        }
649
-
650
-        return $str;
651
-    }
652
-
653
-    /**
654
-     * Tries to put string to the singular form (if it is plural).
655
-     * We assume the table names are in english.
656
-     *
657
-     * @param $str string
658
-     *
659
-     * @return string
660
-     */
661
-    public static function toSingular($str)
662
-    {
663
-        return Inflector::singularize($str);
664
-    }
665
-
666
-    /**
667
-     * Put the first letter of the string in lower case.
668
-     * Very useful to transform a class name into a variable name.
669
-     *
670
-     * @param $str string
671
-     *
672
-     * @return string
673
-     */
674
-    public static function toVariableName($str)
675
-    {
676
-        return strtolower(substr($str, 0, 1)).substr($str, 1);
677
-    }
678
-
679
-    /**
680
-     * Ensures the file passed in parameter can be written in its directory.
681
-     *
682
-     * @param string $fileName
683
-     *
684
-     * @throws TDBMException
685
-     */
686
-    private function ensureDirectoryExist($fileName)
687
-    {
688
-        $dirName = dirname($fileName);
689
-        if (!file_exists($dirName)) {
690
-            $old = umask(0);
691
-            $result = mkdir($dirName, 0775, true);
692
-            umask($old);
693
-            if ($result === false) {
694
-                throw new TDBMException("Unable to create directory: '".$dirName."'.");
695
-            }
696
-        }
697
-    }
698
-
699
-    /**
700
-     * Absolute path to composer json file.
701
-     *
702
-     * @param string $composerFile
703
-     */
704
-    public function setComposerFile($composerFile)
705
-    {
706
-        $this->rootPath = dirname($composerFile).'/';
707
-        $this->composerFile = basename($composerFile);
708
-    }
709
-
710
-    /**
711
-     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
712
-     *
713
-     * @param Type $type The DBAL type
714
-     *
715
-     * @return string The PHP type
716
-     */
717
-    public static function dbalTypeToPhpType(Type $type)
718
-    {
719
-        $map = [
720
-            Type::TARRAY => 'array',
721
-            Type::SIMPLE_ARRAY => 'array',
722
-            Type::JSON_ARRAY => 'array',
723
-            Type::BIGINT => 'string',
724
-            Type::BOOLEAN => 'bool',
725
-            Type::DATETIME => '\DateTimeInterface',
726
-            Type::DATETIMETZ => '\DateTimeInterface',
727
-            Type::DATE => '\DateTimeInterface',
728
-            Type::TIME => '\DateTimeInterface',
729
-            Type::DECIMAL => 'float',
730
-            Type::INTEGER => 'int',
731
-            Type::OBJECT => 'string',
732
-            Type::SMALLINT => 'int',
733
-            Type::STRING => 'string',
734
-            Type::TEXT => 'string',
735
-            Type::BINARY => 'string',
736
-            Type::BLOB => 'string',
737
-            Type::FLOAT => 'float',
738
-            Type::GUID => 'string',
739
-        ];
740
-
741
-        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
742
-    }
743
-
744
-    /**
745
-     * @param string $beanNamespace
746
-     *
747
-     * @return \string[] Returns a map mapping table name to beans name
748
-     */
749
-    public function buildTableToBeanMap($beanNamespace)
750
-    {
751
-        $tableToBeanMap = [];
752
-
753
-        $tables = $this->schema->getTables();
754
-
755
-        foreach ($tables as $table) {
756
-            $tableName = $table->getName();
757
-            $tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
758
-        }
759
-
760
-        return $tableToBeanMap;
761
-    }
614
+		$possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\Generated\\'.$daoFactoryClassName);
615
+		if (empty($possibleFileNames)) {
616
+			throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.');
617
+		}
618
+		$possibleFileName = $this->rootPath.$possibleFileNames[0];
619
+
620
+		$this->ensureDirectoryExist($possibleFileName);
621
+		file_put_contents($possibleFileName, $str);
622
+		@chmod($possibleFileName, 0664);
623
+	}
624
+
625
+	/**
626
+	 * Transforms a string to camelCase (except the first letter will be uppercase too).
627
+	 * Underscores and spaces are removed and the first letter after the underscore is uppercased.
628
+	 *
629
+	 * @param $str string
630
+	 *
631
+	 * @return string
632
+	 */
633
+	public static function toCamelCase($str)
634
+	{
635
+		$str = strtoupper(substr($str, 0, 1)).substr($str, 1);
636
+		while (true) {
637
+			if (strpos($str, '_') === false && strpos($str, ' ') === false) {
638
+				break;
639
+			}
640
+
641
+			$pos = strpos($str, '_');
642
+			if ($pos === false) {
643
+				$pos = strpos($str, ' ');
644
+			}
645
+			$before = substr($str, 0, $pos);
646
+			$after = substr($str, $pos + 1);
647
+			$str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
648
+		}
649
+
650
+		return $str;
651
+	}
652
+
653
+	/**
654
+	 * Tries to put string to the singular form (if it is plural).
655
+	 * We assume the table names are in english.
656
+	 *
657
+	 * @param $str string
658
+	 *
659
+	 * @return string
660
+	 */
661
+	public static function toSingular($str)
662
+	{
663
+		return Inflector::singularize($str);
664
+	}
665
+
666
+	/**
667
+	 * Put the first letter of the string in lower case.
668
+	 * Very useful to transform a class name into a variable name.
669
+	 *
670
+	 * @param $str string
671
+	 *
672
+	 * @return string
673
+	 */
674
+	public static function toVariableName($str)
675
+	{
676
+		return strtolower(substr($str, 0, 1)).substr($str, 1);
677
+	}
678
+
679
+	/**
680
+	 * Ensures the file passed in parameter can be written in its directory.
681
+	 *
682
+	 * @param string $fileName
683
+	 *
684
+	 * @throws TDBMException
685
+	 */
686
+	private function ensureDirectoryExist($fileName)
687
+	{
688
+		$dirName = dirname($fileName);
689
+		if (!file_exists($dirName)) {
690
+			$old = umask(0);
691
+			$result = mkdir($dirName, 0775, true);
692
+			umask($old);
693
+			if ($result === false) {
694
+				throw new TDBMException("Unable to create directory: '".$dirName."'.");
695
+			}
696
+		}
697
+	}
698
+
699
+	/**
700
+	 * Absolute path to composer json file.
701
+	 *
702
+	 * @param string $composerFile
703
+	 */
704
+	public function setComposerFile($composerFile)
705
+	{
706
+		$this->rootPath = dirname($composerFile).'/';
707
+		$this->composerFile = basename($composerFile);
708
+	}
709
+
710
+	/**
711
+	 * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
712
+	 *
713
+	 * @param Type $type The DBAL type
714
+	 *
715
+	 * @return string The PHP type
716
+	 */
717
+	public static function dbalTypeToPhpType(Type $type)
718
+	{
719
+		$map = [
720
+			Type::TARRAY => 'array',
721
+			Type::SIMPLE_ARRAY => 'array',
722
+			Type::JSON_ARRAY => 'array',
723
+			Type::BIGINT => 'string',
724
+			Type::BOOLEAN => 'bool',
725
+			Type::DATETIME => '\DateTimeInterface',
726
+			Type::DATETIMETZ => '\DateTimeInterface',
727
+			Type::DATE => '\DateTimeInterface',
728
+			Type::TIME => '\DateTimeInterface',
729
+			Type::DECIMAL => 'float',
730
+			Type::INTEGER => 'int',
731
+			Type::OBJECT => 'string',
732
+			Type::SMALLINT => 'int',
733
+			Type::STRING => 'string',
734
+			Type::TEXT => 'string',
735
+			Type::BINARY => 'string',
736
+			Type::BLOB => 'string',
737
+			Type::FLOAT => 'float',
738
+			Type::GUID => 'string',
739
+		];
740
+
741
+		return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
742
+	}
743
+
744
+	/**
745
+	 * @param string $beanNamespace
746
+	 *
747
+	 * @return \string[] Returns a map mapping table name to beans name
748
+	 */
749
+	public function buildTableToBeanMap($beanNamespace)
750
+	{
751
+		$tableToBeanMap = [];
752
+
753
+		$tables = $this->schema->getTables();
754
+
755
+		foreach ($tables as $table) {
756
+			$tableName = $table->getName();
757
+			$tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName);
758
+		}
759
+
760
+		return $tableToBeanMap;
761
+	}
762 762
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/BeanDescriptor.php 1 patch
Indentation   +543 added lines, -543 removed lines patch added patch discarded remove patch
@@ -16,228 +16,228 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class BeanDescriptor
18 18
 {
19
-    /**
20
-     * @var Table
21
-     */
22
-    private $table;
23
-
24
-    /**
25
-     * @var SchemaAnalyzer
26
-     */
27
-    private $schemaAnalyzer;
28
-
29
-    /**
30
-     * @var Schema
31
-     */
32
-    private $schema;
33
-
34
-    /**
35
-     * @var AbstractBeanPropertyDescriptor[]
36
-     */
37
-    private $beanPropertyDescriptors = [];
38
-
39
-    /**
40
-     * @var TDBMSchemaAnalyzer
41
-     */
42
-    private $tdbmSchemaAnalyzer;
43
-
44
-    public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
-    {
46
-        $this->table = $table;
47
-        $this->schemaAnalyzer = $schemaAnalyzer;
48
-        $this->schema = $schema;
49
-        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
-        $this->initBeanPropertyDescriptors();
51
-    }
52
-
53
-    private function initBeanPropertyDescriptors()
54
-    {
55
-        $this->beanPropertyDescriptors = $this->getProperties($this->table);
56
-    }
57
-
58
-    /**
59
-     * Returns the foreign-key the column is part of, if any. null otherwise.
60
-     *
61
-     * @param Table  $table
62
-     * @param Column $column
63
-     *
64
-     * @return ForeignKeyConstraint|null
65
-     */
66
-    private function isPartOfForeignKey(Table $table, Column $column)
67
-    {
68
-        $localColumnName = $column->getName();
69
-        foreach ($table->getForeignKeys() as $foreignKey) {
70
-            foreach ($foreignKey->getColumns() as $columnName) {
71
-                if ($columnName === $localColumnName) {
72
-                    return $foreignKey;
73
-                }
74
-            }
75
-        }
76
-
77
-        return;
78
-    }
79
-
80
-    /**
81
-     * @return AbstractBeanPropertyDescriptor[]
82
-     */
83
-    public function getBeanPropertyDescriptors()
84
-    {
85
-        return $this->beanPropertyDescriptors;
86
-    }
87
-
88
-    /**
89
-     * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
-     *
91
-     * @return AbstractBeanPropertyDescriptor[]
92
-     */
93
-    public function getConstructorProperties()
94
-    {
95
-        $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
-            return $property->isCompulsory();
97
-        });
98
-
99
-        return $constructorProperties;
100
-    }
101
-
102
-    /**
103
-     * Returns the list of columns that have default values for a given table.
104
-     *
105
-     * @return AbstractBeanPropertyDescriptor[]
106
-     */
107
-    public function getPropertiesWithDefault()
108
-    {
109
-        $properties = $this->getPropertiesForTable($this->table);
110
-        $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
111
-            return $property->hasDefault();
112
-        });
113
-
114
-        return $defaultProperties;
115
-    }
116
-
117
-    /**
118
-     * Returns the list of properties exposed as getters and setters in this class.
119
-     *
120
-     * @return AbstractBeanPropertyDescriptor[]
121
-     */
122
-    public function getExposedProperties()
123
-    {
124
-        $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
125
-            return $property->getTable()->getName() == $this->table->getName();
126
-        });
127
-
128
-        return $exposedProperties;
129
-    }
130
-
131
-    /**
132
-     * Returns the list of properties for this table (including parent tables).
133
-     *
134
-     * @param Table $table
135
-     *
136
-     * @return AbstractBeanPropertyDescriptor[]
137
-     */
138
-    private function getProperties(Table $table)
139
-    {
140
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
141
-        if ($parentRelationship) {
142
-            $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
143
-            $properties = $this->getProperties($parentTable);
144
-            // we merge properties by overriding property names.
145
-            $localProperties = $this->getPropertiesForTable($table);
146
-            foreach ($localProperties as $name => $property) {
147
-                // We do not override properties if this is a primary key!
148
-                if ($property->isPrimaryKey()) {
149
-                    continue;
150
-                }
151
-                $properties[$name] = $property;
152
-            }
153
-        } else {
154
-            $properties = $this->getPropertiesForTable($table);
155
-        }
156
-
157
-        return $properties;
158
-    }
159
-
160
-    /**
161
-     * Returns the list of properties for this table (ignoring parent tables).
162
-     *
163
-     * @param Table $table
164
-     *
165
-     * @return AbstractBeanPropertyDescriptor[]
166
-     */
167
-    private function getPropertiesForTable(Table $table)
168
-    {
169
-        $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
170
-        if ($parentRelationship) {
171
-            $ignoreColumns = $parentRelationship->getLocalColumns();
172
-        } else {
173
-            $ignoreColumns = [];
174
-        }
175
-
176
-        $beanPropertyDescriptors = [];
177
-
178
-        foreach ($table->getColumns() as $column) {
179
-            if (array_search($column->getName(), $ignoreColumns) !== false) {
180
-                continue;
181
-            }
182
-
183
-            $fk = $this->isPartOfForeignKey($table, $column);
184
-            if ($fk !== null) {
185
-                // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
186
-                foreach ($beanPropertyDescriptors as $beanDescriptor) {
187
-                    if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
188
-                        continue 2;
189
-                    }
190
-                }
191
-                // Check that this property is not an inheritance relationship
192
-                $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
193
-                if ($parentRelationship === $fk) {
194
-                    continue;
195
-                }
196
-
197
-                $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
198
-            } else {
199
-                $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
200
-            }
201
-        }
202
-
203
-        // Now, let's get the name of all properties and let's check there is no duplicate.
204
-        /** @var $names AbstractBeanPropertyDescriptor[] */
205
-        $names = [];
206
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
207
-            $name = $beanDescriptor->getUpperCamelCaseName();
208
-            if (isset($names[$name])) {
209
-                $names[$name]->useAlternativeName();
210
-                $beanDescriptor->useAlternativeName();
211
-            } else {
212
-                $names[$name] = $beanDescriptor;
213
-            }
214
-        }
215
-
216
-        // Final check (throw exceptions if problem arises)
217
-        $names = [];
218
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
219
-            $name = $beanDescriptor->getUpperCamelCaseName();
220
-            if (isset($names[$name])) {
221
-                throw new TDBMException('Unsolvable name conflict while generating method name');
222
-            } else {
223
-                $names[$name] = $beanDescriptor;
224
-            }
225
-        }
226
-
227
-        // Last step, let's rebuild the list with a map:
228
-        $beanPropertyDescriptorsMap = [];
229
-        foreach ($beanPropertyDescriptors as $beanDescriptor) {
230
-            $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
231
-        }
232
-
233
-        return $beanPropertyDescriptorsMap;
234
-    }
235
-
236
-    public function generateBeanConstructor()
237
-    {
238
-        $constructorProperties = $this->getConstructorProperties();
239
-
240
-        $constructorCode = '    /**
19
+	/**
20
+	 * @var Table
21
+	 */
22
+	private $table;
23
+
24
+	/**
25
+	 * @var SchemaAnalyzer
26
+	 */
27
+	private $schemaAnalyzer;
28
+
29
+	/**
30
+	 * @var Schema
31
+	 */
32
+	private $schema;
33
+
34
+	/**
35
+	 * @var AbstractBeanPropertyDescriptor[]
36
+	 */
37
+	private $beanPropertyDescriptors = [];
38
+
39
+	/**
40
+	 * @var TDBMSchemaAnalyzer
41
+	 */
42
+	private $tdbmSchemaAnalyzer;
43
+
44
+	public function __construct(Table $table, SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
45
+	{
46
+		$this->table = $table;
47
+		$this->schemaAnalyzer = $schemaAnalyzer;
48
+		$this->schema = $schema;
49
+		$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
50
+		$this->initBeanPropertyDescriptors();
51
+	}
52
+
53
+	private function initBeanPropertyDescriptors()
54
+	{
55
+		$this->beanPropertyDescriptors = $this->getProperties($this->table);
56
+	}
57
+
58
+	/**
59
+	 * Returns the foreign-key the column is part of, if any. null otherwise.
60
+	 *
61
+	 * @param Table  $table
62
+	 * @param Column $column
63
+	 *
64
+	 * @return ForeignKeyConstraint|null
65
+	 */
66
+	private function isPartOfForeignKey(Table $table, Column $column)
67
+	{
68
+		$localColumnName = $column->getName();
69
+		foreach ($table->getForeignKeys() as $foreignKey) {
70
+			foreach ($foreignKey->getColumns() as $columnName) {
71
+				if ($columnName === $localColumnName) {
72
+					return $foreignKey;
73
+				}
74
+			}
75
+		}
76
+
77
+		return;
78
+	}
79
+
80
+	/**
81
+	 * @return AbstractBeanPropertyDescriptor[]
82
+	 */
83
+	public function getBeanPropertyDescriptors()
84
+	{
85
+		return $this->beanPropertyDescriptors;
86
+	}
87
+
88
+	/**
89
+	 * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
90
+	 *
91
+	 * @return AbstractBeanPropertyDescriptor[]
92
+	 */
93
+	public function getConstructorProperties()
94
+	{
95
+		$constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
96
+			return $property->isCompulsory();
97
+		});
98
+
99
+		return $constructorProperties;
100
+	}
101
+
102
+	/**
103
+	 * Returns the list of columns that have default values for a given table.
104
+	 *
105
+	 * @return AbstractBeanPropertyDescriptor[]
106
+	 */
107
+	public function getPropertiesWithDefault()
108
+	{
109
+		$properties = $this->getPropertiesForTable($this->table);
110
+		$defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
111
+			return $property->hasDefault();
112
+		});
113
+
114
+		return $defaultProperties;
115
+	}
116
+
117
+	/**
118
+	 * Returns the list of properties exposed as getters and setters in this class.
119
+	 *
120
+	 * @return AbstractBeanPropertyDescriptor[]
121
+	 */
122
+	public function getExposedProperties()
123
+	{
124
+		$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
125
+			return $property->getTable()->getName() == $this->table->getName();
126
+		});
127
+
128
+		return $exposedProperties;
129
+	}
130
+
131
+	/**
132
+	 * Returns the list of properties for this table (including parent tables).
133
+	 *
134
+	 * @param Table $table
135
+	 *
136
+	 * @return AbstractBeanPropertyDescriptor[]
137
+	 */
138
+	private function getProperties(Table $table)
139
+	{
140
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
141
+		if ($parentRelationship) {
142
+			$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
143
+			$properties = $this->getProperties($parentTable);
144
+			// we merge properties by overriding property names.
145
+			$localProperties = $this->getPropertiesForTable($table);
146
+			foreach ($localProperties as $name => $property) {
147
+				// We do not override properties if this is a primary key!
148
+				if ($property->isPrimaryKey()) {
149
+					continue;
150
+				}
151
+				$properties[$name] = $property;
152
+			}
153
+		} else {
154
+			$properties = $this->getPropertiesForTable($table);
155
+		}
156
+
157
+		return $properties;
158
+	}
159
+
160
+	/**
161
+	 * Returns the list of properties for this table (ignoring parent tables).
162
+	 *
163
+	 * @param Table $table
164
+	 *
165
+	 * @return AbstractBeanPropertyDescriptor[]
166
+	 */
167
+	private function getPropertiesForTable(Table $table)
168
+	{
169
+		$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
170
+		if ($parentRelationship) {
171
+			$ignoreColumns = $parentRelationship->getLocalColumns();
172
+		} else {
173
+			$ignoreColumns = [];
174
+		}
175
+
176
+		$beanPropertyDescriptors = [];
177
+
178
+		foreach ($table->getColumns() as $column) {
179
+			if (array_search($column->getName(), $ignoreColumns) !== false) {
180
+				continue;
181
+			}
182
+
183
+			$fk = $this->isPartOfForeignKey($table, $column);
184
+			if ($fk !== null) {
185
+				// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
186
+				foreach ($beanPropertyDescriptors as $beanDescriptor) {
187
+					if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
188
+						continue 2;
189
+					}
190
+				}
191
+				// Check that this property is not an inheritance relationship
192
+				$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
193
+				if ($parentRelationship === $fk) {
194
+					continue;
195
+				}
196
+
197
+				$beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer);
198
+			} else {
199
+				$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column);
200
+			}
201
+		}
202
+
203
+		// Now, let's get the name of all properties and let's check there is no duplicate.
204
+		/** @var $names AbstractBeanPropertyDescriptor[] */
205
+		$names = [];
206
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
207
+			$name = $beanDescriptor->getUpperCamelCaseName();
208
+			if (isset($names[$name])) {
209
+				$names[$name]->useAlternativeName();
210
+				$beanDescriptor->useAlternativeName();
211
+			} else {
212
+				$names[$name] = $beanDescriptor;
213
+			}
214
+		}
215
+
216
+		// Final check (throw exceptions if problem arises)
217
+		$names = [];
218
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
219
+			$name = $beanDescriptor->getUpperCamelCaseName();
220
+			if (isset($names[$name])) {
221
+				throw new TDBMException('Unsolvable name conflict while generating method name');
222
+			} else {
223
+				$names[$name] = $beanDescriptor;
224
+			}
225
+		}
226
+
227
+		// Last step, let's rebuild the list with a map:
228
+		$beanPropertyDescriptorsMap = [];
229
+		foreach ($beanPropertyDescriptors as $beanDescriptor) {
230
+			$beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
231
+		}
232
+
233
+		return $beanPropertyDescriptorsMap;
234
+	}
235
+
236
+	public function generateBeanConstructor()
237
+	{
238
+		$constructorProperties = $this->getConstructorProperties();
239
+
240
+		$constructorCode = '    /**
241 241
      * The constructor takes all compulsory arguments.
242 242
      *
243 243
 %s
@@ -247,110 +247,110 @@  discard block
 block discarded – undo
247 247
 %s%s    }
248 248
     ';
249 249
 
250
-        $paramAnnotations = [];
251
-        $arguments = [];
252
-        $assigns = [];
253
-        $parentConstructorArguments = [];
254
-
255
-        foreach ($constructorProperties as $property) {
256
-            $className = $property->getClassName();
257
-            if ($className) {
258
-                $arguments[] = $className.' '.$property->getVariableName();
259
-            } else {
260
-                $arguments[] = $property->getVariableName();
261
-            }
262
-            $paramAnnotations[] = $property->getParamAnnotation();
263
-            if ($property->getTable()->getName() === $this->table->getName()) {
264
-                $assigns[] = $property->getConstructorAssignCode()."\n";
265
-            } else {
266
-                $parentConstructorArguments[] = $property->getVariableName();
267
-            }
268
-        }
269
-
270
-        $parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
271
-
272
-        foreach ($this->getPropertiesWithDefault() as $property) {
273
-            $assigns[] = $property->assignToDefaultCode()."\n";
274
-        }
275
-
276
-        return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode('', $assigns));
277
-    }
278
-
279
-    public function getDirectForeignKeysDescriptors()
280
-    {
281
-        $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
282
-
283
-        $descriptors = [];
284
-
285
-        foreach ($fks as $fk) {
286
-            $descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table);
287
-        }
288
-
289
-        return $descriptors;
290
-    }
291
-
292
-    private function getPivotTableDescriptors()
293
-    {
294
-        $descs = [];
295
-        foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
296
-            // There are exactly 2 FKs since this is a pivot table.
297
-            $fks = array_values($table->getForeignKeys());
298
-
299
-            if ($fks[0]->getForeignTableName() === $this->table->getName()) {
300
-                list($localFk, $remoteFk) = $fks;
301
-            } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
302
-                list($remoteFk, $localFk) = $fks;
303
-            } else {
304
-                continue;
305
-            }
306
-
307
-            $descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk);
308
-        }
309
-
310
-        return $descs;
311
-    }
312
-
313
-    /**
314
-     * Returns the list of method descriptors (and applies the alternative name if needed).
315
-     *
316
-     * @return MethodDescriptorInterface[]
317
-     */
318
-    private function getMethodDescriptors()
319
-    {
320
-        $directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
321
-        $pivotTableDescriptors = $this->getPivotTableDescriptors();
322
-
323
-        $descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
324
-
325
-        // Descriptors by method names
326
-        $descriptorsByMethodName = [];
327
-
328
-        foreach ($descriptors as $descriptor) {
329
-            $descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
330
-        }
331
-
332
-        foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
333
-            if (count($descriptorsForMethodName) > 1) {
334
-                foreach ($descriptorsForMethodName as $descriptor) {
335
-                    $descriptor->useAlternativeName();
336
-                }
337
-            }
338
-        }
339
-
340
-        return $descriptors;
341
-    }
342
-
343
-    public function generateJsonSerialize()
344
-    {
345
-        $tableName = $this->table->getName();
346
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
347
-        if ($parentFk !== null) {
348
-            $initializer = '$array = parent::jsonSerialize($stopRecursion);';
349
-        } else {
350
-            $initializer = '$array = [];';
351
-        }
352
-
353
-        $str = '
250
+		$paramAnnotations = [];
251
+		$arguments = [];
252
+		$assigns = [];
253
+		$parentConstructorArguments = [];
254
+
255
+		foreach ($constructorProperties as $property) {
256
+			$className = $property->getClassName();
257
+			if ($className) {
258
+				$arguments[] = $className.' '.$property->getVariableName();
259
+			} else {
260
+				$arguments[] = $property->getVariableName();
261
+			}
262
+			$paramAnnotations[] = $property->getParamAnnotation();
263
+			if ($property->getTable()->getName() === $this->table->getName()) {
264
+				$assigns[] = $property->getConstructorAssignCode()."\n";
265
+			} else {
266
+				$parentConstructorArguments[] = $property->getVariableName();
267
+			}
268
+		}
269
+
270
+		$parentConstructorCode = sprintf("        parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
271
+
272
+		foreach ($this->getPropertiesWithDefault() as $property) {
273
+			$assigns[] = $property->assignToDefaultCode()."\n";
274
+		}
275
+
276
+		return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode('', $assigns));
277
+	}
278
+
279
+	public function getDirectForeignKeysDescriptors()
280
+	{
281
+		$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
282
+
283
+		$descriptors = [];
284
+
285
+		foreach ($fks as $fk) {
286
+			$descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table);
287
+		}
288
+
289
+		return $descriptors;
290
+	}
291
+
292
+	private function getPivotTableDescriptors()
293
+	{
294
+		$descs = [];
295
+		foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
296
+			// There are exactly 2 FKs since this is a pivot table.
297
+			$fks = array_values($table->getForeignKeys());
298
+
299
+			if ($fks[0]->getForeignTableName() === $this->table->getName()) {
300
+				list($localFk, $remoteFk) = $fks;
301
+			} elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
302
+				list($remoteFk, $localFk) = $fks;
303
+			} else {
304
+				continue;
305
+			}
306
+
307
+			$descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk);
308
+		}
309
+
310
+		return $descs;
311
+	}
312
+
313
+	/**
314
+	 * Returns the list of method descriptors (and applies the alternative name if needed).
315
+	 *
316
+	 * @return MethodDescriptorInterface[]
317
+	 */
318
+	private function getMethodDescriptors()
319
+	{
320
+		$directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
321
+		$pivotTableDescriptors = $this->getPivotTableDescriptors();
322
+
323
+		$descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
324
+
325
+		// Descriptors by method names
326
+		$descriptorsByMethodName = [];
327
+
328
+		foreach ($descriptors as $descriptor) {
329
+			$descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
330
+		}
331
+
332
+		foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
333
+			if (count($descriptorsForMethodName) > 1) {
334
+				foreach ($descriptorsForMethodName as $descriptor) {
335
+					$descriptor->useAlternativeName();
336
+				}
337
+			}
338
+		}
339
+
340
+		return $descriptors;
341
+	}
342
+
343
+	public function generateJsonSerialize()
344
+	{
345
+		$tableName = $this->table->getName();
346
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
347
+		if ($parentFk !== null) {
348
+			$initializer = '$array = parent::jsonSerialize($stopRecursion);';
349
+		} else {
350
+			$initializer = '$array = [];';
351
+		}
352
+
353
+		$str = '
354 354
     /**
355 355
      * Serializes the object for JSON encoding.
356 356
      *
@@ -366,76 +366,76 @@  discard block
 block discarded – undo
366 366
     }
367 367
 ';
368 368
 
369
-        $propertiesCode = '';
370
-        foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
371
-            $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
372
-        }
373
-
374
-        // Many2many relationships
375
-        $methodsCode = '';
376
-        foreach ($this->getMethodDescriptors() as $methodDescriptor) {
377
-            $methodsCode .= $methodDescriptor->getJsonSerializeCode();
378
-        }
379
-
380
-        return sprintf($str, $initializer, $propertiesCode, $methodsCode);
381
-    }
382
-
383
-    /**
384
-     * Returns as an array the class we need to extend from and the list of use statements.
385
-     *
386
-     * @return array
387
-     */
388
-    private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
389
-    {
390
-        $classes = [];
391
-        if ($parentFk !== null) {
392
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
393
-            $classes[] = $extends;
394
-        }
395
-
396
-        foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
397
-            $className = $beanPropertyDescriptor->getClassName();
398
-            if (null !== $className) {
399
-                $classes[] = $beanPropertyDescriptor->getClassName();
400
-            }
401
-        }
402
-
403
-        foreach ($this->getMethodDescriptors() as $descriptor) {
404
-            $classes = array_merge($classes, $descriptor->getUsedClasses());
405
-        }
406
-
407
-        $classes = array_unique($classes);
408
-
409
-        return $classes;
410
-    }
411
-
412
-    /**
413
-     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
414
-     *
415
-     * @param string $beannamespace The namespace of the bean
416
-     */
417
-    public function generatePhpCode($beannamespace)
418
-    {
419
-        $tableName = $this->table->getName();
420
-        $baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
421
-        $className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
422
-        $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
423
-
424
-        $classes = $this->generateExtendsAndUseStatements($parentFk);
425
-
426
-        $uses = array_map(function ($className) use ($beannamespace) {
427
-            return 'use '.$beannamespace.'\\'.$className.";\n";
428
-        }, $classes);
429
-        $use = implode('', $uses);
430
-
431
-        if ($parentFk !== null) {
432
-            $extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
433
-        } else {
434
-            $extends = 'AbstractTDBMObject';
435
-            $use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
436
-        }
437
-
438
-        $str = "<?php
369
+		$propertiesCode = '';
370
+		foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
371
+			$propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
372
+		}
373
+
374
+		// Many2many relationships
375
+		$methodsCode = '';
376
+		foreach ($this->getMethodDescriptors() as $methodDescriptor) {
377
+			$methodsCode .= $methodDescriptor->getJsonSerializeCode();
378
+		}
379
+
380
+		return sprintf($str, $initializer, $propertiesCode, $methodsCode);
381
+	}
382
+
383
+	/**
384
+	 * Returns as an array the class we need to extend from and the list of use statements.
385
+	 *
386
+	 * @return array
387
+	 */
388
+	private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null)
389
+	{
390
+		$classes = [];
391
+		if ($parentFk !== null) {
392
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
393
+			$classes[] = $extends;
394
+		}
395
+
396
+		foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
397
+			$className = $beanPropertyDescriptor->getClassName();
398
+			if (null !== $className) {
399
+				$classes[] = $beanPropertyDescriptor->getClassName();
400
+			}
401
+		}
402
+
403
+		foreach ($this->getMethodDescriptors() as $descriptor) {
404
+			$classes = array_merge($classes, $descriptor->getUsedClasses());
405
+		}
406
+
407
+		$classes = array_unique($classes);
408
+
409
+		return $classes;
410
+	}
411
+
412
+	/**
413
+	 * Writes the PHP bean file with all getters and setters from the table passed in parameter.
414
+	 *
415
+	 * @param string $beannamespace The namespace of the bean
416
+	 */
417
+	public function generatePhpCode($beannamespace)
418
+	{
419
+		$tableName = $this->table->getName();
420
+		$baseClassName = TDBMDaoGenerator::getBaseBeanNameFromTableName($tableName);
421
+		$className = TDBMDaoGenerator::getBeanNameFromTableName($tableName);
422
+		$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
423
+
424
+		$classes = $this->generateExtendsAndUseStatements($parentFk);
425
+
426
+		$uses = array_map(function ($className) use ($beannamespace) {
427
+			return 'use '.$beannamespace.'\\'.$className.";\n";
428
+		}, $classes);
429
+		$use = implode('', $uses);
430
+
431
+		if ($parentFk !== null) {
432
+			$extends = TDBMDaoGenerator::getBeanNameFromTableName($parentFk->getForeignTableName());
433
+		} else {
434
+			$extends = 'AbstractTDBMObject';
435
+			$use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
436
+		}
437
+
438
+		$str = "<?php
439 439
 namespace {$beannamespace}\\Generated;
440 440
 
441 441
 use Mouf\\Database\\TDBM\\ResultIterator;
@@ -455,129 +455,129 @@  discard block
 block discarded – undo
455 455
 {
456 456
 ";
457 457
 
458
-        $str .= $this->generateBeanConstructor();
458
+		$str .= $this->generateBeanConstructor();
459 459
 
460
-        foreach ($this->getExposedProperties() as $property) {
461
-            $str .= $property->getGetterSetterCode();
462
-        }
460
+		foreach ($this->getExposedProperties() as $property) {
461
+			$str .= $property->getGetterSetterCode();
462
+		}
463 463
 
464
-        foreach ($this->getMethodDescriptors() as $methodDescriptor) {
465
-            $str .= $methodDescriptor->getCode();
466
-        }
467
-        $str .= $this->generateJsonSerialize();
464
+		foreach ($this->getMethodDescriptors() as $methodDescriptor) {
465
+			$str .= $methodDescriptor->getCode();
466
+		}
467
+		$str .= $this->generateJsonSerialize();
468 468
 
469
-        $str .= $this->generateGetUsedTablesCode();
469
+		$str .= $this->generateGetUsedTablesCode();
470 470
 
471
-        $str .= $this->generateOnDeleteCode();
471
+		$str .= $this->generateOnDeleteCode();
472 472
 
473
-        $str .= '}
473
+		$str .= '}
474 474
 ';
475 475
 
476
-        return $str;
477
-    }
478
-
479
-    /**
480
-     * @param string $beanNamespace
481
-     * @param string $beanClassName
482
-     *
483
-     * @return array first element: list of used beans, second item: PHP code as a string
484
-     */
485
-    public function generateFindByDaoCode($beanNamespace, $beanClassName)
486
-    {
487
-        $code = '';
488
-        $usedBeans = [];
489
-        foreach ($this->table->getIndexes() as $index) {
490
-            if (!$index->isPrimary()) {
491
-                list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
492
-                $code .= $codeForIndex;
493
-                $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
494
-            }
495
-        }
496
-
497
-        return [$usedBeans, $code];
498
-    }
499
-
500
-    /**
501
-     * @param Index  $index
502
-     * @param string $beanNamespace
503
-     * @param string $beanClassName
504
-     *
505
-     * @return array first element: list of used beans, second item: PHP code as a string
506
-     */
507
-    private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
508
-    {
509
-        $columns = $index->getColumns();
510
-        $usedBeans = [];
511
-
512
-        /*
476
+		return $str;
477
+	}
478
+
479
+	/**
480
+	 * @param string $beanNamespace
481
+	 * @param string $beanClassName
482
+	 *
483
+	 * @return array first element: list of used beans, second item: PHP code as a string
484
+	 */
485
+	public function generateFindByDaoCode($beanNamespace, $beanClassName)
486
+	{
487
+		$code = '';
488
+		$usedBeans = [];
489
+		foreach ($this->table->getIndexes() as $index) {
490
+			if (!$index->isPrimary()) {
491
+				list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
492
+				$code .= $codeForIndex;
493
+				$usedBeans = array_merge($usedBeans, $usedBeansForIndex);
494
+			}
495
+		}
496
+
497
+		return [$usedBeans, $code];
498
+	}
499
+
500
+	/**
501
+	 * @param Index  $index
502
+	 * @param string $beanNamespace
503
+	 * @param string $beanClassName
504
+	 *
505
+	 * @return array first element: list of used beans, second item: PHP code as a string
506
+	 */
507
+	private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
508
+	{
509
+		$columns = $index->getColumns();
510
+		$usedBeans = [];
511
+
512
+		/*
513 513
          * The list of elements building this index (expressed as columns or foreign keys)
514 514
          * @var AbstractBeanPropertyDescriptor[]
515 515
          */
516
-        $elements = [];
517
-
518
-        foreach ($columns as $column) {
519
-            $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
520
-            if ($fk !== null) {
521
-                if (!in_array($fk, $elements)) {
522
-                    $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
523
-                }
524
-            } else {
525
-                $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
526
-            }
527
-        }
528
-
529
-        // If the index is actually only a foreign key, let's bypass it entirely.
530
-        if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
531
-            return [[], ''];
532
-        }
533
-
534
-        $methodNameComponent = [];
535
-        $functionParameters = [];
536
-        $first = true;
537
-        foreach ($elements as $element) {
538
-            $methodNameComponent[] = $element->getUpperCamelCaseName();
539
-            $functionParameter = $element->getClassName();
540
-            if ($functionParameter) {
541
-                $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
542
-                $functionParameter .= ' ';
543
-            }
544
-            $functionParameter .= $element->getVariableName();
545
-            if ($first) {
546
-                $first = false;
547
-            } else {
548
-                $functionParameter .= ' = null';
549
-            }
550
-            $functionParameters[] = $functionParameter;
551
-        }
552
-        if ($index->isUnique()) {
553
-            $methodName = 'findOneBy'.implode('And', $methodNameComponent);
554
-            $calledMethod = 'findOne';
555
-            $returnType = "{$beanClassName}";
556
-        } else {
557
-            $methodName = 'findBy'.implode('And', $methodNameComponent);
558
-            $returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
559
-            $calledMethod = 'find';
560
-        }
561
-        $functionParametersString = implode(', ', $functionParameters);
562
-
563
-        $count = 0;
564
-
565
-        $params = [];
566
-        $filterArrayCode = '';
567
-        $commentArguments = [];
568
-        foreach ($elements as $element) {
569
-            $params[] = $element->getParamAnnotation();
570
-            if ($element instanceof ScalarBeanPropertyDescriptor) {
571
-                $filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
572
-            } else {
573
-                ++$count;
574
-                $filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
575
-            }
576
-            $commentArguments[] = substr($element->getVariableName(), 1);
577
-        }
578
-        $paramsString = implode("\n", $params);
579
-
580
-        $code = "
516
+		$elements = [];
517
+
518
+		foreach ($columns as $column) {
519
+			$fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
520
+			if ($fk !== null) {
521
+				if (!in_array($fk, $elements)) {
522
+					$elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer);
523
+				}
524
+			} else {
525
+				$elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column));
526
+			}
527
+		}
528
+
529
+		// If the index is actually only a foreign key, let's bypass it entirely.
530
+		if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
531
+			return [[], ''];
532
+		}
533
+
534
+		$methodNameComponent = [];
535
+		$functionParameters = [];
536
+		$first = true;
537
+		foreach ($elements as $element) {
538
+			$methodNameComponent[] = $element->getUpperCamelCaseName();
539
+			$functionParameter = $element->getClassName();
540
+			if ($functionParameter) {
541
+				$usedBeans[] = $beanNamespace.'\\'.$functionParameter;
542
+				$functionParameter .= ' ';
543
+			}
544
+			$functionParameter .= $element->getVariableName();
545
+			if ($first) {
546
+				$first = false;
547
+			} else {
548
+				$functionParameter .= ' = null';
549
+			}
550
+			$functionParameters[] = $functionParameter;
551
+		}
552
+		if ($index->isUnique()) {
553
+			$methodName = 'findOneBy'.implode('And', $methodNameComponent);
554
+			$calledMethod = 'findOne';
555
+			$returnType = "{$beanClassName}";
556
+		} else {
557
+			$methodName = 'findBy'.implode('And', $methodNameComponent);
558
+			$returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
559
+			$calledMethod = 'find';
560
+		}
561
+		$functionParametersString = implode(', ', $functionParameters);
562
+
563
+		$count = 0;
564
+
565
+		$params = [];
566
+		$filterArrayCode = '';
567
+		$commentArguments = [];
568
+		foreach ($elements as $element) {
569
+			$params[] = $element->getParamAnnotation();
570
+			if ($element instanceof ScalarBeanPropertyDescriptor) {
571
+				$filterArrayCode .= '            '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
572
+			} else {
573
+				++$count;
574
+				$filterArrayCode .= '            '.$count.' => '.$element->getVariableName().",\n";
575
+			}
576
+			$commentArguments[] = substr($element->getVariableName(), 1);
577
+		}
578
+		$paramsString = implode("\n", $params);
579
+
580
+		$code = "
581 581
     /**
582 582
      * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
583 583
      *
@@ -595,27 +595,27 @@  discard block
 block discarded – undo
595 595
     }
596 596
 ";
597 597
 
598
-        return [$usedBeans, $code];
599
-    }
600
-
601
-    /**
602
-     * Generates the code for the getUsedTable protected method.
603
-     *
604
-     * @return string
605
-     */
606
-    private function generateGetUsedTablesCode()
607
-    {
608
-        $hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
609
-        if ($hasParentRelationship) {
610
-            $code = sprintf('        $tables = parent::getUsedTables();
598
+		return [$usedBeans, $code];
599
+	}
600
+
601
+	/**
602
+	 * Generates the code for the getUsedTable protected method.
603
+	 *
604
+	 * @return string
605
+	 */
606
+	private function generateGetUsedTablesCode()
607
+	{
608
+		$hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
609
+		if ($hasParentRelationship) {
610
+			$code = sprintf('        $tables = parent::getUsedTables();
611 611
         $tables[] = %s;
612 612
 
613 613
         return $tables;', var_export($this->table->getName(), true));
614
-        } else {
615
-            $code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
616
-        }
614
+		} else {
615
+			$code = sprintf('        return [ %s ];', var_export($this->table->getName(), true));
616
+		}
617 617
 
618
-        return sprintf('
618
+		return sprintf('
619 619
     /**
620 620
      * Returns an array of used tables by this bean (from parent to child relationship).
621 621
      *
@@ -626,20 +626,20 @@  discard block
 block discarded – undo
626 626
 %s
627 627
     }
628 628
 ', $code);
629
-    }
630
-
631
-    private function generateOnDeleteCode()
632
-    {
633
-        $code = '';
634
-        $relationships = $this->getPropertiesForTable($this->table);
635
-        foreach ($relationships as $relationship) {
636
-            if ($relationship instanceof ObjectBeanPropertyDescriptor) {
637
-                $code .= sprintf('        $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
638
-            }
639
-        }
640
-
641
-        if ($code) {
642
-            return sprintf('
629
+	}
630
+
631
+	private function generateOnDeleteCode()
632
+	{
633
+		$code = '';
634
+		$relationships = $this->getPropertiesForTable($this->table);
635
+		foreach ($relationships as $relationship) {
636
+			if ($relationship instanceof ObjectBeanPropertyDescriptor) {
637
+				$code .= sprintf('        $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
638
+			}
639
+		}
640
+
641
+		if ($code) {
642
+			return sprintf('
643 643
     /**
644 644
      * Method called when the bean is removed from database.
645 645
      *
@@ -649,8 +649,8 @@  discard block
 block discarded – undo
649 649
         parent::onDelete();
650 650
 %s    }
651 651
 ', $code);
652
-        }
652
+		}
653 653
 
654
-        return '';
655
-    }
654
+		return '';
655
+	}
656 656
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/ObjectBeanPropertyDescriptor.php 1 patch
Indentation   +162 added lines, -162 removed lines patch added patch discarded remove patch
@@ -12,156 +12,156 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class ObjectBeanPropertyDescriptor extends AbstractBeanPropertyDescriptor
14 14
 {
15
-    /**
16
-     * @var ForeignKeyConstraint
17
-     */
18
-    private $foreignKey;
19
-
20
-    /**
21
-     * @var SchemaAnalyzer
22
-     */
23
-    private $schemaAnalyzer;
24
-
25
-    public function __construct(Table $table, ForeignKeyConstraint $foreignKey, SchemaAnalyzer $schemaAnalyzer)
26
-    {
27
-        parent::__construct($table);
28
-        $this->foreignKey = $foreignKey;
29
-        $this->schemaAnalyzer = $schemaAnalyzer;
30
-    }
31
-
32
-    /**
33
-     * Returns the foreignkey the column is part of, if any. null otherwise.
34
-     *
35
-     * @return ForeignKeyConstraint|null
36
-     */
37
-    public function getForeignKey()
38
-    {
39
-        return $this->foreignKey;
40
-    }
41
-
42
-    /**
43
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
44
-     *
45
-     * @return null|string
46
-     */
47
-    public function getClassName()
48
-    {
49
-        return TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
50
-    }
51
-
52
-    /**
53
-     * Returns the param annotation for this property (useful for constructor).
54
-     *
55
-     * @return string
56
-     */
57
-    public function getParamAnnotation()
58
-    {
59
-        $str = '     * @param %s %s';
60
-
61
-        return sprintf($str, $this->getClassName(), $this->getVariableName());
62
-    }
63
-
64
-    public function getUpperCamelCaseName()
65
-    {
66
-        // First, are there many column or only one?
67
-        // If one column, we name the setter after it. Otherwise, we name the setter after the table name
68
-        if (count($this->foreignKey->getLocalColumns()) > 1) {
69
-            $name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
70
-            if ($this->alternativeName) {
71
-                $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
72
-
73
-                $name .= 'By'.implode('And', $camelizedColumns);
74
-            }
75
-        } else {
76
-            $column = $this->foreignKey->getLocalColumns()[0];
77
-            // Let's remove any _id or id_.
78
-            if (strpos(strtolower($column), 'id_') === 0) {
79
-                $column = substr($column, 3);
80
-            }
81
-            if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
82
-                $column = substr($column, 0, strlen($column) - 3);
83
-            }
84
-            $name = TDBMDaoGenerator::toCamelCase($column);
85
-            if ($this->alternativeName) {
86
-                $name .= 'Object';
87
-            }
88
-        }
89
-
90
-        return $name;
91
-    }
92
-
93
-    /**
94
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
95
-     *
96
-     * @return bool
97
-     */
98
-    public function isCompulsory()
99
-    {
100
-        // Are all columns nullable?
101
-        $localColumnNames = $this->foreignKey->getLocalColumns();
102
-
103
-        foreach ($localColumnNames as $name) {
104
-            $column = $this->table->getColumn($name);
105
-            if ($column->getNotnull()) {
106
-                return true;
107
-            }
108
-        }
109
-
110
-        return false;
111
-    }
112
-
113
-    /**
114
-     * Returns true if the property has a default value.
115
-     *
116
-     * @return bool
117
-     */
118
-    public function hasDefault()
119
-    {
120
-        return false;
121
-    }
122
-
123
-    /**
124
-     * Returns the code that assigns a value to its default value.
125
-     *
126
-     * @return string
127
-     *
128
-     * @throws \TDBMException
129
-     */
130
-    public function assignToDefaultCode()
131
-    {
132
-        throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
133
-    }
134
-
135
-    /**
136
-     * Returns true if the property is the primary key.
137
-     *
138
-     * @return bool
139
-     */
140
-    public function isPrimaryKey()
141
-    {
142
-        $fkColumns = $this->foreignKey->getLocalColumns();
143
-        sort($fkColumns);
144
-
145
-        $pkColumns = $this->table->getPrimaryKeyColumns();
146
-        sort($pkColumns);
147
-
148
-        return $fkColumns == $pkColumns;
149
-    }
150
-
151
-    /**
152
-     * Returns the PHP code for getters and setters.
153
-     *
154
-     * @return string
155
-     */
156
-    public function getGetterSetterCode()
157
-    {
158
-        $tableName = $this->table->getName();
159
-        $getterName = $this->getGetterName();
160
-        $setterName = $this->getSetterName();
161
-
162
-        $referencedBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
163
-
164
-        $str = '    /**
15
+	/**
16
+	 * @var ForeignKeyConstraint
17
+	 */
18
+	private $foreignKey;
19
+
20
+	/**
21
+	 * @var SchemaAnalyzer
22
+	 */
23
+	private $schemaAnalyzer;
24
+
25
+	public function __construct(Table $table, ForeignKeyConstraint $foreignKey, SchemaAnalyzer $schemaAnalyzer)
26
+	{
27
+		parent::__construct($table);
28
+		$this->foreignKey = $foreignKey;
29
+		$this->schemaAnalyzer = $schemaAnalyzer;
30
+	}
31
+
32
+	/**
33
+	 * Returns the foreignkey the column is part of, if any. null otherwise.
34
+	 *
35
+	 * @return ForeignKeyConstraint|null
36
+	 */
37
+	public function getForeignKey()
38
+	{
39
+		return $this->foreignKey;
40
+	}
41
+
42
+	/**
43
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
44
+	 *
45
+	 * @return null|string
46
+	 */
47
+	public function getClassName()
48
+	{
49
+		return TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
50
+	}
51
+
52
+	/**
53
+	 * Returns the param annotation for this property (useful for constructor).
54
+	 *
55
+	 * @return string
56
+	 */
57
+	public function getParamAnnotation()
58
+	{
59
+		$str = '     * @param %s %s';
60
+
61
+		return sprintf($str, $this->getClassName(), $this->getVariableName());
62
+	}
63
+
64
+	public function getUpperCamelCaseName()
65
+	{
66
+		// First, are there many column or only one?
67
+		// If one column, we name the setter after it. Otherwise, we name the setter after the table name
68
+		if (count($this->foreignKey->getLocalColumns()) > 1) {
69
+			$name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
70
+			if ($this->alternativeName) {
71
+				$camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
72
+
73
+				$name .= 'By'.implode('And', $camelizedColumns);
74
+			}
75
+		} else {
76
+			$column = $this->foreignKey->getLocalColumns()[0];
77
+			// Let's remove any _id or id_.
78
+			if (strpos(strtolower($column), 'id_') === 0) {
79
+				$column = substr($column, 3);
80
+			}
81
+			if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
82
+				$column = substr($column, 0, strlen($column) - 3);
83
+			}
84
+			$name = TDBMDaoGenerator::toCamelCase($column);
85
+			if ($this->alternativeName) {
86
+				$name .= 'Object';
87
+			}
88
+		}
89
+
90
+		return $name;
91
+	}
92
+
93
+	/**
94
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
95
+	 *
96
+	 * @return bool
97
+	 */
98
+	public function isCompulsory()
99
+	{
100
+		// Are all columns nullable?
101
+		$localColumnNames = $this->foreignKey->getLocalColumns();
102
+
103
+		foreach ($localColumnNames as $name) {
104
+			$column = $this->table->getColumn($name);
105
+			if ($column->getNotnull()) {
106
+				return true;
107
+			}
108
+		}
109
+
110
+		return false;
111
+	}
112
+
113
+	/**
114
+	 * Returns true if the property has a default value.
115
+	 *
116
+	 * @return bool
117
+	 */
118
+	public function hasDefault()
119
+	{
120
+		return false;
121
+	}
122
+
123
+	/**
124
+	 * Returns the code that assigns a value to its default value.
125
+	 *
126
+	 * @return string
127
+	 *
128
+	 * @throws \TDBMException
129
+	 */
130
+	public function assignToDefaultCode()
131
+	{
132
+		throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
133
+	}
134
+
135
+	/**
136
+	 * Returns true if the property is the primary key.
137
+	 *
138
+	 * @return bool
139
+	 */
140
+	public function isPrimaryKey()
141
+	{
142
+		$fkColumns = $this->foreignKey->getLocalColumns();
143
+		sort($fkColumns);
144
+
145
+		$pkColumns = $this->table->getPrimaryKeyColumns();
146
+		sort($pkColumns);
147
+
148
+		return $fkColumns == $pkColumns;
149
+	}
150
+
151
+	/**
152
+	 * Returns the PHP code for getters and setters.
153
+	 *
154
+	 * @return string
155
+	 */
156
+	public function getGetterSetterCode()
157
+	{
158
+		$tableName = $this->table->getName();
159
+		$getterName = $this->getGetterName();
160
+		$setterName = $this->getSetterName();
161
+
162
+		$referencedBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
163
+
164
+		$str = '    /**
165 165
      * Returns the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
166 166
      *
167 167
      * @return '.$referencedBeanName.'
@@ -183,20 +183,20 @@  discard block
 block discarded – undo
183 183
 
184 184
 ';
185 185
 
186
-        return $str;
187
-    }
188
-
189
-    /**
190
-     * Returns the part of code useful when doing json serialization.
191
-     *
192
-     * @return string
193
-     */
194
-    public function getJsonSerializeCode()
195
-    {
196
-        return '        if (!$stopRecursion) {
186
+		return $str;
187
+	}
188
+
189
+	/**
190
+	 * Returns the part of code useful when doing json serialization.
191
+	 *
192
+	 * @return string
193
+	 */
194
+	public function getJsonSerializeCode()
195
+	{
196
+		return '        if (!$stopRecursion) {
197 197
             $object = $this->'.$this->getGetterName().'();
198 198
             $array['.var_export($this->getLowerCamelCaseName(), true).'] = $object ? $object->jsonSerialize(true) : null;
199 199
         }
200 200
 ';
201
-    }
201
+	}
202 202
 }
Please login to merge, or discard this patch.