Completed
Push — master ( 1a65d7...018a8e )
by Nil
03:48
created

EmployeesController::getDataModel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * Author: Nil Portugués Calderó <[email protected]>
4
 * Date: 12/9/15
5
 * Time: 2:57 PM.
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace NilPortugues\Tests\App\Controller;
12
13
use Illuminate\Database\Eloquent\Model;
14
use Illuminate\Http\Request;
15
use Illuminate\Support\Facades\DB;
16
use NilPortugues\Api\JsonApi\Server\Actions\ListResource;
17
use NilPortugues\Api\JsonApi\Server\Errors\Error;
18
use NilPortugues\Api\JsonApi\Server\Errors\ErrorBag;
19
use NilPortugues\Laravel5\JsonApi\Controller\JsonApiController;
20
use NilPortugues\Laravel5\JsonApi\Eloquent\EloquentHelper;
21
use NilPortugues\Tests\App\Models\Employees;
22
use NilPortugues\Tests\App\Models\Orders;
23
24
/**
25
 * Class EmployeeController.
26
 */
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