trigger mirror
[m6w6/pq-gateway] / lib / pq / Query / Executor.php
1 <?php
2
3 namespace pq\Query;
4
5 /**
6 * A synchronous query executor
7 */
8 class Executor implements ExecutorInterface
9 {
10 /**
11 * @var \pq\Connection
12 */
13 protected $conn;
14
15 /**
16 * @var \SplObjectStorage
17 */
18 protected $observers;
19
20 /**
21 * @var \pq\Query\WriterInterface
22 */
23 protected $query;
24
25 /**
26 * @var \pq\Result
27 */
28 protected $result;
29
30 /**
31 * Create a synchronous query executor
32 * @param \pq\Connection $conn
33 */
34 function __construct(\pq\Connection $conn) {
35 $this->conn = $conn;
36 $this->observers = new \SplObjectStorage;
37 }
38
39 /**
40 * @inheritdoc
41 * @return \pq\Connection
42 */
43 function getConnection() {
44 return $this->conn;
45 }
46
47 /**
48 * @inheritdoc
49 * @param \pq\Connection $conn
50 * @return \pq\Query\Executor
51 */
52 function setConnection(\pq\Connection $conn) {
53 $this->conn = $conn;
54 return $this;
55 }
56
57 /**
58 * @inheritdoc
59 * @return WriterInterface
60 */
61 function getQuery() {
62 return $this->query;
63 }
64
65 /**
66 * @inheritdoc
67 * @return \pq\Result
68 */
69 function getResult() {
70 return $this->result;
71 }
72
73 /**
74 * Execute the query synchronously through \pq\Connection::execParams()
75 * @param \pq\Query\WriterInterface $query
76 * @param callable $callback
77 * @return mixed
78 */
79 function execute(WriterInterface $query, callable $callback) {
80 $this->result = null;
81 $this->query = $query;
82 $this->notify();
83 $this->result = $this->getConnection()->execParams($query, $query->getParams(), $query->getTypes());
84 $this->notify();
85 return $callback($this->result);
86 }
87
88 /**
89 * @implements \SplSubject
90 * @param \SplObserver $observer
91 */
92 function attach(\SplObserver $observer) {
93 $this->observers->attach($observer);
94 }
95
96 /**
97 * @implements \SplSubject
98 * @param \SplObserver $observer
99 */
100 function detach(\SplObserver $observer) {
101 $this->observers->detach($observer);
102 }
103
104 /**
105 * @implements \SplSubject
106 */
107 function notify() {
108 foreach ($this->observers as $observer){
109 $observer->update($this);
110 }
111 }
112 }