1 <?php
2
3 namespace Skimia\ApiFusion\Http\Controllers\Api;
4
5 use Illuminate\Database\Eloquent\MassAssignmentException;
6 use Input;
7 use League\Fractal\TransformerAbstract;
8 use App\Domain\ResourceService;
9 use Dingo\Api\Exception\StoreResourceFailedException;
10 use Dingo\Api\Exception\UpdateResourceFailedException;
11 use Dingo\Api\Exception\DeleteResourceFailedException;
12 use App\Domain\Exceptions\DomainException;
13 use App\Domain\Exceptions\ValidationException;
14
15 abstract class ResourceServiceController extends ApiController
16 {
17 18 19 20
21 protected $transformer;
22 23 24 25
26 protected $service;
27
28 29 30
31 public function __construct()
32 {
33 $this->requireAuth(['store', 'update', 'destroy']);
34 }
35
36 37 38 39 40
41 public function index()
42 {
43 $items = $this->service->all();
44
45 return $this->response()->collection($items, $this->transformer);
46 }
47
48 49 50 51 52 53
54 public function show($id)
55 {
56 $item = $this->service->single($id);
57
58 return $this->response()->item($item, $this->transformer);
59 }
60
61 62 63 64 65
66 public function store()
67 {
68 try {
69 $this->service->store(Input::get());
70
71 return $this->response()->created();
72 } catch (ValidationException $e) {
73 throw new StoreResourceFailedException('Store failed', $e->getValidationErrors());
74 } catch (DomainException $e) {
75 throw new StoreResourceFailedException('Store failed', [$e->getMessage()]);
76 } catch (MassAssignmentException $e) {
77 throw new StoreResourceFailedException('Store failed : Invalid model Configuration ($fillable)', [$e->getMessage()]);
78 }
79 }
80
81 82 83 84 85
86 public function update()
87 {
88 try {
89 $ids = func_get_args();
90 $id = end($ids);
91 $this->service->update($id, Input::get());
92
93 return $this->response()->noContent();
94 } catch (ValidationException $e) {
95 throw new UpdateResourceFailedException('Update failed', $e->getValidationErrors());
96 } catch (DomainException $e) {
97 throw new UpdateResourceFailedException('Update failed', [$e->getMessage()]);
98 }
99 }
100
101 102 103 104 105
106 public function destroy()
107 {
108 try {
109 $ids = func_get_args();
110 $id = end($ids);
111 $this->service->destroy($id);
112
113 return $this->response()->noContent();
114 } catch (ValidationException $e) {
115 throw new DeleteResourceFailedException('Delete failed', $e->getValidationErrors());
116 } catch (DomainException $e) {
117 throw new DeleteResourceFailedException('Delete failed', [$e->getMessage()]);
118 }
119 }
120 }
121