1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* The Query builder API. |
4
|
|
|
* |
5
|
|
|
* @author RN Kushwaha <[email protected]> |
6
|
|
|
* @since v0.0.1 <Date: 12th April, 2019> |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Dolphin\Mapper; |
10
|
|
|
|
11
|
|
|
use Dolphin\Builders\QueryBuilder; |
12
|
|
|
use Dolphin\Connections\Connection; |
13
|
|
|
use Dolphin\Utils\Utils; |
14
|
|
|
use Exception; |
15
|
|
|
|
16
|
|
|
class Save extends Dolphin |
17
|
|
|
{ |
18
|
|
|
private $qb; |
19
|
|
|
|
20
|
|
|
public function __construct() |
21
|
|
|
{ |
22
|
|
|
$this->qb = new QueryBuilder(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function buildQueryStrSingleFromArr($row = []){ |
26
|
|
|
$ar = []; |
27
|
|
|
$query = "UPDATE ".$this->table." SET "; |
28
|
|
|
foreach($row as $key => $val){ |
29
|
|
|
$ar[':'.$key] = $val; |
30
|
|
|
if($key == 'id') continue; |
31
|
|
|
$query.= $this->qb->quote($key)." =:".$key.","; |
32
|
|
|
} |
33
|
|
|
$query = rtrim($query, ","); |
34
|
|
|
|
35
|
|
|
return ['ar' => $ar, 'query' => $query]; |
36
|
|
|
} |
37
|
|
|
public function createQuery($row){ |
38
|
|
|
$ar = []; |
39
|
|
|
if(isset($row) && isset($row->id) && $row->id > 0 ){ |
40
|
|
|
$mixedData = $this->buildQueryStrSingleFromArr($row); |
41
|
|
|
$query= $mixedData['query']." WHERE ".$this->qb->quote('id')."=:id"; |
42
|
|
|
|
43
|
|
|
return ['query' => $query, 'data' => $mixedData['ar']]; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$queryVal = ''; |
47
|
|
|
$query = "INSERT INTO ".$this->table." ("; |
48
|
|
|
foreach($row as $key => $val){ |
49
|
|
|
$query.= $this->qb->quote($key).", "; |
50
|
|
|
$ar[$key] = $val; |
51
|
|
|
$queryVal.= ":".$key.", "; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$query = rtrim($query, ", ").") VALUES (".$queryVal.rtrim($query, ", ").") "; |
55
|
|
|
|
56
|
|
|
return ['query' => $query, 'data' => $ar]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* It saves the row by primary key [id] |
61
|
|
|
* Or inserts a new row if id is null |
62
|
|
|
* |
63
|
|
|
* @param object $object |
64
|
|
|
* @return boolean |
65
|
|
|
* @throws Exception |
66
|
|
|
* @author RN Kushwaha <[email protected]> |
67
|
|
|
* @since v0.0.5 |
68
|
|
|
*/ |
69
|
|
|
public function save($object): bool |
70
|
|
|
{ |
71
|
|
|
$util = new Utils(); |
72
|
|
|
$row = $util->turnObject($this->className, $object); |
73
|
|
|
|
74
|
|
|
list($query, $data) = $this->createQuery($row); |
75
|
|
|
|
76
|
|
|
try{ |
77
|
|
|
$stmt = Connection::get()->prepare($this->qb->queryPrefix($query)); |
78
|
|
|
$stmt->execute($data); |
79
|
|
|
} catch(Exception $e){ |
80
|
|
|
throw new Exception($e->getMessage()); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
return true; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
} |
87
|
|
|
|