initial commit
[namibia] / module / Fixture / src / Fixture / Service / Fixture.php
1 <?php
2 namespace Fixture\Service;
3
4
5
6 /**
7  * Data fixture utillity service to enable easy setup of test data.
8  * @author andre.fourie
9  */
10 class Fixture
11 {
12
13         /**
14          * @var \Doctrine\ORM\EntityManager
15          */
16         static protected $em;
17         /**
18          * @var array
19          */
20         static protected $references = array();
21
22
23         /**
24          * Set Doctrine Entity Manager.
25          * @param \Doctrine\ORM\EntityManager $em
26          */
27         static public function setEntityManager(\Doctrine\ORM\EntityManager $em)
28         {
29                 self::$em = $em;
30         }
31
32         /**
33          * Add multiple entries.
34          * @param string $entityName
35          * @param array $stackData
36          */
37         static protected function addStack($entityName, array $stackData)
38         {
39                 foreach ($stackData as $key => $data)
40                 {
41                         $referenceName = !is_numeric($key)
42                                 ? $key
43                                 : false;
44                         self::addEntry($entityName, $data, $referenceName);
45                 }
46         }
47
48         /**
49          * Add a single entry.
50          * @param string $entityName
51          * @param array $data
52          * @param string $referenceName
53          */
54         static protected function addEntry($entityName, array $data, $referenceName = false)
55         {
56                 $entity = new $entityName();
57                 $entity->fromArray($data);
58                 self::$em->persist($entity);
59                 self::$em->flush();
60                 if ($referenceName)
61                 {
62                         self::$references[$referenceName] = self::$em->getReference($entityName, $entity->id);
63                 }
64         }
65
66         /**
67          * Retrieve a reference.
68          * @param string $name
69          * @return object|null
70          */
71         static protected function getReference($name)
72         {
73                 self::$em->merge(self::$references[$name]);
74                 return self::$references[$name];
75         }
76
77 }