Skip to content

Consider OpenAPI extension x-no-relation also in other pertinent place #86

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

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ related objects, `x-no-relation` (type: boolean, default: false) is used.

This will not generate 'comments' column in database migrations. But it will generate `getComments()` relation in Yii model file.

In order to make it real database column, extension `x-no-relation` can be used.
In order to make it real database column, OpenAPI extension `x-no-relation` can be used.

```yaml
comments:
Expand Down
5 changes: 1 addition & 4 deletions src/lib/ValidationRulesBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,7 @@ private function prepareTypeScope():void
if ($attribute->isReadOnly()) {
continue;
}
// column/field/property with name `id` is considered as Primary Key by this library, and it is automatically handled by DB/Yii; so remove it from validation `rules()`
if (in_array($attribute->columnName, ['id', $this->model->pkName]) ||
in_array($attribute->propertyName, ['id', $this->model->pkName])
) {
if ($this->isIdColumn($attribute)) {
continue;
}
if (/*$attribute->defaultValue === null &&*/ $attribute->isRequired()) {
Expand Down
6 changes: 3 additions & 3 deletions src/lib/openapi/ComponentSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
use cebe\yii2openapi\lib\SchemaToDatabase;
use Generator;
use Yii;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use function in_array;

class ComponentSchema
Expand Down Expand Up @@ -106,7 +104,9 @@ public function isRequiredProperty(string $propName):bool

public function isNonDb():bool
{
return isset($this->schema->{CustomSpecAttr::TABLE}) && $this->schema->{CustomSpecAttr::TABLE} === false;
return
isset($this->schema->{CustomSpecAttr::TABLE}) &&
$this->schema->{CustomSpecAttr::TABLE} === false;
}

public function resolveTableName(string $schemaName):string
Expand Down
6 changes: 6 additions & 0 deletions src/lib/openapi/PropertySchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ public function __construct(SpecObjectInterface $property, string $name, Compone
$property = $this->property;
}

// don't go reference part if `x-no-relation` is true
if ($this->getAttr(CustomSpecAttr::NO_RELATION)) {
return;
}

if ($property instanceof Reference) {
$this->initReference();
} elseif (
Expand Down Expand Up @@ -497,6 +502,7 @@ public function guessDbType($forReference = false):string
}
return YiiDbSchema::TYPE_TEXT;
case 'object':
case 'array':
{
return YiiDbSchema::TYPE_JSON;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@ public function up()
'id' => $this->primaryKey(),
'name' => $this->text()->notNull(),
'age' => $this->integer()->null()->defaultValue(null),
'tags' => $this->text()->null(),
'tags_arbit' => $this->text()->null(),
'number_arr' => $this->text()->null(),
'number_arr_min_uniq' => $this->text()->null(),
'int_arr' => $this->text()->null(),
'int_arr_min_uniq' => $this->text()->null(),
'bool_arr' => $this->text()->null(),
'arr_arr_int' => $this->text()->null(),
'arr_arr_str' => $this->text()->null(),
'arr_arr_arr_str' => $this->text()->null(),
'arr_of_obj' => $this->text()->null(),
'user_ref_obj_arr' => $this->string()->null()->defaultValue(null),
'one_of_arr' => $this->text()->null(),
'one_of_arr_complex' => $this->text()->null(),
'one_of_from_multi_ref_arr' => $this->text()->null(),
'tags' => 'json NOT NULL',
'tags_arbit' => 'json NOT NULL',
'number_arr' => 'json NOT NULL',
'number_arr_min_uniq' => 'json NOT NULL',
'int_arr' => 'json NOT NULL',
'int_arr_min_uniq' => 'json NOT NULL',
'bool_arr' => 'json NOT NULL',
'arr_arr_int' => 'json NOT NULL',
'arr_arr_str' => 'json NOT NULL',
'arr_arr_arr_str' => 'json NOT NULL',
'arr_of_obj' => 'json NOT NULL',
'user_ref_obj_arr' => 'json NOT NULL',
'one_of_arr' => 'json NOT NULL',
'one_of_arr_complex' => 'json NOT NULL',
'one_of_from_multi_ref_arr' => 'json NOT NULL',
]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@
* @property array $arr_arr_str
* @property array $arr_arr_arr_str
* @property array $arr_of_obj
* @property User[] $user_ref_obj_arr
* @property array $user_ref_obj_arr
* @property array $one_of_arr
* @property array $one_of_arr_complex
* @property array $one_of_from_multi_ref_arr
*
* @property array|\app\models\User[] $userRefObjArrNormal
* @property array|\app\models\User[] $userRefObjArr
*/
abstract class Pet extends \yii\db\ActiveRecord
{
Expand All @@ -53,9 +52,4 @@ public function getUserRefObjArrNormal()
{
return $this->hasMany(\app\models\User::class, ['pet_id' => 'id'])->inverseOf('pet');
}

public function getUserRefObjArr()
{
return $this->hasMany(\app\models\User::class, ['pet_id' => 'id'])->inverseOf('pet');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

return [
'openApiPath' => '@specs/issue_fix/23_consider_openapi_extension_x_no_relation_also_in_other_pertinent_place/index.yaml',
'generateUrls' => false,
'generateModels' => true,
'excludeModels' => [
'Error',
],
'generateControllers' => false,
'generateMigrations' => true,
'generateModelFaker' => true, // `generateModels` must be `true` in order to use `generateModelFaker` as `true`
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
openapi: 3.0.3

info:
title: '#23'
version: 1.0.0

paths:
/:
get:
responses:
'200':
description: The Response



components:
schemas:
Payments:
properties:
id:
type: integer
currency:
type: string
samples:
type: array
x-no-relation: true
items:
$ref: '#/components/schemas/Sample'

Sample:
properties:
id:
type: integer
message:
type: string
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* Table for Payments
*/
class m200000_000000_create_table_payments extends \yii\db\Migration
{
public function up()
{
$this->createTable('{{%payments}}', [
'id' => $this->primaryKey(),
'currency' => $this->text()->null(),
'samples' => 'json NOT NULL',
]);
}

public function down()
{
$this->dropTable('{{%payments}}');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/**
* Table for Sample
*/
class m200000_000001_create_table_samples extends \yii\db\Migration
{
public function up()
{
$this->createTable('{{%samples}}', [
'id' => $this->primaryKey(),
'message' => $this->text()->null(),
]);
}

public function down()
{
$this->dropTable('{{%samples}}');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

namespace app\models;

use Faker\Factory as FakerFactory;
use Faker\Generator;
use Faker\UniqueGenerator;

/**
* Base fake data generator
*/
abstract class BaseModelFaker
{
/**
* @var Generator
*/
protected $faker;
/**
* @var UniqueGenerator
*/
protected $uniqueFaker;

public function __construct()
{
$this->faker = FakerFactory::create(str_replace('-', '_', \Yii::$app->language));
$this->uniqueFaker = new UniqueGenerator($this->faker);
}

abstract public function generateModel($attributes = []);

public function getFaker():Generator
{
return $this->faker;
}

public function getUniqueFaker():UniqueGenerator
{
return $this->uniqueFaker;
}

public function setFaker(Generator $faker):void
{
$this->faker = $faker;
}

public function setUniqueFaker(UniqueGenerator $faker):void
{
$this->uniqueFaker = $faker;
}

/**
* Generate and return model
* @param array|callable $attributes
* @param UniqueGenerator|null $uniqueFaker
* @return \yii\db\ActiveRecord
* @example MyFaker::makeOne(['user_id' => 1, 'title' => 'foo']);
* @example MyFaker::makeOne( function($model, $faker) {
* $model->scenario = 'create';
* $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]);
* return $model;
* });
*/
public static function makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null)
{
$fakeBuilder = new static();
if ($uniqueFaker !== null) {
$fakeBuilder->setUniqueFaker($uniqueFaker);
}
$model = $fakeBuilder->generateModel($attributes);
return $model;
}

/**
* Generate, save and return model
* @param array|callable $attributes
* @param UniqueGenerator|null $uniqueFaker
* @return \yii\db\ActiveRecord
* @example MyFaker::saveOne(['user_id' => 1, 'title' => 'foo']);
* @example MyFaker::saveOne( function($model, $faker) {
* $model->scenario = 'create';
* $model->setAttributes(['user_id' => 1, 'title' => $faker->sentence]);
* return $model;
* });
*/
public static function saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null)
{
$model = static::makeOne($attributes, $uniqueFaker);
$model->save();
return $model;
}

/**
* Generate and return multiple models
* @param int $number
* @param array|callable $commonAttributes
* @return \yii\db\ActiveRecord[]|array
* @example TaskFaker::make(5, ['project_id'=>1, 'user_id' => 2]);
* @example TaskFaker::make(5, function($model, $faker, $uniqueFaker) {
* $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]);
* return $model;
* });
*/
public static function make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array
{
if ($number < 1) {
return [];
}
$fakeBuilder = new static();
if ($uniqueFaker !== null) {
$fakeBuilder->setUniqueFaker($uniqueFaker);
}
return array_map(function () use ($commonAttributes, $fakeBuilder) {
$model = $fakeBuilder->generateModel($commonAttributes);
return $model;
}, range(0, $number -1));
}

/**
* Generate, save and return multiple models
* @param int $number
* @param array|callable $commonAttributes
* @return \yii\db\ActiveRecord[]|array
* @example TaskFaker::save(5, ['project_id'=>1, 'user_id' => 2]);
* @example TaskFaker::save(5, function($model, $faker, $uniqueFaker) {
* $model->setAttributes(['name' => $uniqueFaker->username, 'state'=>$faker->boolean(20)]);
* return $model;
* });
*/
public static function save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null):array
{
if ($number < 1) {
return [];
}
$fakeBuilder = new static();
if ($uniqueFaker !== null) {
$fakeBuilder->setUniqueFaker($uniqueFaker);
}
return array_map(function () use ($commonAttributes, $fakeBuilder) {
$model = $fakeBuilder->generateModel($commonAttributes);
$model->save();
return $model;
}, range(0, $number -1));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace app\models;

class Payments extends \app\models\base\Payments
{


}

Loading