Passed
Pull Request — 3.x (#31)
by
unknown
18:33 queued 03:34
created

TypeBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 5
eloc 25
c 3
b 0
f 0
dl 0
loc 52
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A addValues() 0 5 1
A drop() 0 5 1
A create() 0 17 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Migrations\V2;
6
7
use Cycle\Database\DatabaseInterface;
8
use Cycle\Migrations\Exception\OperationException;
9
10
class TypeBuilder
11
{
12
    public const ENUM = 'ENUM';
13
    public const RANGE = 'RANGE';
14
15
    private DatabaseInterface $db;
16
    private string $name;
17
    private array $values;
18
    private string $type;
19
20
    public function __construct(
21
        string $name,
22
        string $type,
23
        DatabaseInterface $db
24
    ) {
25
        $this->db = $db;
26
        $this->name = $name;
27
        $this->type = $type;
28
    }
29
30
    public function create(): void
31
    {
32
        if (empty($this->values)) {
33
            throw new OperationException('Values can\'t be empty');
34
        }
35
36
        $values = implode(',', array_map(static fn($v) => "'{$v}'", $this->values));
37
38
        $query = sprintf(
39
            'CREATE TYPE %s AS %s (%s);',
40
            $this->name,
41
            $this->type,
42
            $values
43
        );
44
45
        $this->db->execute($query);
46
        $this->db->commit();
47
    }
48
49
    public function drop(): void
50
    {
51
        $query = sprintf('DROP TYPE %s;', $this->name);
52
        $this->db->execute($query);
53
        $this->db->commit();
54
55
    }
56
57
    public function addValues(array $values): self
58
    {
59
        $this->values = $values;
60
61
        return $this;
62
    }
63
}
64