22
33namespace console \commands ;
44
5+ use Yii ;
6+ use yii \base \Model ;
57use yii \console \Controller ;
8+ use yii \console \ExitCode ;
69use yii \helpers \Console ;
710use yii \helpers \{FileHelper , VarDumper };
811use yii \helpers \StringHelper ;
1215 */
1316class 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