|
| 1 | +<?php |
| 2 | +namespace Phpsa\LaravelApiController\Http\Api\Contracts; |
| 3 | + |
| 4 | +use Illuminate\Support\Facades\DB; |
| 5 | +use Phpsa\LaravelApiController\Exceptions\ApiException; |
| 6 | + |
| 7 | +trait HasBatchActions |
| 8 | +{ |
| 9 | + |
| 10 | + public function handleBatchStoreAction($request, array $extraParams) |
| 11 | + { |
| 12 | + $this->validateRequestType($request); |
| 13 | + $this->addCustomParams($extraParams); |
| 14 | + $this->authoriseUserAction('create'); |
| 15 | + |
| 16 | + $this->validate($this->request, $this->rulesForBatchCreate()); |
| 17 | + |
| 18 | + DB::beginTransaction(); |
| 19 | + |
| 20 | + $this->unguardIfNeeded(); |
| 21 | + |
| 22 | + try { |
| 23 | + $records = collect($this->request->get('data'), [])->map(function ($item) { |
| 24 | + $data = $this->qualifyStoreQuery($item); |
| 25 | + $insert = $this->addTableData($data); |
| 26 | + $diff = array_diff(array_keys($data), array_keys($insert)); |
| 27 | + $item = self::$model->create($insert); |
| 28 | + |
| 29 | + $this->storeRelated($item, $diff, $data); |
| 30 | + |
| 31 | + return $item; |
| 32 | + }); |
| 33 | + |
| 34 | + DB::commit(); |
| 35 | + |
| 36 | + return $this->handleStoreResponse($records); |
| 37 | + } catch (\Exception $exception) { |
| 38 | + $message = config('app.debug') ? $exception->getMessage() : 'Failed to create Records'; |
| 39 | + |
| 40 | + DB::rollback(); |
| 41 | + throw new ApiException($message, (int) $exception->getCode(), $exception); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + protected function handleBatchStoreResponse($items) |
| 47 | + { |
| 48 | + return $this->respondWithResource($this->/** @scrutinizer ignore-call */getResourceCollection(), $items, 201); |
| 49 | + } |
| 50 | + |
| 51 | + protected function handleBatchUpdateResponse($items) |
| 52 | + { |
| 53 | + return $this->respondWithResource($this->/** @scrutinizer ignore-call */getResourceCollection(), $items, 200); |
| 54 | + } |
| 55 | + |
| 56 | + protected function rulesForBatchCreate() : array |
| 57 | + { |
| 58 | + return []; |
| 59 | + } |
| 60 | + |
| 61 | + protected function rulesForBatchUpdate() : array |
| 62 | + { |
| 63 | + return []; |
| 64 | + } |
| 65 | +} |
0 commit comments