Skip to content

Commit

Permalink
pref: remove fractal
Browse files Browse the repository at this point in the history
  • Loading branch information
jiannei committed Oct 11, 2023
1 parent f006993 commit ff95cfe
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 61 deletions.
4 changes: 1 addition & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@
],
"require": {
"php": "^8.0",
"ext-json": "*",
"spatie/laravel-fractal": "^6.0"
"ext-json": "*"
},
"require-dev": {
"orchestra/testbench": "^8.0",
"jiannei/laravel-enum": "^3.0",
"league/fractal": "^0.20.1",
"phpunit/phpunit": "^10.0"
},
"autoload": {
Expand Down
109 changes: 52 additions & 57 deletions src/Support/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Traits\Macroable;
use League\Fractal\Pagination\Cursor;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Serializer\DataArraySerializer;
use Spatie\Fractal\Fractal;

class Format
{
Expand Down Expand Up @@ -82,52 +77,39 @@ public function data($data, ?string $message, int $code, $errors = null): array
* Format paginator data.
*
* @param AbstractPaginator|AbstractCursorPaginator $resource
* @param null $transformer
* @param null $resourceName
* @return array
*/
public function paginator(AbstractPaginator|AbstractCursorPaginator $resource, $transformer = null, $resourceName = null): array
public function paginator(AbstractPaginator|AbstractCursorPaginator $resource): array
{
$fractal = fractal()
->collection($resource, $transformer ?: fn ($item) => $item->toArray(), $resourceName)
->serializeWith(DataArraySerializer::class);

return tap($fractal, $this->formatCollection($resource))->toArray();
return [
'data' => $resource->toArray()['data'],
'meta' => $this->formatMeta($resource)
];
}

/**
* Format collection resource data.
*
* @param ResourceCollection $collection
* @param null $transformer
* @param null $resourceName
* @return array
*/
public function resourceCollection(ResourceCollection $collection, $transformer = null, $resourceName = null): array
public function resourceCollection(ResourceCollection $collection): array
{
$fractal = fractal()
->collection($collection->resource, $transformer ?: $this->formatJsonResource(), $resourceName)
->serializeWith(DataArraySerializer::class);

return tap($fractal, $this->formatCollection($collection->resource))->toArray();
return array_filter([
'data' => $collection->toArray(request()),
'meta' => $this->formatMeta($collection->resource)
]);
}

/**
* Format JsonResource Data.
*
* @param JsonResource $resource
* @param null $transformer
* @param null $resourceName
* @return array
*/
public function jsonResource(JsonResource $resource, $transformer = null, $resourceName = null): array
public function jsonResource(JsonResource $resource): array
{
$data = value($this->formatJsonResource(), $resource);

return fractal()
->item($data, $transformer ?: fn () => $data, $resourceName)
->serializeWith(ArraySerializer::class)
->toArray();
return value($this->formatJsonResource(),$resource);
}

/**
Expand All @@ -139,7 +121,7 @@ public function jsonResource(JsonResource $resource, $transformer = null, $resou
*/
protected function formatMessage(int $code, ?string $message): ?string
{
if (! $message && class_exists($enumClass = Config::get('response.enum'))) {
if (!$message && class_exists($enumClass = Config::get('response.enum'))) {
$message = $enumClass::fromValue($code)->description;
}

Expand Down Expand Up @@ -182,6 +164,8 @@ protected function formatStatusCode($code, string $from = 'success'): int
*/
protected function formatJsonResource(): \Closure
{
// vendor/laravel/framework/src/Illuminate/Http/Resources/Json/ResourceResponse.php
// toResponse
return function (JsonResource $resource) {
return array_merge_recursive($resource->resolve(request()), $resource->with(request()), $resource->additional);
};
Expand All @@ -191,32 +175,43 @@ protected function formatJsonResource(): \Closure
* Format paginator data.
*
* @param $collection
* @return \Closure
*/
protected function formatCollection($collection): \Closure
protected function formatMeta($collection)
{
return function (Fractal $item) use ($collection) {
return match (true) {
$collection instanceof CursorPaginator => $item->withCursor(new Cursor(
$collection->cursor()?->encode(),
$collection->previousCursor()?->encode(),
$collection->nextCursor()?->encode(),
count($collection->items())
)),
$collection instanceof LengthAwarePaginator => $item->paginateWith(new IlluminatePaginatorAdapter($collection)),
$collection instanceof Paginator => $item->addMeta([
'pagination' => [
'count' => $collection->lastItem(),
'per_page' => $collection->perPage(),
'current_page' => $collection->currentPage(),
'links' => array_filter([
'previous' => $collection->previousPageUrl(),
'next' => $collection->nextPageUrl(),
]),
],
]),
default => $item,
};
return match (true) {
$collection instanceof CursorPaginator => [
'cursor' => [
'current' => $collection->cursor()?->encode(),
'prev' => $collection->previousCursor()?->encode(),
'next' => $collection->nextCursor()?->encode(),
'count' => count($collection->items()),
]
],
$collection instanceof LengthAwarePaginator => [
'pagination' => [
'count' => $collection->lastItem(),
'per_page' => $collection->perPage(),
'current_page' => $collection->currentPage(),
'total' => $collection->total(),
'total_pages' => $collection->lastPage(),
'links' => array_filter([
'previous' => $collection->previousPageUrl(),
'next' => $collection->nextPageUrl(),
]),
],
],
$collection instanceof Paginator => [
'pagination' => [
'count' => $collection->lastItem(),
'per_page' => $collection->perPage(),
'current_page' => $collection->currentPage(),
'links' => array_filter([
'previous' => $collection->previousPageUrl(),
'next' => $collection->nextPageUrl(),
]),
],
],
default => [],
};
}

Expand All @@ -231,7 +226,7 @@ protected function formatDataFields(array $data): array
$formatConfig = \config('response.format.config', []);

foreach ($formatConfig as $key => $config) {
if (! Arr::has($data, $key)) {
if (!Arr::has($data, $key)) {
continue;
}

Expand All @@ -244,7 +239,7 @@ protected function formatDataFields(array $data): array
$key = $alias;
}

if (! $show) {
if (!$show) {
$data = Arr::except($data, $key);
}
}
Expand Down
3 changes: 2 additions & 1 deletion tests/SuccessTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ public function testSuccessWithResourceData()
public function testSuccessWithCollectionData()
{
// 方式七:返回 Api collection
$users = User::factory()->count(10)->make();
User::factory()->count(3)->create();
$users = User::all();
$response = Response::success(new UserCollection($users));

$this->assertEquals(200, $response->status());
Expand Down

0 comments on commit ff95cfe

Please sign in to comment.