Passed
Push — main ( a3d595...383cbf )
by Dylan
02:02
created

Model::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Lifeboat\Models;
4
5
use Lifeboat\Exceptions\ApiException;
6
use Lifeboat\Exceptions\OAuthException;
7
use Lifeboat\Resource\ObjectResource;
8
use Lifeboat\Services\ObjectFactory;
9
10
/**
11
 * Class Model
12
 * @package Lifeboat\Models
13
 *
14
 * @property int $ID
15
 */
16
abstract class Model extends ObjectResource {
17
18
    abstract public function retrieve(int $id = -1): ?Model;
19
    abstract protected function getSaveURL(): string;
20
21
    /**
22
     * @return array
23
     */
24
    public function toArray(): array
25
    {
26
        return iterator_to_array($this->getIterator());
27
    }
28
29
    /**
30
     * @return bool
31
     */
32
    public function exists(): bool
33
    {
34
        return $this->ID > 0;
35
    }
36
37
    /**
38
     * @see Model::curl_for_model()
39
     *
40
     * @return Model|null
41
     * @throws ApiException
42
     * @throws OAuthException
43
     */
44
    public function save(): ?Model
45
    {
46
        return $this->curl_for_model($this->getSaveURL(),'POST', $this->toArray());
47
    }
48
49
    /**
50
     * @param string $url
51
     * @param string $method
52
     * @param array $data
53
     * @param array $headers
54
     * @return Model|null
55
     * @throws ApiException If the API threw an error
56
     * @throws OAuthException If the client could not connect
57
     */
58
    protected function curl_for_model(string $url, string $method = 'GET', array $data = [], array $headers = []): ?Model
59
    {
60
        $curl = $this->getClient()->curl_api($url, $method, $data, $headers);
61
62
        if ($curl->isValid() && $curl->isJSON()) {
63
            $data   = $curl->getJSON();
64
            $model  = $data['model'];
65
            unset($data['model']);
66
67
            return ObjectFactory::create($this->getClient(), $model, $data);
0 ignored issues
show
Bug introduced by
It seems like $this->getClient() can also be of type null; however, parameter $connector of Lifeboat\Services\ObjectFactory::create() does only seem to accept Lifeboat\Connector, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

67
            return ObjectFactory::create(/** @scrutinizer ignore-type */ $this->getClient(), $model, $data);
Loading history...
68
        }
69
70
        throw new ApiException($curl->getError());
71
    }
72
}
73