Passed
Push — master ( 037c19...09b2b1 )
by Mr
07:16
created

CouchDbMigration::createDesignDoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 3
dl 0
loc 11
ccs 0
cts 9
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/couchdb-adapter project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\CouchDb\Migration;
10
11
use Daikon\Dbal\Exception\DbalException;
12
use Daikon\Dbal\Migration\Migration;
13
use GuzzleHttp\Exception\RequestException;
14
15
abstract class CouchDbMigration extends Migration
16
{
17
    protected function createDatabase(string $database): void
18
    {
19
        $client = $this->connector->getConnection();
20
21
        try {
22
            $client->put('/'.$database);
23
        } catch (RequestException $error) {
24
            if (!$error->hasResponse() || !$error->getResponse()->getStatusCode() === 409) {
25
                throw new DbalException("Failed to create database '$database'.");
26
            }
27
        }
28
    }
29
30
    protected function deleteDatabase(string $database): void
31
    {
32
        $client = $this->connector->getConnection();
33
34
        try {
35
            $client->delete('/'.$database);
36
        } catch (RequestException $error) {
37
            if (!$error->hasResponse() || !$error->getResponse()->getStatusCode() === 404) {
38
                throw new DbalException("Failed to delete database '$database'.");
39
            }
40
        }
41
    }
42
43
    protected function createDesignDoc(string $database, string $name, array $views): void
44
    {
45
        $client = $this->connector->getConnection();
46
47
        $body = [
48
            'language' => 'javascript',
49
            'views' => $views
50
        ];
51
52
        $requestPath = sprintf('/%s/_design/%s', $database, $name);
53
        $client->put($requestPath, ['body' => json_encode($body)]);
54
    }
55
56
    protected function deleteDesignDoc(string $database, string $name): void
57
    {
58
        $client = $this->connector->getConnection();
59
        $requestPath = sprintf('/%s/_design/%s', $database, $name);
60
        $response = $client->head($requestPath);
61
        $revision = trim(current($response->getHeader('ETag')), '"');
62
        $client->delete(sprintf('%s?rev=%s', $requestPath, $revision));
63
    }
64
65
    protected function getDatabaseName(): string
66
    {
67
        $connectorSettings = $this->connector->getSettings();
68
        return $connectorSettings['database'];
69
    }
70
}
71