1: <?php
2:
3: namespace Deimos\ORM\Queries;
4:
5: use Deimos\Database\Connection;
6: use Deimos\Database\Database;
7:
8: class Query extends \Deimos\Database\Queries\Query
9: {
10:
11: /**
12: * @var string $class
13: */
14: protected $class;
15:
16: /**
17: * @var string $table
18: */
19: protected $table;
20:
21: /**
22: * Instruction constructor.
23: *
24: * @param Database $database
25: * @param string $class
26: * @param string $table
27: */
28: public function __construct(Database $database, $class, $table)
29: {
30: parent::__construct($database);
31: $this->class = $class;
32: $this->table = $table;
33:
34: $this->from($this->table);
35: }
36:
37: /**
38: * @return int
39: */
40: public function count()
41: {
42: $self = clone $this;
43: $self->setSelect(['count' => $this->database->raw('COUNT(1)')]);
44:
45: $data = $self->findOne(false);
46:
47: return $data['count'];
48: }
49:
50: /**
51: * @param bool $asObject
52: *
53: * @return array
54: */
55: public function find($asObject = true)
56: {
57: if (!$asObject)
58: {
59: return parent::find();
60: }
61:
62: $objects = $this
63: ->database
64: ->queryInstruction($this)
65: ->fetchAll(
66: Connection::FETCH_CLASS,
67: $this->class,
68: [$this->database, false, $this->table]
69: );
70:
71: foreach ($objects as $object)
72: {
73: $object();
74: }
75:
76: return $objects;
77: }
78:
79: /**
80: * @param bool $asObject
81: *
82: * @return mixed
83: */
84: public function findOne($asObject = true)
85: {
86: if (!$asObject)
87: {
88: return parent::findOne();
89: }
90:
91: $self = clone $this;
92: $self->limit(1);
93:
94: $sth = $self
95: ->database
96: ->queryInstruction($self);
97:
98: $object = $sth->fetchObject(
99: $this->class,
100: [$this->database, false, $this->table]
101: );
102:
103: $object();
104: $sth->closeCursor();
105:
106: return $object;
107: }
108:
109: }