1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Sylius package. |
5
|
|
|
* |
6
|
|
|
* (c) Paweł Jędrzejewski |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Sylius\Bundle\ReviewBundle\EventListener; |
15
|
|
|
|
16
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
17
|
|
|
use Sylius\Bundle\ReviewBundle\Updater\ReviewableRatingUpdaterInterface; |
18
|
|
|
use Sylius\Component\Resource\Exception\UnexpectedTypeException; |
19
|
|
|
use Sylius\Component\Review\Model\ReviewInterface; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @author Mateusz Zalewski <[email protected]> |
23
|
|
|
*/ |
24
|
|
|
final class ReviewChangeListener |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var ReviewableRatingUpdaterInterface |
28
|
|
|
*/ |
29
|
|
|
private $averageRatingUpdater; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param ReviewableRatingUpdaterInterface $averageRatingUpdater |
33
|
|
|
*/ |
34
|
|
|
public function __construct(ReviewableRatingUpdaterInterface $averageRatingUpdater) |
35
|
|
|
{ |
36
|
|
|
$this->averageRatingUpdater = $averageRatingUpdater; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param LifecycleEventArgs $args |
41
|
|
|
*/ |
42
|
|
|
public function postPersist(LifecycleEventArgs $args) |
43
|
|
|
{ |
44
|
|
|
$this->recalculateSubjectRating($args); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param LifecycleEventArgs $args |
49
|
|
|
*/ |
50
|
|
|
public function postUpdate(LifecycleEventArgs $args) |
51
|
|
|
{ |
52
|
|
|
$this->recalculateSubjectRating($args); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param LifecycleEventArgs $args |
57
|
|
|
*/ |
58
|
|
|
public function postRemove(LifecycleEventArgs $args) |
59
|
|
|
{ |
60
|
|
|
$this->recalculateSubjectRating($args); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param LifecycleEventArgs $args |
65
|
|
|
*/ |
66
|
|
|
public function recalculateSubjectRating(LifecycleEventArgs $args): void |
67
|
|
|
{ |
68
|
|
|
$subject = $args->getObject(); |
69
|
|
|
|
70
|
|
|
if (!$subject instanceof ReviewInterface) { |
71
|
|
|
return; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$this->averageRatingUpdater->update($subject->getReviewSubject()); |
|
|
|
|
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: