Passed
Push — master ( d96239...107cfa )
by David
06:15 queued 01:58
created

TDBMDaoGenerator::deleteAllPhpFiles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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 Psr\Container\ContainerInterface;
11
use TheCodingMachine\TDBM\Schema\ForeignKeys;
12
use TheCodingMachine\TDBM\TDBMService;
13
use Zend\Code\Generator\AbstractMemberGenerator;
14
use Zend\Code\Generator\ClassGenerator;
15
use Zend\Code\Generator\DocBlock\Tag\VarTag;
16
use Zend\Code\Generator\DocBlockGenerator;
17
use Zend\Code\Generator\FileGenerator;
18
use Zend\Code\Generator\MethodGenerator;
19
use Zend\Code\Generator\ParameterGenerator;
20
use Zend\Code\Generator\PropertyGenerator;
21
use function str_replace;
22
use TheCodingMachine\TDBM\ConfigurationInterface;
23
use TheCodingMachine\TDBM\TDBMException;
24
use TheCodingMachine\TDBM\TDBMSchemaAnalyzer;
25
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
26
use Symfony\Component\Filesystem\Filesystem;
27
use function strpos;
28
use function substr;
29
use function var_export;
30
31
/**
32
 * This class generates automatically DAOs and Beans for TDBM.
33
 */
34
class TDBMDaoGenerator
35
{
36
    /**
37
     * @var Schema
38
     */
39
    private $schema;
40
41
    /**
42
     * @var TDBMSchemaAnalyzer
43
     */
44
    private $tdbmSchemaAnalyzer;
45
46
    /**
47
     * @var GeneratorListenerInterface
48
     */
49
    private $eventDispatcher;
50
51
    /**
52
     * @var NamingStrategyInterface
53
     */
54
    private $namingStrategy;
55
    /**
56
     * @var ConfigurationInterface
57
     */
58
    private $configuration;
59
60
    /**
61
     * Constructor.
62
     *
63
     * @param ConfigurationInterface $configuration
64
     * @param TDBMSchemaAnalyzer $tdbmSchemaAnalyzer
65
     */
66
    public function __construct(ConfigurationInterface $configuration, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer)
67
    {
68
        $this->configuration = $configuration;
69
        $this->schema = $tdbmSchemaAnalyzer->getSchema();
70
        $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
71
        $this->namingStrategy = $configuration->getNamingStrategy();
72
        $this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
73
    }
74
75
    /**
76
     * Generates all the daos and beans.
77
     *
78
     * @throws TDBMException
79
     */
80
    public function generateAllDaosAndBeans(): void
81
    {
82
        // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
83
84
        $tableList = $this->schema->getTables();
85
86
        // Remove all beans and daos from junction tables
87
        $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
88
        $junctionTableNames = array_map(function (Table $table) {
89
            return $table->getName();
90
        }, $junctionTables);
91
92
        $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
93
            return !in_array($table->getName(), $junctionTableNames, true);
94
        });
95
96
        $this->cleanUpGenerated();
97
98
        $beanDescriptors = [];
99
100
        $beanRegistry = new BeanRegistry($this->configuration, $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
101
        foreach ($tableList as $table) {
102
            $beanDescriptors[] = $beanRegistry->addBeanForTable($table);
103
        }
104
        foreach ($beanDescriptors as $beanDescriptor) {
105
            $beanDescriptor->initBeanPropertyDescriptors();
106
        }
107
        foreach ($beanDescriptors as $beanDescriptor) {
108
            $this->generateBean($beanDescriptor);
109
            $this->generateDao($beanDescriptor);
110
        }
111
112
        $this->generateFactory($beanDescriptors);
113
114
        // Let's call the list of listeners
115
        $this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
116
    }
117
118
    /**
119
     * Removes all files from the Generated folders.
120
     * This is a way to ensure that when a table is deleted, the matching bean/dao are deleted.
121
     * Note: only abstract generated classes are deleted. We do not delete the code that might have been customized
122
     * by the user. The user will need to delete this code him/herself
123
     */
124
    private function cleanUpGenerated(): void
125
    {
126
        $generatedBeanDir = $this->configuration->getPathFinder()->getPath($this->configuration->getBeanNamespace().'\\Generated\\Xxx')->getPath();
127
        $this->deleteAllPhpFiles($generatedBeanDir);
128
129
        $generatedDaoDir = $this->configuration->getPathFinder()->getPath($this->configuration->getDaoNamespace().'\\Generated\\Xxx')->getPath();
130
        $this->deleteAllPhpFiles($generatedDaoDir);
131
    }
132
133
    private function deleteAllPhpFiles(string $directory): void
