Passed
Push — master ( 2bdc71...4b0b05 )
by Csaba
05:10 queued 02:13
created

RestObject::isModification()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 3
eloc 4
nc 2
nop 0
crap 3
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 5
    public function validateUniqueFields()
23
    {
24 5
        $query = $this->getUniqueFieldQuery();
25 5
        $res = $query->get();
26 5
        if ((int)$res->hits() > 0) {
27 2
            $results = json_decode($res->rawResponse())->results;
28 2
            $message = $results[0]->{$this->primaryKey} === $this->getPrimaryKeyValue() ?
29 2
                'Primary key collision' : 'Unique constraint violation';
30 2
            throw new RestException(
31 2
                $message,
32 2
                ['resourceName' => $this->resourceName, 'confilct' => $results[0]]
33
            );
34
        }
35 3
    }
36
37
38 5
    private function getUniqueFieldQuery()
39
    {
40 5
        $uniqueFields = $this->getUniqueFields();
41 5
        $query = $this->getClient()->database($this->getDatabaseName() . '.' . $this->resourceName);
42 5
        if ($this->isModification()) {
43 2
            $uniqueFields = array_diff($uniqueFields, [$this->primaryKey]);
44 2
            $query->where($this->primaryKey, '!=', $this->getPrimaryKeyValue());
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 5
        return $query->limit(1);
56
    }
57
58 5
    private function isModification()
59
    {
60 5
        if ($this->updateMode() || $this->replaceMode()) {
61 2
            return true;
62
        }
63 3
        return false;
64
    }
65
66 1
    public function query()
67
    {
68 1
        $query = $this->getClient()->database($this->getDatabaseName() . '.' . $this->resourceName);
69 1
        return $query;
70
    }
71
}
72