forked from cebe/yii2-openapi
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTransformersGenerator.php
More file actions
93 lines (84 loc) · 3.07 KB
/
TransformersGenerator.php
File metadata and controls
93 lines (84 loc) · 3.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* @copyright Copyright (c) 2018 Carsten Brandt <mail@cebe.cc> and contributors
* @license https://github.com/cebe/yii2-openapi/blob/master/LICENSE
*/
namespace cebe\yii2openapi\lib\generators;
use cebe\yii2openapi\lib\CodeFiles;
use cebe\yii2openapi\lib\Config;
use cebe\yii2openapi\lib\items\Transformer;
use Laminas\Code\Generator\ClassGenerator;
use Laminas\Code\Generator\FileGenerator;
use Yii;
use yii\gii\CodeFile;
class TransformersGenerator
{
/**
* @var \cebe\yii2openapi\lib\Config
*/
protected $config;
/**
* @var array|\cebe\yii2openapi\lib\items\DbModel[]
*/
protected $models;
/**
* @var CodeFiles $files
**/
protected $files;
public function __construct(Config $config, array $models)
{
$this->config = $config;
$this->models = $models;
$this->files = new CodeFiles([]);
}
/**
* @return \cebe\yii2openapi\lib\CodeFiles
* @throws \yii\base\InvalidConfigException
*/
public function generate():CodeFiles
{
if (!$this->config->generateControllers || !$this->config->useJsonApi) {
return $this->files;
}
$transformerPath = Config::getPathFromNamespace($this->config->transformerNamespace);
foreach ($this->models as $model) {
$transformer = Yii::createObject(Transformer::class, [
$model,
$this->config->transformerNamespace,
$this->config->modelNamespace,
$this->config->singularResourceKeys
]);
$dirPath = $transformerPath . ($this->config->extendableTransformers ? '/base' : '');
$ns = $this->config->transformerNamespace . ($this->config->extendableTransformers ? '\\base' : '');
$this->files->add(new CodeFile(
Yii::getAlias("{$dirPath}/{$transformer->name}.php"),
$this->config->render('transformer.php', [
'namespace' => $ns,
'mainNamespace' => $this->config->transformerNamespace,
'extendable' => $this->config->extendableTransformers,
'transformer' => $transformer,
])
));
if (!$this->config->extendableTransformers) {
continue;
}
if (file_exists(Yii::getAlias("$transformerPath/{$transformer->name}.php"))) {
// only generate custom classes if they do not exist, do not override
continue;
}
$classFileGenerator = new FileGenerator();
$reflection = new ClassGenerator(
$transformer->name,
$this->config->transformerNamespace,
null,
$this->config->transformerNamespace . '\\base\\' . $transformer->name
);
$classFileGenerator->setClasses([$reflection]);
$this->files->add(new CodeFile(
Yii::getAlias("$transformerPath/{$transformer->name}.php"),
$classFileGenerator->generate()
));
}
return $this->files;
}
}