Skip to content

Commit

Permalink
add FindModelTrait, add new commands to the AppController, update act…
Browse files Browse the repository at this point in the history
…ions in the UserController
  • Loading branch information
Igor Chepurnoy committed Jul 1, 2016
1 parent 1fbf7ed commit 9d86eec
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 66 deletions.
65 changes: 62 additions & 3 deletions commands/AppController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace app\commands;

use app\models\UserModel;
use Yii;
use yii\helpers\Console;
use yii2mod\cms\models\CmsModel;
use yii2mod\cms\models\enumerables\CmsStatus;
use yii2tech\sitemap\File;
Expand All @@ -10,7 +13,9 @@
* Class AppController
*
* ~~~
* php yii app/generate-sitemap
* php yii app/generate-sitemap - Sitemap composing
* php yii app/clear-table User - Delete all data from specific table
* php yii app/assign-role-to-user admin admin@mail.com - Assign role to the user
* ~~~
*
* @package app\commands
Expand All @@ -23,13 +28,67 @@ class AppController extends BaseController
public function actionGenerateSitemap()
{
$siteMapFile = new File();

$siteMapFile->writeUrl(['site/index'], ['priority' => '0.9']);
$siteMapFile->writeUrl(['site/contact']);
$pages = CmsModel::find()->where(['status' => CmsStatus::ENABLED])->all();
foreach ($pages as $page) {
$siteMapFile->writeUrl([$page->url]);
}

$siteMapFile->close();

return self::EXIT_CODE_NORMAL;
}

/**
* Delete all data from specific table
*
* @param $tableName
* @return int
*
* @throws \yii\db\Exception
*/
public function actionClearTable($tableName)
{
Yii::$app->db->createCommand()->delete($tableName)->execute();

return self::EXIT_CODE_NORMAL;
}

/**
* Assign role to the user
*
* @param $roleName string user role
* @param $email string user email
* @return int
*/
public function actionAssignRoleToUser($roleName, $email)
{
$authManager = Yii::$app->authManager;
$user = UserModel::findByEmail($email);
$role = $authManager->getRole($roleName);

if (empty($user)) {
$this->stdout("User with `{$email}` does not exists.\n", Console::FG_RED);
return self::EXIT_CODE_ERROR;
}

if (empty($role)) {
$this->stdout("Role `{$roleName}` does not exists.\n", Console::FG_RED);
return self::EXIT_CODE_ERROR;
}

// Check if role is already assigned to the user
if (in_array($roleName, array_keys($authManager->getRolesByUser($user->id)))) {
$this->stdout("Role `{$roleName}` already assigned to this user.\n", Console::FG_BLUE);
return self::EXIT_CODE_NORMAL;
}

$authManager->assign($role, $user->id);

$this->stdout("The role `{$roleName}` has been successfully assigned to the user with email {$email}\n", Console::FG_YELLOW);

return self::EXIT_CODE_NORMAL;
}
}

}
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"kartik-v/yii2-widget-sidenav": "*",
"yii2mod/yii2-settings": "*",
"yii2tech/sitemap": "^1.0",
"yii2mod/yii2-scheduling": "*"
"yii2mod/yii2-scheduling": "*",
"yii2tech/admin": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
Expand Down Expand Up @@ -71,4 +72,4 @@
"bower-asset-library": "vendor/bower"
}
}
}
}
4 changes: 1 addition & 3 deletions modules/admin/controllers/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
*/
class SettingsController extends Controller
{

/**
* @return array
*/
Expand All @@ -20,5 +19,4 @@ public function actions()
'cron' => 'yii2mod\cron\actions\CronLogAction',
];
}

}
}
79 changes: 28 additions & 51 deletions modules/admin/controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,24 @@
namespace app\modules\admin\controllers;

use app\models\UserModelSearch;
use app\traits\FindModelTrait;
use Yii;
use app\models\UserModel;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii2mod\editable\EditableAction;

