*/ namespace App\Controller\Admin; use App\Controller\AbstractController; use Hyperf\Contract\LengthAwarePaginatorInterface; use Hyperf\Database\Model\Collection; use Psr\Http\Message\ResponseInterface; abstract class Base extends AbstractController { public function accountId(): int { return $this->request->getAttribute("account_id"); } public function uuid(): string { return $this->account()['uuid']; } public function account() { return $this->request->getAttribute("account"); } /** * Author: cfn * @param array|string $msg * @param LengthAwarePaginatorInterface|Collection|array|null $data * @param null $count * @param null $summary * @return ResponseInterface */ public function success(array|string $msg = "success", LengthAwarePaginatorInterface|Collection|array|null $data = null, $count = null, $summary = null) { if (!is_string($msg)) { $data = $msg; $msg = "success"; } if ($data instanceof LengthAwarePaginatorInterface) { $count = $data->total(); $data = $data->items(); } if ($data instanceof Collection) { $data = $data->toArray(); } return $this->response(0, $msg, $data, $count, $summary); } /** * Author: cfn * @param array|string $msg * @param LengthAwarePaginatorInterface|array|null $data * @param null $count * @param null $summary * @return ResponseInterface */ public function error(array|string $msg = "error", LengthAwarePaginatorInterface|array|null $data = null, $count = null, $summary = null) { if (!is_string($msg)) { $data = $msg; $msg = "error"; } if ($data instanceof LengthAwarePaginatorInterface) { $count = $data->total(); $data = $data->items(); } return $this->response(1, $msg, $data, $count, $summary); } /** * @param int|bool $res * @return ResponseInterface */ public function toAjax(int|bool $res) { if (is_int($res)) { return $res > 0 ? $this->success("操作成功") : $this->error("操作失败"); } if (is_bool($res)) { return $res ? $this->success("操作成功") : $this->error("操作失败"); } return $this->error("操作失败"); } /** * 响应 * @param int $code * @param string $msg * @param array|null $data * @param int|null $count * @param array|null $summary * @return ResponseInterface */ protected function response(int $code, string $msg, array $data = null, int $count = null, array $summary = null): ResponseInterface { $body = compact("code", "msg", "data", "count", "summary"); if ($count === null) unset($body['count']); if ($data === null) unset($body['data']); if ($summary === null) unset($body['summary']); return $this->response->json($body); } }