|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\Common\PropertyChangedListener; |
|
6
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\ValidatedEntityInterface; |
|
7
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Exception\ValidationException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Trait ImplementNotifyChangeTrackingPolicy |
|
11
|
|
|
* |
|
12
|
|
|
* @see https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/change-tracking-policies.html#notify |
|
13
|
|
|
* |
|
14
|
|
|
* @package EdmondsCommerce\DoctrineStaticMeta\Entity\Traits |
|
15
|
|
|
*/ |
|
16
|
|
|
trait ImplementNotifyChangeTrackingPolicy |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var array PropertyChangedListener[] |
|
20
|
|
|
*/ |
|
21
|
|
|
private $notifyChangeTrackingListeners = []; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param PropertyChangedListener $listener |
|
25
|
|
|
*/ |
|
26
|
43 |
|
public function addPropertyChangedListener(PropertyChangedListener $listener) |
|
27
|
|
|
{ |
|
28
|
43 |
|
$this->notifyChangeTrackingListeners[] = $listener; |
|
29
|
43 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* To be called from all set methods |
|
33
|
|
|
* |
|
34
|
|
|
* This method updates the property value, then it runs this through validation |
|
35
|
|
|
* If validation fails, it sets the old value back and throws the caught exception |
|
36
|
|
|
* If validation passes, it then performs the Doctrine notification for property change |
|
37
|
|
|
* |
|
38
|
|
|
* @param string $propName |
|
39
|
|
|
* @param $newValue |
|
40
|
|
|
* |
|
41
|
|
|
* @throws ValidationException |
|
42
|
|
|
*/ |
|
43
|
42 |
|
private function updatePropertyValueThenValidateAndNotify(string $propName, $newValue) |
|
44
|
|
|
{ |
|
45
|
42 |
|
if ($this->$propName === $newValue) { |
|
46
|
5 |
|
return; |
|
47
|
|
|
} |
|
48
|
37 |
|
$oldValue = $this->$propName; |
|
49
|
37 |
|
$this->$propName = $newValue; |
|
50
|
37 |
|
if ($this instanceof ValidatedEntityInterface) { |
|
51
|
|
|
try { |
|
52
|
37 |
|
$this->validateProperty($propName); |
|
53
|
2 |
|
} catch (ValidationException $e) { |
|
54
|
2 |
|
$this->$propName = $oldValue; |
|
55
|
2 |
|
throw $e; |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
35 |
|
foreach ($this->notifyChangeTrackingListeners as $listener) { |
|
59
|
2 |
|
$listener->propertyChanged($this, $propName, $oldValue, $newValue); |
|
60
|
|
|
} |
|
61
|
35 |
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|