Passed
Branch v1.5.1 (f7b1b3)
by Wanderson
01:50
created

Query::update()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 10
rs 10
c 1
b 1
f 0
1
<?php
2
3
namespace Win\Repositories\Database\Sql;
4
5
/**
6
 * SELECT, UPDATE, DELETE, etc
7
 */
8
class Query
9
{
10
	/** @var string */
11
	private $table;
12
13
	/** @var string */
14
	private $raw = null;
15
16
	/** @var array */
17
	private $values = [];
18
19
	/** @var Where */
20
	public $where;
21
22
	/** @var OrderBy */
23
	public $orderBy;
24
25
	/** @var Limit */
26
	public $limit;
27
28
	/**
29
	 * Prepara a query
30
	 * @param string $table
31
	 * @param mixed $values
32
	 * @param string $raw
33
	 */
34
	public function __construct($table, $values = [], $raw = null)
35
	{
36
		$this->table = $table;
37
		$this->values = $values;
38
		$this->raw = $raw;
39
40
		$this->where = new Where();
41
		$this->orderBy = new OrderBy();
42
		$this->limit = new Limit();
43
	}
44
45
	/** @return mixed[] */
46
	public function getValues()
47
	{
48
		return array_values($this->values + $this->where->values);
49
	}
50
51
	/**
52
	 * SELECT * FROM ...
53
	 * @return string
54
	 */
55
	public function select()
56
	{
57
		return ($this->raw ??
58
			'SELECT * FROM ' . $this->table)
59
			. $this->where
60
			. $this->orderBy
61
			. $this->limit;
62
	}
63
64
	/**
65
	 * SELECT COUNT(*) FROM
66
	 * @return string
67
	 */
68
	public function selectCount()
69
	{
70
		return ($this->raw ??
71
			'SELECT COUNT(*) FROM ' . $this->table)
72
			. $this->where;
73
	}
74
75
	/**
76
	 * INSERT INTO ... VALUES
77
	 * @return string
78
	 */
79
	public function insert()
80
	{
81
		$params = str_split(str_repeat('?', count($this->values)));
82
		return 'INSERT INTO ' . $this->table
83
			. ' (' . implode(',', array_keys($this->values)) . ')'
84
			. ' VALUES (' . implode(', ', $params) . ')';
85
	}
86
87
	/**
88
	 * UPDATE ... SET
89
	 * @return string
90
	 */
91
	public function update()
92
	{
93
		$columns = array_map(function ($column) {
94
			return $column . ' = ?';
95
		}, array_keys($this->values));
96
97
		return 'UPDATE ' . $this->table
98
			. ' SET ' . implode(', ', $columns)
99
			. $this->where
100
			. $this->limit;
101
	}
102
103
	/**
104
	 * DELETE FROM ...
105
	 * @return string
106
	 */
107
	public function delete()
108
	{
109
		return 'DELETE FROM ' . $this->table
110
			. $this->where
111
			. $this->limit;
112
	}
113
114
	/**
115
	 * @return string
116
	 */
117
	public function raw()
118
	{
119
		return $this->raw
120
			. $this->where
121
			. $this->limit;
122
	}
123
}
124