1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Knp\RadBundle\DataFixtures; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\DataFixtures\ReferenceRepository; |
6
|
|
|
use Doctrine\Common\Persistence\ObjectManager; |
7
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccess; |
8
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccessor; |
9
|
|
|
|
10
|
|
|
class ObjectFactory |
11
|
|
|
{ |
12
|
|
|
private $manager; |
13
|
|
|
private $className; |
14
|
|
|
private $defaultAttributes = array(); |
15
|
|
|
|
16
|
|
|
public function __construct( |
17
|
|
|
ReferenceRepository $referenceRepository, |
18
|
|
|
ReferenceManipulator $referenceManipulator, |
19
|
|
|
ObjectManager $manager, |
20
|
|
|
$className, |
21
|
|
|
PropertyAccessor $accessor = null |
22
|
|
|
) |
23
|
|
|
{ |
|
|
|
|
24
|
|
|
$this->referenceRepository = $referenceRepository; |
|
|
|
|
25
|
|
|
$this->referenceManipulator = $referenceManipulator; |
|
|
|
|
26
|
|
|
$this->manager = $manager; |
27
|
|
|
$this->className = $className; |
28
|
|
|
$this->accessor = $accessor ?: PropertyAccess::createPropertyAccessor(); |
|
|
|
|
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function add(array $attributes = array()) |
32
|
|
|
{ |
33
|
|
|
// We do not override $attributes because the reference manipulator will use the first element to generate the reference name |
34
|
|
|
$mergedAttributes = array_merge($this->defaultAttributes, $attributes); |
35
|
|
|
$object = new $this->className(); |
36
|
|
|
|
37
|
|
|
foreach ($mergedAttributes as $attribute => $value) { |
38
|
|
|
$this->accessor->setValue($object, $attribute, $value); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$this->referenceRepository->addReference( |
42
|
|
|
$this->referenceManipulator->createReferenceName($this->className, $attributes), |
43
|
|
|
$object |
44
|
|
|
); |
45
|
|
|
|
46
|
|
|
$this->manager->persist($object); |
47
|
|
|
|
48
|
|
|
return $this; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function setDefaults(array $attributes = array()) |
52
|
|
|
{ |
53
|
|
|
$this->defaultAttributes = $attributes; |
54
|
|
|
|
55
|
|
|
return $this; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|