|
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\db\ActiveRecordInterface; |
|
10
|
|
|
use yii\db\BaseActiveRecord; |
|
11
|
|
|
use yii\helpers\ArrayHelper; |
|
12
|
|
|
|
|
13
|
|
|
class Action extends \yii\rest\Action |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* Links the relationships with primary model. |
|
17
|
|
|
* @var callable |
|
18
|
|
|
*/ |
|
19
|
|
|
public $linkRelationships; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var bool Weather allow to do a full replacement of a to-many relationship |
|
23
|
|
|
*/ |
|
24
|
|
|
public $allowFullReplacement = true; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Links the relationships with primary model. |
|
28
|
|
|
* @param $model ActiveRecordInterface |
|
29
|
|
|
* @param array $data |
|
30
|
|
|
*/ |
|
31
|
|
|
protected function linkRelationships($model, array $data = []) |
|
32
|
|
|
{ |
|
33
|
|
|
if ($this->linkRelationships !== null) { |
|
34
|
|
|
call_user_func($this->linkRelationships, $this, $model, $data); |
|
35
|
|
|
return; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
if (!$model instanceof ResourceInterface) { |
|
39
|
|
|
return; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
foreach ($data as $name => $relationship) { |
|
43
|
|
|
if (!$related = $model->getRelation($name, false)) { |
|
|
|
|
|
|
44
|
|
|
continue; |
|
45
|
|
|
} |
|
46
|
|
|
/** @var BaseActiveRecord $relatedClass */ |
|
47
|
|
|
$relatedClass = new $related->modelClass; |
|
|
|
|
|
|
48
|
|
|
$relationships = ArrayHelper::keyExists($relatedClass->formName(), $relationship) ? $relationship[$relatedClass->formName()] : []; |
|
49
|
|
|
|
|
50
|
|
|
$ids = []; |
|
51
|
|
|
foreach ($relationships as $index => $relObject) { |
|
52
|
|
|
if (!isset($relObject['id'])) { |
|
53
|
|
|
continue; |
|
54
|
|
|
} |
|
55
|
|
|
$ids[] = $relObject['id']; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
if (!$records = $relatedClass::find()->andWhere(['in', $relatedClass::primaryKey(), $ids])->all()) { |
|
59
|
|
|
continue; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
if ($related->multiple && !$this->allowFullReplacement) { |
|
63
|
|
|
continue; |
|
64
|
|
|
} |
|
65
|
|
|
$model->unlinkAll($name); |
|
|
|
|
|
|
66
|
|
|
$model->setResourceRelationship($name, $records); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.