Work on making country nullable. Presently the datamapper cant deal with it though...
[rock.divinelegy.git] / DataAccess / DataMapper / Helpers / VOMapsHelper.php
1 <?php
2
3 namespace DataAccess\DataMapper\Helpers;
4
5 use Exception;
6 use ReflectionClass;
7
8 class VOMapsHelper
9 {
10 private $_voName;
11 private $_tableName;
12 private $_accessor;
13
14 public function __construct($voName, $accessor, $tableName)
15 {
16 $this->_voName = $voName;
17
18 if($tableName) {
19 $this->_tableName = $tableName;
20 } else {
21 $this->_tableName = strtolower($voName);
22 }
23
24 if($accessor)
25 {
26 $this->_accessor = $accessor;
27 } else
28 {
29 $this->_accessor = 'get'. str_replace('_', '', $voName);
30 }
31 }
32
33 public function getAccessor()
34 {
35 return $this->_accessor;
36 }
37
38 public function getVOName()
39 {
40 return $this->_voName;
41 }
42
43 public function getTableName()
44 {
45 return $this->_tableName;
46 }
47
48 public function populate($maps, $db, $parent, $row)
49 {
50 $className = $maps[$this->_voName]['class'];
51 $table = $maps[$this->_voName]['table'];
52
53 // If the table we already have contains the id of a row we need in
54 // another table
55 //if(isset($row[$this->_tableName . '_id'])) {
56 if(array_key_exists($this->_tableName . '_id', $row)) { //this is a better choice as somtimes the array key is set, but is equal to null, and isset doesn't like that
57 $join_id = $row[$this->_tableName . '_id'];
58 $statement = $db->prepare(sprintf('SELECT * from %s WHERE id=%u',
59 $table,
60 $join_id));
61
62 $statement->execute();
63 $row = $statement->fetch();
64 } elseif($maps[$this->_voName]['table'] != $maps[$parent]['table']) {
65 // in this case we look in another table for this row's id
66 $join_id = $row['id'];
67 $statement = $db->prepare(sprintf('SELECT * from %s WHERE %s=%u',
68 $table,
69 strtolower($parent . '_id'),
70 $join_id
71 ));
72
73 $statement->execute();
74 $row = $statement->fetch();
75 }
76
77 $constructors = AbstractPopulationHelper::getConstrutorArray($maps, $this->_voName, $row, $db);
78
79 if(count($constructors) == 0)
80 {
81 return new $className;
82 } else {
83 try {
84 $r = new ReflectionClass($className);
85 return $r->newInstanceArgs($constructors);
86 } catch (Exception $e) {
87 return null;
88 }
89 }
90 }
91 }