File: /home/aliazzsr/api.crm.vqode.com/models/core/Role.php
<?php
namespace app\models\core;
use app\components\BaseModel;
use yii\web\ForbiddenHttpException;
/**
* Class Role
* @package app\models\core
*/
class Role extends BaseModel
{
const ADMIN = 1;
const MANAGER = 2;
const USER = 3;
const TEAMLEADER = 4;
const BLOCKED = 5;
private $systemRoles = [self::ADMIN, self::BLOCKED];
public static function tableName()
{
return 'role';
}
public function rules()
{
return [
[['name'], 'required'],
[['name'], 'string', 'max' => 255],
[['name', 'description'], 'safe'],
[['id'], 'systemRoleValidation'],
];
}
public function getUsers()
{
return $this->hasMany(User::className(), ['role_id' => 'id']);
}
public function delete()
{
if ($this->isSystemRole()) {
throw new ForbiddenHttpException('A system role, so cannot be updated either deleted.');
}
$tran = self::getDb()->beginTransaction();
try {
foreach ($this->getUsers()->all() as $user) {
$user->role_id = self::BLOCKED;
$user->save();
}
parent::delete();
$tran->commit();
} catch (\Exception $e) {
$tran->rollBack();
throw new \Exception('Internal server error');
}
return true;
}
public function systemRoleValidation($attribute, $params, $validator)
{
if ($this->isSystemRole()) {
$this->addError($attribute, 'A system role, so cannot be updated either deleted.');
}
}
public function isSystemRole()
{
return in_array($this->id, $this->systemRoles);
}
}
/**
* @SWG\Definition(
* definition="Role",
* type="object",
* description="Role model",
* allOf={
* @SWG\Schema(
* @SWG\Property(property="id", type="integer", example="1"),
* @SWG\Property(property="name", type="string", example="Admin"),
* @SWG\Property(property="description", type="string", example="All existent permissions are granted to Admin.")
* )
* }
* )
*/