Passed
Push — master ( ab52bb...736a62 )
by Anton
02:12
created

UpdateRelationshipAction::run()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 28
rs 8.439
cc 6
eloc 15
nc 9
nop 2
1
<?php
2
/**
3
 * @link http://www.stombox.com/
4
 * @copyright Copyright (c) 2015 Stombox LLC
5
 * @license http://www.stombox.com/license/
6
 */
7
8
namespace tuyakhov\jsonapi;
9
10
use yii\db\BaseActiveRecord;
11
use yii\rest\Action;
12
use yii\web\BadRequestHttpException;
13
use yii\web\ServerErrorHttpException;
14
15
class UpdateRelationshipAction extends Action
16
{
17
    /**
18
     * @param $id
19
     * @param $name
20
     * @throws BadRequestHttpException
21
     * @throws ServerErrorHttpException
22
     */
23
    public function run($id, $name)
24
    {
25
        /** @var BaseActiveRecord $model */
26
        $model = $this->findModel($id);
27
28
        if (!$model instanceof ResourceInterface) {
29
            throw new BadRequestHttpException('Impossible to update relationships for resource');
30
        }
31
32
        $data = \Yii::$app->getRequest()->getBodyParams();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 10 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
33
        $relationships = [];
34
        foreach ($data as $modelName => $identifier) {
35
            if (!isset($identifier['id'])) {
36
                continue;
37
            }
38
            /** @var BaseActiveRecord $modelName */
39
            if ($relationship = $modelName::findOne($identifier['id'])) {
40
                $relationships[] = $relationship;
41
            }
42
        }
43
44
        if (!empty($relationships)) {
45
            $model->unlinkAll($name);
46
            $model->setResourceRelationship($name, $relationships);
47
        }
48
49
        throw new ServerErrorHttpException('Failed to update the relationship for unknown reason.');
50
    }
51
}