1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Anton Tuyakhov <[email protected]> |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace tuyakhov\jsonapi\actions; |
7
|
|
|
|
8
|
|
|
use yii\data\ActiveDataProvider; |
9
|
|
|
use yii\db\BaseActiveRecord; |
10
|
|
|
use yii\web\BadRequestHttpException; |
11
|
|
|
use yii\web\NotFoundHttpException; |
12
|
|
|
use Yii; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* UpdateRelationshipAction implements the API endpoint for updating relationships. |
16
|
|
|
* @link http://jsonapi.org/format/#crud-updating-relationships |
17
|
|
|
*/ |
18
|
|
|
class UpdateRelationshipAction extends Action |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Update of relationships independently. |
22
|
|
|
* @param string $id an ID of the primary resource |
23
|
|
|
* @param string $name a name of the related resource |
24
|
|
|
* @return ActiveDataProvider|BaseActiveRecord |
25
|
|
|
* @throws BadRequestHttpException |
26
|
|
|
* @throws NotFoundHttpException |
27
|
|
|
*/ |
28
|
|
|
public function run($id, $name) |
29
|
|
|
{ |
30
|
|
|
/** @var BaseActiveRecord $model */ |
31
|
|
|
$model = $this->findModel($id); |
32
|
|
|
|
33
|
|
|
if (!$related = $model->getRelation($name, false)) { |
34
|
|
|
throw new NotFoundHttpException('Relationship does not exist'); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
if ($this->checkAccess) { |
38
|
|
|
call_user_func($this->checkAccess, $this->id, $model, $name); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$this->linkRelationships($model, [$name => Yii::$app->getRequest()->getBodyParams()]); |
42
|
|
|
|
43
|
|
|
if ($related->multiple) { |
44
|
|
|
return new ActiveDataProvider([ |
45
|
|
|
'query' => $related |
46
|
|
|
]); |
47
|
|
|
} else { |
48
|
|
|
return $related->one(); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
} |