Completed
Push — master ( da4528...803e91 )
by Corey
03:17 queued 31s
created

CheckinController::actionQuestions()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 33
rs 8.8333
c 0
b 0
f 0
cc 7
nc 6
nop 0
1
<?php
2
3
namespace site\controllers;
4
5
use Yii;
6
use common\interfaces\UserInterface;
7
use common\interfaces\UserBehaviorInterface;
8
use common\interfaces\CategoryInterface;
9
use common\interfaces\BehaviorInterface;
10
use common\interfaces\TimeInterface;
11
use yii\di\Container;
12
use yii\base\InvalidParamException;
13
use yii\web\BadRequestHttpException;
14
use common\components\Controller;
15
use yii\filters\VerbFilter;
16
use common\components\AccessControl;
17
use yii\helpers\ArrayHelper as AH;
18
19
class CheckinController extends Controller
20
{
21
  public function behaviors()
22
  {
23
    return [
24
      'access' => [
25
        'class' => AccessControl::class,
26
        'only' => ['index', 'view', 'questions', 'report', 'history'],
27
        'rules' => [
28
          [
29
            'actions' => ['index', 'view', 'questions', 'report', 'history'],
30
            'allow' => true,
31
            'roles' => ['@'],
32
          ],
33
        ],
34
      ],
35
    ];
36
  }
37
  public function actionIndex() {
38
    $form = Yii::$container->get(\site\models\CheckinForm::class);
39
    if ($form->load(Yii::$app->request->post()) && $form->validate()) {
40
      $form->compiled_behaviors = $form->compileBehaviors();
41
42
      if(sizeof($form->compiled_behaviors) === 0) {
43
        return $this->redirect(['view']);
44
      }
45
46
      // we only store one data set per day, so wipe out previously saved ones
47
      $form->deleteToday();
48
      $form->save();
49
50
      return $this->redirect(['questions']);
51
    } else {
52
      $behaviors  = Yii::$container->get(BehaviorInterface::class)::$behaviors;
53
      return $this->render('index', [
54
        'categories'    => Yii::$container->get(CategoryInterface::class)::$categories,
55
        'model'         => $form,
56
        'behaviorsList' => AH::index($behaviors, null, "category_id")
57
      ]);
58
    }
59
  }
60
61
  public function actionQuestions()
62
  {
63
    $user_behavior = Yii::$container->get(UserBehaviorInterface::class);
64
    $date = Yii::$container->get(TimeInterface::class)->getLocalDate();
65
66
    $user_behaviors = $user_behavior->getUserBehaviorsWithCategory($date);
67
    if(count($user_behaviors) === 0) {
68
      return $this->redirect(['view']);
69
    }
70
71
    $form = Yii::$container->get(\site\models\QuestionForm::class);
72
    if ($form->load(Yii::$app->request->post()) && $form->validate()) {
73
      // we only store one data set per day so clear out any previously saved ones
74
      $form->deleteToday();
75
76
      $behaviors = $user_behavior->findAll($form->getUserBehaviorIds());
77
      if($result = $form->saveAnswers($behaviors)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
78
79
        if(Yii::$app->user->identity->send_email) {
0 ignored issues
show
Bug introduced by
Accessing send_email on the interface yii\web\IdentityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
80
          if(Yii::$app->user->identity->sendEmailReport($date)) {
0 ignored issues
show
Bug introduced by
The method sendEmailReport() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
          if(Yii::$app->user->identity->/** @scrutinizer ignore-call */ sendEmailReport($date)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
81
            Yii::$app->session->setFlash('success', 'Your check-in is complete. A notification has been sent to your report partners.');
0 ignored issues
show
Bug introduced by
The method setFlash() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

81
            Yii::$app->session->/** @scrutinizer ignore-call */ 
82
                                setFlash('success', 'Your check-in is complete. A notification has been sent to your report partners.');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
82
          } else {
83
            Yii::$app->session->setFlash('success', 'Your check-in is complete.');
84
          }
85
        }
86
87
        return $this->redirect(['view']);
88
      }
89
    }
90
91
    return $this->render('questions', [
92
      'model' => $form,
93
      'behaviors' => $user_behaviors
94
    ]);	
95
  }
96
97
  public function actionView(string $date = null)
98
  {
99
    $time = Yii::$container->get(\common\interfaces\TimeInterface::class);
100
    $date = $time->validate($date);
101
    $dt = $time->parse($date);
102
    list($start, $end) = $time->getUTCBookends($date);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This list assign is not used and could be removed.
Loading history...
103
104
    $user          = Yii::$container->get(UserInterface::class);
105
    $user_behavior = Yii::$container->get(UserBehaviorInterface::class);
106
    $categories    = Yii::$container->get(CategoryInterface::class)::$categories;
107
    $behaviors     = Yii::$container->get(BehaviorInterface::class)::$behaviors;
108
109
    $form = Yii::$container->get(\site\models\CheckinForm::class);
110
    $form->setBehaviors($user->getUserBehaviors($date));
111
112
    $raw_pie_data = $user_behavior::decorateWithCategory($user_behavior->getBehaviorsWithCounts($dt));
113
    $answer_pie = $user_behavior->getBehaviorsByCategory($raw_pie_data);
114
115
    return $this->render('view', [
116
      'model'              => $form,
117
      'actual_date'        => $date,
118
      'categories'         => $categories,
119
      'behaviorsList'      => AH::index($behaviors, 'name', "category_id"),
120
      'past_checkin_dates' => $user_behavior->getPastCheckinDates(),
121
      'answer_pie'         => $answer_pie,
122
      'questions'          => $user->getUserQuestions($date),
123
      'isToday'            => $time->getLocalDate() === $date,
124
    ]);
125
  }
126
127
  public function actionReport() {
128
    /* Pie Chart data */
129
    $user_behavior = Yii::$container->get(UserBehaviorInterface::class);
130
    $user_rows     = $user_behavior::decorateWithCategory($user_behavior->getBehaviorsWithCounts(5));
131
    $raw_pie_data  = $user_behavior::decorateWithCategory($user_behavior->getBehaviorsWithCounts());
132
    $answer_pie    = $user_behavior->getBehaviorsByCategory($raw_pie_data);
133
134
    $pie_data   = [
135
      "labels"   => array_column($answer_pie, "name"),
136
      "datasets" => [[
137
          "data"                 => array_map('intval', array_column($answer_pie, "count")),
138
          "backgroundColor"      => array_column($answer_pie, "color"),
139
          "hoverBackgroundColor" => array_column($answer_pie, "highlight"),
140
      ]]
141
    ];
142
143
    /* Bar Chart data */
144
    ['labels' => $labels, 'datasets' => $datasets] = $this->history(30);
145
146
    return $this->render('report', [
147
      'top_behaviors' => $user_rows,
148
      'pie_data' => $pie_data,
149
      'bar_dates' => $labels,
150
      'bar_datasets' => $datasets,
151
    ]);
152
  }
153
154
  public function actionHistory($period) {
155
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
156
    $period = intval($period);
157
    $whitelist_periods = [30, 90, 180];
158
    $period = in_array($period, $whitelist_periods) ? $period : 30;
159
    return $this->history($period);
160
  }
161
162
  private function history($period) {
163
    $user_behavior = Yii::$container->get(UserBehaviorInterface::class);
164
    $category      = Yii::$container->get(CategoryInterface::class);
165
166
    $checkins = $user_behavior->getCheckInBreakdown($period);
167
168
    $accum = [];
169
    foreach($checkins as $date => $cats) {
170
      for($i = 1; $i <= 7; $i ++) {
171
        $accum[$i][] = array_key_exists($i, $cats) ? $cats[$i]['count'] : [];
172
      }
173
    }
174
175
    $bar_datasets = [];
176
    foreach($accum as $idx => $data) {
177
      $bar_datasets[] = [
178
        'label' => ($category::getCategories())[$idx],
179
        'backgroundColor' => $category::$colors[$idx]['color'],
180
        'data' => $data
181
      ];
182
    }
183
    return [
184
      'labels' => array_keys($checkins),
185
      'datasets' => $bar_datasets,
186
    ];
187
  }
188
}
189