ExecuteAbstract::redirectToNext()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Admin\Http\Controllers\Admin;
6
7
use AbterPhp\Framework\Constant\Session;
8
use AbterPhp\Framework\Domain\Entities\IStringerEntity;
9
use AbterPhp\Framework\Form\Extra\DefaultButtons;
10
use AbterPhp\Framework\Http\Service\Execute\IRepoService;
11
use AbterPhp\Framework\I18n\ITranslator;
12
use AbterPhp\Framework\Session\FlashService;
13
use Opulence\Http\Responses\RedirectResponse;
14
use Opulence\Http\Responses\Response;
15
use Opulence\Orm\OrmException;
16
use Opulence\Routing\Urls\URLException;
17
use Opulence\Routing\Urls\UrlGenerator;
18
use Opulence\Sessions\ISession;
19
use Psr\Log\LoggerInterface;
20
21
abstract class ExecuteAbstract extends AdminAbstract
22
{
23
    public const INPUT_NEXT = 'next';
24
25
    public const URL_CREATE = '%s-create';
26
27
    public const CREATE_SUCCESS = 'framework:create-success';
28
    public const CREATE_FAILURE = 'framework:create-failure';
29
    public const UPDATE_SUCCESS = 'framework:update-success';
30
    public const UPDATE_FAILURE = 'framework:update-failure';
31
    public const DELETE_SUCCESS = 'framework:delete-success';
32
    public const DELETE_FAILURE = 'framework:delete-failure';
33
34
    public const LOG_MSG_CREATE_FAILURE = 'Creating %1$s failed.';
35
    public const LOG_MSG_CREATE_SUCCESS = 'Creating %1$s was successful.';
36
    public const LOG_MSG_UPDATE_FAILURE = 'Updating %1$s with id "%2$s" failed.';
37
    public const LOG_MSG_UPDATE_SUCCESS = 'Updating %1$s with id "%2$s" was successful.';
38
    public const LOG_MSG_DELETE_FAILURE = 'Deleting %1$s with id "%2$s" failed.';
39
    public const LOG_MSG_DELETE_SUCCESS = 'Deleting %1$s with id "%2$s" was successful.';
40
41
    public const ENTITY_TITLE_SINGULAR = '';
42
    public const ENTITY_TITLE_PLURAL   = '';
43
44
    protected IRepoService $repoService;
45
46
    protected ISession $session;
47
48
    /**
49
     * ExecuteAbstract constructor.
50
     *
51
     * @param FlashService    $flashService
52
     * @param LoggerInterface $logger
53
     * @param ITranslator     $translator
54
     * @param UrlGenerator    $urlGenerator
55
     * @param IRepoService    $repoService
56
     * @param ISession        $session
57
     */
58
    public function __construct(
59
        FlashService $flashService,
60
        LoggerInterface $logger,
61
        ITranslator $translator,
62
        UrlGenerator $urlGenerator,
63
        IRepoService $repoService,
64
        ISession $session
65
    ) {
66
        parent::__construct($flashService, $logger, $translator, $urlGenerator);
67
68
        $this->repoService = $repoService;
69
        $this->session     = $session;
70
    }
71
72
    /**
73
     * @return Response
74
     * @throws URLException
75
     */
76
    public function create(): Response
77
    {
78
        $postData = $this->getPostData();
79
        $fileData = $this->getFileData();
80
81
        $errors = $this->repoService->validateForm(array_merge($postData, $fileData), IRepoService::CREATE);
82
83
        if (count($errors) > 0) {
84
            $this->flashService->mergeErrorMessages($errors);
85
            $this->logger->info(sprintf(static::LOG_MSG_CREATE_FAILURE, static::ENTITY_SINGULAR), $errors);
86
87
            return $this->redirectToNext();
88
        }
89
90
        try {
91
            $entity = $this->repoService->create($postData, $fileData);
92
93
            $this->logger->info(sprintf(static::LOG_MSG_CREATE_SUCCESS, static::ENTITY_SINGULAR));
94
            $this->flashService->mergeSuccessMessages([$this->getMessage(static::CREATE_SUCCESS)]);
95
        } catch (\Exception $e) {
96
            $this->flashService->mergeErrorMessages([$this->getMessage(static::CREATE_FAILURE)]);
97
            $this->logger->info(
98
                sprintf(static::LOG_MSG_CREATE_FAILURE, static::ENTITY_SINGULAR),
99
                $this->getExceptionContext($e)
100
            );
101
102
            return $this->redirectToNext();
103
        }
104
105
        return $this->redirectToNext($entity);
106
    }
107
108
    /**
109
     * @param string $entityId
110
     *
111
     * @return Response
112
     * @throws URLException
113
     */
114
    public function update(string $entityId): Response
115
    {
116
        $postData = $this->getPostData();
117
        $fileData = $this->getFileData();
118
119
        $errors = $this->repoService->validateForm(array_merge($postData, $fileData), IRepoService::UPDATE);
120
121
        try {
122
            $entity = $this->repoService->retrieveEntity($entityId);
123
        } catch (OrmException $e) {
124
            return $this->redirectToNext();
125
        }
126
127
        if (count($errors) > 0) {
128
            $this->logger->info(sprintf(static::LOG_MSG_UPDATE_FAILURE, static::ENTITY_SINGULAR, $entityId), $errors);
129
            $this->flashService->mergeErrorMessages($errors);
130
131
            return $this->redirectToNext($entity);
132
        }
133
134
        try {
135
            $this->repoService->update($entity, $postData, $fileData);
136
            $this->logger->info(sprintf(static::LOG_MSG_UPDATE_SUCCESS, static::ENTITY_SINGULAR, $entityId));
137
            $this->flashService->mergeSuccessMessages([$this->getMessage(static::UPDATE_SUCCESS)]);
138
        } catch (\Exception $e) {
139
            $this->logger->error(
140
                sprintf(static::LOG_MSG_UPDATE_FAILURE, static::ENTITY_SINGULAR, $entityId),
141
                $this->getExceptionContext($e)
142
            );
143
            $this->flashService->mergeErrorMessages([$this->getMessage(static::UPDATE_FAILURE)]);
144
        }
145
146
        return $this->redirectToNext($entity);
147
    }
148
149
    /**
150
     * @param string $entityId
151
     *
152
     * @return Response
153
     * @throws URLException
154
     */
155
    public function delete(string $entityId): Response
156
    {
157
        $entity = $this->repoService->retrieveEntity($entityId);
158
159
        try {
160
            $this->repoService->delete($entity);
161
            $this->logger->info(sprintf(static::LOG_MSG_DELETE_SUCCESS, static::ENTITY_SINGULAR, $entityId));
162
            $this->flashService->mergeSuccessMessages([$this->getMessage(static::DELETE_SUCCESS)]);
163
        } catch (\Exception $e) {
164
            $this->logger->error(
165
                sprintf(static::LOG_MSG_DELETE_FAILURE, static::ENTITY_SINGULAR, $entityId),
166
                [static::LOG_CONTEXT_EXCEPTION => $e->getMessage()]
167
            );
168
            $this->flashService->mergeErrorMessages([$this->getMessage(static::DELETE_FAILURE)]);
169
        }
170
171
        return $this->redirectToNext();
172
    }
173
174
    /**
175
     * @return array
176
     */
177
    protected function getPostData(): array
178
    {
179
        return $this->request->getPost()->getAll();
180
    }
181
182
    /**
183
     * @return array
184
     */
185
    protected function getFileData(): array
186
    {
187
        return $this->request->getFiles()->getAll();
188
    }
189
190
    /**
191
     * @param IStringerEntity|null $entity
192
     *
193
     * @return Response
194
     * @throws URLException
195
     */
196
    protected function redirectToNext(?IStringerEntity $entity = null): Response
197
    {
198
        $next = $this->request->getInput(static::INPUT_NEXT, DefaultButtons::BTN_VALUE_NEXT_BACK);
199
200
        $entityId = $entity ? $entity->getId() : null;
201
202
        $url = $this->getUrl($next, $entityId);
203
204
        $response = new RedirectResponse($url);
205
        $response->send();
206
207
        return $response;
208
    }
209
210
    /**
211
     * @param string      $next
212
     * @param string|null $entityId
213
     *
214
     * @return string
215
     * @throws URLException
216
     */
217
    protected function getUrl(string $next, string $entityId = null): string
218
    {
219
        switch ($next) {
220
            case DefaultButtons::BTN_VALUE_NEXT_BACK:
221
                return $this->getShowUrl();
222
            case DefaultButtons::BTN_VALUE_NEXT_EDIT:
223
                if (null === $entityId) {
224
                    return $this->getCreateUrl();
225
                }
226
227
                return $this->getEditUrl($entityId);
228
            case DefaultButtons::BTN_VALUE_NEXT_CREATE:
229
                return $this->getCreateUrl();
230
        }
231
232
        return $this->getCreateUrl();
233
    }
234
235
    /**
236
     * @return string
237
     * @throws URLException
238
     */
239
    protected function getCreateUrl(): string
240
    {
241
        $urlName = strtolower(sprintf(static::URL_CREATE, static::ROUTING_PATH));
242
        $url     = $this->urlGenerator->createFromName($urlName);
243
244
        return $url;
245
    }
246
247
    /**
248
     * @return string
249
     * @throws URLException
250
     */
251
    protected function getShowUrl(): string
252
    {
253
        if ($this->session->has(Session::LAST_GRID_URL)) {
254
            return (string)$this->session->get(Session::LAST_GRID_URL);
255
        }
256
257
        $url = $this->urlGenerator->createFromName(static::ROUTING_PATH);
258
259
        return $url;
260
    }
261
262
    /**
263
     * @param string $id
264
     *
265
     * @return string
266
     * @throws URLException
267
     */
268
    protected function getEditUrl(string $id): string
269
    {
270
        $routeName = sprintf(static::URL_EDIT, static::ROUTING_PATH);
271
272
        $url = $this->urlGenerator->createFromName($routeName, $id);
273
274
        return $url;
275
    }
276
277
    /**
278
     * @param string $messageType
279
     *
280
     * @return string
281
     */
282
    protected function getMessage(string $messageType)
283
    {
284
        $entityName = $this->translator->translate(static::ENTITY_TITLE_SINGULAR);
285
286
        return $this->translator->translate($messageType, $entityName);
287
    }
288
}
289