-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrickManager.php
694 lines (662 loc) · 26.3 KB
/
TrickManager.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
<?php
declare(strict_types=1);
namespace App\Domain\ServiceLayer;
use App\Domain\DTO\CreateTrickDTO;
use App\Domain\DTO\UpdateTrickDTO;
use App\Domain\Entity\Trick;
use App\Domain\Entity\User;
use App\Domain\Repository\TrickRepository;
use App\Service\Event\CustomEventFactoryInterface;
use App\Utils\Traits\RouterHelperTrait;
use App\Utils\Traits\SessionHelperTrait;
use App\Utils\Traits\StringHelperTrait;
use App\Utils\Traits\UuidHelperTrait;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Ramsey\Uuid\UuidInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class TrickManager.
*
* Manage tricks to handle, and retrieve them as a "service layer".
*/
class TrickManager extends AbstractServiceLayer
{
use LoggerAwareTrait;
use RouterHelperTrait;
use SessionHelperTrait;
use StringHelperTrait;
use UuidHelperTrait;
/**
* Define a session key name to store current trick total count.
*/
const TRICK_COUNT_SESSION_KEY = 'trickCount';
/**
* @var CustomEventFactoryInterface
*/
private $customEventFactory;
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* @var TrickRepository
*/
private $repository;
/**
* TrickManager constructor.
*
* @param CustomEventFactoryInterface $customEventFactory
* @param EntityManagerInterface $entityManager
* @param TrickRepository $repository
* @param LoggerInterface $logger
* @param RouterInterface $router
* @param SessionInterface $session
*
* @return void
*/
public function __construct(
CustomEventFactoryInterface $customEventFactory,
EntityManagerInterface $entityManager,
TrickRepository $repository,
LoggerInterface $logger,
RouterInterface $router,
SessionInterface $session
) {
parent::__construct($entityManager, $logger);
$this->customEventFactory = $customEventFactory;
$this->entityManager = $entityManager;
$this->repository = $repository;
$this->setLogger($logger);
$this->setRouter($router);
$this->setSession($session);
}
/**
* Adapt Trick list parameters depending on particular conditions to adjust values for showing process
* when it's possible only if no error is detected with incoherent passed values.
*
* @param array $condition an array which must contain only 1 value which is a true condition name
* @param array $parameters
*
* @return array
*/
private function adaptTrickListParameters(array $condition, array $parameters): array
{
if (\count($condition) > 1) {
throw new \RuntimeException("Condition can't be checked: only one condition must be passed at once!");
}
if (!empty($condition)) {
switch ($condition) {
// Error: check if $offset or $limit values are wrong:
// so reset list to default parameters for descending order
case \array_key_exists('descendingOrderAndWrongParameters', $condition):
$parameters['offset'] = $parameters['maxOffset'] + 1 - $this->getTrickListConfigParameters()['numberPerLoading'];
$parameters['limit'] = $this->getTrickListConfigParameters()['numberPerLoading'];
$parameters['error'] = true;
break;
// Error: check if $offset or $limit values are wrong:
// so reset list to default parameters for ascending order
case \array_key_exists('ascendingOrderAndWrongParameters', $condition):
$parameters['offset'] = 0;
$parameters['limit'] = $this->getTrickListConfigParameters()['numberPerLoading'];
$parameters['error'] = true;
break;
// Particular case: check if calculated $offset is not under $minOffset:
// lowest $offset must be 0 for descending order
case \array_key_exists('descendingOrderUnderMinimumOffset', $condition):
$modulo = $parameters['countAll'] % $this->getTrickListConfigParameters()['numberPerLoading'];
$parameters['offset'] = $parameters['minOffset'];
$parameters['limit'] = 0 == $modulo ? 1 : $modulo; // recalculate $limit to show last tricks
$parameters['error'] = false;
break;
// Particular case: check if calculated $offset + $limit is not over $maxOffset:
// highest offset must be equal to (total count - 1) for ascending order
case \array_key_exists('ascendingOrderOverMaxOffset', $condition):
$parameters['limit'] = $parameters['maxOffset'] + 1 - $parameters['offset']; // recalculate $limit to show last tricks
$parameters['error'] = false;
break;
}
$this->logger->error(
sprintf("[trace app SnowTricks] TrickManager/filterParametersWithOrder - \"%s\" case => parameters: %s", key($condition), serialize($parameters))
);
}
return $parameters;
}
/**
* Add (persist if necessary) and save (flush if necessary) a (new) Trick entity in database.
*
* Please note combinations:
* - $isPersisted = false, bool $isFlushed = false means Trick entity must be instantiated only.
* - $isPersisted = true, bool $isFlushed = true means Trick entity is added to unit of work and saved in database.
* - $isPersisted = true, bool $isFlushed = false means Trick entity is added to unit of work only.
* - $isPersisted = false, bool $isFlushed = true means Trick entity is saved in database only with possible change(s) in unit of work.
*
* @param Trick $trick
* @param bool $isPersisted
* @param bool $isFlushed
*
* @return Trick|null
*
* @throws \Exception
*/
public function addAndSaveTrick(Trick $trick, bool $isPersisted = false, bool $isFlushed = false): ?Trick
{
$object = $this->addAndSaveNewEntity($trick, $isPersisted, $isFlushed);
return \is_null($object) ? null : $trick;
}
/**
* Check if a form submitted trick name is the same or seems to be similar when compared.
*
* Please note this submitted name can be compared to all existing tricks names excepted current trick name,
* or in the other hand to current trick (to update) name only.
*
* @param string $submittedName
* @param Trick $trick|null a trick to update or null if it is a creation
* @param bool $isTrickChecked
*
* @return bool
*/
public function checkSameOrSimilarTrickName(
string $submittedName,
Trick $trick = null,
bool $isTrickChecked = false
): bool {
// Prepare data to filter for trick creation by getting all tricks
if (\is_null($trick)) {
$dataToFilter = $this->getRepository()->findAll();
// Prepare data to filter for trick update by excluding trick to update or checking it only
} else {
$dataToFilter = !$isTrickChecked
? $this->findOthersByExcludedUuid($trick->getUuid())
: [$trick];
}
$cleanSubmittedName = preg_replace('/[\s_-]+/', '', $submittedName);
// Filter comparison results with data
$results = array_filter($dataToFilter, function ($item) use ($cleanSubmittedName) {
/** @var Trick $item */
$cleanExistingName = preg_replace('/[\s_-]+/', '', $item->getName());
// Compare both cleaned names on each side with insensitive case
if (strtolower($cleanExistingName) === strtolower($cleanSubmittedName)) {
return true;
}
return false;
});
return empty($results) ? false : true;
}
/**
* Count all tricks without filter.
*
* @return int
*
* @throws \Doctrine\ORM\NonUniqueResultException
* @throws \Doctrine\ORM\NoResultException
* @throws \UnexpectedValueException
*/
public function countAll(): int
{
$result = $this->repository->countAll();
if (\is_null($result)) {
throw new \UnexpectedValueException('Trick total count error: list cannot be generated!');
}
return $result;
}
/**
* Create an event related to trick and dispatch it.
*
* An auto configured User subscriber listens to that kind of event.
*
* @param string $eventContext
* @param Trick $trick
* @param User $authenticatedUser
*
* @return void
*
* @see https://symfony.com/blog/new-in-symfony-4-3-simpler-event-dispatching#supporting-both-dispatchers
*
* @throws \Exception
*/
public function createAndDispatchTrickEvent(string $eventContext, Trick $trick, User $authenticatedUser): void
{
$event = $this->customEventFactory->createFromContext(
$eventContext,
['user' => $authenticatedUser, 'trick' => $trick]
);
if (\is_null($event)) {
throw new \Exception('Event was not created due to wrong parameters!');
}
$eventName = $this->customEventFactory->getEventNameByContext($eventContext);
/** @var EventDispatcherInterface $eventDispatcher */
$eventDispatcher = $this->customEventFactory->getEventDispatcher();
// CAUTION! Use LegacyEventDispatcherProxy for forward and backward compatibility since Sf 4.3!
$eventDispatcher = LegacyEventDispatcherProxy::decorate($eventDispatcher);
$eventDispatcher->dispatch($event, $eventName);
}
/**
* Create a Trick entity with necessary data.
*
* @param CreateTrickDTO $createTrickDTO
* @param User|UserInterface $authenticatedUser
* @param bool $isPersisted
* @param bool $isFlushed
*
* @return Trick
*
* @throws \Exception
*/
public function createTrick(
CreateTrickDTO $createTrickDTO,
UserInterface $authenticatedUser,
bool $isPersisted = false,
bool $isFlushed = false
): ?Trick {
$newTrick = new Trick(
$createTrickDTO->getGroup(), // At this time an array of TrickGroup is returned to possibly manage several "categories".
$authenticatedUser,
$createTrickDTO->getName(),
$createTrickDTO->getDescription(),
$this->makeSlug($createTrickDTO->getName()), // At this time slug is not customized in form, so create it with trick name.
$createTrickDTO->getIsPublished()
);
// Save data in database
return $this->addAndSaveTrick($newTrick, $isPersisted, $isFlushed); // null or the entity
}
/**
* Find all created tricks necessary data associated to a particular user author based on his uuid.
*
* Please note this is used to generate links to tricks update form.
*
* @param UuidInterface $userUuid
*
* @return array
*/
public function findOnesByAuthor(UuidInterface $userUuid): array
{
return $this->repository->findAllByAuthor($userUuid);
}
/**
* Find all other tricks necessary data by excluding a particular trick based on its uuid.
*
* @param UuidInterface $uuid
*
* @return mixed
*/
public function findOthersByExcludedUuid(UuidInterface $uuid)
{
return $this->repository->findOthersByExcludedUuid($uuid);
}
/**
* Find Trick by name string.
*
* @param string $name
*
* @return Trick|null
*
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function findSingleByName(string $name): ?Trick
{
return $this->repository->findOneByName($name);
}
/**
* Find Trick to show on single page by encoded uuid string.
*
* @param string $encodedUuid
*
* @return Trick|null
*
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function findSingleToShowByEncodedUuid(string $encodedUuid): ?Trick
{
$uuid = $this->decode($encodedUuid);
return $this->repository->findOneToShowByUuid($uuid);
}
/**
* Find Trick to update in form by encoded uuid string.
*
* @param string $encodedUuid
*
* @return Trick|null
*
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function findSingleToUpdateInFormByEncodedUuid(string $encodedUuid): ?Trick
{
$uuid = $this->decode($encodedUuid);
return $this->repository->findOneToUpdateInFormByUuid($uuid);
}
/**
* Get default trick list.
*
* This is used for first load for instance.
*
* @return array
*
* @throws \Doctrine\ORM\NonUniqueResultException
* @throws \Doctrine\ORM\NoResultException
*/
public function getTrickListParameters(): array
{
$startOffset = $this->getStartOffset();
$parameters = $this->filterParametersWithOrder($startOffset);
return $parameters;
}
/**
* Get filtered trick list depending on parameters.
*
* @param int $offset
* @param int $limit
* @param string $order
*
* @return array|null
*
* @throws \Doctrine\ORM\NonUniqueResultException
* @throws \Doctrine\ORM\NoResultException
*/
public function getFilteredList(
int $offset, // can be adjusted to be coherent
int $limit = Trick::TRICK_NUMBER_PER_LOADING, // can be updated after first load to be coherent
string $order = Trick::TRICK_LOADING_MODE
): ?array {
// Define init value to define starting rank in SQL query:
//So in ASC order, first assigned rank in SQL query will start at "0", and in DESC order it will start at $this->countAll() - 1
$init = ('DESC' === $order) ? $this->countAll() : -1;
// Offset starts at 0 (i.e. the 15th Trick rank has a value of 14).
$start = $offset;
$end = $offset + $limit;
return $this->repository->findByLimitOffsetWithOrder($order, $init, $start, $end);
}
/**
* Get default parameters to show a trick list.
*
* (e.g. sort direction, trick number for "load more", ...)
*
* @return array
*/
public function getTrickListConfigParameters(): array
{
return [
'loadingMode' => Trick::TRICK_LOADING_MODE,
'numberPerLoading' => Trick::TRICK_NUMBER_PER_LOADING,
'numberPerPage' => Trick::TRICK_NUMBER_PER_PAGE
];
}
/**
* Get pagination parameters to manage page links.
*
* This is used on complete trick list access page "tricks".
*
* @param int $pageIndex
*
* @return array|null
*
* @throws \Doctrine\ORM\NonUniqueResultException
* @throws \Doctrine\ORM\NoResultException
*/
public function getTrickListPaginationParameters(int $pageIndex): ?array
{
// Count all tricks
$countAll = $this->countAll();
$listDefaultParameters = $this->getTrickListConfigParameters();
$loadingMode = $listDefaultParameters['loadingMode'];
$trickNumberPerPage = $listDefaultParameters['numberPerPage'];
$trickNumberToShowModulo = $countAll % $trickNumberPerPage;
$trickNumberOnLastPage = 0 === $trickNumberToShowModulo ? 1 : $trickNumberToShowModulo;
$calculatedPageCount = $countAll / $trickNumberPerPage;
$pageCount = (0 === $trickNumberToShowModulo) ? $calculatedPageCount : (int) floor($calculatedPageCount) + 1;
// Page doesn't exist and obviously cannot be reached! This will throw a not found exception.
if ($pageIndex <= 0 || $pageIndex > $pageCount) {
return null;
}
// Adjust offset and limit value depending on loading mode
if ('DESC' === $loadingMode) {
// Define offset
$offset = ($countAll - $pageIndex * $trickNumberPerPage < 0) ? 0 : $countAll - $pageIndex * $trickNumberPerPage;
// Check if last page is reached (thanks to offset value under min value) or not to adjust limit!
$isLastPage = 0 === $offset;
$limit = $isLastPage ? $trickNumberOnLastPage : $trickNumberPerPage;
} else {
// Define offset
$offset = (1 === $pageIndex) ? 0 : ($pageIndex - 1) * $trickNumberPerPage;
// Check if last page is reached (thanks to offset value over max offset value) or not to adjust limit!
$isLastPage = 0 === $offset + $trickNumberPerPage > $countAll - 1;
$limit = $isLastPage ? $trickNumberOnLastPage : $trickNumberPerPage;
}
// Particular case for both cases: show all tricks directly if $countAll === $trickNumberPerPage
if ($countAll === $trickNumberPerPage) {
// Adjust limit again!
$limit = $trickNumberPerPage;
}
return [
'currentPage' => $pageIndex,
'currentOffset' => $offset,
'currentLimit' => $limit,
'pageCount' => $pageCount,
'loadingMode' => $loadingMode,
'trickCount' => $countAll
];
}
/**
* Define start offset accordingly to sort direction.
*
* @return int
*
* @throws \Doctrine\ORM\NonUniqueResultException
* @throws \Doctrine\ORM\NoResultException
*/
public function getStartOffset(): int
{
// Get tricks total number
$countAll = $this->countAll();
$startOffset = ('DESC' === $this->getTrickListConfigParameters()['loadingMode'])
? $countAll - $this->getTrickListConfigParameters()['numberPerLoading'] : 0;
return $startOffset;
}
/**
* Filter allowed $offset and $limit values depending on sort direction,
* and redefine them if it is possible, to avoid issues.
*
* @param int $offset
* @param int $limit
* @param string $order
*
* @return array
*
* @throws \Doctrine\ORM\NonUniqueResultException
* @throws \Doctrine\ORM\NoResultException
*/
public function filterParametersWithOrder(
int $offset,
int $limit = Trick::TRICK_NUMBER_PER_LOADING,
string $order = Trick::TRICK_LOADING_MODE
): array {
$count = $this->repository->countAll();
$minOffset = 0;
$maxOffset = $count - 1;
// Check a valid start offset for both modes
// In "DESC" mode, the lowest valid offset value is: -$limit
// In "ASC" mode, the highest valid offset value is: $maxOffset + $limit + 1
// This is the client side version to declare it in the same way but it can be simplified on server side by:
//$validOffset = ($offset >= $minOffset) && ($offset < $maxOffset + 1);
$validOffset = ($offset >= -$limit) && ($offset < $maxOffset + $limit + 1);
// Check a valid limit for both modes
$validLimit = ($limit >= 1); // && ($limit < $maxOffset + 1); will throw an exception by defining a limit max value
// Check correctly defined order
$validOrder = ('ASC' === $order) || ('DESC' === $order);
// Define parameters some of whom can be adjusted!
$parameters = [
'order' => $order,
'countAll' => $count,
'minOffset' => $minOffset,
'maxOffset' => $maxOffset,
'offset' => $offset,
'limit' => $limit,
'error' => false
];
// Define evaluated conditions
$conditions = [
'descendingOrderAndWrongParameters' => 'DESC' === $order && (!$validOffset || !$validLimit),
'ascendingOrderAndWrongParameters' => 'ASC' === $order && (!$validOffset || !$validLimit),
'descendingOrderUnderMinimumOffset' => 'DESC' === $order && ($offset < $minOffset),
'ascendingOrderOverMaxOffset' => 'ASC' === $order && ($offset + $limit > $maxOffset)
];
// Filter the condition evaluated to true
if (!$validOrder) {
// Reset list to descending order initial state by default if $order is wrong.
$condition = ['descendingOrderAndWrongParameters' => true];
} else {
$condition = array_filter($conditions, function ($value) {
return true === $value;
});
}
// Update parameters by possibly bubbling up error
$parameters = $this->adaptTrickListParameters($condition, $parameters);
return $parameters;
}
/*
* Filter complete trick list pagination request attribute.
*
* @param Request $request
* @param string $route
*
* @return int
*
* @throws \Exception
*/
public function filterPaginationRequestAttribute(Request $request): int
{
// Prevent issue if "page" attribute has no default value defined (no redirection is made)
$page = \is_null($request->attributes->get('page')) ? '' : $request->attributes->get('page');
// This regex below represents "<\d+>?1" (requirements and/or default) declared "page" attribute combinations or empty attribute.
$isDefaultParameter = preg_match("/^(<\\d\+>)?1?$/", $page);
$isPageParameterCorrect = \ctype_digit((string) $page) && $page >= 1;
// Wrong parameters
// This is an optional check thanks to requirements and default empty parameters on route at this time
if (!$isPageParameterCorrect && !$isDefaultParameter) {
$this->logger->error(
sprintf("[trace app SnowTricks] TrickManager/filterPaginationRequestAttribute => pagination error with parameter: %s", $page)
);
throw new \UnexpectedValueException('Trick list pagination parameters error: list cannot be generated!');
}
// Adjust Default parameter
return $isPageParameterCorrect && !$isDefaultParameter ? (int) $page : 1;
}
/**
* Filter trick list request attributes preparing parameters to check.
*
* @param Request $request
*
* @return array
*
* @throws \UnexpectedValueException
*/
public function filterListRequestAttributes(Request $request): array
{
if (!$request->attributes->has('offset') || !\ctype_digit((string) $request->attributes->get('offset'))) {
$this->logger->error("[trace app SnowTricks] TrickManager/filterListRequestAttributes => list error: at least, offset route placeholder is expected!");
throw new \UnexpectedValueException('Trick list parameters error: list cannot be generated!');
}
// Get starting rank
$offset = (int) $request->attributes->get('offset');
// Check if limit parameter exists or use default limit value
$limit = \ctype_digit((string) $request->attributes->get('limit'))
? (int) $request->attributes->get('limit')
: $this->getTrickListConfigParameters()['numberPerLoading'];
return [
'offset' => $offset,
'limit' => $limit
];
}
/**
* Get entity manager.
*
* @return EntityManagerInterface
*/
public function getEntityManager(): EntityManagerInterface
{
return $this->entityManager;
}
/**
* Get Trick entity repository.
*
* @return TrickRepository
*/
public function getRepository(): TrickRepository
{
return $this->repository;
}
/**
* Check if total count is outdated.
*
* For instance, this can happen when entities are added or removed and an ajax request is performed.
*
* @param int $count
*
* @return bool
*/
public function isCountAllOutdated(int $count): bool
{
$keyName = self::TRICK_COUNT_SESSION_KEY;
if ($this->session->has($keyName) && $this->session->get($keyName) !== $count) {
// Update trick total count stored in session
$this->session->set($keyName, $count);
return true;
}
return false;
}
/**
* Remove a trick and all associated entities depending on cascade operations.
*
* @param Trick $trick
* @param bool $isFlushed
*
* @return bool
*/
public function removeTrick(Trick $trick, bool $isFlushed = true): bool
{
// Proceed to removal in database
return $this->removeAndSaveNoMoreEntity($trick, $isFlushed);
}
/**
* Update a Trick entity with necessary data.
*
* @param UpdateTrickDTO $updateTrickDTO
* @param Trick $trickToUpdate
* @param User|UserInterface $authenticatedUser
* @param bool $mustAuthorBeReplaced
* @param bool $isFlushed
*
* @return Trick
*
* @throws \Exception
*/
public function updateTrick(
UpdateTrickDTO $updateTrickDTO,
Trick $trickToUpdate,
UserInterface $authenticatedUser,
bool $mustAuthorBeReplaced = false,
bool $isFlushed = false
): Trick {
// Must author be replaced (updated)?
// CAUTION! This is the case when an author account is deleted, then a particular anonymous becomes trick author.
// At this time user author is not changed on update to keep the original author.
!$mustAuthorBeReplaced ?: $trickToUpdate->modifyUser($authenticatedUser);
// Update trick simple data
$trickToUpdate
->modifyTrickGroup($updateTrickDTO->getGroup()) // At this time only one TrickGroup is returned.
->modifyName($updateTrickDTO->getName())
->modifyDescription($updateTrickDTO->getDescription())
->customizeSlug($this->makeSlug($updateTrickDTO->getName())) // At this time slug is not customized in form, so create it with trick name.
->modifyUpdateDate(new \DateTime('now'))
->modifyIsPublished($updateTrickDTO->getIsPublished()); // This can change with administrator account!
// Save data in database if expected
$trickToUpdate = $this->addAndSaveTrick($trickToUpdate, false, $isFlushed);
return $trickToUpdate;
}
}