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

ViewRelatedAction::run()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 29
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 29
rs 8.439
cc 6
eloc 15
nc 9
nop 2
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\rest\Action;
13
use yii\web\BadRequestHttpException;
14
use yii\web\NotFoundHttpException;
15
16
class ViewRelatedAction extends Action
17
{
18
    /**
19
     * Prepares the data provider that should return the requested collection of the models.
20
     * @var callable
21
     */
22
    public $prepareDataProvider;
23
24
    /**
25
     * @param $id
26
     * @param $name
27
     * @return ActiveDataProvider|\yii\db\ActiveRecordInterface
28
     * @throws BadRequestHttpException
29
     * @throws NotFoundHttpException
30
     */
31
    public function run($id, $name)
32
    {
33
        $model = $this->findModel($id);
34
35
        if (!$model instanceof ResourceInterface) {
36
            throw new BadRequestHttpException('Impossible to fetch related resource');
37
        }
38
39
        if ($this->checkAccess) {
40
            call_user_func($this->checkAccess, $this->id, $model);
41
        }
42
43
        /** @var ActiveQuery $related */
44
        if (!$related = $model->getRelation($name, false)) {
45
            throw new NotFoundHttpException('Resource does not exist');
46
        }
47
48
        if ($this->prepareDataProvider !== null) {
49
            return call_user_func($this->prepareDataProvider, $this, $related);
50
        }
51
52
        if ($related->multiple) {
53
            return new ActiveDataProvider([
54
                'query' => $related
55
            ]);
56
        } else {
57
            return $related->one();
58
        }
59
    }
60
}