CrudBuilder::insert()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Maphper\Lib;
3
class CrudBuilder {
4
	private function quote($str) {
5
		return '`' . str_replace('.', '`.`', trim($str, '`')) . '`';
6
	}
7
8
	public function delete($table, $criteria, $args, $limit = null, $offset = null, $order = null) {
9
		$limit = $limit ? ' LIMIT ' . $limit : '';
10
		$offset = $offset ? ' OFFSET ' . $offset : '';
11
        $order = $order ? ' ORDER BY ' . $order : '';
12
		return new Query('DELETE FROM ' . $table . ' WHERE ' . ($criteria ?: '1 = 1 ') . $order . $limit . $offset, $args);
13
	}
14
15
16
	private function buildSaveQuery($data, $prependField = false) {
17
		$sql = [];
18
		$args = [];
19
		foreach ($data as $field => $value) {
20
			//For dates with times set, search on time, if the time is not set, search on date only.
21
			//E.g. searching for all records posted on '2015-11-14' should return all records that day, not just the ones posted at 00:00:00 on that day
22
			if ($value instanceof \DateTimeInterface) {
23
				if ($value->format('H:i:s')  == '00:00:00') $value = $value->format('Y-m-d');
24
				else $value = $value->format('Y-m-d H:i:s');
25
			}
26
			if (is_object($value)) continue;
27
			if ($prependField){
28
				$sql[] = $this->quote($field) . ' = :' . $field;
29
			} else {
30
				$sql[] = ':' . $field;
31
			}
32
			$args[$field] = $value;
33
		}
34
		return ['sql' => $sql, 'args' => $args];
35
	}
36
37
	public function insert($table, $data) {
38
		$query = $this->buildSaveQuery($data);
39
		return new Query('INSERT INTO ' . $this->quote($table) . ' (' .implode(', ', array_keys($query['args'])).') VALUES ( ' . implode(', ', $query['sql']). ' )', $query['args']);
40
	}
41
42
	public function update($table, array $primaryKey, $data) {
43
		$query = $this->buildSaveQuery($data, true);
44
		$where = [];
45
		foreach($primaryKey as $field) $where[] = $this->quote($field) . ' = :' . $field;
46
		return new Query('UPDATE ' . $this->quote($table) . ' SET ' . implode(', ', $query['sql']). ' WHERE '. implode(' AND ', $where), $query['args']);
47
	}
48
}
49