Passed
Pull Request — master (#59)
by
unknown
03:44
created

ViewRelationshipAction   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A run() 0 22 4
1
<?php
2
3
namespace tuyakhov\jsonapi\actions;
4
5
use Yii;
6
use yii\base\Model;
7
use yii\web\NotFoundHttpException;
8
use tuyakhov\jsonapi\Inflector;
9
use tuyakhov\jsonapi\Relationship;
10
11
12
class ViewRelationshipAction extends Action
13
{
14
    /**
15
     * @var string the scenario to be assigned to the new model before it is validated and saved.
16
     */
17
    public $scenario = Model::SCENARIO_DEFAULT;
18
19
    /**
20
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
21
     */
22
    public $viewAction = 'view-relationship';
23
24
    /**
25
     * Gets a relationship between resources
26
     * @return array a relationship definition between resources
27
     * @throws NotFoundHttpException if the relationship doesn't exist
28
     */
29
    public function run($id, $name)
30
    {
31
        /* @var $model \yii\db\ActiveRecord */
32
        $model = $this->findModel($id);
33
34
        if (!$related = $model->getRelation($name, false)) {
35
            throw new NotFoundHttpException('Relationship does not exist');
36
        }
37
38
        if ($this->checkAccess) {
39
            call_user_func($this->checkAccess, $this->id, $model, $name);
40
        }
41
42
        $relationship = new Relationship([
43
            'multiple' => $related->multiple
44
        ]);
45
        
46
        if ($related->multiple) {
47
            return $relationship->addRelated($related->all());
48
        }
49
50
        return $relationship->addRelated($related->one());
51
    }
52
}