Skip to content

Commit 2db7968

Browse files
authored
Merge pull request #28 from siggi-k/openapiSchema
DbModel with openapiSchema
2 parents 16862ad + 9497bf4 commit 2db7968

File tree

79 files changed

+564
-38
lines changed

Some content is hidden

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

79 files changed

+564
-38
lines changed

src/generator/ApiGenerator.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
namespace cebe\yii2openapi\generator;
99

10+
use cebe\yii2openapi\lib\items\DbModel;
1011
use yii\db\mysql\Schema as MySqlSchema;
1112
use SamIT\Yii2\MariaDb\Schema as MariaDbSchema;
1213
use yii\db\pgsql\Schema as PgSqlSchema;
@@ -133,6 +134,17 @@ class ApiGenerator extends Generator
133134
*/
134135
public $excludeModels = [];
135136

137+
/**
138+
* @var array Map for custom dbModels
139+
*
140+
* @see DbModel::$scenarioDefaultDescription with acceptedInputs: {scenarioName}, {scenarioConst}, {modelName}.
141+
* @example
142+
* 'dbModel' => [
143+
* 'scenarioDefaultDescription' => "Scenario {scenarioName}",
144+
* ]
145+
*/
146+
public $dbModel = [];
147+
136148
/**
137149
* @var array Map for custom controller names not based on model name for exclusive cases
138150
* @example

src/generator/default/dbmodel.php

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,18 @@
1111
<?= '<?php' ?>
1212

1313

14+
/**
15+
* This file is generated by Gii, do not change manually!
16+
*/
17+
1418
namespace <?= $namespace ?>;
1519

