Skip to content
This repository was archived by the owner on Jun 4, 2024. It is now read-only.

Commit d6eb614

Browse files
authored
Merge pull request #88 from Insolita/2_0_improves
2 0 improves
2 parents 95be14d + ff62d85 commit d6eb614

File tree

62 files changed

+3231
-1643
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+3231
-1643
lines changed

src/generator/ApiGenerator.php

Lines changed: 113 additions & 418 deletions
Large diffs are not rendered by default.

src/generator/default/model.php

Lines changed: 23 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,43 @@
1-
<?= '<?php' ?>
1+
<?php
2+
/**
3+
* @var \cebe\yii2openapi\lib\items\DbModel $model
4+
* @var string $namespace
5+
* @var string $relationNamespace
6+
**/
7+
use yii\helpers\Inflector;
8+
use yii\helpers\VarDumper;
29

10+
?>
11+
<?= '<?php' ?>
312

413
namespace <?= $namespace ?>;
514

615
use yii\base\Model;
716

817
/**
9-
* <?= str_replace("\n", "\n * ", trim($description)) ?>
18+
* <?= empty($model->description) ? '' : str_replace("\n", "\n * ", ' ' . trim($model->description)) ?>
1019

1120
*
1221
*/
13-
class <?= $className ?> extends Model
22+
class <?= $model->getClassName() ?> extends Model
1423
{
15-
<?php foreach ($attributes as $attribute): ?>
24+
<?php foreach ($model->attributes as $attribute): ?>
1625
/**
17-
* @var <?= trim(($attribute['type'] ?? 'mixed') . ' ' . str_replace("\n", "\n * ", rtrim($attribute['description']))) ?>
26+
* @var <?=$attribute->phpType.' '.$attribute->description.PHP_EOL?>
27+
*/
28+
public $<?= $attribute->propertyName ?>;
1829

19-
*/
20-
public $<?= $attribute['name'] ?>;
2130
<?php endforeach; ?>
31+
<?php foreach ($model->relations as $relationName => $relation): ?>
32+
/**
33+
* @var <?=$relation->isHasOne()? $relation->getClassName(): 'array|'.$relation->getClassName().'[]'.PHP_EOL?>
34+
*/
35+
public $<?= $relationName ?>;
2236

37+
<?php endforeach; ?>
2338

2439
public function rules()
2540
{
26-
return [
27-
<?php
28-
$safeAttributes = [];
29-
$requiredAttributes = [];
30-
$integerAttributes = [];
31-
$stringAttributes = [];
32-
33-
foreach ($attributes as $attribute) {
34-
if ($attribute['readOnly']) {
35-
continue;
36-
}
37-
if ($attribute['required']) {
38-
$requiredAttributes[$attribute['name']] = $attribute['name'];
39-
}
40-
switch ($attribute['type']) {
41-
case 'integer':
42-
$integerAttributes[$attribute['name']] = $attribute['name'];
43-
break;
44-
case 'string':
45-
$stringAttributes[$attribute['name']] = $attribute['name'];
46-
break;
47-
default:
48-
case 'array':
49-
$safeAttributes[$attribute['name']] = $attribute['name'];
50-
break;
51-
}
52-
}
53-
if (!empty($stringAttributes)) {
54-
echo " [['" . implode("', '", $stringAttributes) . "'], 'trim'],\n";
55-
}
56-
if (!empty($requiredAttributes)) {
57-
echo " [['" . implode("', '", $requiredAttributes) . "'], 'required'],\n";
58-
}
59-
if (!empty($stringAttributes)) {
60-
echo " [['" . implode("', '", $stringAttributes) . "'], 'string'],\n";
61-
}
62-
if (!empty($integerAttributes)) {
63-
echo " [['" . implode("', '", $integerAttributes) . "'], 'integer'],\n";
64-
}
65-
if (!empty($safeAttributes)) {
66-
echo " // TODO define more concreate validation rules!\n";
67-
echo " [['" . implode("','", $safeAttributes) . "'], 'safe'],\n";
68-
}
69-
70-
?>
71-
];
41+
return <?=$model->getValidationRules()?>;
7242
}
7343
}

src/lib/AttributeResolver.php

Lines changed: 197 additions & 262 deletions
Large diffs are not rendered by default.