134
    {
135
        $files = glob($directory.'/*.php');
136
        $fileSystem = new Filesystem();
137
        $fileSystem->remove($files);
0 ignored issues
show
Bug introduced by
It seems like $files can also be of type false; however, parameter $files of Symfony\Component\Filesystem\Filesystem::remove() does only seem to accept iterable|string, maybe add an additional type check? ( Ignorable by Annotation )

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

137
        $fileSystem->remove(/** @scrutinizer ignore-type */ $files);
Loading history...
138
    }
139
140
    /**
141
     * Writes the PHP bean file with all getters and setters from the table passed in parameter.
142
     *
143
     * @param BeanDescriptor  $beanDescriptor
144
     *
145
     * @throws TDBMException
146
     */
147
    public function generateBean(BeanDescriptor $beanDescriptor): void
148
    {
149
        $className = $beanDescriptor->getBeanClassName();
150
        $baseClassName = $beanDescriptor->getBaseBeanClassName();
151
        $table = $beanDescriptor->getTable();
152
        $beannamespace = $this->configuration->getBeanNamespace();
153
        $file = $beanDescriptor->generatePhpCode();
154
        if ($file === null) {
155
            return;
156
        }
157
158
        $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\Generated\\'.$baseClassName)->getPathname();
159
160
        $fileContent = $file->generate();
161
162
        // Hard code PSR-2 fix
163
        $fileContent = $this->psr2Fix($fileContent);
164
        // Add the declare strict-types directive
165
        $commentEnd = strpos($fileContent, ' */') + 3;
166
        $fileContent = substr($fileContent, 0, $commentEnd) . "\n\ndeclare(strict_types=1);" . substr($fileContent, $commentEnd + 1);
167
168
        $this->dumpFile($possibleBaseFileName, $fileContent);
169
170
        $possibleFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\'.$className)->getPathname();
171
172
        if (!file_exists($possibleFileName)) {
173
            $tableName = $table->getName();
174
            $str = "<?php
175
/*
176
 * This file has been automatically generated by TDBM.
177
 * You can edit this file as it will not be overwritten.
178
 */
179
180
declare(strict_types=1);
181
182
namespace {$beannamespace};
183
184
use {$beannamespace}\\Generated\\{$baseClassName};
185
186
/**
187
 * The $className class maps the '$tableName' table in database.
188
 */
189
class $className extends $baseClassName
190
{
191
}
192
";
193
194
            $this->dumpFile($possibleFileName, $str);
195
        }
196
    }
197
198
    /**
199
     * Writes the PHP bean DAO with simple functions to create/get/save objects.
200
     *
201
     * @param BeanDescriptor  $beanDescriptor
202
     *
203
     * @throws TDBMException
204
     */
205
    private function generateDao(BeanDescriptor $beanDescriptor): void
206
    {
207
        $className = $beanDescriptor->getDaoClassName();
208
        $baseClassName = $beanDescriptor->getBaseDaoClassName();
209
        $beanClassName = $beanDescriptor->getBeanClassName();
210
        $table = $beanDescriptor->getTable();
211
        $file = $beanDescriptor->generateDaoPhpCode();
212
        if ($file === null) {
213
            return;
214
        }
215
        $daonamespace = $this->configuration->getDaoNamespace();
216
        $tableName = $table->getName();
217
218
        $beanClassWithoutNameSpace = $beanClassName;
219
220
        $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\Generated\\'.$baseClassName)->getPathname();
221
222
        $fileContent = $file->generate();
223
224
        // Hard code PSR-2 fix
225
        $fileContent = $this->psr2Fix($fileContent);
226
        // Add the declare strict-types directive
227
        $commentEnd = strpos($fileContent, ' */') + 3;
228
        $fileContent = substr($fileContent, 0, $commentEnd) . "\n\ndeclare(strict_types=1);" . substr($fileContent, $commentEnd + 1);
229
230
        $this->dumpFile($possibleBaseFileName, $fileContent);
231
232
233
        $possibleFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\'.$className)->getPathname();
234
235
        // Now, let's generate the "editable" class
236
        if (!file_exists($possibleFileName)) {
237
            $str = "<?php
238
/*
239
 * This file has been automatically generated by TDBM.
240
 * You can edit this file as it will not be overwritten.
241
 */
242
243
declare(strict_types=1);
244
245
namespace {$daonamespace};
246
247
use {$daonamespace}\\Generated\\{$baseClassName};
248
249
/**
250
 * The $className class will maintain the persistence of $beanClassWithoutNameSpace class into the $tableName table.
251
 */
252
class $className extends $baseClassName
253
{
254
}
255
";
256
            $this->dumpFile($possibleFileName, $str);
257
        }
258
    }
259
260
    /**
261
     * Fixes PSR-2 for files generated by Zend-Code
262
     */
263
    private function psr2Fix(string $content): string
