Skip to content

Commit d9f4310

Browse files
authored
Merge pull request #18 from SOHELAHMED7/enhance-faker-to-consider-relations
Resolve - Enhance faker generation to consider DB relations
2 parents 82f04d4 + 21ec09c commit d9f4310

File tree

63 files changed

+1602
-24
lines changed

Some content is hidden

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

63 files changed

+1602
-24
lines changed

src/generator/default/faker.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,9 @@ public function generateModel($attributes = [])
4343
{
4444
$faker = $this->faker;
4545
$uniqueFaker = $this->uniqueFaker;
46-
$model = new <?= $model->getClassName() ?>();
46+
$model = new <?= $modelClass ?>();
4747
<?php foreach ($model->attributes as $attribute):
48-
if (!$attribute->fakerStub || $attribute->isReference()) {
48+
if (!$attribute->fakerStub /*|| $attribute->isReference()*/) {
4949
continue;
5050
}
5151
?>
@@ -62,4 +62,17 @@ public function generateModel($attributes = [])
6262
}
6363
return $model;
6464
}
65+
<?php if ($model->hasOneRelations):?>
66+
67+
public static function dependentOn()
68+
{
69+
return [
70+
// just model class names
71+
<?php foreach ($model->hasOneRelations as $key => $hasOneRelation): ?>
72+
<?php echo \yii\helpers\VarDumper::export($model->hasOneRelations[$key]->getClassName()).','.PHP_EOL ?>
73+
<?php endforeach; ?>
74+
75+
];
76+
}
77+
<?php endif;?>
6578
}

src/lib/AttributeResolver.php

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

88
namespace cebe\yii2openapi\lib;
99

10+
use cebe\yii2openapi\lib\Config;
1011
use cebe\yii2openapi\lib\CustomSpecAttr;
1112
use cebe\yii2openapi\lib\exceptions\InvalidDefinitionException;
1213
use cebe\yii2openapi\lib\items\Attribute;
@@ -66,20 +67,24 @@ class AttributeResolver
6667
*/
6768
private $junctions;
6869

69-
/**@var bool */
70+
/** @var bool */
7071
private $isJunctionSchema;
7172

72-
/**@var bool */
73+
/** @var bool */
7374
private $hasMany2Many;
7475

75-
public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions)
76+
/** @var Config */
77+
private $config;
78+
79+
public function __construct(string $schemaName, ComponentSchema $schema, JunctionSchemas $junctions, ?Config $config = null)
7680
{
7781
$this->schemaName = $schemaName;
7882
$this->schema = $schema;
7983
$this->tableName = $schema->resolveTableName($schemaName);
8084
$this->junctions = $junctions;
8185
$this->isJunctionSchema = $junctions->isJunctionSchema($schemaName);
8286
$this->hasMany2Many = $junctions->hasMany2Many($schemaName);
87+
$this->config = $config;
8388
}
8489

8590
/**
@@ -391,7 +396,7 @@ protected function catchManyToMany(
391396
*/
392397
protected function guessFakerStub(Attribute $attribute, PropertySchema $property):?string
393398
{
394-
$resolver = Yii::createObject(['class' => FakerStubResolver::class], [$attribute, $property]);
399+
$resolver = Yii::createObject(['class' => FakerStubResolver::class], [$attribute, $property, $this->config]);
395400
return $resolver->resolve();
396401
}
397402

src/lib/FakerStubResolver.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,14 @@ class FakerStubResolver
3232
*/
3333
private $property;
3434

35-
public function __construct(Attribute $attribute, PropertySchema $property)
35+
/** @var Config */
36+
private $config;
37+
38+
public function __construct(Attribute $attribute, PropertySchema $property, ?Config $config = null)
3639
{
3740
$this->attribute = $attribute;
3841
$this->property = $property;
42+
$this->config = $config;
3943
}
4044

4145
public function resolve():?string
@@ -46,6 +50,14 @@ public function resolve():?string
4650
if ($this->attribute->isReadOnly() && $this->attribute->isVirtual()) {
4751
return null;
4852
}
53+
54+
// column name ends with `_id`
55+
if (substr($this->attribute->columnName, -strlen('_id'))==='_id') {
56+
return '$faker->randomElement(\\'.$this->config->modelNamespace
57+
. ($this->config->modelNamespace ? '\\' : '')
58+
. ucfirst($this->attribute->reference).'::find()->select("id")->column())';
59+
}
60+
4961
$limits = $this->attribute->limits;
5062
switch ($this->attribute->phpType) {
5163
case 'bool':

src/lib/SchemaToDatabase.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public function prepareModels():array
8989
$schemaName = $junctions->trimPrefix($schemaName);
9090
}
9191
/**@var \cebe\yii2openapi\lib\AttributeResolver $resolver */
92-
$resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions]);
92+
$resolver = Yii::createObject(AttributeResolver::class, [$schemaName, $schema, $junctions, $this->config]);
9393
$models[$schemaName] = $resolver->resolve();
9494
}
9595
foreach ($models as $model) {

tests/DbTestCase.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ protected function checkFiles(array $actual, array $expected)
101101
self::assertFileExists($file);
102102
self::assertFileExists($expectedFilePath);
103103

104-
$this->assertFileEquals($expectedFilePath, $file, "Failed asserting that file contents of\n$file\nare equal to file contents of\n$expectedFilePath");
104+
$this->assertFileEquals($expectedFilePath, $file, "Failed asserting that file contents of\n$file\nare equal to file contents of\n$expectedFilePath \n\n cp $file $expectedFilePath \n\n ");
105105
}
106106
}
107107

