Completed
Branch feature/pre-split (f1ffcf)
by Anton
03:59
created

IndexDefinition::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework, Core Components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\ORM\Schemas\Definitions;
8
9
/**
10
 * Index definition options.
11
 */
12
final class IndexDefinition
13
{
14
    /**
15
     * @var array
16
     */
17
    private $index;
18
19
    /**
20
     * @var bool
21
     */
22
    private $unique;
23
24
    /**
25
     * @param array $columns
26
     * @param bool  $unique
27
     */
28
    public function __construct(array $columns, bool $unique = false)
29
    {
30
        $this->index = $columns;
31
        $this->unique = $unique;
32
    }
33
34
    /**
35
     * @return array
36
     */
37
    public function getColumns(): array
38
    {
39
        return $this->index;
40
    }
41
42
    /**
43
     * @return bool
44
     */
45
    public function isUnique(): bool
46
    {
47
        return $this->unique;
48
    }
49
50
    /**
51
     * Generate unique index name.
52
     *
53
     * @return string
54
     */
55
    public function getName(): string
56
    {
57
        $name = ($this->isUnique() ? 'unique_' : 'index_') . join('_', $this->getColumns());
58
59
        return strlen($name) > 64 ? md5($name) : $name;
60
    }
61
62
    /**
63
     * So we can compare indexes.
64
     *
65
     * @return string
66
     */
67
    public function __toString()
68
    {
69
        return json_encode([
70
            $this->index,
71
            $this->unique
72
        ]);
73
    }
74
}