Skip to content

Resolve Model name generated more than once in Faker #25

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

Merged
merged 6 commits into from
May 31, 2023
Merged
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
5 changes: 3 additions & 2 deletions src/generator/default/faker.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* @var \cebe\yii2openapi\lib\items\DbModel $model
* @var string $namespace
* @var string $modelNamespace
* @var array $deps list of all models that this model is dependent on
**/

$modelClass = ($modelNamespace !== $namespace ? '\\'.trim($modelNamespace, '\\').'\\' : '').$model->getClassName();
Expand Down Expand Up @@ -68,8 +69,8 @@ public static function dependentOn()
{
return [
// just model class names
<?php foreach ($model->hasOneRelations as $key => $hasOneRelation): ?>
<?php echo \yii\helpers\VarDumper::export($model->hasOneRelations[$key]->getClassName()).','.PHP_EOL ?>
<?php foreach ($deps as $dep): ?>
<?php echo \yii\helpers\VarDumper::export($dep).','.PHP_EOL ?>
<?php endforeach; ?>

];
Expand Down
7 changes: 7 additions & 0 deletions src/lib/generators/ModelsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ public function generate():CodeFiles
)
));
if ($this->config->generateModelFaker) {
$deps = []; # list of all models that this model is dependent on
foreach ($model->hasOneRelations as $key => $hasOneRelation) {
$deps[] = $model->hasOneRelations[$key]->getClassName();
}
$deps = array_unique($deps);

$this->files->add(new CodeFile(
Yii::getAlias("$fakerPath/{$className}Faker.php"),
$this->config->render(
Expand All @@ -77,6 +83,7 @@ public function generate():CodeFiles
'model' => $model,
'modelNamespace' => $this->config->modelNamespace,
'namespace' => $this->config->fakerNamespace,
'deps' => $deps,
]
)
));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace app\models;

class Account extends \app\models\base\Account
{


}

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php
namespace app\models;

use Faker\UniqueGenerator;

/**
* Fake data generator for Account
* @method static Account makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null);
* @method static Account saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null);
* @method static Account[] make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null)
* @method static Account[] save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null)
*/
class AccountFaker extends BaseModelFaker
{

/**
* @param array|callable $attributes
* @return Account|\yii\db\ActiveRecord
* @example
* $model = (new PostFaker())->generateModels(['author_id' => 1]);
* $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) {
* $model->scenario = 'create';
* $model->author_id = 1;
* return $model;
* });
**/
public function generateModel($attributes = [])
{
$faker = $this->faker;
$uniqueFaker = $this->uniqueFaker;
$model = new Account();
//$model->id = $uniqueFaker->numberBetween(0, 1000000);
$model->name = substr($faker->userName(), 0, 40);
if (!is_callable($attributes)) {
$model->setAttributes($attributes, false);
} else {
$model = $attributes($model, $faker, $uniqueFaker);
}
return $model;
}
}
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 E123 extends \app\models\base\E123
{


}

Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
namespace app\models;

use Faker\UniqueGenerator;

/**
* Fake data generator for E123
* @method static E123 makeOne($attributes = [], ?UniqueGenerator $uniqueFaker = null);
* @method static E123 saveOne($attributes = [], ?UniqueGenerator $uniqueFaker = null);
* @method static E123[] make(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null)
* @method static E123[] save(int $number, $commonAttributes = [], ?UniqueGenerator $uniqueFaker = null)
*/
class E123Faker extends BaseModelFaker
{

/**
* @param array|callable $attributes
* @return E123|\yii\db\ActiveRecord
* @example
* $model = (new PostFaker())->generateModels(['author_id' => 1]);
* $model = (new PostFaker())->generateModels(function($model, $faker, $uniqueFaker) {
* $model->scenario = 'create';
* $model->author_id = 1;
* return $model;
* });
**/
public function generateModel($attributes = [])
{
$faker = $this->faker;
$uniqueFaker = $this->uniqueFaker;
$model = new E123();
//$model->id = $uniqueFaker->numberBetween(0, 1000000);
$model->name = $faker->sentence;
$model->account_id = $faker->randomElement(\app\models\Account::find()->select("id")->column());
$model->account_2_id = $faker->randomElement(\app\models\Account::find()->select("id")->column());
$model->account_3_id = $faker->randomElement(\app\models\Account::find()->select("id")->column());
if (!is_callable($attributes)) {
$model->setAttributes($attributes, false);
} else {
$model = $attributes($model, $faker, $uniqueFaker);
}
return $model;
}

public static function dependentOn()
{
return [
// just model class names
'Account',

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

namespace app\models\base;

/**
* user account
*
* @property int $id
* @property string $name account name
*
*/
abstract class Account extends \yii\db\ActiveRecord
{
public static function tableName()
{
return '{{%accounts}}';
}

public function rules()
{
return [
'trim' => [['name'], 'trim'],
'required' => [['name'], 'required'],
'name_string' => [['name'], 'string', 'max' => 40],
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace app\models\base;

/**
* desc
*
* @property int $id
* @property string $name
* @property int $account_id user account
* @property int $account_2_id user account
* @property int $account_3_id user account
*
* @property \app\models\Account $account
* @property \app\models\Account $account2
* @property \app\models\Account $account3
*/
abstract class E123 extends \yii\db\ActiveRecord
{
public static function tableName()
{
return '{{%e123s}}';
}

public function rules()
{
return [
'trim' => [['name'], 'trim'],
'account_id_integer' => [['account_id'], 'integer'],
'account_id_exist' => [['account_id'], 'exist', 'targetRelation' => 'Account'],
'account_2_id_integer' => [['account_2_id'], 'integer'],
'account_2_id_exist' => [['account_2_id'], 'exist', 'targetRelation' => 'Account2'],
'account_3_id_integer' => [['account_3_id'], 'integer'],
'account_3_id_exist' => [['account_3_id'], 'exist', 'targetRelation' => 'Account3'],
'name_string' => [['name'], 'string'],
];
}

public function getAccount()
{
return $this->hasOne(\app\models\Account::class, ['id' => 'account_id']);
}

public function getAccount2()
{
return $this->hasOne(\app\models\Account::class, ['id' => 'account_2_id']);
}

public function getAccount3()
{
return $this->hasOne(\app\models\Account::class, ['id' => 'account_3_id']);
}
}
Loading