BatchUpdater::update()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace CouchDB\Util;
4
5
use CouchDB\Database;
6
use CouchDB\Encoder\JSONEncoder;
7
use GuzzleHttp\ClientInterface;
8
9
/**
10
 * @author Markus Bachmann <[email protected]>
11
 */
12
class BatchUpdater
13
{
14
    /**
15
     * @var ClientInterface
16
     */
17
    private $client;
18
19
    /**
20
     * @var Database
21
     */
22
    private $database;
23
24
    /**
25
     * @var array
26
     */
27
    private $data;
28
29
    /**
30
     * Constructor.
31
     *
32
     * @param ClientInterface $client
33
     * @param Database        $db
34
     */
35 3
    public function __construct(ClientInterface $client, Database $db)
36
    {
37 3
        $this->client = $client;
38 3
        $this->database = $db;
39
40 3
        $this->data = ['docs' => []];
41 3
    }
42
43
    /**
44
     * Enqueue the document for a update.
45
     *
46
     * @param array $doc
47
     *
48
     * @return BatchUpdater
49
     */
50 1
    public function update(array $doc)
51
    {
52 1
        $this->data['docs'][] = $doc;
53
54 1
        return $this;
55
    }
56
57
    /**
58
     * Enqueue a document for deletion.
59
     *
60
     * @param string $id
61
     * @param string $rev
62
     *
63
     * @return BatchUpdater
64
     */
65 1
    public function delete($id, $rev)
66
    {
67 1
        $this->data['docs'][] = ['_id' => $id, '_rev' => $rev, '_deleted' => true];
68
69 1
        return $this;
70
    }
71
72
    /**
73
     * Execute the queue.
74
     *
75
     * @return array
76
     */
77 2
    public function execute()
78
    {
79 2
        $response = $this->client->request('POST', "/{$this->database->getName()}/_bulk_docs", [
80 2
            'body'    => JSONEncoder::encode($this->data),
81 2
            'headers' => ['Content-Type' => 'application/json'],
82 2
        ]);
83
84 2
        return JSONEncoder::decode((string) $response->getBody());
85
    }
86
}
87