1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright Copyright (c) Flipbox Digital Limited |
5
|
|
|
* @license https://github.com/flipbox/salesforce/blob/master/LICENSE.md |
6
|
|
|
* @link https://github.com/flipbox/salesforce |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace flipbox\craft\salesforce\helpers; |
10
|
|
|
|
11
|
|
|
use Craft; |
12
|
|
|
use flipbox\craft\salesforce\transformers\DynamicModelResponse; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
use yii\base\DynamicModel; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @author Flipbox Factory <[email protected]> |
18
|
|
|
* @since 1.1.0 |
19
|
|
|
*/ |
20
|
|
|
class TransformerHelper |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* The sync payload action name |
24
|
|
|
*/ |
25
|
|
|
const PAYLOAD_ACTION_SYNC = 'sync'; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* The sync payload action name |
29
|
|
|
*/ |
30
|
|
|
const PAYLOAD_ACTION_SAVE = 'save'; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param ResponseInterface $response |
34
|
|
|
* @return DynamicModel |
35
|
|
|
*/ |
36
|
|
|
public static function responseToModel(ResponseInterface $response): DynamicModel |
37
|
|
|
{ |
38
|
|
|
return call_user_func_array( |
39
|
|
|
new DynamicModelResponse(), |
40
|
|
|
[ |
41
|
|
|
$response |
42
|
|
|
] |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param $transformer |
48
|
|
|
* @return bool |
49
|
|
|
*/ |
50
|
|
|
public static function isTransformerClass($transformer): bool |
51
|
|
|
{ |
52
|
|
|
return is_string($transformer) && |
53
|
|
|
class_exists($transformer) && |
54
|
|
|
( |
55
|
|
|
method_exists($transformer, '__invoke') || |
56
|
|
|
is_callable([$transformer, '__invoke']) |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param $transformer |
62
|
|
|
* @return bool |
63
|
|
|
*/ |
64
|
|
|
public static function isTransformerClassArray($transformer): bool |
65
|
|
|
{ |
66
|
|
|
if (!is_array($transformer)) { |
67
|
|
|
false; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return static::isTransformerClass($transformer['class'] ?? null); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @noinspection PhpDocMissingThrowsInspection |
75
|
|
|
* |
76
|
|
|
* @param $transformer |
77
|
|
|
* @return callable|null |
78
|
|
|
*/ |
79
|
|
|
public static function resolveTransformer($transformer) |
80
|
|
|
{ |
81
|
|
|
if (is_callable($transformer)) { |
82
|
|
|
return $transformer; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
if (static::isTransformerClass($transformer)) { |
86
|
|
|
return new $transformer(); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
if (static::isTransformerClassArray($transformer)) { |
90
|
|
|
/** @noinspection PhpIncompatibleReturnTypeInspection */ |
91
|
|
|
/** @noinspection PhpUnhandledExceptionInspection */ |
92
|
|
|
return Craft::createObject($transformer); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
return null; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|