Passed
Pull Request — develop (#43)
by
unknown
04:42
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 1
                'Primary key collision' :
30 2
                'Unique constraint violation';
31 2
            throw new RestException(
32 2
                $message,
33 2
                ['resourceName' => $this->resourceName, 'confilct' => $results[0]]
34
            );
35
        }
36 3
    }
37
38
39 5
    private function getUniqueFieldQuery()
40
    {
41 5
        $uniqueFields = $this->getUniqueFields();
42 5
        $query = $this->getClient()->database($this->getDatabaseName().'.'.$this->resourceName);
43 5
        if ($this->isModification()) {
44 2
            $uniqueFields = array_diff($uniqueFields, [$this->primaryKey]);
45 2
            $query->where($this->primaryKey, '!=', $this->getPrimaryKeyValue());
46
        }
47
        // @codeCoverageIgnoreStart
48
        $query->where(function ($query) use ($uniqueFields) {
49
            foreach ($uniqueFields as $fieldName) {
50
                if (property_exists($this->resource, $fieldName)) {
51
                    $query->orWhere($fieldName, '==', $this->resource->{$fieldName});
52
                }
53
            }
54
        });
55
        // @codeCoverageIgnoreEnd
56 5
        return $query->limit(1);
57
    }
58
59 5
    private function isModification()
60
    {
61 5
        if ($this->updateMode() || $this->replaceMode()) {
62 2
            return true;
63
        }
64 3
        return false;
65
    }
66
67 1
    public function query()
68
    {
69 1
        $query = $this->getClient()->database($this->getDatabaseName().'.'.$this->resourceName);
70 1
        return $query;
71
    }
72
}
73