Passed
Pull Request — master (#116)
by David
03:37 queued 43s
created

TDBMDaoGenerator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

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