2018-01-24 11:40:34 +08:00
|
|
|
<?php
|
|
|
|
|
2020-03-23 21:31:35 +08:00
|
|
|
namespace App\Contracts;
|
2018-01-24 11:40:34 +08:00
|
|
|
|
2021-06-09 23:20:25 +08:00
|
|
|
use App\Support\Resources\CustomAnonymousResourceCollection;
|
|
|
|
use App\Support\Resources\CustomPaginatedResourceResponse;
|
2020-05-16 06:20:16 +08:00
|
|
|
use Illuminate\Http\Resources\Json\JsonResource;
|
2021-06-09 23:20:25 +08:00
|
|
|
use Illuminate\Pagination\AbstractPaginator;
|
2020-05-16 06:20:16 +08:00
|
|
|
|
2018-01-24 11:40:34 +08:00
|
|
|
/**
|
2020-03-23 21:31:35 +08:00
|
|
|
* Base class for a resource/response
|
2018-01-24 11:40:34 +08:00
|
|
|
*/
|
2020-05-16 06:20:16 +08:00
|
|
|
class Resource extends JsonResource
|
2018-01-24 11:40:34 +08:00
|
|
|
{
|
2019-07-16 03:14:40 +08:00
|
|
|
/**
|
|
|
|
* Iterate through the list of $fields and check if they're a "Unit"
|
|
|
|
* If they are, then add the response
|
|
|
|
*
|
|
|
|
* @param $response
|
|
|
|
* @param array $fields
|
|
|
|
*/
|
|
|
|
public function checkUnitFields(&$response, array $fields): void
|
|
|
|
{
|
|
|
|
foreach ($fields as $f) {
|
|
|
|
if ($this->{$f} instanceof Unit) {
|
|
|
|
$response[$f] = $this->{$f}->getResponseUnits();
|
|
|
|
} else {
|
|
|
|
$response[$f] = $this->{$f};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-06-09 23:20:25 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Customize the response to exclude all the extra data that isn't used. Based on:
|
|
|
|
* https://gist.github.com/derekphilipau/4be52164a69ce487dcd0673656d280da
|
|
|
|
*
|
|
|
|
* @param \Illuminate\Http\Request $request
|
|
|
|
*
|
|
|
|
* @return \Illuminate\Http\JsonResponse
|
|
|
|
*/
|
|
|
|
public function toResponse($request)
|
|
|
|
{
|
|
|
|
return $this->resource instanceof AbstractPaginator
|
|
|
|
? (new CustomPaginatedResourceResponse($this))->toResponse($request)
|
|
|
|
: parent::toResponse($request);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function collection($resource)
|
|
|
|
{
|
|
|
|
return tap(new CustomAnonymousResourceCollection($resource, static::class), function ($collection) {
|
|
|
|
if (property_exists(static::class, 'preserveKeys')) {
|
|
|
|
$collection->preserveKeys = (new static([]))->preserveKeys === true;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2018-01-24 11:40:34 +08:00
|
|
|
}
|