123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace app\models\entity;
- use yii\db\ActiveRecord;
- use DateInterval;
- use DateTime;
- /**
- * This is the model class for table "user_activity".
- *
- * Активность пользователя.
- *
- * @property int $id
- * @property int $employee
- * @property string $start [datetime]
- * @property string $end [datetime]
- */
- class UserActivity extends ActiveRecord
- {
- const FORMAT = 'Y-m-d H:i:s';
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return 'user_activity';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['employee', 'start'], 'required'],
- [['employee'], 'integer'],
- [['start', 'end'], 'string', 'max' => 255],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'employee' => 'Employee ID',
- 'start' => 'Date of start activity',
- 'end' => 'Date of end activity',
- ];
- }
- /**
- * Если ближайшие 10 минут пользователь был активен, продлеваем конец сессии на 10 минут.
- * Иначе создаём новую сессию.
- *
- * @param int $userId
- * @return string
- * @throws \Exception
- */
- public static function ping(int $userId)
- {
- if (!$userId) return '';
- $lastRecord = self::find()
- ->where(['employee' => $userId])
- ->orderBy('end DESC')
- ->limit(1)
- ->one()
- ;
- $now = new DateTime();
- if ($lastRecord) {
- $end = strtotime($lastRecord->end);
- if ($end > $now->getTimestamp()) {
- $now->add(new DateInterval('PT10M'));
- $lastRecord->end = $now->format(self::FORMAT);
- $lastRecord->save();
- return 'Время продлено';
- }
- }
- $userActivity = new self();
- $userActivity->employee = $userId;
- $userActivity->start = $now->format(self::FORMAT);
- $now->add(new DateInterval('PT10M'));
- $userActivity->end = $now->format(self::FORMAT);
- $userActivity->save();
- return 'Создана новая активность';
- }
- }
|