Database::insert()   B
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 0
cp 0
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 16
nc 4
nop 1
crap 12
1
<?php
2
3
namespace CouchDB;
4
5
use CouchDB\Encoder\JSONEncoder;
6
use CouchDB\Exception\Exception;
7
use GuzzleHttp\ClientInterface;
8
9
/**
10
 * @author Markus Bachmann <[email protected]>
11
 */
12
class Database
13
{
14
    /**
15
     * @var Connection
16
     */
17
    private $conn;
18
19
    /**
20
     * @var string
21
     */
22
    private $name;
23
24
    /**
25
     * @var ClientInterface
26
     */
27
    private $client;
28
29
    /**
30
     * @param string          $name   The database name.
31
     * @param Connection      $conn   The current connection.
32
     * @param ClientInterface $client The client
33
     */
34 19
    public function __construct($name, Connection $conn, ClientInterface $client)
35
    {
36 19
        $this->conn = $conn;
37 19
        $this->name = $name;
38 19
        $this->client = $client;
39 19
    }
40
41
    /**
42
     * Gets the current connection.
43
     *
44
     * @return Connection
45
     */
46 1
    public function getConnection()
47
    {
48 1
        return $this->conn;
49
    }
50
51
    /**
52
     * Find a document by a id.
53
     *
54
     * @param string $id
55
     *
56
     * @throws Exception If the document doesn't exists.
57
     *
58
     * @return mixed
59
     */
60 2 View Code Duplication
    public function find($id)
61
    {
62 2
        $response = $this->client->request('GET', sprintf('/%s/%s', $this->name, $id));
63 2
        $json = (string) $response->getBody();
64
65 2
        if (404 === $response->getStatusCode()) {
66 1
            throw new Exception('Document does not exist');
67
        }
68
69 1
        return JSONEncoder::decode($json);
70
    }
71
72
    /**
73
     * Find all documents from the database.
74
     *
75
     * @param int|null    $limit
76
     * @param string|null $startKey
77
     *
78
     * @return mixed
79
     */
80 1
    public function findAll($limit = null, $startKey = null)
81
    {
82 1
        $path = "/{$this->name}/_all_docs?include_docs=true";
83
84 1
        if (null !== $limit) {
85 1
            $path .= '&limit='.(integer) $limit;
86 1
        }
87 1
        if (null !== $startKey) {
88 1
            $path .= '&startkey='.(string) $startKey;
89 1
        }
90
91 1
        $json = (string) $this->client->request('GET', $path)->getBody();
92 1
        $docs = JSONEncoder::decode($json);
93
94 1
        return $docs;
95
    }
96
97
    /**
98
     * Find a documents by a id.
99
     *
100
     * @param array    $ids
101
     * @param null|int $limit
102
     * @param null|int $offset
103
     *
104
     * @return array|null
105
     */
106 1
    public function findDocuments(array $ids, $limit = null, $offset = null)
107
    {
108 1
        $path = "/{$this->name}/_all_docs?include_docs=true";
109
110 1
        if (null !== $limit) {
111 1
            $path .= '&limit='.(integer) $limit;
112 1
        }
113 1
        if (null !== $offset) {
114 1
            $path .= '&skip='.(integer) $offset;
115 1
        }
116
117 1
        $response = $this->client->request('POST', $path, [
118 1
            'body'    => JSONEncoder::encode(['keys' => $ids]),
119 1
            'headers' => ['Content-Type'             => 'application/json'],
120 1
        ]);
121
122 1
        return JSONEncoder::decode((string) $response->getBody());
123
    }
124
125
    /**
126
     * Insert a new document.
127
     *
128
     * @param array $doc
129
     *
130
     * @deprecated To update a document use Database::update, it will be removed in version 2
131
     *
132
     * @throws Exception
133
     */
134
    public function insert(array &$doc)
135
    {
136
        if (isset($doc['_id'])) {
137
            $clone = $doc;
138
            unset($clone['_id']);
139
140
            $response = $this->client->request('PUT', "/{$this->name}/{$doc['_id']}", [
141
                'body'    => JSONEncoder::encode($clone),
142
                'headers' => ['Content-Type' => 'application/json'],
143
            ]);
144
        } else {
145
            $response = $this->client->request('POST', "/{$this->name}/", [
146
                'body'    => JSONEncoder::encode($doc),
147
                'headers' => ['Content-Type' => 'application/json'],
148
            ]);
149
        }
150
151
        if (201 !== $response->getStatusCode()) {
152
            throw new Exception('Unable to save document');
153
        }
154
155
        $value = JSONEncoder::decode((string) $response->getBody());
156
157
        $doc['_id'] = $value['id'];
158
        $doc['_rev'] = $value['rev'];
159
    }
160
161
    /**
162
     * Updates a document.
163
     *
164
     * @param string $id  The id from the document
165
     * @param array  $doc A reference from the document
166
     *
167
     * @throws Exception
168
     */
169 2
    public function update($id, array &$doc)
170
    {
171 2
        $json = JSONEncoder::encode($doc);
172
173 2
        $response = $this->client->request('PUT', "/{$this->name}/{$id}", [
174 2
            'body'    => $json,
175 2
            'headers' => ['Content-Type' => 'application/json'],
176 2
        ]);
177
178 2
        if (201 !== $response->getStatusCode()) {
179 1
            throw new Exception('Unable to save document');
180
        }
181
182 1
        $value = JSONEncoder::decode((string) $response->getBody());
183
184 1
        $doc['_id'] = $value['id'];
185 1
        $doc['_rev'] = $value['rev'];
186 1
    }
187
188
    /**
189
     * Deletes a document.
190
     *
191
     * @param string $id
192
     * @param string $rev
193
     *
194
     * @throws \RuntimeException
195
     *
196
     * @return bool
197
     */
198 2 View Code Duplication
    public function delete($id, $rev)
199
    {
200 2
        $response = $this->client->request('DELETE', "/{$this->name}/{$id}?rev={$rev}");
201
202 2
        if (200 !== $response->getStatusCode()) {
203 1
            throw new Exception(sprintf('Unable to delete %s', $id));
204
        }
205
206 1
        return true;
207
    }
208
209
    /**
210
     * Creates a batch updater.
211
     *
212
     * @return Util\BatchUpdater
213
     */
214 1
    public function createBatchUpdater()
215
    {
216 1
        return new Util\BatchUpdater($this->client, $this);
217
    }
218
219
    /**
220
     * Return the database informations.
221
     *
222
     * @return array
223
     */
224 1
    public function getInfo()
225
    {
226 1
        $json = (string) $this->client->request('GET', "/{$this->name}/")->getBody();
227
228 1
        return JSONEncoder::decode($json);
229
    }
230
231
    /**
232
     * Return informations about the last changes from the database.
233
     *
234
     * @throws \RuntimeException If the request was not successfull
235
     *
236
     * @return array
237
     */
238 2
    public function getChanges()
239
    {
240 2
        $response = $this->client->request('GET', "/{$this->name}/_changes");
241
242 2
        if (200 !== $response->getStatusCode()) {
243 1
            throw new Exception('Request wasn\'t successfull');
244
        }
245
246 1
        return JSONEncoder::decode((string) $response->getBody());
247
    }
248
249
    /**
250
     * Return the database name.
251
     *
252
     * @return string
253
     */
254 2
    public function getName()
255
    {
256 2
        return $this->name;
257
    }
258
}
259