1620
/**
17-
*<?= empty($model->description) ? '' : str_replace("\n", "\n * ", ' ' . trim($model->description)) ?>
21+
*<?= $model->getModelClassDescription() ?>
1822

1923
*
2024
<?php foreach ($model->dbAttributes() as $attribute): ?>
21-
* @property <?= $attribute->getFormattedDescription() ?>
25+
* @property <?= $attribute->getPropertyAnnotation() ?>
2226

2327
<?php endforeach; ?>
2428
*
@@ -45,6 +49,16 @@
4549
*/
4650
abstract class <?= $model->getClassName() ?> extends \yii\db\ActiveRecord
4751
{
52+
<?php if($scenarios = $model->getScenarios()):
53+
foreach($scenarios as $scenario): ?>
54+
/**
55+
*<?= $scenario['description'] ?>
56+
57+
*/
58+
public const <?= $scenario['const'] ?> = '<?= $scenario['name'] ?>';
59+
60+
<?php endforeach; ?>
61+
<?php endif ?>
4862
<?php if (count($model->virtualAttributes())):?>
4963
protected $virtualAttributes = ['<?=implode("', '", array_map(function ($attr) {
5064
return $attr->columnName;
@@ -62,6 +76,33 @@ public static function tableName()
6276
{
6377
return <?= var_export($model->getTableAlias()) ?>;
6478
}
79+
<?php if($scenarios): ?>
80+
81+
/**
82+
* Automatically generated scenarios from the model 'x-scenarios'.
83+
* @return array a list of scenarios and the corresponding active attributes.
84+
*/
85+
public function scenarios()
86+
{
87+
/**
88+
* Each scenario is assigned attributes as in the 'default' scenario.
89+
* The advantage is that the scenario can be used immediately.
90+
* This can be overridden in the child model if needed.
91+
*/
92+
$default = parent::scenarios()[self::SCENARIO_DEFAULT];
93+
94+
return [
95+
<?php foreach($scenarios as $scenario): ?>
96+
self::<?= $scenario['const'] ?> => $default,
97+
<?php endforeach; ?>
98+
/**
99+
* The 'default' scenario and all scenarios mentioned in the rules() using 'on' and 'except'
100+
* are automatically included in the scenarios() function for the model.
101+
*/
102+
...parent::scenarios(),
103+
];
104+
}
105+
<?php endif;?>
65106
<?php if (count($model->virtualAttributes())):?>
66107

67108
public function attributes()

src/lib/AttributeResolver.php

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class AttributeResolver
6060
/**
6161
* @var ComponentSchema
6262
*/
63-
private $schema;
63+
private $componentSchema;
6464

6565
/**
6666
* @var \cebe\yii2openapi\lib\items\JunctionSchemas
@@ -79,7 +79,7 @@ class AttributeResolver
7979
public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null)
8080
{
8181
$this->schemaName = $schemaName;
82-
$this->schema = $schema;
82+
$this->componentSchema = $schema;
8383
$this->tableName = $schema->resolveTableName($schemaName);
8484
$this->junctions = $junctions;
8585
$this->isJunctionSchema = $junctions->isJunctionSchema($schemaName);
@@ -94,10 +94,10 @@ public function __construct(string $schemaName, ComponentSchema $schema, Junctio
9494
*/
9595
public function resolve():DbModel
9696
{
97-
foreach ($this->schema->getProperties() as $property) {
97+
foreach ($this->componentSchema->getProperties() as $property) {
9898
/** @var $property \cebe\yii2openapi\lib\openapi\PropertySchema */
9999

100-
$isRequired = $this->schema->isRequiredProperty($property->getName());
100+
$isRequired = $this->componentSchema->isRequiredProperty($property->getName());
101101
$nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null;
102102
if ($nullableValue === false) { // see docs in README regarding NOT NULL, required and nullable
103103
$isRequired = true;
@@ -113,18 +113,20 @@ public function resolve():DbModel
113113
}
114114
return Yii::createObject(DbModel::class, [
115115
[
116-
'pkName' => $this->schema->getPkName(),
116+
/** @see \cebe\openapi\spec\Schema */
117+
'openapiSchema' => $this->componentSchema->getSchema(),
118+
'pkName' => $this->componentSchema->getPkName(),
117119
'name' => $this->schemaName,
118120
'tableName' => $this->tableName,
119-
'description' => $this->schema->getDescription(),
121+
'description' => $this->componentSchema->getDescription(),
120122
'attributes' => $this->attributes,
121123
'relations' => $this->relations,
122124
'nonDbRelations' => $this->nonDbRelations,
123125
'many2many' => $this->many2many,
124-
'indexes' => $this->prepareIndexes($this->schema->getIndexes()),
126+
'indexes' => $this->prepareIndexes($this->componentSchema->getIndexes()),
125127
//For valid primary keys for junction tables
126128
'junctionCols' => $this->isJunctionSchema ? $this->junctions->junctionCols($this->schemaName) : [],
127-
'isNotDb' => $this->schema->isNonDb(),
129+
'isNotDb' => $this->componentSchema->isNonDb(),
128130
],
129131
]);
130132
}
@@ -185,7 +187,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo
185187
'relatedSchemaName' => $junkAttribute['relatedClassName'],
186188
'tableName' => $this->tableName,
187189
'relatedTableName' => $junkAttribute['relatedTableName'],
188-
'pkAttribute' => $this->attributes[$this->schema->getPkName()],
190+
'pkAttribute' => $this->attributes[$this->componentSchema->getPkName()],
189191
'hasViaModel' => true,
190192
'viaModelName' => $viaModel,
191193
'viaRelationName' => Inflector::id2camel($junkRef, '_'),
@@ -197,7 +199,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo
197199

198200
$this->relations[Inflector::pluralize($junkRef)] =
199201
Yii::createObject(AttributeRelation::class, [$junkRef, $junkAttribute['junctionTable'], $viaModel])
200-
->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->schema->getPkName()]);
202+
->asHasMany([$junkAttribute['pairProperty'] . '_id' => $this->componentSchema->getPkName()]);
201203
return;
202204
}
203205

@@ -328,7 +330,7 @@ protected function resolveProperty(
328330
AttributeRelation::class,
329331
[$property->getName(), $relatedTableName, $relatedClassName]
330332
)
331-
->asHasMany([$foreignPk => $this->schema->getPkName()]);
333+
->asHasMany([$foreignPk => $this->componentSchema->getPkName()]);
332334
return;
333335
}
334336
$relatedClassName = $property->getRefClassName();
@@ -347,10 +349,10 @@ protected function resolveProperty(
347349
AttributeRelation::class,
348350
[$property->getName(), $relatedTableName, $relatedClassName]
349351
)
350-
->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->schema->getPkName()]);
352+
->asHasMany([Inflector::camel2id($this->schemaName, '_') . '_id' => $this->componentSchema->getPkName()]);
351353
return;
352354
}
353-
if ($this->schema->isNonDb() && $attribute->isReference()) {
355+
if ($this->componentSchema->isNonDb() && $attribute->isReference()) {
354356
$this->attributes[$property->getName()] = $attribute;
355357
return;
356358
}
@@ -398,7 +400,7 @@ protected function catchManyToMany(
398400
'relatedSchemaName' => $relatedSchemaName,
399401
'tableName' => $this->tableName,
400402
'relatedTableName' => $relatedTableName,
401-
'pkAttribute' => $this->attributes[$this->schema->getPkName()],
403+
'pkAttribute' => $this->attributes[$this->componentSchema->getPkName()],
402404
],
403405
]);
404406
$this->many2many[$propertyName] = $relation;
@@ -480,7 +482,7 @@ protected function resolvePropertyRef(PropertySchema $property, Attribute $attri
480482
$fkProperty = new PropertySchema(
481483
$property->getRefSchema()->getSchema(),
482484
$property->getName(),
483-
$this->schema
485+
$this->componentSchema
484486
);
485487
[$min, $max] = $fkProperty->guessMinMax();
486488
$attribute->setPhpType($fkProperty->guessPhpType())

src/lib/Config.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,17 @@ class Config extends BaseObject
109109
*/
110110
public $excludeModels = [];
111111

112+
/**
113+
* @var array Map for custom dbModels
114+
*
115+
* @see DbModel::$scenarioDefaultDescription with acceptedInputs: {scenarioName}, {scenarioConst}, {modelName}.
116+
* @example
117+
* 'dbModel' => [
118+
* 'scenarioDefaultDescription' => "Scenario {scenarioName}",
119+
* ]
120+
*/
121+
public $dbModel = [];
122+
112123
/**
113124
* @var array Map for custom controller names not based on model name for exclusive cases
114125
* @example

src/lib/generators/ModelsGenerator.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ public function generate():CodeFiles
5656
}
5757
foreach ($this->models as $model) {
5858
$className = $model->getClassName();
59+
if (!empty($this->config->dbModel['scenarioDefaultDescription'])) {
60+
$model->scenarioDefaultDescription = $this->config->dbModel['scenarioDefaultDescription'];
61+
}
5962
if ($model->isNotDb === false) {
6063
$this->files->add(new CodeFile(
6164
Yii::getAlias("$modelPath/base/$className.php"),

src/lib/helpers/FormatHelper.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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\helpers;
9+
10+
class FormatHelper
11+
{
12+
/**
13+
* @param string $description
14+
* @param int $spacing
15+
* @return string
16+
*/
17+
public static function getFormattedDescription(string $description, int $spacing = 1): string
18+
{
19+
$descriptionArr = explode("\n", trim($description));
20+
$descriptionArr = array_map(function ($item) {
21+
return $item === '' ? '' : ' ' . $item;
22+
}, $descriptionArr);
23+
return implode("\n".str_repeat(" ", $spacing)."*", $descriptionArr);
24+
}
25+
}

src/lib/items/Attribute.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
namespace cebe\yii2openapi\lib\items;
99

10+
use cebe\yii2openapi\lib\helpers\FormatHelper;
1011
use yii\helpers\VarDumper;
1112
use \Yii;
1213
use cebe\yii2openapi\lib\openapi\PropertySchema;
@@ -295,11 +296,16 @@ public function getMinLength():?int
295296
return $this->limits['minLength'];
296297
}
297298

298-
public function getFormattedDescription():string
299+
/**
300+
* @return string
301+
*/
302+
public function getPropertyAnnotation(): string
299303
{
300-
$comment = $this->columnName.' '.$this->description;
301-
$type = $this->phpType;
302-
return $type.' $'.str_replace("\n", "\n * ", rtrim($comment));
304+
$annotation = $this->phpType . ' $' . $this->columnName;
305+
if (!empty($this->description)) {
306+
$annotation .= FormatHelper::getFormattedDescription($this->description);
307+
}
308+
return $annotation;
303309
}
304310

305311
public function toColumnSchema():ColumnSchema

0 commit comments

Comments
 (0)