Failed Conditions
Push — master ( 55bfad...b74acd )
by Maximo
02:48
created

BaseCustomFieldsController::getById()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.243

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 4
nop 1
dl 0
loc 19
ccs 7
cts 10
cp 0.7
crap 3.243
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Exception\UnprocessableEntityHttpException;
8
use Phalcon\Http\Response;
9
use Baka\Http\QueryParser;
10
11
/**
12
 * Class BaseController
13
 *
14
 * @package Gewaer\Api\Controllers
15
 * @property Users $userData
16
 *
17
 */
18
abstract class BaseCustomFieldsController extends \Baka\Http\Rest\CrudCustomFieldsController
19
{
20
    /**
21
     * Custom Model
22
     */
23
    protected $customModel;
24
25
    /**
26
     * Get Uer
27
     *
28
     * @param mixed $id
29
     *
30
     * @method GET
31
     * @url /v1/company/{id}
32
     *
33
     * @return Response
34
     */
35 2
    public function getById($id) : Response
36
    {
37
        //find the info
38 2
        $company = $this->model->findFirst([
39 2
            'id = ?0 AND is_deleted = 0 and users_id = ?1',
40 2
            'bind' => [$id, $this->userData->getId()],
41
        ]);
42
43
        //get relationship
44 2
        if ($this->request->hasQuery('relationships')) {
45
            $relationships = $this->request->getQuery('relationships', 'string');
46
47
            $company = QueryParser::parseRelationShips($relationships, $company);
48
        }
49
50 2
        if ($company) {
51 2
            return $this->response($company->toFullArray());
52
        } else {
53
            throw new UnprocessableEntityHttpException('Record not found');
54
        }
55
    }
56
57
    /**
58
     * Add a new item
59
     *
60
     * @method POST
61
     * @url /v1/company
62
     *
63
     * @return Response
64
     */
65 2
    public function create() : Response
66
    {
67 2
        $request = $this->request->getPost();
68
69 2
        if (empty($request)) {
70
            $request = $this->request->getJsonRawBody(true);
71
        }
72
73
        //transaction
74 2
        $this->db->begin();
75
76
        //alwasy overwrite userid
77 2
        $request['users_id'] = $this->userData->getId();
78
79 2
        $this->model->setCustomFields($request);
80
        //try to save all the fields we allow
81 2
        if ($this->model->save($request, $this->createFields)) {
82 2
            $this->db->commit();
83 2
            return $this->response($this->model->findFirst($this->model->getId())->toFullArray());
84
        } else {
85
            $this->db->rollback();
86
            throw new UnprocessableEntityHttpException((string) $this->model->getMessages()[0]);
87
        }
88
    }
89
}
90