Passed
Pull Request — master (#116)
by David
03:42
created

TDBMDaoGenerator::generateBean()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 47
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 47
rs 9.6333
c 0
b 0
f 0
cc 3
nc 4
nop 4
1
<?php
2
declare(strict_types=1);
3
4
namespace TheCodingMachine\TDBM\Utils;
5
6
use Doctrine\Common\Inflector\Inflector;
7
use Doctrine\DBAL\Schema\Schema;
8
use Doctrine\DBAL\Schema\Table;
9
use Doctrine\DBAL\Types\Type;
10
use function str_replace;
11
use TheCodingMachine\TDBM\ConfigurationInterface;
12
use TheCodingMachine\TDBM\TDBMException;
13
use TheCodingMachine\TDBM\TDBMSchemaAnalyzer;
14
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15
use Symfony\Component\Filesystem\Filesystem;
16
17
/**
18
 * This class generates automatically DAOs and Beans for TDBM.
19
 */
20
class TDBMDaoGenerator
21
{
22
    /**
23
     * @var Schema
24
     */
25
    private $schema;
26
27
    /**
28
     * @var TDBMSchemaAnalyzer
29
     */
30
    private $tdbmSchemaAnalyzer;
31
32
    /**
33
     * @var GeneratorListenerInterface
34
     */
35
    private $eventDispatcher;
36
37
    /**
38
     * @var NamingStrategyInterface
39
     */
40
    private $namingStrategy;
41
    /**
42
     * @var ConfigurationInterface
43
     */
44
    private $configuration;
45
46
    /**
47
     * Constructor.
48
     *
49
     * @param ConfigurationInterface $configuration
50
     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
51
     */
52
    public function __construct(ConfigurationInterface $configuration, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
53
    {
54
        $this->configuration = $configuration;
55
        $this->schema = $tdbmSchemaAnalyzer->getSchema();
56
        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
57
        $this->namingStrategy = $configuration->getNamingStrategy();
58
        $this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
59
    }
60
61
    /**
62
     * Generates all the daos and beans.
63
     *
64
     * @throws TDBMException
65
     */
66
    public function generateAllDaosAndBeans(): void
67
    {
68
        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
69
70
        $tableList = $this->schema->getTables();
71
72
        // Remove all beans and daos from junction tables
73
        $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
74
        $junctionTableNames = array_map(function (Table $table) {
75
            return $table->getName();
76
        }, $junctionTables);
77
78
        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
79
            return !in_array($table->getName(), $junctionTableNames);
80
        });
81
82
        $this->cleanUpGenerated();
83
84
        $beanDescriptors = [];
85
86
        foreach ($tableList as $table) {
87
            $beanDescriptors[] = $this->generateDaoAndBean($table);
88
        }
89
90
91
        $this->generateFactory($tableList);
92
93
        // Let's call the list of listeners
94
        $this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
95
    }
96
97
    /**
98
     * Removes all files from the Generated folders.
99
     * This is a way to ensure that when a table is deleted, the matching bean/dao are deleted.
100
     * Note: only abstract generated classes are deleted. We do not delete the code that might have been customized
101
     * by the user. The user will need to delete this code him/herself
102
     */
103
    private function cleanUpGenerated(): void
104
    {
105
        $generatedBeanDir = $this->configuration->getPathFinder()->getPath($this->configuration->getBeanNamespace().'\\Generated\\Xxx')->getPath();
106
        $this->deleteAllPhpFiles($generatedBeanDir);
107
108
        $generatedDaoDir = $this->configuration->getPathFinder()->getPath($this->configuration->getDaoNamespace().'\\Generated\\Xxx')->getPath();
109
        $this->deleteAllPhpFiles($generatedDaoDir);
110
    }
111
112
    private function deleteAllPhpFiles(string $directory): void
113
    {
114
        $files = glob($directory.'/*.php');
115
        $fileSystem = new Filesystem();
116
        $fileSystem->remove($files);
117
    }
118
119
    /**
120
     * Generates in one method call the daos and the beans for one table.
121
     *
122
     * @param Table $table
123
     *
124
     * @return BeanDescriptor
125
     * @throws TDBMException
126
     */
127
    private function generateDaoAndBean(Table $table) : BeanDescriptor
128
    {
129
        $tableName = $table->getName();
130
        $daoName = $this->namingStrategy->getDaoClassName($tableName);
131
        $beanName = $this->namingStrategy->getBeanClassName($tableName);
132
        $baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
133
        $baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
134
135
        $beanDescriptor = new BeanDescriptor($table, $this->configuration->getBeanNamespace(), $this->configuration->getBeanNamespace().'\\Generated', $this->configuration->getDaoNamespace(), $this->configuration->getDaoNamespace().'\\Generated', $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy, $this->configuration->getAnnotationParser(), $this->configuration->getCodeGeneratorListener(), $this->configuration);
136
        $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table);
137
        $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table);
138
        return $beanDescriptor;
139
    }
140
141
    /**
142
     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
143
     *
144
     * @param BeanDescriptor  $beanDescriptor
145
     * @param string          $className       The name of the class
146
     * @param string          $baseClassName   The name of the base class which will be extended (name only, no directory)
147
     * @param Table           $table           The table
148
     *
149
     * @throws TDBMException
150
     */
