Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like TDBMDaoGenerator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use TDBMDaoGenerator, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
18 | class TDBMDaoGenerator |
||
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 | // TODO: extract ClassNameMapper in its own package! |
||
80 | $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.$this->composerFile); |
||
81 | // TODO: check that no class name ends with "Base". Otherwise, there will be name clash. |
||
82 | |||
83 | $tableList = $this->schema->getTables(); |
||
84 | |||
85 | // Remove all beans and daos from junction tables |
||
86 | $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
||
87 | $junctionTableNames = array_map(function (Table $table) { |
||
88 | return $table->getName(); |
||
89 | }, $junctionTables); |
||
90 | |||
91 | $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) { |
||
92 | return !in_array($table->getName(), $junctionTableNames); |
||
93 | }); |
||
94 | |||
95 | foreach ($tableList as $table) { |
||
96 | $this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc); |
||
97 | } |
||
98 | |||
99 | $this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper); |
||
100 | |||
101 | // Ok, let's return the list of all tables. |
||
102 | // These will be used by the calling script to create Mouf instances. |
||
103 | |||
104 | return array_map(function (Table $table) { return $table->getName(); }, $tableList); |
||
105 | } |
||
106 | |||
107 | /** |
||
108 | * Generates in one method call the daos and the beans for one table. |
||
109 | * |
||
110 | * @param Table $table |
||
111 | * @param string $daonamespace |
||
112 | * @param string $beannamespace |
||
113 | * @param ClassNameMapper $classNameMapper |
||
114 | * @param bool $storeInUtc |
||
115 | * |
||
116 | * @throws TDBMException |
||
117 | */ |
||
118 | public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
||
119 | { |
||
120 | $tableName = $table->getName(); |
||
121 | $daoName = $this->getDaoNameFromTableName($tableName); |
||
122 | $beanName = $this->getBeanNameFromTableName($tableName); |
||
123 | $baseBeanName = $this->getBaseBeanNameFromTableName($tableName); |
||
124 | $baseDaoName = $this->getBaseDaoNameFromTableName($tableName); |
||
125 | |||
126 | $beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer); |
||
127 | $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc); |
||
128 | $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper); |
||
129 | } |
||
130 | |||
131 | /** |
||
132 | * Returns the name of the bean class from the table name. |
||
133 | * |
||
134 | * @param $tableName |
||
135 | * |
||
136 | * @return string |
||
137 | */ |
||
138 | public static function getBeanNameFromTableName($tableName) |
||
142 | |||
143 | /** |
||
144 | * Returns the name of the DAO class from the table name. |
||
145 | * |
||
146 | * @param $tableName |
||
147 | * |
||
148 | * @return string |
||
149 | */ |
||
150 | public static function getDaoNameFromTableName($tableName) |
||
154 | |||
155 | /** |
||
156 | * Returns the name of the base bean class from the table name. |
||
157 | * |
||
158 | * @param $tableName |
||
159 | * |
||
160 | * @return string |
||
161 | */ |
||
162 | public static function getBaseBeanNameFromTableName($tableName) |
||
166 | |||
167 | /** |
||
168 | * Returns the name of the base DAO class from the table name. |
||
169 | * |
||
170 | * @param $tableName |
||
171 | * |
||
172 | * @return string |
||
173 | */ |
||
174 | public static function getBaseDaoNameFromTableName($tableName) |
||
178 | |||
179 | /** |
||
180 | * Writes the PHP bean file with all getters and setters from the table passed in parameter. |
||
181 | * |
||
182 | * @param BeanDescriptor $beanDescriptor |
||
183 | * @param string $className The name of the class |
||
184 | * @param string $baseClassName The name of the base class which will be extended (name only, no directory) |
||
185 | * @param Table $table The table |
||
186 | * @param string $beannamespace The namespace of the bean |
||
187 | * @param ClassNameMapper $classNameMapper |
||
188 | * |
||
189 | * @throws TDBMException |
||
190 | */ |
||
191 | public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
||
|
|||
192 | { |
||
193 | $str = $beanDescriptor->generatePhpCode($beannamespace); |
||
194 | |||
195 | $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName); |
||
196 | if (empty($possibleBaseFileNames)) { |
||
197 | throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.'); |
||
198 | } |
||
199 | $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0]; |
||
200 | |||
201 | $this->ensureDirectoryExist($possibleBaseFileName); |
||
202 | file_put_contents($possibleBaseFileName, $str); |
||
203 | @chmod($possibleBaseFileName, 0664); |
||
204 | |||
205 | $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className); |
||
206 | if (empty($possibleFileNames)) { |
||
207 | // @codeCoverageIgnoreStart |
||
208 | throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.'); |
||
209 | // @codeCoverageIgnoreEnd |
||
210 | } |
||
211 | $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
||
212 | View Code Duplication | if (!file_exists($possibleFileName)) { |
|
213 | $tableName = $table->getName(); |
||
214 | $str = "<?php |
||
215 | /* |
||
216 | * This file has been automatically generated by TDBM. |
||
217 | * You can edit this file as it will not be overwritten. |
||
218 | */ |
||
219 | |||
220 | namespace {$beannamespace}; |
||
221 | |||
222 | /** |
||
223 | * The $className class maps the '$tableName' table in database. |
||
224 | */ |
||
225 | class $className extends $baseClassName |
||
226 | { |
||
227 | |||
228 | }"; |
||
229 | $this->ensureDirectoryExist($possibleFileName); |
||
230 | file_put_contents($possibleFileName, $str); |
||
231 | @chmod($possibleFileName, 0664); |
||
232 | } |
||
233 | } |
||
234 | |||
235 | /** |
||
236 | * Tries to find a @defaultSort annotation in one of the columns. |
||
237 | * |
||
238 | * @param Table $table |
||
239 | * |
||
240 | * @return array First item: column name, Second item: column order (asc/desc) |
||
241 | */ |
||
242 | private function getDefaultSortColumnFromAnnotation(Table $table) |
||
261 | |||
262 | /** |
||
263 | * Writes the PHP bean DAO with simple functions to create/get/save objects. |
||
264 | * |
||
265 | * @param BeanDescriptor $beanDescriptor |
||
266 | * @param string $className The name of the class |
||
267 | * @param string $baseClassName |
||
268 | * @param string $beanClassName |
||
269 | * @param Table $table |
||
270 | * @param string $daonamespace |
||
271 | * @param string $beannamespace |
||
272 | * @param ClassNameMapper $classNameMapper |
||
273 | * |
||
274 | * @throws TDBMException |
||
275 | */ |
||
276 | public function generateDao(BeanDescriptor $beanDescriptor, $className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper) |
||
277 | { |
||
278 | $tableName = $table->getName(); |
||
279 | $primaryKeyColumns = $table->getPrimaryKeyColumns(); |
||
280 | |||
281 | list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table); |
||
282 | |||
283 | // FIXME: lowercase tables with _ in the name should work! |
||
284 | $tableCamel = self::toSingular(self::toCamelCase($tableName)); |
||
285 | |||
286 | $beanClassWithoutNameSpace = $beanClassName; |
||
287 | $beanClassName = $beannamespace.'\\'.$beanClassName; |
||
288 | |||
289 | list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace); |
||
290 | |||
291 | $usedBeans[] = $beanClassName; |
||
292 | // Let's suppress duplicates in used beans (if any) |
||
293 | $usedBeans = array_flip(array_flip($usedBeans)); |
||
294 | $useStatements = array_map(function ($usedBean) { |
||
295 | return "use $usedBean;\n"; |
||
296 | }, $usedBeans); |
||
297 | |||
298 | $str = "<?php |
||
299 | |||
300 | /* |
||
301 | * This file has been automatically generated by TDBM. |
||
302 | * DO NOT edit this file, as it might be overwritten. |
||
303 | * If you need to perform changes, edit the $className class instead! |
||
304 | */ |
||
305 | |||
306 | namespace {$daonamespace}; |
||
307 | |||
308 | use Mouf\\Database\\TDBM\\TDBMService; |
||
309 | use Mouf\\Database\\TDBM\\ResultIterator; |
||
310 | use Mouf\\Database\\TDBM\\ArrayIterator; |
||
311 | ".implode('', $useStatements)." |
||
312 | |||
313 | /** |
||
314 | * The $baseClassName class will maintain the persistence of $beanClassWithoutNameSpace class into the $tableName table. |
||
315 | * |
||
316 | */ |
||
317 | class $baseClassName |
||
318 | { |
||
319 | |||
320 | /** |
||
321 | * @var TDBMService |
||
322 | */ |
||
323 | protected \$tdbmService; |
||
324 | |||
325 | /** |
||
326 | * The default sort column. |
||
327 | * |
||
328 | * @var string |
||
329 | */ |
||
330 | private \$defaultSort = ".($defaultSort ? "'$defaultSort'" : 'null').'; |
||
331 | |||
332 | /** |
||
333 | * The default sort direction. |
||
334 | * |
||
335 | * @var string |
||
336 | */ |
||
337 | private $defaultDirection = '.($defaultSort && $defaultSortDirection ? "'$defaultSortDirection'" : "'asc'")."; |
||
338 | |||
339 | /** |
||
340 | * Sets the TDBM service used by this DAO. |
||
341 | * |
||
342 | * @param TDBMService \$tdbmService |
||
343 | */ |
||
344 | public function __construct(TDBMService \$tdbmService) |
||
345 | { |
||
346 | \$this->tdbmService = \$tdbmService; |
||
347 | } |
||
348 | |||
349 | /** |
||
350 | * Persist the $beanClassWithoutNameSpace instance. |
||
351 | * |
||
352 | * @param $beanClassWithoutNameSpace \$obj The bean to save. |
||
353 | */ |
||
354 | public function save($beanClassWithoutNameSpace \$obj) |
||
355 | { |
||
356 | \$this->tdbmService->save(\$obj); |
||
357 | } |
||
358 | |||
359 | /** |
||
360 | * Get all $tableCamel records. |
||
361 | * |
||
362 | * @return {$beanClassWithoutNameSpace}[]|ResultIterator|ResultArray |
||
363 | */ |
||
364 | public function findAll() |
||
365 | { |
||
366 | if (\$this->defaultSort) { |
||
367 | \$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection; |
||
368 | } else { |
||
369 | \$orderBy = null; |
||
370 | } |
||
371 | return \$this->tdbmService->findObjects('$tableName', null, [], \$orderBy); |
||
372 | } |
||
373 | "; |
||
374 | |||
375 | if (count($primaryKeyColumns) === 1) { |
||
376 | $primaryKeyColumn = $primaryKeyColumns[0]; |
||
377 | $str .= " |
||
378 | /** |
||
379 | * Get $beanClassWithoutNameSpace specified by its ID (its primary key) |
||
380 | * If the primary key does not exist, an exception is thrown. |
||
381 | * |
||
382 | * @param string|int \$id |
||
383 | * @param bool \$lazyLoading If set to true, the object will not be loaded right away. Instead, it will be loaded when you first try to access a method of the object. |
||
384 | * @return $beanClassWithoutNameSpace |
||
385 | * @throws TDBMException |
||
386 | */ |
||
387 | public function getById(\$id, \$lazyLoading = false) |
||
388 | { |
||
389 | return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading); |
||
390 | } |
||
391 | "; |
||
392 | } |
||
393 | $str .= " |
||
394 | /** |
||
395 | * Deletes the $beanClassWithoutNameSpace passed in parameter. |
||
396 | * |
||
397 | * @param $beanClassWithoutNameSpace \$obj object to delete |
||
398 | * @param bool \$cascade if true, it will delete all object linked to \$obj |
||
399 | */ |
||
400 | public function delete($beanClassWithoutNameSpace \$obj, \$cascade = false) |
||
401 | { |
||
402 | if (\$cascade === true) { |
||
403 | \$this->tdbmService->deleteCascade(\$obj); |
||
404 | } else { |
||
405 | \$this->tdbmService->delete(\$obj); |
||
406 | } |
||
407 | } |
||
408 | |||
409 | |||
410 | /** |
||
411 | * Get a list of $beanClassWithoutNameSpace specified by its filters. |
||
412 | * |
||
413 | * @param mixed \$filter The filter bag (see TDBMService::findObjects for complete description) |
||
414 | * @param array \$parameters The parameters associated with the filter |
||
415 | * @param mixed \$orderBy The order string |
||
416 | * @param array \$additionalTablesFetch A list of additional tables to fetch (for performance improvement) |
||
417 | * @param int \$mode Either TDBMService::MODE_ARRAY or TDBMService::MODE_CURSOR (for large datasets). Defaults to TDBMService::MODE_ARRAY. |
||
418 | * @return {$beanClassWithoutNameSpace}[]|ResultIterator|ResultArray |
||
419 | */ |
||
420 | protected function find(\$filter = null, array \$parameters = [], \$orderBy=null, array \$additionalTablesFetch = [], \$mode = null) |
||
421 | { |
||
422 | if (\$this->defaultSort && \$orderBy == null) { |
||
423 | \$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection; |
||
424 | } |
||
425 | return \$this->tdbmService->findObjects('$tableName', \$filter, \$parameters, \$orderBy, \$additionalTablesFetch, \$mode); |
||
426 | } |
||
427 | |||
428 | /** |
||
429 | * Get a single $beanClassWithoutNameSpace specified by its filters. |
||
430 | * |
||
431 | * @param mixed \$filter The filter bag (see TDBMService::findObjects for complete description) |
||
432 | * @param array \$parameters The parameters associated with the filter |
||
433 | * @return $beanClassWithoutNameSpace |
||
434 | */ |
||
435 | protected function findOne(\$filter=null, array \$parameters = []) |
||
436 | { |
||
437 | return \$this->tdbmService->findObject('$tableName', \$filter, \$parameters); |
||
438 | } |
||
439 | |||
440 | /** |
||
441 | * Sets the default column for default sorting. |
||
442 | * |
||
443 | * @param string \$defaultSort |
||
444 | */ |
||
445 | public function setDefaultSort(\$defaultSort) |
||
446 | { |
||
447 | \$this->defaultSort = \$defaultSort; |
||
448 | } |
||
449 | "; |
||
450 | |||
451 | $str .= $findByDaoCode; |
||
452 | $str .= '} |
||
453 | '; |
||
454 | |||
455 | $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName); |
||
456 | if (empty($possibleBaseFileNames)) { |
||
457 | // @codeCoverageIgnoreStart |
||
458 | throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.'); |
||
459 | // @codeCoverageIgnoreEnd |
||
460 | } |
||
461 | $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0]; |
||
462 | |||
463 | $this->ensureDirectoryExist($possibleBaseFileName); |
||
464 | file_put_contents($possibleBaseFileName, $str); |
||
465 | @chmod($possibleBaseFileName, 0664); |
||
466 | |||
467 | $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className); |
||
468 | if (empty($possibleFileNames)) { |
||
469 | // @codeCoverageIgnoreStart |
||
470 | throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.'); |
||
471 | // @codeCoverageIgnoreEnd |
||
472 | } |
||
473 | $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
||
474 | |||
475 | // Now, let's generate the "editable" class |
||
476 | View Code Duplication | if (!file_exists($possibleFileName)) { |
|
477 | $str = "<?php |
||
478 | |||
479 | /* |
||
480 | * This file has been automatically generated by TDBM. |
||
481 | * You can edit this file as it will not be overwritten. |
||
482 | */ |
||
483 | |||
484 | namespace {$daonamespace}; |
||
485 | |||
486 | /** |
||
487 | * The $className class will maintain the persistence of $beanClassWithoutNameSpace class into the $tableName table. |
||
488 | */ |
||
489 | class $className extends $baseClassName |
||
490 | { |
||
491 | |||
492 | } |
||
493 | "; |
||
494 | $this->ensureDirectoryExist($possibleFileName); |
||
495 | file_put_contents($possibleFileName, $str); |
||
496 | @chmod($possibleFileName, 0664); |
||
497 | } |
||
498 | } |
||
499 | |||
500 | /** |
||
501 | * Generates the factory bean. |
||
502 | * |
||
503 | * @param Table[] $tableList |
||
504 | */ |
||
505 | private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper) |
||
572 | |||
573 | /** |
||
574 | * Transforms a string to camelCase (except the first letter will be uppercase too). |
||
575 | * Underscores and spaces are removed and the first letter after the underscore is uppercased. |
||
576 | * |
||
577 | * @param $str string |
||
578 | * |
||
579 | * @return string |
||
580 | */ |
||
581 | public static function toCamelCase($str) |
||
600 | |||
601 | /** |
||
602 | * Tries to put string to the singular form (if it is plural). |
||
603 | * We assume the table names are in english. |
||
604 | * |
||
605 | * @param $str string |
||
606 | * |
||
607 | * @return string |
||
608 | */ |
||
609 | public static function toSingular($str) |
||
613 | |||
614 | /** |
||
615 | * Put the first letter of the string in lower case. |
||
616 | * Very useful to transform a class name into a variable name. |
||
617 | * |
||
618 | * @param $str string |
||
619 | * |
||
620 | * @return string |
||
621 | */ |
||
622 | public static function toVariableName($str) |
||
626 | |||
627 | /** |
||
628 | * Ensures the file passed in parameter can be written in its directory. |
||
629 | * |
||
630 | * @param string $fileName |
||
631 | * |
||
632 | * @throws TDBMException |
||
633 | */ |
||
634 | private function ensureDirectoryExist($fileName) |
||
646 | |||
647 | /** |
||
648 | * Absolute path to composer json file. |
||
649 | * |
||
650 | * @param string $rootPath |
||
651 | */ |
||
652 | public function setComposerFile($composerFile) |
||
653 | { |
||
654 | $this->rootPath = dirname($composerFile).'/'; |
||
655 | $this->composerFile = basename($composerFile); |
||
656 | } |
||
657 | |||
658 | /** |
||
659 | * Transforms a DBAL type into a PHP type (for PHPDoc purpose). |
||
660 | * |
||
661 | * @param Type $type The DBAL type |
||
662 | * |
||
663 | * @return string The PHP type |
||
664 | */ |
||
665 | public static function dbalTypeToPhpType(Type $type) |
||
691 | |||
692 | /** |
||
693 | * @param string $beanNamespace |
||
694 | * |
||
695 | * @return \string[] Returns a map mapping table name to beans name |
||
696 | */ |
||
697 | public function buildTableToBeanMap($beanNamespace) |
||
710 | } |
||
711 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.