1: <?php
2:
3: namespace Alchemy\orm;
4: use Alchemy\core\query\Query;
5: use Alchemy\core\schema\Table;
6: use Alchemy\util\Monad;
7: use Exception;
8:
9:
10: /**
11: * Extension of Monad to allow building a SELECT statement while
12: * retaining a reference to the Session you started with
13: */
14: class SessionSelect extends Monad {
15: protected $session;
16: protected $mapper;
17:
18:
19: /**
20: * Object constructor.
21: *
22: * @param Session $session Session to use for running select
23: * @param string $mapper DataMapper class to return objects as
24: */
25: public function __construct(Session $session, $mapper) {
26: $this->session = $session;
27: $this->mapper = $mapper;
28:
29: $table = $mapper::table();
30:
31: $this->value = Query::Select($table);
32: $this->value->columns($table->columns());
33: }
34:
35:
36: /**
37: * Execute the query and return a set of all results
38: *
39: * @return array
40: */
41: public function all() {
42: return $this->session->execute($this->mapper, $this->value);
43: }
44:
45:
46: /**
47: * Return the first result of the query.
48: *
49: * @return DataMapper Query Result
50: */
51: public function first() {
52: $all = $this->limit(1)->all();
53: return count($all) == 0 ? null : $all[0];
54: }
55:
56:
57: /**
58: * Similar to {@see SessionSelect::first()}, but doesn't actually
59: * limit the query sent to the database. Instead, the full results
60: * of the query are retrieved, and an exception is thrown if there
61: * are more than one.
62: *
63: * @return DataMapper Query Result
64: */
65: public function one() {
66: $all = $this->all();
67:
68: if (count($all) != 1) {
69: throw new \Exception("Expected 1 row, got " . count($all));
70: }
71:
72: return $all[0];
73: }
74: }
75: