Passed
Push — master ( 41f848...de078e )
by Corey
05:23 queued 02:26
created

CheckinForm::mergeWithDefault()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 8
rs 10
cc 2
nc 1
nop 1
1
<?php
2
namespace site\models;
3
4
use Yii;
5
use yii\base\Model;
6
use yii\db\Expression;
7
use yii\helpers\ArrayHelper as AH;
8
use common\interfaces\BehaviorInterface;
9
10
/**
11
 * Checkin form
12
 */
13
class CheckinForm extends Model
14
{
15
  public $behaviors1;
16
  public $behaviors2;
17
  public $behaviors3;
18
  public $behaviors4;
19
  public $behaviors5;
20
  public $behaviors6;
21
  public $behaviors7;
22
23
  public $compiled_behaviors;
24
25
  /**
26
   * @inheritdoc
27
   */
28
  public function rules()
29
  {
30
    return [
31
      [
32
        [
33
          'behaviors1',
34
          'behaviors2',
35
          'behaviors3',
36
          'behaviors4',
37
          'behaviors5',
38
          'behaviors6',
39
          'behaviors7'
40
        ],
41
        'validateBehaviors'],
42
    ];
43
  }
44
45
  public function attributeLabels() {
46
    return [
47
      'behaviors1' => 'Restoration',
48
      'behaviors2' => 'Forgetting Priorities',
49
      'behaviors3' => 'Anxiety',
50
      'behaviors4' => 'Speeding Up',
51
      'behaviors5' => 'Ticked Off',
52
      'behaviors6' => 'Exhausted',
53
      'behaviors7' => 'Relapsed/Moral Failure'
54
    ];
55
  }
56
57
  public function setBehaviors($behaviors) {
58
    foreach($behaviors as $category_id => $bhvr_set) {
59
      $attribute = "behaviors$category_id";
60
			$this->$attribute = [];
61
      foreach($bhvr_set as $behavior) {
62
        $this->{$attribute}[] = $behavior['id'];
63
      }
64
    }   
65
  }
66
67
  public function validateBehaviors($attribute, $params) {
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed. ( Ignorable by Annotation )

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

67
  public function validateBehaviors($attribute, /** @scrutinizer ignore-unused */ $params) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
68
    if (!$this->hasErrors()) {
69
      foreach($this->$attribute as $behavior) {
70
        if(!is_numeric($behavior)) {
71
          $this->addError($attribute, 'One of your behaviors is not an integer!');
72
        }
73
      }
74
    }
75
  }
76
77
  public function compileBehaviors() {
78
    $behaviors = array_merge((array)$this->behaviors1,
79
                           (array)$this->behaviors2,
80
                           (array)$this->behaviors3,
81
                           (array)$this->behaviors4,
82
                           (array)$this->behaviors5,
83
                           (array)$this->behaviors6,
84
                           (array)$this->behaviors7);
85
86
    return array_filter($behaviors); // strip out false values
87
  }
88
89
  public function deleteToday() {
90
    $time = Yii::$container->get(\common\interfaces\TimeInterface::class);
91
    $user_behavior = Yii::$container->get(\common\interfaces\UserBehaviorInterface::class);
92
93
    $date = $time->getLocalDate();
94
    list($start, $end) = $time->getUTCBookends($date);
95
96
    $user_behavior->deleteAll("user_id=:user_id 
97
      AND date > :start_date 
98
      AND date < :end_date", 
99
      [
100
        "user_id" => Yii::$app->user->id, 
101
        ':start_date' => $start, 
102
        ":end_date" => $end
103
      ]
104
    );
105
106
    // delete cached behaviors
107
    array_map(function($period) use ($time) {
108
      $key = "checkins_".Yii::$app->user->id."_{$period}_".$time->getLocalDate();
109
      Yii::$app->cache->delete($key);
110
    }, [30, 90, 180]);
111
  }
112
113
  /**
114
   * Takes an array of the default behaivors and given behaviors from the user and returns them merged together.
115
   * This is used for the generation of the CheckinForm behavior list.
116
   * @param array $user_behaviors an array of UserBehaviors indexed by the category. Typically just the result of self::$getByDate().
117
   * @return array the two supplied arrays merged together
118
   */
119
  public function mergeWithDefault(array $user_behaviors) {
120
    $behaviors = AH::index(Yii::$container->get(BehaviorInterface::class)::$behaviors, 'name', "category_id");
121
    array_walk($behaviors, function(&$bhvrs, $cat_id) use ($user_behaviors) {
122
      if(array_key_exists($cat_id, $user_behaviors)) {
123
        $bhvrs = AH::merge($bhvrs, $user_behaviors[$cat_id]);
124
      }
125
    });
126
    return $behaviors;
127
  }
128
129
  public function save() {
130
    if(empty($this->compiled_behaviors)) {
131
      $this->commpiled_behaviors = $this->compileBehaviors();
0 ignored issues
show
Bug Best Practice introduced by
The property commpiled_behaviors does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
132
    }
133
134
    $user_behavior = Yii::$container->get(\common\interfaces\UserBehaviorInterface::class);
135
136
    $rows = [];
137
    foreach($this->compiled_behaviors as $behavior_id) {
138
      $behavior_id = (int)$behavior_id;
139
      $behavior = \common\models\Behavior::getBehavior('id', $behavior_id);
140
      $category_id = $behavior['category_id'];
141
      $temp = [
142
        Yii::$app->user->id,
143
        (int)$behavior_id,
144
        (int)$category_id,
145
        new Expression("now()::timestamp")
146
      ];
147
      $rows[] = $temp;
148
    }
149
150
    Yii::$app
151
      ->db
152
      ->createCommand()
153
      ->batchInsert(
154
        $user_behavior->tableName(),
155
        ['user_id', 'behavior_id', 'category_id', 'date'],
156
        $rows
157
      )->execute();
158
159
    // if the user has publicised their check-in graph, create the image
160
    if(Yii::$app->user->identity->expose_graph) {
0 ignored issues
show
Bug introduced by
Accessing expose_graph on the interface yii\web\IdentityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
161
      $checkins_last_month = $user_behavior->getCheckInBreakdown();
162
163
      if($checkins_last_month) {
164
        Yii::$container
165
          ->get(\common\components\Graph::class, [Yii::$app->user->identity])
166
          ->create($checkins_last_month, true);
167
      }
168
    }
169
  }
170
}
171