Skip to content

Commit 9d86eec

Browse files
author
Igor Chepurnoy
committed
add FindModelTrait, add new commands to the AppController, update actions in the UserController
1 parent 1fbf7ed commit 9d86eec

File tree

6 files changed

+134
-66
lines changed

6 files changed

+134
-66
lines changed

commands/AppController.php

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
namespace app\commands;
44

5+
use app\models\UserModel;
6+
use Yii;
7+
use yii\helpers\Console;
58
use yii2mod\cms\models\CmsModel;
69
use yii2mod\cms\models\enumerables\CmsStatus;
710
use yii2tech\sitemap\File;
@@ -10,7 +13,9 @@
1013
* Class AppController
1114
*
1215
* ~~~
13-
* php yii app/generate-sitemap
16+
* php yii app/generate-sitemap - Sitemap composing
17+
* php yii app/clear-table User - Delete all data from specific table
18+
* php yii app/assign-role-to-user admin [email protected] - Assign role to the user
1419
* ~~~
1520
*
1621
* @package app\commands
@@ -23,13 +28,67 @@ class AppController extends BaseController
2328
public function actionGenerateSitemap()
2429
{
2530
$siteMapFile = new File();
31+
2632
$siteMapFile->writeUrl(['site/index'], ['priority' => '0.9']);
2733
$siteMapFile->writeUrl(['site/contact']);
2834
$pages = CmsModel::find()->where(['status' => CmsStatus::ENABLED])->all();
2935
foreach ($pages as $page) {
3036
$siteMapFile->writeUrl([$page->url]);
3137
}
38+
3239
$siteMapFile->close();
40+
41+
return self::EXIT_CODE_NORMAL;
42+
}
43+
44+
/**
45+
* Delete all data from specific table
46+
*
47+
* @param $tableName
48+
* @return int
49+
*
50+
* @throws \yii\db\Exception
51+
*/
52+
public function actionClearTable($tableName)
53+
{
54+
Yii::$app->db->createCommand()->delete($tableName)->execute();
55+
56+
return self::EXIT_CODE_NORMAL;
57+
}
58+
59+
/**
60+
* Assign role to the user
61+
*
62+
* @param $roleName string user role
63+
* @param $email string user email
64+
* @return int
65+
*/
66+
public function actionAssignRoleToUser($roleName, $email)
67+
{
68+
$authManager = Yii::$app->authManager;
69+
$user = UserModel::findByEmail($email);
70+
$role = $authManager->getRole($roleName);
71+
72+
if (empty($user)) {
73+
$this->stdout("User with `{$email}` does not exists.\n", Console::FG_RED);
74+
return self::EXIT_CODE_ERROR;
75+
}
76+
77+
if (empty($role)) {
78+
$this->stdout("Role `{$roleName}` does not exists.\n", Console::FG_RED);
79+
return self::EXIT_CODE_ERROR;
80+
}
81+
82+
// Check if role is already assigned to the user
83+
if (in_array($roleName, array_keys($authManager->getRolesByUser($user->id)))) {
84+
$this->stdout("Role `{$roleName}` already assigned to this user.\n", Console::FG_BLUE);
85+
return self::EXIT_CODE_NORMAL;
86+
}
87+
88+
$authManager->assign($role, $user->id);
89+
90+
$this->stdout("The role `{$roleName}` has been successfully assigned to the user with email {$email}\n", Console::FG_YELLOW);
91+
92+
return self::EXIT_CODE_NORMAL;
3393
}
34-
}
35-
94+
}

composer.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@
3434
"kartik-v/yii2-widget-sidenav": "*",
3535
"yii2mod/yii2-settings": "*",
3636
"yii2tech/sitemap": "^1.0",
37-
"yii2mod/yii2-scheduling": "*"
37+
"yii2mod/yii2-scheduling": "*",
38+
"yii2tech/admin": "*"
3839
},
3940
"require-dev": {
4041
"yiisoft/yii2-codeception": "*",
@@ -71,4 +72,4 @@
7172
"bower-asset-library": "vendor/bower"
7273
}
7374
}
74-
}
75+
}

modules/admin/controllers/SettingsController.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
*/
1111
class SettingsController extends Controller
1212
{
13-
1413
/**
1514
* @return array
1615
*/
@@ -20,5 +19,4 @@ public function actions()
2019
'cron' => 'yii2mod\cron\actions\CronLogAction',
2120
];
2221
}
23-
24-
}
22+
}

modules/admin/controllers/UserController.php

Lines changed: 28 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,24 @@
33
namespace app\modules\admin\controllers;
44

55
use app\models\UserModelSearch;
6+
use app\traits\FindModelTrait;
67
use Yii;
78
use app\models\UserModel;
89
use yii\web\Controller;
9-
use yii\web\NotFoundHttpException;
1010
use yii\filters\VerbFilter;
1111
use yii2mod\editable\EditableAction;
1212

1313
/**
14-
* UserController implements the CRUD actions for UserModel model.
14+
* Class UserController
15+
* @package app\modules\admin\controllers
1516
*/
1617
class UserController extends Controller
1718
{
19+
use FindModelTrait;
20+
1821
/**
1922
* Returns a list of behaviors that this component should behave as.
23+
*
2024
* @return array
2125
*/
2226
public function behaviors()
@@ -36,6 +40,7 @@ public function behaviors()
3640

3741
/**
3842
* Declares external actions for the controller.
43+
*
3944
* @return array
4045
*/
4146
public function actions()
@@ -45,33 +50,34 @@ public function actions()
4550
'class' => EditableAction::className(),
4651
'modelClass' => UserModel::className(),
4752
'forceCreate' => false
48-
]
53+
],
54+
'index' => [
55+
'class' => 'yii2tech\admin\actions\Index',
56+
'newSearchModel' => function () {
57+
return new UserModelSearch();
58+
},
59+
],
60+
'delete' => [
61+
'class' => 'yii2tech\admin\actions\Delete',
62+
'findModel' => function ($id) {
63+
return $this->findModel(UserModel::className(), $id);
64+
},
65+
'flash' => 'User has been deleted.'
66+
],
4967
];
5068
}
5169

