1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Factory; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\NotifyPropertyChanged; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Validation\EntityValidatorFactory; |
8
|
|
|
|
9
|
|
|
class EntityFactory |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var EntityValidatorFactory |
13
|
|
|
*/ |
14
|
|
|
protected $entityValidatorFactory; |
15
|
|
|
/** |
16
|
|
|
* @var EntityManagerInterface |
17
|
|
|
*/ |
18
|
|
|
private $entityManager; |
19
|
|
|
|
20
|
19 |
|
public function __construct(EntityValidatorFactory $entityValidatorFactory, EntityManagerInterface $entityManager) |
21
|
|
|
{ |
22
|
19 |
|
$this->entityValidatorFactory = $entityValidatorFactory; |
23
|
19 |
|
$this->entityManager = $entityManager; |
24
|
19 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Build a new entity with the validator factory preloaded |
28
|
|
|
* |
29
|
|
|
* Optionally pass in an array of property=>value |
30
|
|
|
* |
31
|
|
|
* @param string $entityFqn |
32
|
|
|
* |
33
|
|
|
* @param array $values |
34
|
|
|
* |
35
|
|
|
* @return mixed |
36
|
|
|
*/ |
37
|
18 |
|
public function create(string $entityFqn, array $values = []) |
38
|
|
|
{ |
39
|
18 |
|
$entity = new $entityFqn($this->entityValidatorFactory); |
40
|
18 |
|
$this->addListenerToEntityIfRequired($entity); |
41
|
18 |
|
foreach ($values as $property => $value) { |
42
|
2 |
|
$setter = 'set' . $property; |
43
|
2 |
|
if (!method_exists($entity, $setter)) { |
44
|
1 |
|
throw new \InvalidArgumentException( |
45
|
1 |
|
'The entity ' . $entityFqn . ' does not have the setter method ' . $setter |
46
|
|
|
); |
47
|
|
|
} |
48
|
1 |
|
$entity->$setter($value); |
49
|
|
|
} |
50
|
|
|
|
51
|
17 |
|
return $entity; |
52
|
|
|
} |
53
|
|
|
|
54
|
18 |
|
private function addListenerToEntityIfRequired($entity): void |
55
|
|
|
{ |
56
|
18 |
|
if (!$entity instanceof NotifyPropertyChanged) { |
57
|
|
|
return; |
58
|
|
|
} |
59
|
18 |
|
$listener = $this->entityManager->getUnitOfWork(); |
60
|
18 |
|
$entity->addPropertyChangedListener($listener); |
61
|
18 |
|
} |
62
|
|
|
} |
63
|
|
|
|