Passed
Push — master ( f8375c...888862 )
by Anton
01:53
created

Index::getName()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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