151
    public function generateBean(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, Table $table): void
152
    {
153
        $beannamespace = $this->configuration->getBeanNamespace();
154
155
        $possibleFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\'.$className)->getPathname();
156
157
        if (!file_exists($possibleFileName)) {
158
            $tableName = $table->getName();
159
            $str = "<?php
160
/*
161
 * This file has been automatically generated by TDBM.
162
 * You can edit this file as it will not be overwritten.
163
 */
164
165
declare(strict_types=1);
166
167
namespace {$beannamespace};
168
169
use {$beannamespace}\\Generated\\{$baseClassName};
170
171
/**
172
 * The $className class maps the '$tableName' table in database.
173
 */
174
class $className extends $baseClassName
175
{
176
}
177
";
178
179
            $this->dumpFile($possibleFileName, $str);
180
        }
181
182
        $file = $beanDescriptor->generatePhpCode();
183
        if ($file === null) {
184
            return;
185
        }
186
187
        $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\Generated\\'.$baseClassName)->getPathname();
188
189
        $fileContent = $file->generate();
190
191
        // Hard code PSR-2 fix
192
        $fileContent = str_replace("\n\n}\n", '}', $fileContent);
193
        // Add the declare strict-types directive
194
        $commentEnd = strpos($fileContent, ' */') + 3;
195
        $fileContent = substr($fileContent, 0, $commentEnd) . "\n\ndeclare(strict_types=1);" . substr($fileContent, $commentEnd + 1);
196
197
        $this->dumpFile($possibleBaseFileName, $fileContent);
198
    }
199
200
    /**
201
     * Writes the PHP bean DAO with simple functions to create/get/save objects.
202
     *
203
     * @param BeanDescriptor  $beanDescriptor
204
     * @param string          $className       The name of the class
205
     * @param string          $baseClassName
206
     * @param string          $beanClassName
207
     * @param Table           $table
208
     *
209
     * @throws TDBMException
210
     */
211
    private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table): void
212
    {
213
        $daonamespace = $this->configuration->getDaoNamespace();
214
        $tableName = $table->getName();
215
216
        $beanClassWithoutNameSpace = $beanClassName;
217
218
        $possibleFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\'.$className)->getPathname();
219
220
        // Now, let's generate the "editable" class
221
        if (!file_exists($possibleFileName)) {
222
            $str = "<?php
223
/*
224
 * This file has been automatically generated by TDBM.
225
 * You can edit this file as it will not be overwritten.
226
 */
227
228
declare(strict_types=1);
229
230
namespace {$daonamespace};
231
232
use {$daonamespace}\\Generated\\{$baseClassName};
233
234
/**
235
 * The $className class will maintain the persistence of $beanClassWithoutNameSpace class into the $tableName table.
236
 */
237
class $className extends $baseClassName
238
{
239
}
240
";
241
            $this->dumpFile($possibleFileName, $str);
242
        }
243
244
        $file = $beanDescriptor->generateDaoPhpCode();
245
        if ($file === null) {
246
            return;
247
        }
248
249
        $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\Generated\\'.$baseClassName)->getPathname();
250
251
        $fileContent = $file->generate();
252
253
        // Hard code PSR-2 fix
254
        $fileContent = str_replace("\n\n}\n", '}', $fileContent);
255
        // Add the declare strict-types directive
256
        $commentEnd = strpos($fileContent, ' */') + 3;
257
        $fileContent = substr($fileContent, 0, $commentEnd) . "\n\ndeclare(strict_types=1);" . substr($fileContent, $commentEnd + 1);
258
259
        $this->dumpFile($possibleBaseFileName, $fileContent);
260
    }
261
262
    /**
263
     * Generates the factory bean.
264
     *
265
     * @param Table[] $tableList
266
     * @throws TDBMException
267
     */
268
    private function generateFactory(array $tableList) : void
269
    {
270
        $daoNamespace = $this->configuration->getDaoNamespace();
271
        $daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
272
273
        // For each table, let's write a property.
274
275
        $str = "<?php
276
declare(strict_types=1);
277
278
/*
279
 * This file has been automatically generated by TDBM.
280
 * DO NOT edit this file, as it might be overwritten.
281
 */
282
283
namespace {$daoNamespace}\\Generated;
284
285
";
286
        foreach ($tableList as $table) {
287
            $tableName = $table->getName();
288
            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
289
            $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
290
        }
291
292
        $str .= "
293
/**
294
 * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
295
 *
296
 */
297
class $daoFactoryClassName
298
{
299
";
300
301
        foreach ($tableList as $table) {
302
            $tableName = $table->getName();
303
            $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
304
            $daoInstanceName = self::toVariableName($daoClassName);
305
306
            $str .= '    /**
307
     * @var '.$daoClassName.'
308
     */
309
    private $'.$daoInstanceName.';
310
311
    /**
312
     * Returns an instance of the '.$daoClassName.' class.
313
     *
314
     * @return '.$daoClassName.'
315
     */
316
    public function get'.$daoClassName.'() : '.$daoClassName.'
317
    {
318
        return $this->'.$daoInstanceName.';
319
    }
320
321
    /**
322
     * Sets the instance of the '.$daoClassName.' class that will be returned by the factory getter.
323
     *
324
     * @param '.$daoClassName.' $'.$daoInstanceName.'
325
     */
326
    public function set'.$daoClassName.'('.$daoClassName.' $'.$daoInstanceName.') : void
327
    {
328
        $this->'.$daoInstanceName.' = $'.$daoInstanceName.';
329
    }';
330
        }
331
332
        $str .= '
333
}
334
';
335
336
        $possibleFileName = $this->configuration->getPathFinder()->getPath($daoNamespace.'\\Generated\\'.$daoFactoryClassName)->getPathname();
337
338
        $this->dumpFile($possibleFileName, $str);
339
    }
