|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the DataImporter package. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Loïc Sapone <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
11
|
|
|
* file that was distributed with this source code. |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
namespace IQ2i\DataImporter\Dto; |
|
15
|
|
|
|
|
16
|
|
|
use Nette\PhpGenerator\PhpFile; |
|
17
|
|
|
use Nette\PhpGenerator\PsrPrinter; |
|
18
|
|
|
|
|
19
|
|
|
use function Symfony\Component\String\u; |
|
20
|
|
|
|
|
21
|
|
|
class Generator |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* @var string |
|
25
|
|
|
*/ |
|
26
|
|
|
private const NAMESPACE = 'App\Dto'; |
|
27
|
|
|
|
|
28
|
1 |
|
public function generate(string $class, array $columns, string $namespace = null): string |
|
29
|
|
|
{ |
|
30
|
1 |
|
$file = new PhpFile(); |
|
31
|
1 |
|
$file->setStrictTypes(); |
|
32
|
|
|
|
|
33
|
1 |
|
$namespace = $file->addNamespace($namespace ?? self::NAMESPACE); |
|
34
|
1 |
|
$class = $namespace->addClass($class); |
|
35
|
|
|
|
|
36
|
1 |
|
foreach ($columns as $column) { |
|
37
|
1 |
|
$property = $class->addProperty($column['name']) |
|
38
|
1 |
|
->setPrivate() |
|
39
|
1 |
|
->setType('?'.$column['type']) |
|
40
|
1 |
|
->setInitialized(); |
|
41
|
|
|
|
|
42
|
1 |
|
if (null !== $column['serialized_name']) { |
|
43
|
|
|
$namespace->addUse(\Symfony\Component\Serializer\Annotation\SerializedName::class); |
|
44
|
|
|
|
|
45
|
|
|
$property->addAttribute(\Symfony\Component\Serializer\Annotation\SerializedName::class, [$column['serialized_name']]); |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
1 |
|
foreach ($columns as $column) { |
|
50
|
1 |
|
$class->addMethod('get'.u($column['name'])->camel()->title()) |
|
51
|
1 |
|
->setPublic() |
|
52
|
1 |
|
->setReturnType('?'.$column['type']) |
|
53
|
1 |
|
->addBody('return $this->?;', [$column['name']]); |
|
54
|
|
|
|
|
55
|
1 |
|
$setter = $class->addMethod('set'.u($column['name'])->camel()->title()) |
|
56
|
1 |
|
->setPublic() |
|
57
|
1 |
|
->setReturnType('self') |
|
58
|
1 |
|
->addBody('$this->? = $?;', [$column['name'], $column['name']]) |
|
59
|
1 |
|
->addBody('') |
|
60
|
1 |
|
->addBody('return $this;'); |
|
61
|
|
|
|
|
62
|
1 |
|
$setter->addParameter($column['name']) |
|
63
|
1 |
|
->setType('?'.$column['type']); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
$printer = new PsrPrinter(); |
|
67
|
|
|
|
|
68
|
1 |
|
return $printer->printFile($file); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|