src/lib/CodeFiles.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
/**
4+
* @copyright Copyright (c) 2018 Carsten Brandt <[email protected]> and contributors
5+
* @license https://github.com/cebe/yii2-openapi/blob/master/LICENSE
6+
*/
7+
8+
namespace cebe\yii2openapi\lib;
9+
10+
use yii\gii\CodeFile;
11+
use function array_merge;
12+
13+
class CodeFiles
14+
{
15+
/**
16+
* @var array|\yii\gii\CodeFile[]
17+
*/
18+
private $files;
19+
20+
/**
21+
* @param array|\yii\gii\CodeFile[] $files
22+
*/
23+
public function __construct(array $files = [])
24+
{
25+
$this->files = $files;
26+
}
27+
28+
public function add(CodeFile $file):void
29+
{
30+
$this->files[] = $file;
31+
}
32+
33+
34+
public function merge(CodeFiles $files):void
35+
{
36+
$this->files = array_merge($this->files, $files->all());
37+
}
38+
39+
/**
40+
* @return array|\yii\gii\CodeFile[]
41+
*/
42+
public function all():array
43+
{
44+
return $this->files;
45+
}
46+
}

src/lib/Config.php

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
<?php
2+
3+
/**
4+
* @copyright Copyright (c) 2018 Carsten Brandt <[email protected]> and contributors
5+
* @license https://github.com/cebe/yii2-openapi/blob/master/LICENSE
6+
*/
7+
8+
namespace cebe\yii2openapi\lib;
9+
10+
use cebe\openapi\Reader;
11+
use cebe\openapi\spec\OpenApi;
12+
use Closure;
13+
use Yii;
14+
use yii\base\BaseObject;
15+
use yii\base\InvalidConfigException;
16+
use yii\helpers\StringHelper;
17+
use function call_user_func;
18+
19+
class Config extends BaseObject
20+
{
21+
/**
22+
* @var string path to the OpenAPI specification file. This can be an absolute path or a Yii path alias.
23+
*/
24+
public $openApiPath;
25+
26+
/**
27+
* @var bool whether to generate URL rules for Yii UrlManager from the API spec.
28+
*/
29+
public $generateUrls = true;
30+
31+
/**
32+
* @var string file name for URL rules.
33+
*/
34+
public $urlConfigFile = '@app/config/urls.rest.php';
35+
36+
/**
37+
* @var array Special url prefixes
38+
* @example
39+
* 'urlPrefixes' => [
40+
* //Prefix will be ignored in url pattern,
41+
* //Rule like ['/calendar/<controller>/<action>' => '<controller>/<action>']
42+
* 'calendar' => '',
43+
* //Controller for url with this prefix will be located directly at defined path and namespace
44+
* //Rule like ['/api/v1/<controller>/<action>' => '/api/v1/<controller>/<action>']
45+
* 'api/v1/' => ['path' => '@app/modules/api/controllers/v1/', 'namespace' => '\app\modules\api\v1'],
46+
* //Controller for url with this prefix will be located directly at defined namespace, path resolved by namespace
47+
* //Rule like ['/prefix/<controller>/<action>' => '/xxx/<controller>/<action>']
48+
* 'prefix' => ['module' => 'xxx','namespace' => '\app\modules\xxx\controllers']
49+
* ]
50+
**/
51+
public $urlPrefixes = [];
52+
53+
/**
54+
* @var bool whether to generate Controllers from the spec.
55+
*/
56+
public $generateControllers = true;
57+
58+
/**
59+
* @var bool use actions that return responses by JsonApi spec instead of default yii rest
60+
*/
61+
public $useJsonApi = false;
62+
63+
/**
64+
* @var bool if true, transformers will be generate in base subdirectory and overridable classes will extend it
65+
*/
66+
public $extendableTransformers = true;
67+
68+
/**
69+
* @var bool if true singular resource keys will be used /post/{id}, plural by default
70+
*/
71+
public $singularResourceKeys = false;
72+
73+
/**
74+
* @var string namespace to create controllers in. This must be resolvable via Yii alias.
75+
* Defaults to `null` which means to use the application controller namespace: `Yii::$app->controllerNamespace`.
76+
*/
77+
public $controllerNamespace;
78+
79+
/**
80+
* @var bool whether to generate ActiveRecord models from the spec.
81+
*/
82+
public $generateModels = true;
83+
84+
/**
85+
* @var bool whether to generate Faker for generating dummy data for each model.
86+
*/
87+
public $generateModelFaker = true;
88+
89+
/**
90+
* @var bool namespace to create models in. This must be resolvable via Yii alias.
91+
* Defaults to `app\models`.
92+
*/
93+
public $modelNamespace = 'app\\models';
94+
95+
/**
96+
* @var bool namespace to create fake data generators in. This must be resolvable via Yii alias.
97+
* Defaults to `app\models`.
98+
*/
99+
public $fakerNamespace = 'app\\models';
100+
101+
/**
102+
* @var string namespace to create fractal transformers in. (Only when generatedControllers and useJsonApi checked)
103+
* Defaults to `app\transformers`.
104+
*/
105+
public $transformerNamespace = 'app\\transformers';
106+
107+
/**
108+
* @var array List of model names to exclude.
109+
*/
110+
public $excludeModels = [];
111+
112+
/**
113+
* @var array Map for custom controller names not based on model name for exclusive cases
114+
* @example
115+
* 'controllerModelMap' => [
116+
* 'User' => 'Profile', //use ProfileController for User model
117+
* 'File' => 'Upload', //use UploadController for File model
118+
* ]
119+
**/
120+
public $controllerModelMap = [];
121+
122+
/**
123+
* @var bool Generate database models only for Schemas that not starts with underscore
124+
*/
125+
public $skipUnderscoredSchemas = true;
126+
127+
/**
128+
* @var bool Generate database models only for Schemas that have the `x-table` annotation.
129+
*/
130+
public $generateModelsOnlyXTable = false;
131+
132+
/**
133+
* @var bool whether to generate database migrations.
134+
*/
135+
public $generateMigrations = true;
136+
137+
/**
138+
* @var string path to create migration files in.
139+
* Defaults to `@app/migrations`.
140+
*/
141+
public $migrationPath = '@app/migrations';
142+
143+
/**
144+
* @var string namespace to create migrations in.
145+
* Defaults to `null` which means that migrations are generated without namespace.
146+
*/
147+
public $migrationNamespace;
148+
149+
private $fileRenderer;
150+
151+
/**
152+
* @var OpenApi
153+
*/
154+
private $openApi;
155+
156+
/**
157+
* @return \cebe\openapi\spec\OpenApi
158+
* @throws \cebe\openapi\exceptions\IOException
159+
* @throws \cebe\openapi\exceptions\TypeErrorException
160+
* @throws \cebe\openapi\exceptions\UnresolvableReferenceException
161+
*/
162+
public function getOpenApi():OpenApi
163+
{
164+
if ($this->openApi === null) {
165+
$file = Yii::getAlias($this->openApiPath);
166+
if (StringHelper::endsWith($this->openApiPath, '.json', false)) {
167+
$this->openApi = Reader::readFromJsonFile($file, OpenApi::class, false);
168+
} else {
169+
$this->openApi = Reader::readFromYamlFile($file, OpenApi::class, false);
170+
}
171+
}
172+
return $this->openApi;
173+
}
174+
175+
public function getPathFromNamespace(string $namespace):string
176+
{
177+
return Yii::getAlias('@' . str_replace('\\', '/', ltrim($namespace, '\\')));
178+
}
179+
180+
public function setFileRenderer(Closure $renderCallback):void
181+
{
182+
$this->fileRenderer = $renderCallback;
183+
}
184+
185+
/**
186+
* Generates code using the specified code template and parameters.
187+
* Note that the code template will be used as a PHP file.
188+
* @param string $template the code template file. This must be specified as a file path
189+
* relative to [[templatePath]].
190+
* @param array $params list of parameters to be passed to the template file.
191+
* @return string the generated code
192+
* @throws \yii\base\InvalidConfigException
193+
*/
194+
public function render(string $template, array $params = []):string
195+
{
196+
if (!$this->fileRenderer) {
197+
throw new InvalidConfigException('Renderer is not configured');
198+
}
199+
return call_user_func($this->fileRenderer, $template, $params);
200+
}
201+
}

src/lib/CustomSpecAttr.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class CustomSpecAttr
1212
// --- For component schema ---
1313
//Custom table name
1414
public const TABLE = 'x-table';
15-
//Primary key property name, if it different from "id" (Only one value, compound keys not supported yet)
15+
//Primary key property name, if it is different from "id" (Only one value, compound keys not supported yet)
1616
public const PRIMARY_KEY = 'x-pk';
1717
//List of table indexes
1818
public const INDEXES = 'x-indexes';

0 commit comments

Comments
 (0)