Blame view

frontend/controllers/ChatController.php 1.94 KB
fbdb1f1c   Yarik   test
1
2
3
  <?php
  namespace frontend\controllers;
  
6a97773c   Administrator   01.03.16
4
5
  use common\models\Chat;
  use common\models\Message;
fbdb1f1c   Yarik   test
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  use Yii;
  use common\models\User;
  use yii\data\ActiveDataProvider;
  use yii\filters\AccessControl;
  use yii\web\Controller;
  use yii\web\NotFoundHttpException;
  
  
  /**
   * Site controller
   */
  class ChatController extends Controller
  {
      public $defaultAction = 'list';
  
      public function behaviors()
      {
          return [
              'access' => [
                  'class' => AccessControl::className(),
                  'rules' => [
                      [
6a97773c   Administrator   01.03.16
28
                          'actions' => ['list', 'message', 'message-save'],
fbdb1f1c   Yarik   test
29
30
31
32
33
34
35
36
37
38
39
40
41
42
                          'allow' => true,
                          'roles' => ['@'],
                      ],
                  ],
              ],
          ];
      }
  
  
      public function actionList()
      {
          return $this->render('list');
      }
  
6a97773c   Administrator   01.03.16
43
      public function actionMessage($user_id)
fbdb1f1c   Yarik   test
44
      {
6a97773c   Administrator   01.03.16
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
          $user = \Yii::$app->user->identity;
  
          $chat = Chat::find()
              ->where([
              'or',
              ['from_user' => $user_id,],
              ['to_user' => $user_id,],
              ])
              ->andWhere([
                  'or',
                  ['from_user'=> $user->id,],
                  ['to_user'=>  $user->id,],
              ])->one();
          if(!$chat instanceof Chat){
              $chat = new Chat();
              $chat->from_user =  $user->id;
              $chat->to_user =  $user_id;
              $chat->save();
  
          }
  
  
          $post = \Yii::$app->request->post();
          if(isset($post)){
  
  
  
              $message = new Message();
  
  
              if($message->load($post, 'Message')){
  
                  $message->chat_id = $chat->chat_id;
                  $message->user_id = $user->id;
                  $message->save();
  
                  return $this->redirect(['chat/message', 'user_id'=>$user_id]);
              }
          }
  
          return $this->render('message',[
              'chat' => $chat,
              'user_id' => $user_id
          ]);
fbdb1f1c   Yarik   test
89
      }
6a97773c   Administrator   01.03.16
90
  
fbdb1f1c   Yarik   test
91
  }