|
1
|
|
|
<?php |
|
2
|
|
|
namespace Fathomminds\Rest\Database\Clusterpoint; |
|
3
|
|
|
|
|
4
|
|
|
use Fathomminds\Rest\Exceptions\RestException; |
|
5
|
|
|
use Fathomminds\Rest\Objects\RestObject as CoreRestObject; |
|
6
|
|
|
|
|
7
|
|
|
class RestObject extends CoreRestObject |
|
8
|
|
|
{ |
|
9
|
|
|
protected $primaryKey = '_id'; |
|
10
|
|
|
protected $databaseClass = Database::class; |
|
11
|
|
|
|
|
12
|
3 |
|
public function find($client = null) |
|
13
|
|
|
{ |
|
14
|
3 |
|
if ($client === null) { |
|
15
|
1 |
|
$client = $this->getClient(); |
|
16
|
|
|
} |
|
17
|
3 |
|
return (new Finder($client)) |
|
18
|
3 |
|
->database($this->getDatabaseName()) |
|
19
|
3 |
|
->from($this->getResourceName()); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
4 |
|
public function validateUniqueFields() |
|
23
|
|
|
{ |
|
24
|
4 |
|
$uniqueFields = $this->getUniqueFields(); |
|
25
|
4 |
|
$query = $this->getClient()->database($this->getDatabaseName() . '.' . $this->resourceName); |
|
26
|
4 |
|
if ($this->updateMode) { |
|
27
|
1 |
|
$uniqueFields = array_diff($uniqueFields, [$this->primaryKey]); |
|
28
|
1 |
|
$query->where($this->primaryKey, '!=', $this->getPrimaryKeyValue()); |
|
29
|
|
|
} |
|
30
|
4 |
|
$query = $this->getUniqueFieldQuery($query, $uniqueFields); |
|
31
|
4 |
|
$res = $query->limit(1)->get(); |
|
32
|
4 |
|
if ((int)$res->hits() > 0) { |
|
33
|
2 |
|
$results = json_decode($res->rawResponse())->results; |
|
34
|
2 |
|
$message = $results[0]->{$this->primaryKey} === $this->getPrimaryKeyValue() ? |
|
35
|
1 |
|
'Primary key collision' : |
|
36
|
2 |
|
'Unique constraint violation'; |
|
37
|
2 |
|
throw new RestException( |
|
38
|
|
|
$message, |
|
39
|
2 |
|
['resourceName' => $this->resourceName, 'confilct' => $results[0]] |
|
40
|
|
|
); |
|
41
|
|
|
} |
|
42
|
2 |
|
} |
|
43
|
|
|
|
|
44
|
|
|
private function getUniqueFieldQuery($query, $uniqueFields) |
|
45
|
|
|
{ |
|
46
|
|
|
// @codeCoverageIgnoreStart |
|
47
|
|
|
$query->where(function ($query) use ($uniqueFields) { |
|
48
|
|
|
foreach ($uniqueFields as $fieldName) { |
|
49
|
|
|
if (property_exists($this->resource, $fieldName)) { |
|
50
|
|
|
$query->orWhere($fieldName, '==', $this->resource->{$fieldName}); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
}); |
|
54
|
|
|
// @codeCoverageIgnoreEnd |
|
55
|
4 |
|
return $query; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
1 |
|
public function query() |
|
59
|
|
|
{ |
|
60
|
1 |
|
$query = $this->database->getClient()->database($this->database->getDatabaseName().'.'.$this->resourceName); |
|
61
|
1 |
|
return $query; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|