1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Db\Doctrine\Subscriber; |
5
|
|
|
|
6
|
|
|
use Doctrine\Common\EventSubscriber; |
7
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
8
|
|
|
use Doctrine\ORM\Event\PreUpdateEventArgs; |
9
|
|
|
use Doctrine\ORM\Events; |
10
|
|
|
use SlayerBirden\DataFlowServer\Db\Entities\DbConfiguration; |
11
|
|
|
use SlayerBirden\DataFlowServer\Validation\Exception\ValidationException; |
12
|
|
|
|
13
|
|
|
final class Validation implements EventSubscriber |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @inheritDoc |
17
|
|
|
*/ |
18
|
140 |
|
public function getSubscribedEvents(): array |
19
|
|
|
{ |
20
|
|
|
return [ |
21
|
140 |
|
Events::preUpdate, |
22
|
140 |
|
Events::prePersist, |
23
|
|
|
]; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param PreUpdateEventArgs $args |
28
|
|
|
* @throws ValidationException |
29
|
|
|
*/ |
30
|
18 |
|
public function preUpdate(PreUpdateEventArgs $args): void |
31
|
|
|
{ |
32
|
18 |
|
$entity = $args->getObject(); |
33
|
18 |
|
if ($entity instanceof DbConfiguration) { |
34
|
4 |
|
$this->validate($entity); |
35
|
|
|
} |
36
|
18 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param LifecycleEventArgs $args |
40
|
|
|
* @throws ValidationException |
41
|
|
|
*/ |
42
|
40 |
|
public function prePersist(LifecycleEventArgs $args): void |
43
|
|
|
{ |
44
|
40 |
|
$entity = $args->getObject(); |
45
|
40 |
|
if ($entity instanceof DbConfiguration) { |
46
|
10 |
|
$this->validate($entity); |
47
|
|
|
} |
48
|
36 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param DbConfiguration $configuration |
52
|
|
|
* @throws ValidationException |
53
|
|
|
*/ |
54
|
14 |
|
private function validate(DbConfiguration $configuration): void |
55
|
|
|
{ |
56
|
14 |
|
$msg = '%s is required field if "url" is not set.'; |
57
|
14 |
|
if (!empty($configuration->getUrl())) { |
58
|
8 |
|
return; |
59
|
|
|
} |
60
|
|
|
|
61
|
6 |
|
if (empty($configuration->getDbname())) { |
62
|
|
|
throw new ValidationException(sprintf($msg, 'dbname')); |
63
|
|
|
} |
64
|
6 |
|
if (empty($configuration->getDriver())) { |
65
|
4 |
|
throw new ValidationException(sprintf($msg, 'driver')); |
66
|
|
|
} |
67
|
2 |
|
if (empty($configuration->getHost())) { |
68
|
|
|
throw new ValidationException(sprintf($msg, 'host')); |
69
|
|
|
} |
70
|
2 |
|
if (empty($configuration->getUser())) { |
71
|
|
|
throw new ValidationException(sprintf($msg, 'user')); |
72
|
|
|
} |
73
|
2 |
|
if (empty($configuration->getPort())) { |
74
|
|
|
throw new ValidationException(sprintf($msg, 'port')); |
75
|
|
|
} |
76
|
|
|
|
77
|
2 |
|
if (empty($configuration->getTitle())) { |
78
|
|
|
throw new ValidationException('Title is empty.'); |
79
|
|
|
} |
80
|
2 |
|
} |
81
|
|
|
} |
82
|
|
|
|