Passed
Pull Request — master (#528)
by Stefano
03:43
created

ModelBaseController::remove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2019 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
namespace App\Controller\Model;
14
15
use App\Controller\AppController;
16
use BEdita\SDK\BEditaClientException;
17
use Cake\Event\Event;
18
use Cake\Http\Exception\UnauthorizedException;
19
use Cake\Http\Response;
20
use Cake\Utility\Hash;
21
22
/**
23
 * Model base controller class
24
 *
25
 * @property \App\Controller\Component\PropertiesComponent $Properties
26
 */
27
abstract class ModelBaseController extends AppController
28
{
29
    /**
30
     * Resource type in use (object_types, properties, property_types)
31
     *
32
     * @var string
33
     */
34
    protected $resourceType = null;
35
36
    /**
37
     * Single resource view existence flag.
38
     *
39
     * @var bool
40
     */
41
    protected $singleView = true;
42
43
    /**
44
     * {@inheritDoc}
45
     */
46
    public function initialize(): void
47
    {
48
        parent::initialize();
49
50
        $this->loadComponent('Properties');
51
52
        $this->Schema->setConfig([
53
            'type' => $this->resourceType,
54
            'internalSchema' => true,
55
        ]);
56
    }
57
58
    /**
59
     * Restrict `model` module access to `admin` for now
60
     *
61
     * {@inheritDoc}
62
     */
63
    public function beforeFilter(Event $event): ?Response
64
    {
65
        $res = parent::beforeFilter($event);
66
        if ($res !== null) {
67
            return $res;
68
        }
69
70
        $roles = $this->Auth->user('roles');
71
        if (empty($roles) || !in_array('admin', $roles)) {
72
            throw new UnauthorizedException(__('Module access not authorized'));
73
        }
74
75
        return null;
76
    }
77
78
    /**
79
     * Display resources list.
80
     *
81
     * @return \Cake\Http\Response|null
82
     */
83
    public function index(): ?Response
84
    {
85
        $this->request->allowMethod(['get']);
86
        $query = $this->request->getQueryParams() + ['page_size' => 500];
87
88
        try {
89
            $response = $this->apiClient->get(
90
                sprintf('/model/%s', $this->resourceType),
91
                $query
92
            );
93
        } catch (BEditaClientException $e) {
94
            $this->log($e, 'error');
95
            $this->Flash->error($e->getMessage(), ['params' => $e]);
96
97
            return $this->redirect(['_name' => 'dashboard']);
98
        }
99
100
        $this->set('resources', (array)$response['data']);
101
        $this->set('meta', (array)$response['meta']);
102
        $this->set('links', (array)$response['links']);
103
        $this->set('schema', $this->Schema->getSchema());
104
        $this->set('properties', $this->Properties->indexList($this->resourceType));
105
        $this->set('filter', $this->Properties->filterList($this->resourceType));
106
107
        return null;
108
    }
109
110
    /**
111
     * View single resource.
112
     *
113
     * @param string|int $id Resource ID.
114
     *
115
     * @return \Cake\Http\Response|null
116
     */
117
    public function view($id): ?Response
118
    {
119
        try {
120
            $response = $this->apiClient->get(sprintf('/model/%s/%s', $this->resourceType, $id));
121
        } catch (BEditaClientException $e) {
122
            $this->log($e, 'error');
123
            $this->Flash->error($e->getMessage(), ['params' => $e]);
124
125
            return $this->redirect(['_name' => 'model:list:' . $this->resourceType]);
126
        }
127
128
        $resource = (array)$response['data'];
129
        $this->set(compact('resource'));
130
        $this->set('schema', $this->Schema->getSchema());
131
        $this->set('properties', $this->Properties->viewGroups($resource, $this->resourceType));
132
133
        return null;
134
    }
135
136
    /**
137
     * Save resource.
138
     *
139
     * @return \Cake\Http\Response|null
140
     */
141
    public function save(): ?Response
142
    {
143
        $data = $this->request->getData();
144
        $id = Hash::get($data, 'id');
145
        unset($data['id']);
146
        $body = [
147
            'data' => [
148
                'type' => $this->resourceType,
149
                'attributes' => $data,
150
            ],
151
        ];
152
        $endpoint = sprintf('/model/%s', $this->resourceType);
153
154
        try {
155
            if (empty($id)) {
156
                $response = $this->apiClient->post($endpoint, json_encode($body));
157
                $id = Hash::get($response, 'data.id');
158
            } else {
159
                $body['data']['id'] = $id;
160
                $this->apiClient->patch(sprintf('%s/%s', $endpoint, $id), json_encode($body));
161
            }
162
        } catch (BEditaClientException $e) {
163
            $this->log($e, 'error');
164
            $this->Flash->error($e->getMessage(), ['params' => $e]);
165
        }
166
167
        if (!$this->singleView) {
168
            return $this->redirect(['_name' => 'model:list:' . $this->resourceType]);
169
        }
170
171
        return $this->redirect(
172
            [
173
                '_name' => 'model:view:' . $this->resourceType,
174
                'id' => $id,
175
            ]
176
        );
177
    }
178
179
    /**
180
     * Remove single resource.
181
     *
182
     * @param string $id Resource ID.
183
     *
184
     * @return \Cake\Http\Response|null
185
     */
186
    public function remove(string $id): ?Response
187
    {
188
        try {
189
            $this->apiClient->delete(sprintf('/model/%s/%s', $this->resourceType, $id));
190
        } catch (BEditaClientException $e) {
191
            $this->log($e, 'error');
192
            $this->Flash->error($e->getMessage(), ['params' => $e]);
193
        }
194
195
        return $this->redirect(['_name' => 'model:list:' . $this->resourceType]);
196
    }
197
198
    /**
199
     * {@inheritDoc}
200
     */
201
    public function beforeRender(Event $event): ?Response
202
    {
203
        $this->set('resourceType', $this->resourceType);
204
        $this->set('moduleLink', ['_name' => 'model:list:' . $this->resourceType]);
205
206
        return parent::beforeRender($event);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::beforeRender($event) targeting App\Controller\AppController::beforeRender() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
207
    }
208
}
209