Passed
Push — master ( 7dcb7e...64a507 )
by Anton
02:31
created

UpdateRelationshipAction   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 8
c 1
b 0
f 1
lcom 0
cbo 8
dl 0
loc 52
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C run() 0 42 8
1
<?php
2
/**
3
 * @author Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\jsonapi\actions;
7
8
use tuyakhov\jsonapi\ResourceInterface;
9
use yii\data\ActiveDataProvider;
10
use yii\db\BaseActiveRecord;
11
use yii\helpers\ArrayHelper;
12
use yii\rest\Action;
13
use yii\web\BadRequestHttpException;
14
use yii\web\NotFoundHttpException;
15
16
class UpdateRelationshipAction extends Action
17
{
18
    /**
19
     * @param $id
20
     * @param $name
21
     * @return array|null|ActiveDataProvider|\yii\db\ActiveRecord|\yii\db\ActiveRecordInterface
22
     * @throws BadRequestHttpException
23
     * @throws NotFoundHttpException
24
     */
25
    public function run($id, $name)
26
    {
27
        /** @var BaseActiveRecord $model */
28
        $model = $this->findModel($id);
29
30
        if (!$model instanceof ResourceInterface) {
31
            throw new BadRequestHttpException('Impossible to update relationships for resource');
32
        }
33
34
        if (!$related = $model->getRelation($name, false)) {
35
            throw new NotFoundHttpException('Relationship does not exist');
36
        }
37
        $relatedClass = $related->modelClass;
38
39
        $data = \Yii::$app->getRequest()->getBodyParams();
40
        $data = ArrayHelper::isIndexed($data) ? $data : [$data];
41
42
        $ids = [];
43
        foreach ($data as $index => $relationshipObject) {
44
            if (!isset($relationshipObject['id'])) {
45
                continue;
46
            }
47
            $ids[] = $relationshipObject['id'];
48
        }
49
        /** @var BaseActiveRecord $relatedClass */
50
        $relationships = $relatedClass::find()
51
            ->andWhere(['in', $relatedClass::primaryKey(), $ids])
52
            ->all();
53
54
        if (!empty($relationships)) {
55
            $model->unlinkAll($name);
56
            $model->setResourceRelationship($name, $relationships);
57
        }
58
59
        if ($related->multiple) {
60
            return new ActiveDataProvider([
61
                'query' => $related
62
            ]);
63
        } else {
64
            return $related->one();
65
        }
66
    }
67
}