Skip to content

Commit

Permalink
Update QueryBuilder.php
Browse files Browse the repository at this point in the history
  • Loading branch information
Nuno Chaves authored Sep 26, 2018
1 parent 696ff86 commit 77565f1
Showing 1 changed file with 39 additions and 10 deletions.
49 changes: 39 additions & 10 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,43 @@ public function find()
return $this;
}

/* insert / update */

public function setDocument($document)
{
if (is_array($document) || is_object($document)) {
$this->document = json_encode($document);
}

return $this;
}


public function save($document)
{
$rid = null;

if (is_array($document) || is_object($document)) {
if (is_object($document) && isset($document->_rid)) $rid = $document->_rid;
elseif (is_array($document) && array_key_exists('_rid', $document)) $rid = $document['_rid'];

$document = json_encode($document);
}

$col = $this->connection->selectCollection($this->collection);
$result = $rid ?
$col->replaceDocument($rid, $document) :
$col->createDocument($document);
$resultObj = json_decode($result);

if (isset($resultObj->code) && isset($resultObj->message)) {
throw new \Exception("$resultObj->code : $resultObj->message");
}

return $resultObj->_rid ?? null;
}

/* DELETE */

/**
* @return $this
Expand Down Expand Up @@ -181,41 +218,34 @@ public function deleteAll()
}


/* helpers */

/**
* @return string
*/
public function toJson()
{
return $this->response;
}


/**
* @return mixed
*/
public function toObject()
{
$res = json_decode($this->response);
$docs = $res->Documents ?? [];

if (!is_array($docs) || empty($docs)) return [];

return count($docs) > 1 ? $docs : $docs[0];
}


/**
* @return array|mixed
*/
public function toArray()
{
$res = json_decode($this->response);
$docs = $res->Documents ?? [];

return $this->multipleResults == true && count($docs) > 0 ? $docs : $docs[0];
}


/**
* @param $fieldName
* @param null $default
Expand All @@ -224,7 +254,6 @@ public function toArray()
public function getValue($fieldName, $default = null)
{
$obj = $this->toObject();

return isset($obj->{$fieldName}) ? $obj->{$fieldName} : $default;
}

Expand Down

0 comments on commit 77565f1

Please sign in to comment.