tests/fixtures/blog.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,13 @@
7373
->asReference('Category')
7474
->setRequired()
7575
->setDescription('Category of posts')
76-
->setFakerStub('$uniqueFaker->numberBetween(0, 1000000)'),
76+
->setFakerStub('$faker->randomElement(\Category::find()->select("id")->column())'),
7777
'created_at' => (new Attribute('created_at', ['phpType' => 'string', 'dbType' => 'date']))
7878
->setFakerStub('$faker->dateTimeThisCentury->format(\'Y-m-d\')'),
7979
'created_by' => (new Attribute('created_by', ['phpType' => 'int', 'dbType' => 'integer']))
8080
->asReference('User')
8181
->setDescription('The User')
82-
->setFakerStub('$uniqueFaker->numberBetween(0, 1000000)'),
82+
->setFakerStub('$faker->randomElement(\User::find()->select("id")->column())'),
8383
],
8484
'relations' => [
8585
'category' => new AttributeRelation('category',
@@ -110,12 +110,12 @@
110110
->setSize(128)
111111
->asReference('Post')
112112
->setDescription('A blog post (uid used as pk for test purposes)')
113-
->setFakerStub('substr($uniqueFaker->sha256, 0, 128)'),
113+
->setFakerStub('$faker->randomElement(\Post::find()->select("id")->column())'),
114114
'author' => (new Attribute('author', ['phpType' => 'int', 'dbType' => 'integer']))
115115
->setRequired()
116116
->asReference('User')
117117
->setDescription('The User')
118-
->setFakerStub('$uniqueFaker->numberBetween(0, 1000000)'),
118+
->setFakerStub('$faker->randomElement(\User::find()->select("id")->column())'),
119119
'message' => (new Attribute('message', ['phpType' => 'array', 'dbType' => 'json', 'xDbType' => 'json']))
120120
->setRequired()->setDefault([])->setFakerStub('[]'),
121121
'meta_data' => (new Attribute('meta_data', ['phpType' => 'array', 'dbType' => 'json', 'xDbType' => 'json']))

tests/specs/blog/models/CommentFaker.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ public function generateModel($attributes = [])
3030
$uniqueFaker = $this->uniqueFaker;
3131
$model = new Comment();
3232
//$model->id = $uniqueFaker->numberBetween(0, 1000000);
33+
$model->post_id = $faker->randomElement(\app\models\Post::find()->select("id")->column());
34+
$model->author_id = $faker->randomElement(\app\models\User::find()->select("id")->column());
3335
$model->message = [];
3436
$model->meta_data = [];
3537
$model->created_at = $faker->unixTime;
@@ -40,4 +42,14 @@ public function generateModel($attributes = [])
4042
}
4143
return $model;
4244
}
45+
46+
public static function dependentOn()
47+
{
48+
return [
49+
// just model class names
50+
'Post',
51+
'User',
52+
53+
];
54+
}
4355
}

tests/specs/blog/models/PostFaker.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,25 @@ public function generateModel($attributes = [])
3232
$model->uid = substr($uniqueFaker->sha256, 0, 128);
3333
$model->title = substr($faker->sentence, 0, 255);
3434
$model->slug = substr($uniqueFaker->slug, 0, 200);
35+
$model->category_id = $faker->randomElement(\app\models\Category::find()->select("id")->column());
3536
$model->active = $faker->boolean;
3637
$model->created_at = $faker->dateTimeThisCentury->format('Y-m-d');
38+
$model->created_by_id = $faker->randomElement(\app\models\User::find()->select("id")->column());
3739
if (!is_callable($attributes)) {
3840
$model->setAttributes($attributes, false);
3941
} else {
4042
$model = $attributes($model, $faker, $uniqueFaker);
4143
}
4244
return $model;
4345
}
46+
47+
public static function dependentOn()
48+
{
49+
return [
50+
// just model class names
51+
'Category',
52+
'User',
53+
54+
];
55+
}
4456
}

tests/specs/blog_v2/models/CommentFaker.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ public function generateModel($attributes = [])
3030
$uniqueFaker = $this->uniqueFaker;
3131
$model = new Comment();
3232
//$model->id = $uniqueFaker->numberBetween(0, 1000000);
33+
$model->post_id = $faker->randomElement(\app\models\Post::find()->select("id")->column());
34+
$model->user_id = $faker->randomElement(\app\models\User::find()->select("id")->column());
3335
$model->message = $faker->sentence;
3436
$model->meta_data = substr($faker->text(300), 0, 300);
3537
$model->created_at = $faker->dateTimeThisYear('now', 'UTC')->format('Y-m-d H:i:s');
@@ -40,4 +42,14 @@ public function generateModel($attributes = [])
4042
}
4143
return $model;
4244
}
45+
46+
public static function dependentOn()
47+
{
48+
return [
49+
// just model class names
50+
'Post',
51+
'User',
52+
53+
];
54+
}
4355
}

tests/specs/blog_v2/models/PostFaker.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,25 @@ public function generateModel($attributes = [])
3333
$model->title = substr($faker->sentence, 0, 255);
3434
$model->slug = substr($uniqueFaker->slug, 0, 200);
3535
$model->lang = $faker->randomElement(['ru','eng']);
36+
$model->category_id = $faker->randomElement(\app\models\Category::find()->select("id")->column());
3637
$model->active = $faker->boolean;
3738
$model->created_at = $faker->dateTimeThisCentury->format('Y-m-d');
39+
$model->created_by_id = $faker->randomElement(\app\models\User::find()->select("id")->column());
3840
if (!is_callable($attributes)) {
3941
$model->setAttributes($attributes, false);
4042
} else {
4143
$model = $attributes($model, $faker, $uniqueFaker);
4244
}
4345
return $model;
4446
}
47+
48+
public static function dependentOn()
49+
{
50+
return [
51+
// just model class names
52+
'Category',
53+
'User',
54+
55+
];
56+
}
4557
}

0 commit comments

Comments
 (0)