Passed
Branch feature/upgrade-code-quality (2a4d43)
by Csaba
01:57
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->limit(1)->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 5
    private function isModification()
39
    {
40 5
        if ($this->updateMode() || $this->replaceMode()) {
41 2
            return true;
42
        }
43 3
        return false;
44
    }
45
46 5
    private function getUniqueFieldQuery()
47
    {
48 5
        $uniqueFields = $this->getUniqueFields();
49 5
        $query = $this->getClient()->database($this->getDatabaseName() . '.' . $this->resourceName);
50 5
        if ($this->isModification()) {
51 2
            $uniqueFields = array_diff($uniqueFields, [$this->primaryKey]);
52 2
            $query->where($this->primaryKey, '!=', $this->getPrimaryKeyValue());
53
        }
54
        // @codeCoverageIgnoreStart
55
        $query->where(function ($query) use ($uniqueFields) {
56
            foreach ($uniqueFields as $fieldName) {
57
                if (property_exists($this->resource, $fieldName)) {
58
                    $query->orWhere($fieldName, '==', $this->resource->{$fieldName});
59
                }
60
            }
61
        });
62
        // @codeCoverageIgnoreEnd
63 5
        return $query;
64
    }
65
66 1
    public function query()
67
    {
68 1
        $query = $this->database->getClient()->database($this->database->getDatabaseName().'.'.$this->resourceName);
69 1
        return $query;
70
    }
71
}
72