IndexDefinition::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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