/**
* UserController implements the CRUD actions for UserModel model.
* Class UserController
* @package app\modules\admin\controllers
*/
class UserController extends Controller
{
use FindModelTrait;

/**
* Returns a list of behaviors that this component should behave as.
*
* @return array
*/
public function behaviors()
Expand All @@ -36,6 +40,7 @@ public function behaviors()

/**
* Declares external actions for the controller.
*
* @return array
*/
public function actions()
Expand All @@ -45,33 +50,34 @@ public function actions()
'class' => EditableAction::className(),
'modelClass' => UserModel::className(),
'forceCreate' => false
]
],
'index' => [
'class' => 'yii2tech\admin\actions\Index',
'newSearchModel' => function () {
return new UserModelSearch();
},
],
'delete' => [
'class' => 'yii2tech\admin\actions\Delete',
'findModel' => function ($id) {
return $this->findModel(UserModel::className(), $id);
},
'flash' => 'User has been deleted.'
],
];
}

/**
* Lists all users.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}

/**
* Creates a new UserModel model.
*
* If creation is successful, the browser will be redirected to the 'view' page.
*
* @return mixed
*/
public function actionCreate()
{
$model = new UserModel(['scenario' => 'createUser']);

if ($model->load(Yii::$app->request->post())) {
if ($model->createUser()) {
Yii::$app->session->setFlash('success', 'User has been created.');
Expand All @@ -82,18 +88,19 @@ public function actionCreate()
return $this->render('create', [
'model' => $model,
]);

}

/**
* Updates an existing UserModel model.
*
* If update is successful, the browser will be redirected to the 'view' page.
*
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model = $this->findModel(UserModel::className(), $id);

if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if (!empty($model->newPassword)) {
Expand All @@ -107,35 +114,5 @@ public function actionUpdate($id)
return $this->render('update', [
'model' => $model,
]);

}

/**
* Deletes an existing UserModel model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
Yii::$app->session->setFlash('success', 'User has been deleted.');
return $this->redirect(['index']);
}

/**
* Finds the UserModel model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return UserModel the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserModel::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
}
11 changes: 4 additions & 7 deletions modules/admin/views/user/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Json;
use yii\widgets\Pjax;
use yii2mod\editable\EditableColumn;
use yii2mod\user\models\enumerables\UserStatus;
Expand All @@ -21,7 +20,7 @@
<p>
<?php echo Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['enablePushState' => false, 'timeout' => 3000]); ?>
<?php Pjax::begin(['enablePushState' => false, 'timeout' => 10000]); ?>
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
Expand All @@ -43,7 +42,7 @@
'type' => 'select',
'editableOptions' => function ($model) {
return [
'source' => Json::encode(UserStatus::listData()),
'source' => UserStatus::listData(),
'value' => $model->status,
];
},
Expand All @@ -53,9 +52,7 @@
[
'attribute' => 'createdAt',
'label' => 'Created date',
'value' => function ($model) {
return date("d-M-Y", $model->createdAt);
},
'format' => 'date',
'filter' => false,
],
[
Expand All @@ -68,4 +65,4 @@
?>
<?php Pjax::end(); ?>

</div>
</div>
36 changes: 36 additions & 0 deletions traits/FindModelTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace app\traits;

use Yii;
use yii\db\ActiveRecord;
use yii\web\NotFoundHttpException;

/**
* Class FindModelTrait
* @package app\traits
*/
trait FindModelTrait
{
/**
* @var string message for the NotFoundHttpException
*/
protected $notFoundMessage = 'The requested page does not exist.';

/**
* Finds model
*
* @param $modelClass ActiveRecord
* @param mixed $condition primary key value or a set of column values
* @return ActiveRecord
* @throws NotFoundHttpException
*/
protected function findModel($modelClass, $condition)
{
if (($model = $modelClass::findOne($condition)) !== null) {
return $model;
} else {
throw new NotFoundHttpException($this->notFoundMessage);
}
}
}

0 comments on commit 9d86eec

Please sign in to comment.