Skip to content

Commit

Permalink
Merge pull request #21 from siggi-k/faker-controller
Browse files Browse the repository at this point in the history
faker/refresh
  • Loading branch information
cebe authored Jun 6, 2024
2 parents 9cedc45 + f2192c9 commit 21a702a
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions console/commands/FakerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

namespace console\commands;

use Yii;
use yii\base\Model;
use yii\console\Controller;
use yii\console\ExitCode;
use yii\helpers\Console;
use yii\helpers\{FileHelper, VarDumper};
use yii\helpers\StringHelper;
Expand All @@ -12,6 +15,9 @@
*/
class FakerController extends Controller
{
/**
* Fill tables with fake data
*/
public function actionIndex()
{
$fakers = FileHelper::findFiles(\Yii::getAlias('@common/models'), [
Expand All @@ -36,6 +42,45 @@ public function actionIndex()
}
}

/**
* Delete all table contents
*/
public function actionClear($requireConfirm = true): int
{
if ($requireConfirm && !$this->confirm('Do you really want to delete all data?')) {
return ExitCode::OK;
}

$fakers = FileHelper::findFiles(\Yii::getAlias('@common/models'), [
'only' => ['*Faker.php'],
'except' => ['BaseModelFaker.php'],
]);

$sortedFakersModels = static::sortModels($fakers, '\\common\\models\\faker\\');
$sortedFakersModels_DESC = array_reverse($sortedFakersModels);
foreach ($sortedFakersModels_DESC as $modelName) {
/** @var Model $modelClass */
$modelClass = 'common\\models\\base\\'.$modelName;
Yii::$app->db->createCommand()->delete($modelClass::tableName())->execute();
$this->stdout("Data from $modelName was deleted\n");
}
return ExitCode::OK;
}

/**
* Delete all table contents and refill with fake data
*/
public function actionRefresh(): int
{
if (!$this->confirm('Do you really want to delete all data and generate new fake data?')) {
return ExitCode::OK;
}

$this->actionClear(false);
$this->actionIndex();
return ExitCode::OK;
}

public static function sortModels(array $fakers, string $fakerNamespace = 'app\\models\\')
{
$modelsDependencies = [];
Expand Down

0 comments on commit 21a702a

Please sign in to comment.