|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace prgTW\BaseCRM\Resource\Partial; |
|
4
|
|
|
|
|
5
|
|
|
use prgTW\BaseCRM\Resource\DetachedResource; |
|
6
|
|
|
use prgTW\BaseCRM\Resource\ResourceCollection; |
|
7
|
|
|
use prgTW\BaseCRM\Transport\Transport; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* @property Transport transport |
|
11
|
|
|
* @method string getResourceName($resourceClassName = null) |
|
12
|
|
|
* @method string getChildResourceName($resourceClassName = null) |
|
13
|
|
|
* @method string getObjectFromArray(array $params, $instanceClassName = null, $idParam = 'id') |
|
14
|
|
|
* @method string getFullUri($suffix = '') |
|
15
|
|
|
*/ |
|
16
|
|
|
trait CreateResource |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @param DetachedResource $resource |
|
20
|
|
|
* @param array $fieldNames |
|
21
|
|
|
* @param bool $useKey |
|
22
|
|
|
* |
|
23
|
|
|
* @throws \InvalidArgumentException on resource scopes mismatch |
|
24
|
|
|
* @return Resource|ResourceCollection |
|
|
|
|
|
|
25
|
|
|
*/ |
|
26
|
|
|
public function create(DetachedResource $resource, array $fieldNames = [], $useKey = true) |
|
27
|
|
|
{ |
|
28
|
|
|
$newResourceName = $resource->getResourceName(); |
|
29
|
|
|
$childResourceName = $this->getChildResourceName(); |
|
30
|
|
|
if ($newResourceName !== $childResourceName) |
|
31
|
|
|
{ |
|
32
|
|
|
//@codeCoverageIgnoreStart |
|
33
|
|
|
throw new \InvalidArgumentException(sprintf('Cannot create resource "%s" under resource "%s"', $newResourceName, $this->getResourceName())); |
|
|
|
|
|
|
34
|
|
|
//@codeCoverageIgnoreEnd |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$uri = $this->getFullUri(); |
|
38
|
|
|
$options = []; |
|
39
|
|
|
$dehydrated = $resource->dehydrate($fieldNames); |
|
|
|
|
|
|
40
|
|
|
if (true === $useKey) |
|
41
|
|
|
{ |
|
42
|
|
|
$options['query'] = [$childResourceName => $dehydrated]; |
|
43
|
|
|
} |
|
44
|
|
|
else |
|
45
|
|
|
{ |
|
46
|
|
|
$options['query'] = $dehydrated; |
|
47
|
|
|
} |
|
48
|
|
|
$data = $this->transport->post($uri, null, $options); |
|
49
|
|
|
|
|
50
|
|
|
if (array_key_exists($childResourceName, $data)) |
|
51
|
|
|
{ |
|
52
|
|
|
$data = $this->getObjectFromArray($data[$childResourceName]); |
|
53
|
|
|
} |
|
54
|
|
|
else |
|
55
|
|
|
{ |
|
56
|
|
|
$data = array_map([$this, 'getObjectFromArray'], $data); |
|
57
|
|
|
|
|
58
|
|
|
return new ResourceCollection($data); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return $data; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
This check compares the return type specified in the
@returnannotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.