264
    {
265
        return str_replace(
266
            [
267
                "\n\n}\n",
268
                "{\n\n    use",
269
            ],
270
            [
271
                '}',
272
                "{\n    use",
273
            ],
274
            $content
275
        );
276
    }
277
278
    /**
279
     * Generates the factory bean.
280
     *
281
     * @param BeanDescriptor[] $beanDescriptors
282
     * @throws TDBMException
283
     */
284
    private function generateFactory(array $beanDescriptors) : void
285
    {
286
        $daoNamespace = $this->configuration->getDaoNamespace();
287
        $daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
288
289
        $file = new FileGenerator();
290
        $file->setDocBlock(
291
            new DocBlockGenerator(
292
                <<<DOC
293
This file has been automatically generated by TDBM.
294
DO NOT edit this file, as it might be overwritten.
295
DOC
296
            )
297
        );
298
        $class = new ClassGenerator();
299
        $file->setClass($class);
300
        $class->setName($daoFactoryClassName);
301
        $file->setNamespace($daoNamespace.'\\Generated');
302
303
        $class->setDocBlock(new DocBlockGenerator("The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM."));
304
305
        $containerProperty = new PropertyGenerator('container');
306
        $containerProperty->setVisibility(AbstractMemberGenerator::VISIBILITY_PRIVATE);
307
        $containerProperty->setDocBlock(new DocBlockGenerator(null, null, [new VarTag(null, ['\\'.ContainerInterface::class])]));
308
        $class->addPropertyFromGenerator($containerProperty);
309
310
        $constructorMethod = new MethodGenerator(
311
            '__construct',
312
            [ new ParameterGenerator('container', ContainerInterface::class) ],
313
            MethodGenerator::FLAG_PUBLIC,
314
            '$this->container = $container;'
315
        );
316
        $constructorMethod = $this->configuration->getCodeGeneratorListener()->onDaoFactoryConstructorGenerated($constructorMethod, $beanDescriptors, $this->configuration, $class);
317
        if ($constructorMethod !== null) {
318
            $class->addMethodFromGenerator($constructorMethod);
319
        }
320
321
        // For each table, let's write a property.
322
        foreach ($beanDescriptors as $beanDescriptor) {
323
            $daoClassName = $beanDescriptor->getDaoClassName();
324
            $daoInstanceName = self::toVariableName($daoClassName);
325
326
            $daoInstanceProperty = new PropertyGenerator($daoInstanceName);
327
            $daoInstanceProperty->setVisibility(AbstractMemberGenerator::VISIBILITY_PRIVATE);
328
            $daoInstanceProperty->setDocBlock(new DocBlockGenerator(null, null, [new VarTag(null, ['\\' . $daoNamespace . '\\' . $daoClassName, 'null'])]));
329
            $class->addPropertyFromGenerator($daoInstanceProperty);
330
331
            $fullClassNameVarExport = var_export($daoNamespace.'\\'.$daoClassName, true);
332
            $getterBody = <<<BODY
333
if (!\$this->$daoInstanceName) {
334
    \$this->$daoInstanceName = \$this->container->get($fullClassNameVarExport);
335
}
336
337
return \$this->$daoInstanceName;
338
BODY;
339
340
            $getterMethod = new MethodGenerator(
341
                'get' . $daoClassName,
342
                [],
343
                MethodGenerator::FLAG_PUBLIC,
344
                $getterBody
345
            );
346
            $getterMethod->setReturnType($daoNamespace.'\\'.$daoClassName);
347
            $getterMethod = $this->configuration->getCodeGeneratorListener()->onDaoFactoryGetterGenerated($getterMethod, $beanDescriptor, $this->configuration, $class);
348
            if ($getterMethod !== null) {
349
                $class->addMethodFromGenerator($getterMethod);
350
            }
351
352
            $setterMethod = new MethodGenerator(
353
                'set' . $daoClassName,
354
                [new ParameterGenerator($daoInstanceName, '\\' . $daoNamespace . '\\' . $daoClassName)],
355
                MethodGenerator::FLAG_PUBLIC,
356
                '$this->' . $daoInstanceName . ' = $' . $daoInstanceName . ';'
357
            );
358
            $setterMethod->setReturnType('void');
359
            $setterMethod = $this->configuration->getCodeGeneratorListener()->onDaoFactorySetterGenerated($setterMethod, $beanDescriptor, $this->configuration, $class);
360
            if ($setterMethod !== null) {
361
                $class->addMethodFromGenerator($setterMethod);
362
            }
363
        }
364
365
        $file = $this->configuration->getCodeGeneratorListener()->onDaoFactoryGenerated($file, $beanDescriptors, $this->configuration);
366
367
        if ($file !== null) {
368
            $possibleFileName = $this->configuration->getPathFinder()->getPath($daoNamespace.'\\Generated\\'.$daoFactoryClassName)->getPathname();
369
370
            $fileContent = $file->generate();
371
372
            // Hard code PSR-2 fix
373
            $fileContent = $this->psr2Fix($fileContent);
374
            // Add the declare strict-types directive
375
            $commentEnd = strpos($fileContent, ' */') + 3;
376
            $fileContent = substr($fileContent, 0, $commentEnd) . "\n\ndeclare(strict_types=1);" . substr($fileContent, $commentEnd + 1);
377
378
            $this->dumpFile($possibleFileName, $fileContent);
379
        }
380
    }
