Completed
Push — master ( 0daec9...07eda8 )
by Paweł
02:54
created

AccountController::actionIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 06.05.2018
6
 */
7
8
namespace app\modules\api\v1\controllers;
9
10
11
use app\models\Tag;
12
use app\modules\api\v1\components\ActiveController;
13
use app\modules\api\v1\models\Account;
14
use app\modules\api\v1\models\AccountSearch;
15
use yii\helpers\ArrayHelper;
16
use yii\helpers\Inflector;
17
use yii\helpers\StringHelper;
18
use yii\helpers\Url;
19
use yii\web\ServerErrorHttpException;
20
21
class AccountController extends ActiveController
22
{
23
    public $modelClass = Account::class;
24
25
    public function actions()
26
    {
27
        $actions = parent::actions();
28
        unset($actions['create'], $actions['index']);
29
30
        return $actions;
31
    }
32
33
    public function actionIndex()
34
    {
35
        $searchModel = new AccountSearch();
36
37
        return $searchModel->search(\Yii::$app->request->queryParams);
38
    }
39
40
    public function actionCreate()
41
    {
42
        $bodyParams = \Yii::$app->getRequest()->getBodyParams();
43
44
        $username = ArrayHelper::getValue($bodyParams, 'username');
45
        $tags = ArrayHelper::remove($bodyParams, 'tags', '');
46
47
        $account = $this->findOrCreateModel($username);
48
        $isNewRecord = $account->isNewRecord;
49
50
        $account->load($bodyParams, '');
51
        if ($account->save()) {
52
            $this->linkTags($tags, $account);
53
54
            $response = \Yii::$app->getResponse();
55
            $response->setStatusCode($isNewRecord ? 201 : 200);
56
57
            // TODO uncomment after create "view" endpoint
58
//            $id = implode(',', array_values($model->getPrimaryKey(true)));
59
//            $response->getHeaders()->set('Location', Url::toRoute(['view', 'id' => $id], true));
60
61
        } elseif (!$account->hasErrors()) {
62
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
63
        }
64
65
        return $account;
66
    }
67
68
    protected function linkTags(string $tags, Account $account): void
69
    {
70
        $tags = StringHelper::explode($tags, ',', true, true);
71
        $tags = array_unique($tags);
72
73
        foreach ($tags as $name) {
74
            try {
75
                $tag = Tag::findOne(['slug' => Inflector::slug($name)]);
76
                if ($tag === null) {
77
                    $tag = new Tag();
78
                    $tag->name = $name;
79
                    $tag->insert();
80
                }
81
                $account->link('tags', $tag);
82
            } catch (\Throwable $exception) {
83
                \Yii::error(sprintf('API: account tag error: %s', $exception->getMessage()), __METHOD__);
84
                continue;
85
            }
86
        }
87
    }
88
89
    /**
90
     * @param $username
91
     * @return \app\modules\api\v1\models\Account|null
92
     */
93
    protected function findOrCreateModel($username)
94
    {
95
        $account = Account::findOne(['username' => $username]);
96
97
        if ($account === null) {
98
            $account = new Account();
99
            $account->setScenario($this->createScenario);
100
        }
101
102
        return $account;
103
    }
104
}