diff --git a/console/commands/FakerController.php b/console/commands/FakerController.php index 8cf8b65..2e6e744 100644 --- a/console/commands/FakerController.php +++ b/console/commands/FakerController.php @@ -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; @@ -12,6 +15,9 @@ */ class FakerController extends Controller { + /** + * Fill tables with fake data + */ public function actionIndex() { $fakers = FileHelper::findFiles(\Yii::getAlias('@common/models'), [ @@ -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 = [];