Skip to content

Commit 21a702a

Browse files
authored
Merge pull request #21 from siggi-k/faker-controller
faker/refresh
2 parents 9cedc45 + f2192c9 commit 21a702a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: console/commands/FakerController.php

+45
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22

33
namespace console\commands;
44

5+
use Yii;
6+
use yii\base\Model;
57
use yii\console\Controller;
8+
use yii\console\ExitCode;
69
use yii\helpers\Console;
710
use yii\helpers\{FileHelper, VarDumper};
811
use yii\helpers\StringHelper;
@@ -12,6 +15,9 @@
1215
*/
1316
class FakerController extends Controller
1417
{
18+
/**
19+
* Fill tables with fake data
20+
*/
1521
public function actionIndex()
1622
{
1723
$fakers = FileHelper::findFiles(\Yii::getAlias('@common/models'), [
@@ -36,6 +42,45 @@ public function actionIndex()
3642
}
3743
}
3844

45+
/**
46+
* Delete all table contents
47+
*/
48+
public function actionClear($requireConfirm = true): int
49+
{
50+
if ($requireConfirm && !$this->confirm('Do you really want to delete all data?')) {
51+
return ExitCode::OK;
52+
}
53+
54+
$fakers = FileHelper::findFiles(\Yii::getAlias('@common/models'), [
55+
'only' => ['*Faker.php'],
56+
'except' => ['BaseModelFaker.php'],
57+
]);
58+
59+
$sortedFakersModels = static::sortModels($fakers, '\\common\\models\\faker\\');
60+
$sortedFakersModels_DESC = array_reverse($sortedFakersModels);
61+
foreach ($sortedFakersModels_DESC as $modelName) {
62+
/** @var Model $modelClass */
63+
$modelClass = 'common\\models\\base\\'.$modelName;
64+
Yii::$app->db->createCommand()->delete($modelClass::tableName())->execute();
65+
$this->stdout("Data from $modelName was deleted\n");
66+
}
67+
return ExitCode::OK;
68+
}
69+
70+
/**
71+
* Delete all table contents and refill with fake data
72+
*/
73+
public function actionRefresh(): int
74+
{
75+
if (!$this->confirm('Do you really want to delete all data and generate new fake data?')) {
76+
return ExitCode::OK;
77+
}
78+
79+
$this->actionClear(false);
80+
$this->actionIndex();
81+
return ExitCode::OK;
82+
}
83+
3984
public static function sortModels(array $fakers, string $fakerNamespace = 'app\\models\\')
4085
{
4186
$modelsDependencies = [];

0 commit comments

Comments
 (0)