Mock.php
2.9 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
<?php
namespace Lackoxygen\TiktokShop\Mock;
use Lackoxygen\TiktokShop\Attribute\Config;
use Lackoxygen\TiktokShop\Attribute\Request;
use Lackoxygen\TiktokShop\Exception\ClientException;
use Lackoxygen\TiktokShop\Exception\MockException;
use Lackoxygen\TiktokShop\Util\Json;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Arr;
class Mock
{
protected string $passage;
protected string $method;
protected Annotation $annotation;
public function __construct(string $passage, string $method)
{
$this->passage = $passage;
$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'])
);
}
public function response(): Response
{
$methodAnnotation = $this->annotation->method(
$this->passage,
$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;
}
protected function extractUrlAnnotation(array $methodAnnotation)
{
$tag = '@link';
$line = $methodAnnotation[$tag] ?? [];
return $line ? $line[0] : false;
}
}