2
2
3
3
namespace console \commands ;
4
4
5
+ use Yii ;
6
+ use yii \base \Model ;
5
7
use yii \console \Controller ;
8
+ use yii \console \ExitCode ;
6
9
use yii \helpers \Console ;
7
10
use yii \helpers \{FileHelper , VarDumper };
8
11
use yii \helpers \StringHelper ;
12
15
*/
13
16
class FakerController extends Controller
14
17
{
18
+ /**
19
+ * Fill tables with fake data
20
+ */
15
21
public function actionIndex ()
16
22
{
17
23
$ fakers = FileHelper::findFiles (\Yii::getAlias ('@common/models ' ), [
@@ -36,6 +42,45 @@ public function actionIndex()
36
42
}
37
43
}
38
44
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
+
39
84
public static function sortModels (array $ fakers , string $ fakerNamespace = 'app \\models \\' )
40
85
{
41
86
$ modelsDependencies = [];
0 commit comments