/
chieforik
/
AgroPro
Обзор
Документация
Войти
/
chieforik
/
AgroPro
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
models/User.php
276 строк
7 KB
Орловский Александр
Первый
25 сен 2025, 02:26
25 сен 2025, 02:26
1567008
Код
Авторство
О чём код?
<?php namespace app\models; use Yii; use yii\web\IdentityInterface; /** * This is the model class for table "user". * * @property int $id * @property string $first_name Имя * @property string $last_name Фамилия * @property string|null $middle_name Отчество * @property string $phone Номер телефона * @property string|null $email Почта * @property string $password_hash Хеш пароля * @property string $auth_key Ключ аутентификации * @property string|null $organization Организация * @property int $created_at Дата создания * @property int $updated_at Дата обновления * * @property Field[] $fields */ class User extends \yii\db\ActiveRecord implements IdentityInterface { public $password; /** * {@inheritdoc} */ public static function tableName() { return '{{%user}}'; } /** * {@inheritdoc} */ public function rules() { return [ [['first_name', 'last_name', 'phone'], 'required'], [['created_at', 'updated_at'], 'integer'], [['first_name', 'last_name', 'middle_name'], 'string', 'max' => 50], [['phone'], 'string', 'max' => 20], [['email', 'organization'], 'string', 'max' => 150], [['email'], 'email'], [['email'], 'unique'], [['phone'], 'unique'], [['phone'], 'match', 'pattern' => '/^\+7\d{10}$/', 'message' => 'Телефон должен быть в формате +7XXXXXXXXXX'], [['password'], 'string', 'min' => 6, 'on' => ['create', 'update']], [['first_name', 'last_name', 'middle_name'], 'match', 'pattern' => '/^[а-яА-ЯёЁ\s\-]+$/u', 'message' => 'Только русские буквы, пробелы и дефисы'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'first_name' => 'Имя', 'last_name' => 'Фамилия', 'middle_name' => 'Отчество', 'phone' => 'Номер телефона', 'email' => 'Почта', 'password' => 'Пароль', 'organization' => 'Организация', 'created_at' => 'Дата создания', 'updated_at' => 'Дата обновления', 'fullName' => 'ФИО', 'shortName' => 'Фамилия И.О.', ]; } /** * {@inheritdoc} */ public function behaviors() { return [ 'timestamp' => [ 'class' => \yii\behaviors\TimestampBehavior::className(), 'createdAtAttribute' => 'created_at', 'updatedAtAttribute' => 'updated_at', ], ]; } /** * @return \yii\db\ActiveQuery */ public function getFields() { return $this->hasMany(Field::className(), ['user_id' => 'id']); } /** * Полное ФИО пользователя * @return string */ public function getFullName() { $parts = [$this->last_name, $this->first_name]; if (!empty($this->middle_name)) { $parts[] = $this->middle_name; } return implode(' ', $parts); } /** * Краткое ФИО (Петров И.С.) * @return string */ public function getShortName() { $shortFirstName = mb_substr($this->first_name, 0, 1) . '.'; $shortMiddleName = !empty($this->middle_name) ? mb_substr($this->middle_name, 0, 1) . '.' : ''; return $this->last_name . ' ' . $shortFirstName . $shortMiddleName; } /** * {@inheritdoc} */ public static function findIdentity($id) { return static::findOne($id); } /** * {@inheritdoc} */ public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['auth_key' => $token]); } /** * Finds user by phone * @param string $phone * @return static|null */ public static function findByPhone($phone) { return static::findOne(['phone' => $phone]); } /** * Finds user by email * @param string $email * @return static|null */ public static function findByEmail($email) { return static::findOne(['email' => $email]); } /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getAuthKey() { return $this->auth_key; } /** * {@inheritdoc} */ public function validateAuthKey($authKey) { return $this->auth_key === $authKey; } /** * Validates password * @param string $password password to validate * @return bool if password provided is valid for current user */ public function validatePassword($password) { return Yii::$app->security->validatePassword($password, $this->password_hash); } /** * Generates password hash from password and sets it to the model * @param string $password */ public function setPassword($password) { $this->password_hash = Yii::$app->security->generatePasswordHash($password); } /** * Generates "remember me" authentication key */ public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomString(); } /** * Before save обработка */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($insert) { $this->generateAuthKey(); } if ($this->password) { $this->setPassword($this->password); } return true; } return false; } /** * Получить список пользователей для dropdown * @return array */ public static function getUsersList() { $users = static::find() ->select(['id', 'first_name', 'last_name', 'middle_name']) ->all(); $result = []; foreach ($users as $user) { $result[$user->id] = $user->shortName; } return $result; } /** * Форматированный телефон * @return string */ public function getFormattedPhone() { if (preg_match('/^\+7(\d{3})(\d{3})(\d{2})(\d{2})$/', $this->phone, $matches)) { return "+7 ({$matches[1]}) {$matches[2]}-{$matches[3]}-{$matches[4]}"; } return $this->phone; } /** * Проверка, заполнена ли почта * @return bool */ public function getHasEmail() { return !empty($this->email); } /** * Проверка, заполнено ли отчество * @return bool */ public function getHasMiddleName() { return !empty($this->middle_name); } }