storage test
[m6w6/pq-gateway] / lib / pq / Mapper / Storage.php
1 <?php
2
3 namespace pq\Mapper;
4
5 use InvalidArgumentException;
6 use pq\Connection;
7 use pq\Gateway\Table;
8 use pq\Transaction;
9
10 class Storage implements StorageInterface
11 {
12 /**
13 * The mapping of this storage
14 * @var MapInterface
15 */
16 var $map;
17
18 /**
19 * The underlying table gateway
20 * @var Table
21 */
22 private $gateway;
23
24 /**
25 * Buffered transaction
26 * @var Transaction
27 */
28 private $xaction;
29
30 /**
31 * Create a storage for $map
32 * @param MapInterface $map
33 */
34 function __construct(MapInterface $map) {
35 $this->map = $map;
36 $this->gateway = $map->getGateway();
37 }
38
39 /**
40 * Find by PK
41 * @param mixed $pk
42 * @return object
43 */
44 function get($pk) {
45 $id = $this->gateway->getIdentity();
46 if (count($id) == 1 && is_scalar($pk)) {
47 $pk = [current($id->getColumns()) => $pk];
48 } elseif (!is_array($pk) || count($pk) !== count($id)) {
49 throw InvalidArgumentException(
50 "Insufficient identity provided; not all fields of %s are provided in %s",
51 json_encode($id->getColumns()), json_encode($pk));
52 }
53
54 $where = [];
55 foreach ($pk as $k => $v) {
56 $where["$k="] = $v;
57 }
58 $rowset = $this->gateway->find($where);
59
60 return $this->map->map($rowset->current());
61 }
62
63 /**
64 * Find
65 * @param array $where
66 * @param string $order
67 * @param int $limit
68 * @param int $offset
69 * @return object[]
70 */
71 function find($where = [], $order = null, $limit = null, $offset = null) {
72 /* @var pq\Gateway\Rowset $rowset */
73 $rowset = $this->gateway->find($where, $order, $limit, $offset);
74 return $this->map->mapAll($rowset);
75 }
76
77 /**
78 * Delete
79 * @param object $object
80 */
81 function delete($object) {
82 $cache = $this->map->getObjects();
83 $row = $cache->asRow($object)->delete();
84 $cache->resetObject($row);
85 $cache->resetRow($object);
86 }
87
88 /**
89 * Save
90 * @param object $object
91 */
92 function save($object) {
93 $this->map->unmap($object);
94 }
95
96 /**
97 * Buffer in a transaction
98 */
99 function buffer() {
100 switch ($this->gateway->getConnection()->transactionStatus) {
101 case Connection::TRANS_INTRANS:
102 break;
103 default:
104 $this->gateway->getQueryExecutor()->execute(new \pq\Query\Writer("START TRANSACTION"));
105 }
106 }
107
108 /**
109 * Commit
110 */
111 function flush() {
112 switch ($this->gateway->getConnection()->transactionStatus) {
113 case Connection::TRANS_IDLE:
114 break;
115 default:
116 $this->gateway->getQueryExecutor()->execute(new \pq\Query\Writer("COMMIT"));
117 }
118 }
119
120 /**
121 * Rollback
122 */
123 function discard() {
124 switch ($this->gateway->getConnection()->transactionStatus) {
125 case Connection::TRANS_IDLE:
126 break;
127 default:
128 $this->gateway->getQueryExecutor()->execute(new \pq\Query\Writer("ROLLBACK"));
129 }
130 $this->map->getObjects()->reset();
131 }
132 }