This repository has been archived by the owner on Sep 23, 2022. It is now read-only.
/
ObjectFactory.php
57 lines (46 loc) · 1.74 KB
/
ObjectFactory.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
<?php
namespace Knp\RadBundle\DataFixtures;
use Doctrine\Common\DataFixtures\ReferenceRepository;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
class ObjectFactory
{
private $manager;
private $className;
private $defaultAttributes = array();
public function __construct(
ReferenceRepository $referenceRepository,
ReferenceManipulator $referenceManipulator,
ObjectManager $manager,
$className,
PropertyAccessor $accessor = null
)
{
$this->referenceRepository = $referenceRepository;
$this->referenceManipulator = $referenceManipulator;
$this->manager = $manager;
$this->className = $className;
$this->accessor = $accessor ?: PropertyAccess::createPropertyAccessor();
}
public function add(array $attributes = array())
{
// We do not override $attributes because the reference manipulator will use the first element to generate the reference name
$mergedAttributes = array_merge($this->defaultAttributes, $attributes);
$object = new $this->className();
foreach ($mergedAttributes as $attribute => $value) {
$this->accessor->setValue($object, $attribute, $value);
}
$this->referenceRepository->addReference(
$this->referenceManipulator->createReferenceName($this->className, $attributes),
$object
);
$this->manager->persist($object);
return $this;
}
public function setDefaults(array $attributes = array())
{
$this->defaultAttributes = $attributes;
return $this;
}
}