381
382
    /**
383
     * Transforms a string to camelCase (except the first letter will be uppercase too).
384
     * Underscores and spaces are removed and the first letter after the underscore is uppercased.
385
     * Quoting is removed if present.
386
     *
387
     * @param string $str
388
     *
389
     * @return string
390
     */
391
    public static function toCamelCase(string $str) : string
392
    {
393
        $str = str_replace(array('`', '"', '[', ']'), '', $str);
394
395
        $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
396
        while (true) {
397
            $pos = strpos($str, '_');
398
            if ($pos === false) {
399
                $pos = strpos($str, ' ');
400
                if ($pos === false) {
401
                    break;
402
                }
403
            }
404
405
            $before = substr($str, 0, $pos);
406
            $after = substr($str, $pos + 1);
407
            $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
408
        }
409
410
        return $str;
411
    }
412
413
    /**
414
     * Tries to put string to the singular form (if it is plural).
415
     * We assume the table names are in english.
416
     *
417
     * @param string $str
418
     *
419
     * @return string
420
     */
421
    public static function toSingular(string $str): string
422
    {
423
        return Inflector::singularize($str);
424
    }
425
426
    /**
427
     * Put the first letter of the string in lower case.
428
     * Very useful to transform a class name into a variable name.
429
     *
430
     * @param string $str
431
     *
432
     * @return string
433
     */
434
    public static function toVariableName(string $str): string
435
    {
436
        return strtolower(substr($str, 0, 1)).substr($str, 1);
437
    }
438
439
    /**
440
     * Ensures the file passed in parameter can be written in its directory.
441
     *
442
     * @param string $fileName
443
     *
444
     * @throws TDBMException
445
     */
446
    private function ensureDirectoryExist(string $fileName): void
447
    {
448
        $dirName = dirname($fileName);
449
        if (!file_exists($dirName)) {
450
            $old = umask(0);
451
            $result = mkdir($dirName, 0775, true);
452
            umask($old);
453
            if ($result === false) {
454
                throw new TDBMException("Unable to create directory: '".$dirName."'.");
455
            }
456
        }
457
    }
458
459
    private function dumpFile(string $fileName, string $content) : void
460
    {
461
        $this->ensureDirectoryExist($fileName);
462
        $fileSystem = new Filesystem();
463
        $fileSystem->dumpFile($fileName, $content);
464
        @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

464
        /** @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...
465
    }
466
467
    /**
468
     * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
469
     *
470
     * @param Type $type The DBAL type
471
     *
472
     * @return string The PHP type
473
     */
474
    public static function dbalTypeToPhpType(Type $type) : string
475
    {
476
        $map = [
477
            Type::TARRAY => 'array',
478
            Type::SIMPLE_ARRAY => 'array',
479
            'json' => 'array',  // 'json' is supported from Doctrine DBAL 2.6 only.
480
            Type::JSON_ARRAY => 'array',
481
            Type::BIGINT => 'string',
482
            Type::BOOLEAN => 'bool',
483
            Type::DATETIME_IMMUTABLE => '\DateTimeImmutable',
484
            Type::DATETIMETZ_IMMUTABLE => '\DateTimeImmutable',
485
            Type::DATE_IMMUTABLE => '\DateTimeImmutable',
486
            Type::TIME_IMMUTABLE => '\DateTimeImmutable',
487
            Type::DECIMAL => 'string',
488
            Type::INTEGER => 'int',
489
            Type::OBJECT => 'string',
490
            Type::SMALLINT => 'int',
491
            Type::STRING => 'string',
492
            Type::TEXT => 'string',
493
            Type::BINARY => 'resource',
494
            Type::BLOB => 'resource',
495
            Type::FLOAT => 'float',
496
            Type::GUID => 'string',
497
        ];
498
499
        return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
500
    }
501
502
    /**
503
     * @param Table $table
504
     * @return string[]
505
     * @throws TDBMException
506
     */
507
    public static function getPrimaryKeyColumnsOrFail(Table $table): array
508
    {
509
        if ($table->getPrimaryKey() === null) {
510
            // Security check: a table MUST have a primary key
511
            throw new TDBMException(sprintf('Table "%s" does not have any primary key', $table->getName()));
512
        }
513
        return $table->getPrimaryKey()->getUnquotedColumns();
514
    }
515
}
516