Issues (17)

src/actions/ViewRelatedAction.php (1 issue)

1
<?php
2
/**
3
 * @author Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\jsonapi\actions;
7
8
9
use tuyakhov\jsonapi\Pagination;
10
use tuyakhov\jsonapi\ResourceInterface;
11
use yii\data\ActiveDataProvider;
12
use yii\db\ActiveQuery;
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
        /** @var ActiveQuery $related */
40
        if (!$related = $model->getRelation($name, false)) {
41
            throw new NotFoundHttpException('Resource does not exist');
42
        }
43
44
        if ($this->checkAccess) {
45
            call_user_func($this->checkAccess, $this->id, $model, $name);
46
        }
47
48
        if ($this->prepareDataProvider !== null) {
49
            return call_user_func($this->prepareDataProvider, $this, $related, $name);
50
        }
51
52
        if ($related->multiple) {
53
            return new ActiveDataProvider([
54
                'query' => $related,
55
                'pagination' => [
56
                    'class' => Pagination::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

56
                    'class' => /** @scrutinizer ignore-deprecated */ Pagination::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
57
                ],
58
            ]);
59
        } else {
60
            return $related->one();
61
        }
62
    }
63
}
64