Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Bug: allOf with description #51 #55

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
},
"require": {
"php": "^7.4 || ^8.0",
"cebe/php-openapi": "^1.5.0",
"cebe/php-openapi": "dev-165-better-way-to-resolve-allof",
"yiisoft/yii2": "~2.0.48",
"yiisoft/yii2-gii": "~2.0.0 | ~2.1.0 | ~2.2.0| ~2.3.0",
"laminas/laminas-code": ">=3.4 <=4.13",
Expand Down Expand Up @@ -58,6 +58,10 @@
{
"type": "composer",
"url": "https://asset-packagist.org"
},
{
"type": "vcs",
"url": "http://github.com/SOHELAHMED7/php-openapi"
}
]
}
5 changes: 3 additions & 2 deletions src/generator/ApiGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ public function makeConfig():Config
unset($props[$key]);
}
$this->config = new Config($props);
$this->config->resolvedOpenApi = $this->getOpenApiWithoutReferences();
$this->config->setFileRenderer(function ($template, $params) {
return $this->render($template, $params);
});
Expand Down Expand Up @@ -511,9 +512,9 @@ protected function getOpenApiWithoutReferences():OpenApi
if ($this->_openApiWithoutRef === null) {
$file = Yii::getAlias($this->openApiPath);
if (StringHelper::endsWith($this->openApiPath, '.json', false)) {
$this->_openApiWithoutRef = Reader::readFromJsonFile($file, OpenApi::class, true);
$this->_openApiWithoutRef = Reader::readFromJsonFile($file, OpenApi::class, true, true);
} else {
$this->_openApiWithoutRef = Reader::readFromYamlFile($file, OpenApi::class, true);
$this->_openApiWithoutRef = Reader::readFromYamlFile($file, OpenApi::class, true, true);
}
}
return $this->_openApiWithoutRef;
Expand Down
8 changes: 4 additions & 4 deletions src/generator/default/dbmodel.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
*/
abstract class <?= $model->getClassName() ?> extends \yii\db\ActiveRecord
{
<?php if($scenarios = $model->getScenarios()):
foreach($scenarios as $scenario): ?>
<?php if ($scenarios = $model->getScenarios()):
foreach ($scenarios as $scenario): ?>
/**
*<?= $scenario['description'] ?>

Expand All @@ -76,7 +76,7 @@ public static function tableName()
{
return <?= var_export($model->getTableAlias()) ?>;
}
<?php if($scenarios): ?>
<?php if ($scenarios): ?>

/**
* Automatically generated scenarios from the model 'x-scenarios'.
Expand All @@ -92,7 +92,7 @@ public function scenarios()
$default = parent::scenarios()[self::SCENARIO_DEFAULT];

return [
<?php foreach($scenarios as $scenario): ?>
<?php foreach ($scenarios as $scenario): ?>
self::<?= $scenario['const'] ?> => $default,
<?php endforeach; ?>
/**
Expand Down
38 changes: 28 additions & 10 deletions src/lib/AttributeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,18 @@ class AttributeResolver
/** @var Config */
private $config;

public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null)
{
public $resolvedComponentSchema;

public function __construct(
string $schemaName,
ComponentSchema $schema,
JunctionSchemas $junctions,
?Config $config = null,
$resolvedComponentSchema = null
) {
$this->schemaName = $schemaName;
$this->componentSchema = $schema;
$this->resolvedComponentSchema = $resolvedComponentSchema;
$this->tableName = $schema->resolveTableName($schemaName);
$this->junctions = $junctions;
$this->isJunctionSchema = $junctions->isJunctionSchema($schemaName);
Expand All @@ -94,9 +102,18 @@ public function __construct(string $schemaName, ComponentSchema $schema, Junctio
*/
public function resolve():DbModel
{
foreach ($this->componentSchema->getProperties() as $property) {
foreach ($this->componentSchema->getProperties() as $key => $property) {
/** @var $property \cebe\yii2openapi\lib\openapi\PropertySchema */

$resolvedProperty = null;
if ($this->resolvedComponentSchema) {
foreach ($this->resolvedComponentSchema->getProperties() as $key2 => $prop) {
if ($key === $key2) {
$resolvedProperty = $prop;
}
}
}

$isRequired = $this->componentSchema->isRequiredProperty($property->getName());
$nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null;
if ($nullableValue === false) { // see docs in README regarding NOT NULL, required and nullable
Expand All @@ -106,9 +123,9 @@ public function resolve():DbModel
if ($this->isJunctionSchema) {
$this->resolveJunctionTableProperty($property, $isRequired);
} elseif ($this->hasMany2Many) {
$this->resolveHasMany2ManyTableProperty($property, $isRequired);
$this->resolveHasMany2ManyTableProperty($property, $isRequired, $resolvedProperty);
} else {
$this->resolveProperty($property, $isRequired, $nullableValue);
$this->resolveProperty($property, $isRequired, $nullableValue, $resolvedProperty);
}
}
return Yii::createObject(DbModel::class, [
Expand Down Expand Up @@ -169,7 +186,7 @@ protected function resolveJunctionTableProperty(PropertySchema $property, bool $
* @throws \cebe\yii2openapi\lib\exceptions\InvalidDefinitionException
* @throws \yii\base\InvalidConfigException
*/
protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bool $isRequired):void
protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bool $isRequired, $resolvedProperty = null):void
{
if ($this->junctions->isManyToManyProperty($this->schemaName, $property->getName())) {
return;
Expand Down Expand Up @@ -203,7 +220,7 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo
return;
}

$this->resolveProperty($property, $isRequired);
$this->resolveProperty($property, $isRequired, $resolvedProperty);
}

/**
Expand All @@ -216,14 +233,15 @@ protected function resolveHasMany2ManyTableProperty(PropertySchema $property, bo
protected function resolveProperty(
PropertySchema $property,
bool $isRequired,
$nullableValue = 'ARG_ABSENT'
$nullableValue = 'ARG_ABSENT',
$resolvedProperty = null
):void {
if ($nullableValue === 'ARG_ABSENT') {
$nullableValue = $property->getProperty()->getSerializableData()->nullable ?? null;
}
$attribute = Yii::createObject(Attribute::class, [$property->getName()]);
$attribute->setRequired($isRequired)
->setDescription($property->getAttr('description', ''))
->setDescription($resolvedProperty ? $resolvedProperty->getAttr('description', '') : $property->getAttr('description', ''))
->setReadOnly($property->isReadonly())
->setDefault($property->guessDefault())
->setXDbType($property->getAttr(CustomSpecAttr::DB_TYPE))
Expand Down Expand Up @@ -262,7 +280,7 @@ protected function resolveProperty(
$attribute->setPhpType($fkProperty->guessPhpType())
->setDbType($fkProperty->guessDbType(true))
->setSize($fkProperty->getMaxLength())
->setDescription($property->getRefSchema()->getDescription())
->setDescription($resolvedProperty ? $resolvedProperty->getAttr('description', '') : $property->getRefSchema()->getDescription())
->setDefault($fkProperty->guessDefault())
->setLimits($min, $max, $fkProperty->getMinLength());

Expand Down
2 changes: 2 additions & 0 deletions src/lib/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ class Config extends BaseObject
*/
private $openApi;

public $resolvedOpenApi;

/**
* @return \cebe\openapi\spec\OpenApi
* @throws \cebe\openapi\exceptions\IOException
Expand Down
3 changes: 2 additions & 1 deletion src/lib/SchemaToDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public function prepareModels():array
$junctions = $this->findJunctionSchemas();
foreach ($openApi->components->schemas as $schemaName => $openApiSchema) {
$schema = Yii::createObject(ComponentSchema::class, [$openApiSchema, $schemaName]);
$resolvedComponentSchema = Yii::createObject(ComponentSchema::class, [$this->config->resolvedOpenApi->components->schemas[$schemaName], $schemaName]);

if (!$this->canGenerateModel($schemaName, $schema)) {
continue;
Expand All @@ -89,7 +90,7 @@ public function prepareModels():array
$schemaName = $junctions->trimPrefix($schemaName);
}
/**@var \cebe\yii2openapi\lib\AttributeResolver $resolver */
$resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]);
$resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config, $resolvedComponentSchema]);
$models[$schemaName] = $resolver->resolve();
}
foreach ($models as $model) {
Expand Down
8 changes: 4 additions & 4 deletions tests/specs/blog_jsonapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -690,8 +690,8 @@ components:
included:
type: array
items:
allOf:
- $ref: '#/components/schemas/_PostResource'
# allOf: # TODO undo
$ref: '#/components/schemas/_PostResource'
CategoryCreatedResponse:
description: Single category info
headers:
Expand Down Expand Up @@ -806,8 +806,8 @@ components:
included:
type: array
items:
allOf:
- $ref: '#/components/schemas/_PostResource'
# allOf: # TODO undo
$ref: '#/components/schemas/_PostResource'
PostListResponse:
description: List posts with pagination
content:
Expand Down
14 changes: 14 additions & 0 deletions tests/specs/issue_fix/51_bug_allof_with_description/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

return [
'openApiPath' => '@specs/issue_fix/51_bug_allof_with_description/index.yml',
'generateUrls' => true,
'generateModels' => true,
'excludeModels' => [
'Error',
],
'generateControllers' => true,
'generateMigrations' => true,
'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true`
];

29 changes: 29 additions & 0 deletions tests/specs/issue_fix/51_bug_allof_with_description/index.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
openapi: 3.0.3

info:
title: 'Bug: allOf with description #51'
version: 1.0.0

components:
schemas:
Invoice:
title: Invoice
x-table: invoices
type: object
properties:
id:
type: integer
description: The PK
reference_invoice:
allOf:
- $ref: '#/components/schemas/Invoice'
- x-faker: false
- description: This field is only set on invoices of type "cancellation_invoice"


paths:
'/':
get:
responses:
'200':
description: OK
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
/**
* OpenAPI UrlRules
*
* This file is auto generated.
*/
return [
'GET ' => 'default/',
'' => 'default/options',
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace app\controllers;

class DefaultController extends \app\controllers\base\DefaultController
{

public function checkAccess($action, $model = null, $params = [])
{
//TODO implement checkAccess
}

public function action()
{
//TODO implement action
}


}

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace app\controllers\base;

abstract class DefaultController extends \yii\rest\Controller
{
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}

/**
* Checks the privilege of the current user.
*
* This method checks whether the current user has the privilege
* to run the specified action against the specified data model.
* If the user does not have access, a [[ForbiddenHttpException]] should be thrown.
*
* @param string $action the ID of the action to be executed
* @param object $model the model to be accessed. If null, it means no specific model is being accessed.
* @param array $params additional parameters
* @throws \yii\web\ForbiddenHttpException if the user does not have access
*/
abstract public function checkAccess($action, $model = null, $params = []);

abstract public function action();

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

/**
* Table for Invoice
*/
class m200000_000000_create_table_invoices extends \yii\db\Migration
{
public function up()
{
$this->createTable('{{%invoices}}', [
'id' => $this->primaryKey(),
'reference_invoice_id' => $this->integer()->null()->defaultValue(null),
]);
$this->addForeignKey('fk_invoices_reference_invoice_id_invoices_id', '{{%invoices}}', 'reference_invoice_id', '{{%invoices}}', 'id');
}

public function down()
{
$this->dropForeignKey('fk_invoices_reference_invoice_id_invoices_id', '{{%invoices}}');
$this->dropTable('{{%invoices}}');
}
}
Loading
Loading