Passed
Push — master ( 42aa49...a46232 )
by Anton
04:55
created

ViewRelatedAction::run()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 8
nop 2
dl 0
loc 27
rs 9.2222
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\jsonapi\actions;
7
8
9
use tuyakhov\jsonapi\ResourceInterface;
10
use yii\data\ActiveDataProvider;
11
use yii\db\ActiveQuery;
12
use yii\web\BadRequestHttpException;
13
use yii\web\NotFoundHttpException;
14
15
class ViewRelatedAction extends Action
16
{
17
    /**
18
     * Prepares the data provider that should return the requested collection of the models.
19
     * @var callable
20
     */
21
    public $prepareDataProvider;
22
23
    /**
24
     * @param $id
25
     * @param $name
26
     * @return ActiveDataProvider|\yii\db\ActiveRecordInterface
27
     * @throws BadRequestHttpException
28
     * @throws NotFoundHttpException
29
     */
30
    public function run($id, $name)
31
    {
32
        $model = $this->findModel($id);
33
34
        if (!$model instanceof ResourceInterface) {
35
            throw new BadRequestHttpException('Impossible to fetch related resource');
36
        }
37
38
        /** @var ActiveQuery $related */
39
        if (!$related = $model->getRelation($name, false)) {
40
            throw new NotFoundHttpException('Resource does not exist');
41
        }
42
43
        if ($this->checkAccess) {
44
            call_user_func($this->checkAccess, $this->id, $model, $name);
45
        }
46
47
        if ($this->prepareDataProvider !== null) {
48
            return call_user_func($this->prepareDataProvider, $this, $related, $name);
49
        }
50
51
        if ($related->multiple) {
52
            return new ActiveDataProvider([
53
                'query' => $related
54
            ]);
55
        } else {
56
            return $related->one();
57
        }
58
    }
59
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
60