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
|
|
|
} |
|
|
|
|
60
|
|
|
|
This check marks files that end in a newline character, i.e. an empy line.