JsLogController::actionIndex()   B
last analyzed

Complexity

Conditions 8
Paths 32

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 32
nop 0
dl 0
loc 41
rs 8.0195
c 0
b 0
f 0
1
<?php
2
3
namespace bedezign\yii2\audit\controllers;
4
5
use bedezign\yii2\audit\Audit;
6
use bedezign\yii2\audit\models;
7
use Yii;
8
use yii\helpers\Json;
9
use yii\web\Response;
10
11
/**
12
 * JsLogController
13
 * @package bedezign\yii2\audit\controllers
14
 */
15
class JsLogController extends \yii\web\Controller
16
{
17
    /**
18
     * @param \yii\base\Action $action
19
     * @return bool
20
     * @throws \yii\web\BadRequestHttpException
21
     */
22
    public function beforeAction($action)
23
    {
24
        $this->enableCsrfValidation = false;
25
        return parent::beforeAction($action);
26
    }
27
28
    /**
29
     * @return array
30
     */
31
    public function actionIndex()
32
    {
33
        Yii::$app->response->format = Response::FORMAT_JSON;
34
        $data = Json::decode(Yii::$app->request->post('data'));
35
        if (!isset($data['auditEntry'])) {
36
            $entry = Audit::getInstance()->getEntry(true);
37
            $data['auditEntry'] = $entry->id;
38
        }
39
40
        // Convert data into the loggable object
41
        $javascript = new models\AuditJavascript();
42
        $map = [
43
            'auditEntry' => 'entry_id',
44
            'message'    => 'message',
45
            'type'       => 'type',
46
            'file'       => 'origin',
47
            'line'       => function ($value) use ($javascript) {
48
                $javascript->origin .= ':' . $value;
49
            },
50
            'col'        => function ($value) use ($javascript) {
51
                $javascript->origin .= ':' . $value;
52
            },
53
            'data'       => function ($value) use ($javascript) {
54
                if (count($value)) $javascript->data = $value;
55
            },
56
        ];
57
58
        foreach ($map as $key => $target)
59
            if (isset($data[$key])) {
60
                if (is_callable($target)) $target($data[$key]);
61
                else $javascript->$target = $data[$key];
62
            }
63
64
        if (!$javascript->type)
65
            $javascript->type = 'unknown';
66
67
        if ($javascript->save())
68
            return ['result' => 'ok', 'entry' => $data['auditEntry']];
69
70
        return ['result' => 'error', 'errors' => $javascript->getErrors()];
71
    }
72
}