/
AbstractController.php
321 lines (269 loc) · 9.56 KB
/
AbstractController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller;
use App\Configuration\LanguageFormattings;
use App\Entity\Bookmark;
use App\Entity\User;
use App\Repository\BookmarkRepository;
use App\Repository\Query\BaseQuery;
use App\Timesheet\DateTimeFactory;
use App\Utils\LocaleFormats;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseAbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* The abstract base controller.
* @method null|User getUser()
*/
abstract class AbstractController extends BaseAbstractController implements ServiceSubscriberInterface
{
/**
* @deprecated since 1.6, will be removed with 2.0
*/
public const ROLE_ADMIN = User::ROLE_ADMIN;
protected function getTranslator(): TranslatorInterface
{
return $this->container->get('translator');
}
private function getLogger(): LoggerInterface
{
return $this->container->get('logger');
}
/**
* Adds a "successful" flash message to the stack.
*
* @param string $translationKey
* @param array $parameter
*/
protected function flashSuccess(string $translationKey, array $parameter = []): void
{
$this->addFlashTranslated('success', $translationKey, $parameter);
}
/**
* Adds a "warning" flash message to the stack.
*
* @param string $translationKey
* @param array $parameter
*/
protected function flashWarning(string $translationKey, array $parameter = []): void
{
$this->addFlashTranslated('warning', $translationKey, $parameter);
}
/**
* Adds a "error" flash message to the stack.
*
* @param string $translationKey
* @param array $parameter
*/
protected function flashError(string $translationKey, array $parameter = []): void
{
$this->addFlashTranslated('error', $translationKey, $parameter);
}
/**
* Adds an exception flash message for failed update/create actions.
*
* @param \Exception $exception
*/
protected function flashUpdateException(\Exception $exception): void
{
$this->flashException($exception, 'action.update.error');
}
/**
* Adds an exception flash message for failed delete actions.
*
* @param \Exception $exception
*/
protected function flashDeleteException(\Exception $exception): void
{
$this->flashException($exception, 'action.delete.error');
}
/**
* Adds a "error" flash message and logs the Exception.
*
* @param \Exception $exception
* @param string $translationKey
* @param array $parameter
*/
protected function flashException(\Exception $exception, string $translationKey, array $parameter = []): void
{
$this->logException($exception);
if (!\array_key_exists('%reason%', $parameter)) {
$parameter['%reason%'] = $exception->getMessage();
}
$this->addFlashTranslated('error', $translationKey, $parameter);
}
/**
* Adds a fully translated (both $message and all keys in $parameter) flash message to the stack.
*
* @param string $type
* @param string $message
* @param array $parameter
*/
protected function addFlashTranslated(string $type, string $message, array $parameter = []): void
{
if (!empty($parameter)) {
foreach ($parameter as $key => $value) {
$parameter[$key] = $this->getTranslator()->trans($value, [], 'flashmessages');
}
$message = $this->getTranslator()->trans(
$message,
$parameter,
'flashmessages'
);
}
$this->addFlash($type, $message);
}
protected function logException(\Exception $ex): void
{
$this->getLogger()->critical($ex->getMessage());
}
public static function getSubscribedServices()
{
return array_merge(parent::getSubscribedServices(), [
'translator' => TranslatorInterface::class,
'logger' => LoggerInterface::class,
LanguageFormattings::class => LanguageFormattings::class,
]);
}
protected function getDateTimeFactory(?User $user = null): DateTimeFactory
{
if (null === $user) {
$user = $this->getUser();
}
return DateTimeFactory::createByUser($user);
}
protected function getLocaleFormats(string $locale): LocaleFormats
{
return new LocaleFormats($this->container->get(LanguageFormattings::class), $locale);
}
private function getLastSearch(BaseQuery $query): ?array
{
$name = 'search_' . $this->getSearchName($query);
if (!$this->get('session')->has($name)) {
return null;
}
return $this->get('session')->get($name);
}
private function removeLastSearch(BaseQuery $query): void
{
$name = 'search_' . $this->getSearchName($query);
if ($this->get('session')->has($name)) {
$this->get('session')->remove($name);
}
}
private function getSearchName(BaseQuery $query): string
{
return substr($query->getName(), 0, 50);
}
/**
* @param Request $request
* @internal
*/
protected function ignorePersistedSearch(Request $request): void
{
$request->query->set('performSearch', true);
}
protected function handleSearch(FormInterface $form, Request $request): bool
{
$data = $form->getData();
if (!($data instanceof BaseQuery)) {
throw new \InvalidArgumentException('handleSearchForm() requires an instanceof BaseQuery as form data');
}
$actions = ['resetSearchFilter', 'removeDefaultQuery', 'setDefaultQuery'];
foreach ($actions as $action) {
if ($request->query->has($action)) {
if (!$this->isCsrfTokenValid('search', $request->query->get('_token'))) {
$this->flashError('action.csrf.error');
return false;
}
}
}
$request->query->remove('_token');
if ($request->query->has('resetSearchFilter')) {
$data->resetFilter();
$this->removeLastSearch($data);
return true;
}
$submitData = $request->query->all();
// allow to use forms with block-prefix
if (!empty($formName = $form->getConfig()->getName()) && $request->request->has($formName)) {
$submitData = $request->request->get($formName);
}
$searchName = $this->getSearchName($data);
/** @var BookmarkRepository $bookmarkRepo */
$bookmarkRepo = $this->getDoctrine()->getRepository(Bookmark::class);
$bookmark = $bookmarkRepo->getSearchDefaultOptions($this->getUser(), $searchName);
if ($bookmark !== null) {
if ($request->query->has('removeDefaultQuery')) {
$bookmarkRepo->deleteBookmark($bookmark);
$bookmark = null;
return true;
} else {
$data->setBookmark($bookmark);
}
}
// apply persisted search data ONLY if search form was not submitted manually
if (!$request->query->has('performSearch')) {
$sessionSearch = $this->getLastSearch($data);
if ($sessionSearch !== null) {
$submitData = array_merge($sessionSearch, $submitData);
} elseif ($bookmark !== null && !$request->query->has('setDefaultQuery')) {
$submitData = array_merge($bookmark->getContent(), $submitData);
$data->flagAsBookmarkSearch();
}
}
// clean up parameters from unknown search values
foreach ($submitData as $name => $values) {
if (!$form->has($name)) {
unset($submitData[$name]);
}
}
$form->submit($submitData, false);
if (!$form->isValid()) {
$data->resetByFormError($form->getErrors(true));
return false;
}
$params = [];
foreach ($form->all() as $name => $child) {
$params[$name] = $child->getViewData();
}
// these should NEVER be saved
$filter = ['setDefaultQuery', 'removeDefaultQuery', 'performSearch'];
foreach ($filter as $name) {
if (isset($params[$name])) {
unset($params[$name]);
}
}
if ($request->query->has('performSearch')) {
$this->get('session')->set('search_' . $searchName, $params);
}
// filter stuff, that does not belong in a bookmark
$filter = ['page'];
foreach ($filter as $name) {
if (isset($params[$name])) {
unset($params[$name]);
}
}
if ($request->query->has('setDefaultQuery')) {
$this->removeLastSearch($data);
if ($bookmark === null) {
$bookmark = new Bookmark();
$bookmark->setType(Bookmark::SEARCH_DEFAULT);
$bookmark->setUser($this->getUser());
$bookmark->setName($searchName);
}
$bookmark->setContent($params);
$bookmarkRepo->saveBookmark($bookmark);
return true;
}
return false;
}
}