Passed
Pull Request — master (#177)
by Corey
05:23
created

CheckinForm::mergeWithDefault()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
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
  /**
115
   * mergeWithDefault()
116
   * Takes an array of the default behaivors and given behaviors from the user and returns them merged together.
117
   * This is used for the generation of the CheckinForm behavior list.
118
   * @param array $user_behaviors an array of UserBehaviors indexed by the category. Typically just the result of self::$getByDate().
119
   * @return array the two supplied arrays merged together
120
   */
121
  public function mergeWithDefault($user_behaviors) {
122
    $behaviors = AH::index(Yii::$container->get(BehaviorInterface::class)::$behaviors, 'name', "category_id");
123
    array_walk($behaviors, function(&$bhvrs, $cat_id) use ($user_behaviors) {
124
      if(array_key_exists($cat_id, $user_behaviors)) {
125
        $bhvrs = AH::merge($bhvrs, $user_behaviors[$cat_id]);
126
      }
127
    });
128
    return $behaviors;
129
  }
130
131
  public function save() {
132
    if(empty($this->compiled_behaviors)) {
133
      $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...
134
    }
135
136
    $user_behavior = Yii::$container->get(\common\interfaces\UserBehaviorInterface::class);
137
138
    $rows = [];
139
    foreach($this->compiled_behaviors as $behavior_id) {
140
      $behavior_id = (int)$behavior_id;
141
      $behavior = \common\models\Behavior::getBehavior('id', $behavior_id);
142
      $category_id = $behavior['category_id'];
143
      $temp = [
144
        Yii::$app->user->id,
145
        (int)$behavior_id,
146
        (int)$category_id,
147
        new Expression("now()::timestamp")
148
      ];
149
      $rows[] = $temp;
150
    }
151
152
    Yii::$app
153
      ->db
154
      ->createCommand()
155
      ->batchInsert(
156
        $user_behavior->tableName(),
157
        ['user_id', 'behavior_id', 'category_id', 'date'],
158
        $rows
159
      )->execute();
160
161
    // if the user has publicised their check-in graph, create the image
162
    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...
163
      $checkins_last_month = $user_behavior->getCheckInBreakdown();
164
165
      if($checkins_last_month) {
166
        Yii::$container
167
          ->get(\common\components\Graph::class, [Yii::$app->user->identity])
168
          ->create($checkins_last_month, true);
169
      }
170
    }
171
  }
172
}
173