GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#171)
by
unknown
04:00
created

AuditTrailBehavior::getCommaString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 2
rs 9.4285
c 1
b 0
f 0
1
<?php
2
namespace bedezign\yii2\audit;
3
4
use Yii;
5
use yii\base\Exception;
6
use yii\db\ActiveRecord;
7
8
use bedezign\yii2\audit\models\AuditTrail;
9
use yii\web\Application;
10
11
use yii\db\Query;
12
13
/**
14
 * Class AuditTrailBehavior
15
 * @package bedezign\yii2\audit
16
 *
17
 * @property \yii\db\ActiveRecord $owner
18
 */
19
class AuditTrailBehavior extends \yii\base\Behavior
20
{
21
22
    /**
23
     * Array with fields to save
24
     * You don't need to configure both `allowed` and `ignored`
25
     * @var array
26
     */
27
    public $allowed = [];
28
29
    /**
30
     * Array with fields to ignore
31
     * You don't need to configure both `allowed` and `ignored`
32
     * @var array
33
     */
34
    public $ignored = [];
35
36
    /**
37
     * Array with classes to ignore
38
     * @var array
39
     */
40
    public $ignoredClasses = [];
41
42
    /**
43
     * Is the behavior is active or not
44
     * @var boolean
45
     */
46
    public $active = true;
47
48
    /**
49
     * Date format to use in stamp - set to "Y-m-d H:i:s" for datetime or "U" for timestamp
50
     * @var string
51
     */
52
    public $dateFormat = 'Y-m-d H:i:s';
53
54
    /**
55
     * @var array
56
     */
57
    private $_oldAttributes = [];
58
59
    /**
60 304
     * Array with fields you want to override before saving the row into audit_trail table
61
     * @var array
62
     */
63 304
    public $overRide = [];
64 304
65 304
66 304
    /**
67 114
     * @inheritdoc
68
     */
69
    public function events()
70
    {
71
        return [
72
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
73 37
            ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
74
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
75 15
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
76 37
        ];
77
    }
78
79
    /**
80
     *
81 24
     */
82
    public function afterFind()
83 8
    {
84 8
        $this->setOldAttributes($this->owner->getAttributes());
85 24
    }
86
87
    /**
88
     *
89
     */
90 23
    public function afterInsert()
91
    {
92 9
        $this->audit('CREATE');
93 9
        $this->setOldAttributes($this->owner->getAttributes());
94 23
    }
95
96
    /**
97
     *
98
     */
99 12
    public function afterUpdate()
100
    {
101 4
        $this->audit('UPDATE');
102 4
        $this->setOldAttributes($this->owner->getAttributes());
103 12
    }
104
105
    /**
106
     *
107
     */
108
    public function afterDelete()
109 53
    {
110
        $this->audit('DELETE');
111
        $this->setOldAttributes([]);
112 53
    }
113 9
114
    /**
115
     * @param $action
116 16
     * @throws \yii\db\Exception
117 9
     */
118
    public function audit($action)
119
    {
120 35
        // Not active? get out of here
121 2
        if (!$this->active) {
122 6
            return;
123
        }
124
        // Lets check if the whole class should be ignored
125 11
        if (sizeof($this->ignoredClasses) > 0 && array_search(get_class($this->owner), $this->ignoredClasses) !== false) {
126 29
            return;
127
        }
128
        // If this is a delete then just write one row and get out of here
129
        if ($action == 'DELETE') {
130
            $this->saveAuditTrailDelete();
131
            return;
132
        }
133
        // Now lets actually write the attributes
134 11
        $this->auditAttributes($action);
135
    }
136 11
137 11
    /**
138 11
     * Clean attributes of fields that are not allowed or ignored.
139
     *
140
     * @param $attributes
141
     * @return mixed
142
     */
143
    protected function cleanAttributes($attributes)
144
    {
145
        $attributes = $this->cleanAttributesAllowed($attributes);
146
        $attributes = $this->cleanAttributesIgnored($attributes);
147 11
        $attributes = $this->cleanAttributesOverRide($attributes);
148
        return $attributes;
149 11
    }
150 2
151 2
    /**
152 2
     * Unset attributes which are not allowed
153 2
     *
154 2
     * @param $attributes
155 2
     * @return mixed
156 11
     */
157
    protected function cleanAttributesAllowed($attributes)
158
    {
159
        if (sizeof($this->allowed) > 0) {
160
            foreach ($attributes as $f => $v) {
161
                if (array_search($f, $this->allowed) === false) {
162
                    unset($attributes[$f]);
163
                }
164
            }
165 11
        }
166
        return $attributes;
167 11
    }
168 2
169 2
    /**
170 2
     * Unset attributes which are ignored
171 2
     *
172 2
     * @param $attributes
173 2
     * @return mixed
174 11
     */
175
    protected function cleanAttributesIgnored($attributes)
176
    {
177
        if (sizeof($this->ignored) > 0) {
178
            foreach ($attributes as $f => $v) {
179
                if (array_search($f, $this->ignored) !== false) {
180
                    unset($attributes[$f]);
181 27
                }
182
            }
183
        }
184 11
        return $attributes;
185 11
    }
186
187 11
    /**
188 3
     * attributes which need to get override with a new value
189
     *
190
     * @param $attributes
191 10
     * @return mixed
192 10
     */
193 10
    protected function cleanAttributesOverRide($attributes)
194 10
    {
195 10
        if (sizeof($this->overRide) > 0 && sizeof($attributes) >0) {
196
            foreach ($this->overRide as $field => $queryParams) {
197 10
                $newOverRideValues = $this->getNewOverRideValues($attributes[$field], $queryParams);
198 26
199
                if (count($newOverRideValues) >1) {
200
                    $attributes[$field] = $this->getCommaString($newOverRideValues, $queryParams['return_field']);
201
                } elseif (count($newOverRideValues) == 1) {
202
                    $attributes[$field] = $newOverRideValues[0][$queryParams['return_field']];
203
                }
204
            }
205
        }
206
        return $attributes;
207
    }
208
209
    /**
210
     * @param string $searchFieldValue
211
     * @param string $queryParams
212
     * @return mixed
213 26
     */
214
    private function getNewOverRideValues($searchFieldValue, $queryParams)
215
    {
216 26
        $query = new Query;
217 10
218 14
        $query->select($queryParams['return_field'])
219
              ->from($queryParams['table_name'])
220 14
              ->where([$queryParams['search_field'] => $searchFieldValue]);
221 16
222 10
        $rows = $query->all();
223 10
224
        return $rows;
225 26
    }
226 26
227 10
    /**
228 10
     * @param array $array
229 10
     * @param string $return_field
230 26
     * @return mixed
231
     */
232
233
    private function getCommaString($array, $return_field)
234
    {
235 6
        $tempArray = [];
236
237 2
        foreach ($array as $key => $value) {
238 2
            $tempArray[] = $value[$return_field];
239 6
        }
240 6
241 6
        return implode(',', $tempArray);
242 6
    }
243 6
244 6
    /**
245 2
     * @param string $action
246 6
     * @throws \yii\db\Exception
247
     */
248
    protected function auditAttributes($action)
249
    {
250
        // Get the new and old attributes
251 29
        $newAttributes = $this->cleanAttributes($this->owner->getAttributes());
252
        $oldAttributes = $this->cleanAttributes($this->getOldAttributes());
253 29
        // If no difference then get out of here
254
        if (count(array_diff_assoc($newAttributes, $oldAttributes)) <= 0) {
255
            return;
256
        }
257
        // Get the trail data
258
        $entry_id = $this->getAuditEntryId();
259 27
        $user_id = $this->getUserId();
260
        $model = $this->owner->className();
261 27
        $model_id = $this->getNormalizedPk();
262 27
        $created = date($this->dateFormat);
263
264
        $this->saveAuditTrail($action, $newAttributes, $oldAttributes, $entry_id, $user_id, $model, $model_id, $created);
265
    }
266
267 12
    /**
268
     * Save the audit trails for a create or update action
269 12
     *
270 12
     * @param $action
271
     * @param $newAttributes
272
     * @param $oldAttributes
273
     * @param $entry_id
274
     * @param $user_id
275
     * @param $model
276 12
     * @param $model_id
277
     * @param $created
278 12
     * @throws \yii\db\Exception
279
     */
280
    protected function saveAuditTrail($action, $newAttributes, $oldAttributes, $entry_id, $user_id, $model, $model_id, $created)
281
    {
282
        // Build a list of fields to log
283
        $rows = array();
284
        foreach ($newAttributes as $field => $new) {
285 32
            $old = isset($oldAttributes[$field]) ? $oldAttributes[$field] : '';
286
            // If they are not the same lets write an audit log
287 12
            if ($new != $old) {
288 32
                $rows[] = [$entry_id, $user_id, $old, $new, $action, $model, $model_id, $field, $created];
289
            }
290
        }
291 32
        // Record the field changes with a batch insert
292
        if (!empty($rows)) {
293
            $columns = ['entry_id', 'user_id', 'old_value', 'new_value', 'action', 'model', 'model_id', 'field', 'created'];
294 12
            $audit = Audit::getInstance();
295
            $audit->getDb()->createCommand()->batchInsert(AuditTrail::tableName(), $columns, $rows)->execute();
296
        }
297
    }
298
299
    /**
300
     * Save the audit trails for a delete action
301
     */
302
    protected function saveAuditTrailDelete()
303
    {
304
        $audit = Audit::getInstance();
305
        $audit->getDb()->createCommand()->insert(AuditTrail::tableName(), [
306
            'action' => 'DELETE',
307
            'entry_id' => $this->getAuditEntryId(),
308
            'user_id' => $this->getUserId(),
309
            'model' => $this->owner->className(),
310
            'model_id' => $this->getNormalizedPk(),
311
            'created' => date($this->dateFormat),
312
        ])->execute();
313
    }
314
315
    /**
316
     * @return array
317
     */
318
    public function getOldAttributes()
319
    {
320
        return $this->_oldAttributes;
321
    }
322
323
    /**
324
     * @param $value
325
     */
326
    public function setOldAttributes($value)
327
    {
328
        $this->_oldAttributes = $value;
329
    }
330
331
    /**
332
     * @return string
333
     */
334
    protected function getNormalizedPk()
335
    {
336
        $pk = $this->owner->getPrimaryKey();
337
        return is_array($pk) ? json_encode($pk) : $pk;
338
    }
339
340
    /**
341
     * @return int|null|string
342
     */
343
    protected function getUserId()
344
    {
345
        return (Yii::$app instanceof Application && Yii::$app->user) ? Yii::$app->user->id : null;
346
    }
347
348
    /**
349
     * @return models\AuditEntry|null|static
350
     * @throws \Exception
351
     */
352
    protected function getAuditEntryId()
353
    {
354
        $module = Audit::getInstance();
355
        if (!$module) {
356
            $module = \Yii::$app->getModule(Audit::findModuleIdentifier());
357
        }
358
        if (!$module) {
359
            throw new \Exception('Audit module cannot be loaded');
360
        }
361
        return Audit::getInstance()->getEntry(true)->id;
362
    }
363
364
}
365