Skip to content

Commit d428362

Browse files
authored
Create Clientable
1 parent 403bd3c commit d428362

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

src/Traits/Clientable

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?php
2+
3+
namespace ZhenMu\Support\Traits;
4+
5+
trait Clientable
6+
{
7+
use Arrayable;
8+
9+
/** @var \GuzzleHttp\Psr7\Response */
10+
protected $response;
11+
12+
protected array $result = [];
13+
14+
public static function make()
15+
{
16+
return new static();
17+
}
18+
19+
abstract public function getHttpClient();
20+
21+
abstract public function handleEmptyResponse(?string $content = null);
22+
23+
abstract public function isErrorResponse(): bool;
24+
25+
abstract public function handleErrorResponse(?string $content = null);
26+
27+
abstract public function hasPaginate(): bool;
28+
29+
abstract public function getTotal(): ?int;
30+
31+
abstract public function getPageSize(): ?int;
32+
33+
abstract public function getCurrentPage(): ?int;
34+
35+
abstract public function getLastPage(): ?int;
36+
37+
abstract public function getDataList(): static|array|null;
38+
39+
protected function castResponse()
40+
{
41+
$this->result = json_decode($content = $this->response->getBody()->getContents(), true) ?? [];
42+
$this->attributes = $this->result;
43+
44+
if (empty($this->result)) {
45+
$this->handleEmptyResponse($content);
46+
}
47+
48+
if ($this->isErrorResponse()) {
49+
$this->handleErrorResponse($content);
50+
}
51+
52+
return true;
53+
}
54+
55+
public function paginate()
56+
{
57+
if (!$this->hasPaginate()) {
58+
return null;
59+
}
60+
61+
$paginate = new \Illuminate\Pagination\LengthAwarePaginator(
62+
items: $this->getDataList(),
63+
total: $this->getTotal(),
64+
perPage: $this->getPageSize(),
65+
currentPage: $this->getCurrentPage(),
66+
);
67+
68+
$paginate
69+
->withPath('/'.\request()->path())
70+
->withQueryString();
71+
72+
return $paginate;
73+
}
74+
75+
76+
public function __call($method, $args)
77+
{
78+
$this->response = $this->getHttpClient()->$method(...$args);
79+
80+
$this->castResponse();
81+
82+
return $this;
83+
}
84+
}

0 commit comments

Comments
 (0)