Passed
Push — master ( 000eb6...3b543f )
by RN
07:12
created

Save::buildQueryStrSingleFromArr()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 7
c 1
b 1
f 0
nc 3
nop 1
dl 0
loc 10
rs 10
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 = array()){
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
34
      return ['ar' => $ar, 'query' => $query];
35
    }
36
    public function createQuery($row){
37
        $ar = [];
38
        if(isset($row) && isset($row->id) && $row->id > 0 ){
39
            $query = "UPDATE ".$this->table." SET ";
0 ignored issues
show
Unused Code introduced by
The assignment to $query is dead and can be removed.
Loading history...
40
            $mixedData = $this->buildQueryStrSingleFromArr($row);
41
            $query = rtrim($mixedData['query'], ",");
42
            $query.= " WHERE ".$this->qb->quote('id')."=:id";
43
44
            return ['query' => $query, 'data' => $mixedData['ar']];
45
        }
46
47
        $queryVal = '';
48
        $query = "INSERT INTO ".$this->table." (";
49
        foreach($row as $key => $val){
50
            $query.= $this->qb->quote($key).", ";
51
            $ar[$key] = $val;
52
            $queryVal.= ":".$key.", ";
53
        }
54
55
        $query = rtrim($query, ", ").") VALUES (".$queryVal.rtrim($query, ", ").") ";
56
57
        return ['query' => $query, 'data' => $ar];
58
    }
59
60
    /**
61
     * It saves the row by primary key [id]
62
     * Or inserts a new row if id is null
63
     *
64
     * @param object $object
65
     * @return boolean
66
     * @throws Exception
67
     * @author RN Kushwaha <[email protected]>
68
     * @since v0.0.5
69
     */
70
    public function save($object)
71
    {
72
        $util = new Utils();
73
        $row = $util->turnObject($this->className, $object);
74
75
        list($query, $data) = $this->createQuery($row);
76
77
        try{
78
            $stmt = Connection::get()->prepare($this->qb->queryPrefix($query));
79
            $stmt->execute($data);
80
        } catch(Exception $e){
81
            throw new Exception($e->getMessage());
82
        }
83
84
        return true;
85
    }
86
87
}
88