Mock.php
3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?php
namespace Lackoxygen\TiktokShop\Support\Mock;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use Lackoxygen\TiktokShop\Exception\ClientException;
use Lackoxygen\TiktokShop\Exception\MockException;
use Lackoxygen\TiktokShop\Support\Json;
class Mock
{
/**
* @var string
*/
protected string $request;
/**
* @var string
*/
protected string $method;
/**
* @var Annotation
*/
protected Annotation $annotation;
/**
* @param string $request
* @param string $method
*/
public function __construct(string $request, string $method)
{
$this->request = $request;
$this->method = $method;
$this->annotation = new Annotation();
}
/**
* @param string $url
* @return Response
* @throws ClientException
* @throws MockException
*/
protected function request(string $url): Response
{
if (empty($url)) {
throw new MockException('Unable to simulate data, no document address provided');
}
$pathInfo = parse_url($url, PHP_URL_PATH);
$pathParts = explode('/', $pathInfo);
$articleId = end($pathParts);
$client = new Client([
'base_uri' => 'https://op.jinritemai.com'
]);
try {
$response = $client->get('doc/external/open/queryDocArticleDetail', [
RequestOptions::QUERY => [
'articleId' => $articleId,
'onlyView' => false
]
]);
} catch (GuzzleException $e) {
throw new ClientException($e);
}
$content = $response->getBody()->getContents();
$array = Json::unmarshal($content);
if (0 !== $array['code']) {
throw new MockException(sprintf('Abnormal response error, %s', $array['message']));
}
$articleContent = Json::unmarshal($array['data']['article']['content']);
return new Response(
200,
['server' => 'mock', 'version' => $array['data']['article']['info']['version']],
new Stream($articleContent['demo']['responseDemo']['responseSuccess'])
);
}
/**
* @return Response
*/
public function response(): Response
{
$methodAnnotation = $this->annotation->method(
$this->request,
$this->method
);
$url = $this->extractUrlAnnotation(
$methodAnnotation
);
try {
$response = $this->request($url);
} catch (ClientException|MockException $e) {
return new Response(
500,
['server' => 'mock'],
new Stream($e->getMessage())
);
}
return $response;
}
/**
* @param array $methodAnnotation
* @return false|mixed
*/
protected function extractUrlAnnotation(array $methodAnnotation)
{
$tag = '@link';
$line = $methodAnnotation[$tag] ?? [];
return $line ? $line[0] : false;
}
}