52-
/**
53-
* Lists all users.
54-
* @return mixed
55-
*/
56-
public function actionIndex()
57-
{
58-
$searchModel = new UserModelSearch();
59-
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
60-
61-
return $this->render('index', [
62-
'dataProvider' => $dataProvider,
63-
'searchModel' => $searchModel,
64-
]);
65-
}
66-
6770
/**
6871
* Creates a new UserModel model.
72+
*
6973
* If creation is successful, the browser will be redirected to the 'view' page.
74+
*
7075
* @return mixed
7176
*/
7277
public function actionCreate()
7378
{
7479
$model = new UserModel(['scenario' => 'createUser']);
80+
7581
if ($model->load(Yii::$app->request->post())) {
7682
if ($model->createUser()) {
7783
Yii::$app->session->setFlash('success', 'User has been created.');
@@ -82,18 +88,19 @@ public function actionCreate()
8288
return $this->render('create', [
8389
'model' => $model,
8490
]);
85-
8691
}
8792

8893
/**
8994
* Updates an existing UserModel model.
95+
*
9096
* If update is successful, the browser will be redirected to the 'view' page.
97+
*
9198
* @param integer $id
9299
* @return mixed
93100
*/
94101
public function actionUpdate($id)
95102
{
96-
$model = $this->findModel($id);
103+
$model = $this->findModel(UserModel::className(), $id);
97104

98105
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
99106
if (!empty($model->newPassword)) {
@@ -107,35 +114,5 @@ public function actionUpdate($id)
107114
return $this->render('update', [
108115
'model' => $model,
109116
]);
110-
111-
}
112-
113-
/**
114-
* Deletes an existing UserModel model.
115-
* If deletion is successful, the browser will be redirected to the 'index' page.
116-
* @param integer $id
117-
* @return mixed
118-
*/
119-
public function actionDelete($id)
120-
{
121-
$this->findModel($id)->delete();
122-
Yii::$app->session->setFlash('success', 'User has been deleted.');
123-
return $this->redirect(['index']);
124-
}
125-
126-
/**
127-
* Finds the UserModel model based on its primary key value.
128-
* If the model is not found, a 404 HTTP exception will be thrown.
129-
* @param integer $id
130-
* @return UserModel the loaded model
131-
* @throws NotFoundHttpException if the model cannot be found
132-
*/
133-
protected function findModel($id)
134-
{
135-
if (($model = UserModel::findOne($id)) !== null) {
136-
return $model;
137-
} else {
138-
throw new NotFoundHttpException('The requested page does not exist.');
139-
}
140117
}
141-
}
118+
}

modules/admin/views/user/index.php

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
use yii\helpers\Html;
44
use yii\grid\GridView;
5-
use yii\helpers\Json;
65
use yii\widgets\Pjax;
76
use yii2mod\editable\EditableColumn;
87
use yii2mod\user\models\enumerables\UserStatus;
@@ -21,7 +20,7 @@
2120
<p>
2221
<?php echo Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?>
2322
</p>
24-
<?php Pjax::begin(['enablePushState' => false, 'timeout' => 3000]); ?>
23+
<?php Pjax::begin(['enablePushState' => false, 'timeout' => 10000]); ?>
2524
<?php echo GridView::widget([
2625
'dataProvider' => $dataProvider,
2726
'filterModel' => $searchModel,
@@ -43,7 +42,7 @@
4342
'type' => 'select',
4443
'editableOptions' => function ($model) {
4544
return [
46-
'source' => Json::encode(UserStatus::listData()),
45+
'source' => UserStatus::listData(),
4746
'value' => $model->status,
4847
];
4948
},
@@ -53,9 +52,7 @@
5352
[
5453
'attribute' => 'createdAt',
5554
'label' => 'Created date',
56-
'value' => function ($model) {
57-
return date("d-M-Y", $model->createdAt);
58-
},
55+
'format' => 'date',
5956
'filter' => false,
6057
],
6158
[
@@ -68,4 +65,4 @@
6865
?>
6966
<?php Pjax::end(); ?>
7067

71-
</div>
68+
</div>

traits/FindModelTrait.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
namespace app\traits;
4+
5+
use Yii;
6+
use yii\db\ActiveRecord;
7+
use yii\web\NotFoundHttpException;
8+
9+
/**
10+
* Class FindModelTrait
11+
* @package app\traits
12+
*/
13+
trait FindModelTrait
14+
{
15+
/**
16+
* @var string message for the NotFoundHttpException
17+
*/
18+
protected $notFoundMessage = 'The requested page does not exist.';
19+
20+
/**
21+
* Finds model
22+
*
23+
* @param $modelClass ActiveRecord
24+
* @param mixed $condition primary key value or a set of column values
25+
* @return ActiveRecord
26+
* @throws NotFoundHttpException
27+
*/
28+
protected function findModel($modelClass, $condition)
29+
{
30+
if (($model = $modelClass::findOne($condition)) !== null) {
31+
return $model;
32+
} else {
33+
throw new NotFoundHttpException($this->notFoundMessage);
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)