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