Skip to content

Commit

Permalink
feat: 使用 Fractal 重构 Format
Browse files Browse the repository at this point in the history
  • Loading branch information
jiannei committed Oct 11, 2023
1 parent 623de65 commit d10582f
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 9 deletions.
1 change: 0 additions & 1 deletion src/Support/Facades/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Illuminate\Support\Facades\Facade as IlluminateFacade;

/**
*
* @method static JsonResponse response($data = [], int $status = 200, array $headers = [], int $options = 0)
* @method static array data($data, ?string $message, int $code, $errors = null)
* @method static array paginator(AbstractPaginator|AbstractCursorPaginator $resource)
Expand Down
9 changes: 9 additions & 0 deletions src/Support/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Jiannei\Response\Laravel\Support;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
Expand Down Expand Up @@ -57,6 +58,14 @@ public function response($data = [], int $status = 200, array $headers = [], int
*/
public function data($data, ?string $message, int $code, $errors = null): array
{
$data = match (true) {
$data instanceof ResourceCollection => $this->resourceCollection($data),
$data instanceof JsonResource => $this->jsonResource($data),
$data instanceof AbstractPaginator || $data instanceof AbstractCursorPaginator => $this->paginator($data),
$data instanceof Arrayable || (is_object($data) && method_exists($data, 'toArray')) => $data->toArray(),
default => Arr::wrap($data)
};

return $this->formatDataFields([
'status' => $this->formatStatus($code),
'code' => $code,
Expand Down
8 changes: 0 additions & 8 deletions src/Support/Traits/JsonResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,14 +199,6 @@ public function fail(string $message = '', int $code = 500, $errors = null, arra
*/
public function success($data = [], string $message = '', int $code = 200, array $headers = [], int $option = 0)
{
$data = match (true) {
$data instanceof ResourceCollection => Format::resourceCollection($data),
$data instanceof JsonResource => Format::jsonResource($data),
$data instanceof AbstractPaginator || $data instanceof AbstractCursorPaginator => Format::paginator($data),
$data instanceof Arrayable || (is_object($data) && method_exists($data, 'toArray')) => $data->toArray(),
default => Arr::wrap($data)
};

return Format::response(Format::data($data,$message,$code), $code, $headers, $option);
}
}

0 comments on commit d10582f

Please sign in to comment.