1 | <?php |
||
27 | class EmployeesController extends JsonApiController |
||
28 | { |
||
29 | /** |
||
30 | * @return \Illuminate\Database\Eloquent\Model |
||
31 | */ |
||
32 | public function getDataModel() |
||
33 | { |
||
34 | return new Employees(); |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @return callable |
||
39 | */ |
||
40 | protected function createResourceCallable() |
||
41 | { |
||
42 | $createOrderResource = function (Model $model, array $data) { |
||
43 | if (!empty($data['relationships']['order']['data'])) { |
||
44 | $orderData = $data['relationships']['order']['data']; |
||
45 | |||
46 | if (!empty($orderData['type'])) { |
||
47 | $orderData = [$orderData]; |
||
48 | } |
||
49 | |||
50 | foreach ($orderData as $order) { |
||
51 | $attributes = array_merge($order['attributes'], ['employee_id' => $model->getKey()]); |
||
52 | Orders::create($attributes); |
||
53 | } |
||
54 | } |
||
55 | }; |
||
56 | |||
57 | return function (array $data, array $values, ErrorBag $errorBag) use ($createOrderResource) { |
||
58 | |||
59 | $attributes = []; |
||
60 | foreach ($values as $name => $value) { |
||
61 | $attributes[$name] = $value; |
||
62 | } |
||
63 | |||
64 | if (!empty($data['id'])) { |
||
65 | $attributes[$this->getDataModel()->getKeyName()] = $values['id']; |
||
66 | } |
||
67 | |||
68 | DB::beginTransaction(); |
||
69 | try { |
||
70 | $model = $this->getDataModel()->create($attributes); |
||
71 | $createOrderResource($model, $data); |
||
72 | DB::commit(); |
||
73 | |||
74 | return $model; |
||
75 | } catch (\Exception $e) { |
||
76 | DB::rollback(); |
||
77 | $errorBag[] = new Error('creation_error', 'Resource could not be created'); |
||
78 | throw new \Exception(); |
||
79 | } |
||
80 | |||
81 | }; |
||
82 | } |
||
83 | |||
84 | /** |
||
85 | * @param Request $request |
||
86 | * |
||
87 | * @return \Symfony\Component\HttpFoundation\Response |
||
88 | */ |
||
89 | public function getOrdersByEmployee(Request $request) |
||
90 | { |
||
91 | $resource = new ListResource($this->serializer); |
||
92 | |||
93 | $totalAmount = function () use ($request) { |
||
94 | $id = (new Orders())->getKeyName(); |
||
95 | |||
96 | return Orders::query()->where('employee_id', '=', $request->employee_id)->get([$id])->count(); |
||
97 | }; |
||
98 | |||
99 | $results = function () use ($request) { |
||
100 | return EloquentHelper::paginate( |
||
101 | $this->serializer, |
||
102 | Orders::query()->where('employee_id', '=', $request->employee_id) |
||
103 | )->get(); |
||
104 | }; |
||
105 | |||
106 | $uri = route('employees.orders', ['employee_id' => $request->employee_id]); |
||
107 | |||
108 | return $resource->get($totalAmount, $results, $uri, Orders::class); |
||
109 | } |
||
110 | } |
||
111 |