340
341
    /**
342
     * Transforms a string to camelCase (except the first letter will be uppercase too).
343
     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
344
     * Quoting is removed if present.
345
     *
346
     * @param string $str
347
     *
348
     * @return string
349
     */
350
    public static function toCamelCase(string $str) : string
351
    {
352
        $str = str_replace(array('`', '"', '[', ']'), '', $str);
353
354
        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
355
        while (true) {
356
            $pos = strpos($str, '_');
357
            if ($pos === false) {
358
                $pos = strpos($str, ' ');
359
                if ($pos === false) {
360
                    break;
361
                }
362
            }
363
364
            $before = substr($str, 0, $pos);
365
            $after = substr($str, $pos + 1);
366
            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
367
        }
368
369
        return $str;
370
    }
371
372
    /**
373
     * Tries to put string to the singular form (if it is plural).
374
     * We assume the table names are in english.
375
     *
376
     * @param string $str
377
     *
378
     * @return string
379
     */
380
    public static function toSingular(string $str): string
381
    {
382
        return Inflector::singularize($str);
383
    }
384
385
    /**
386
     * Put the first letter of the string in lower case.
387
     * Very useful to transform a class name into a variable name.
388
     *
389
     * @param string $str
390
     *
391
     * @return string
392
     */
393
    public static function toVariableName(string $str): string
394
    {
395
        return strtolower(substr($str, 0, 1)).substr($str, 1);
396
    }
397
398
    /**
399
     * Ensures the file passed in parameter can be written in its directory.
400
     *
401
     * @param string $fileName
402
     *
403
     * @throws TDBMException
404
     */
405
    private function ensureDirectoryExist(string $fileName): void
406
    {
407
        $dirName = dirname($fileName);
408
        if (!file_exists($dirName)) {
409
            $old = umask(0);
410
            $result = mkdir($dirName, 0775, true);
411
            umask($old);
412
            if ($result === false) {
413
                throw new TDBMException("Unable to create directory: '".$dirName."'.");
414
            }
415
        }
416
    }
417
418
    private function dumpFile(string $fileName, string $content) : void
419
    {
420
        $this->ensureDirectoryExist($fileName);
421
        $fileSystem = new Filesystem();
422
        $fileSystem->dumpFile($fileName, $content);
423
        @chmod($fileName, 0664);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

423
        /** @scrutinizer ignore-unhandled */ @chmod($fileName, 0664);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
424
    }
425
426
    /**
427
     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
428
     *
429
     * @param Type $type The DBAL type
430
     *
431
     * @return string The PHP type
432
     */
433
    public static function dbalTypeToPhpType(Type $type) : string
434
    {
435
        $map = [
436
            Type::TARRAY => 'array',
437
            Type::SIMPLE_ARRAY => 'array',
438
            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
439
            Type::JSON_ARRAY => 'array',
440
            Type::BIGINT => 'string',
441
            Type::BOOLEAN => 'bool',
442
            Type::DATETIME_IMMUTABLE => '\DateTimeImmutable',
443
            Type::DATETIMETZ_IMMUTABLE => '\DateTimeImmutable',
444
            Type::DATE_IMMUTABLE => '\DateTimeImmutable',
445
            Type::TIME_IMMUTABLE => '\DateTimeImmutable',
446
            Type::DECIMAL => 'string',
447
            Type::INTEGER => 'int',
448
            Type::OBJECT => 'string',
449
            Type::SMALLINT => 'int',
450
            Type::STRING => 'string',
451
            Type::TEXT => 'string',
452
            Type::BINARY => 'resource',
453
            Type::BLOB => 'resource',
454
            Type::FLOAT => 'float',
455
            Type::GUID => 'string',
456
        ];
457
458
        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
459
    }
460
461
    /**
462
     * @param Table $table
463
     * @return string[]
464
     * @throws TDBMException
465
     */
466
    public static function getPrimaryKeyColumnsOrFail(Table $table): array
467
    {
468
        if ($table->getPrimaryKey() === null) {
469
            // Security check: a table MUST have a primary key
470
            throw new TDBMException(sprintf('Table "%s" does not have any primary key', $table->getName()));
471
        }
472
        return $table->getPrimaryKey()->getUnquotedColumns();
473
    }
474
}
475