UserActivity.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace app\models\entity;
  3. use yii\db\ActiveRecord;
  4. use DateInterval;
  5. use DateTime;
  6. /**
  7. * This is the model class for table "user_activity".
  8. *
  9. * Активность пользователя.
  10. *
  11. * @property int $id
  12. * @property int $employee
  13. * @property string $start [datetime]
  14. * @property string $end [datetime]
  15. */
  16. class UserActivity extends ActiveRecord
  17. {
  18. const FORMAT = 'Y-m-d H:i:s';
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public static function tableName()
  23. {
  24. return 'user_activity';
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function rules()
  30. {
  31. return [
  32. [['employee', 'start'], 'required'],
  33. [['employee'], 'integer'],
  34. [['start', 'end'], 'string', 'max' => 255],
  35. ];
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function attributeLabels()
  41. {
  42. return [
  43. 'id' => 'ID',
  44. 'employee' => 'Employee ID',
  45. 'start' => 'Date of start activity',
  46. 'end' => 'Date of end activity',
  47. ];
  48. }
  49. /**
  50. * Если ближайшие 10 минут пользователь был активен, продлеваем конец сессии на 10 минут.
  51. * Иначе создаём новую сессию.
  52. *
  53. * @param int $userId
  54. * @return string
  55. * @throws \Exception
  56. */
  57. public static function ping(int $userId)
  58. {
  59. if (!$userId) return '';
  60. $lastRecord = self::find()
  61. ->where(['employee' => $userId])
  62. ->orderBy('end DESC')
  63. ->limit(1)
  64. ->one()
  65. ;
  66. $now = new DateTime();
  67. if ($lastRecord) {
  68. $end = strtotime($lastRecord->end);
  69. if ($end > $now->getTimestamp()) {
  70. $now->add(new DateInterval('PT10M'));
  71. $lastRecord->end = $now->format(self::FORMAT);
  72. $lastRecord->save();
  73. return 'Время продлено';
  74. }
  75. }
  76. $userActivity = new self();
  77. $userActivity->employee = $userId;
  78. $userActivity->start = $now->format(self::FORMAT);
  79. $now->add(new DateInterval('PT10M'));
  80. $userActivity->end = $now->format(self::FORMAT);
  81. $userActivity->save();
  82. return 'Создана новая активность';
  83. }
  84. }