Completed
Push — 1.0 ( 731e1a...f45751 )
by Simonas
9s
created

IndexSuffixFinder::setNextFreeIndex()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
c 0
b 0
f 0
rs 9.2
cc 3
eloc 14
nc 4
nop 2
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Service;
13
14
/**
15
 * Constructs index name with date's suffix.
16
 */
17
class IndexSuffixFinder
18
{
19
    /**
20
     * Constructs index name with date suffix. Sets name in the connection.
21
     *
22
     * E.g. 2022.03.22-5 (if 4 indexes exists already for given date)
23
     *
24
     * @param Manager        $manager Connection to act upon.
25
     * @param null|\DateTime $time    Date for which the suffix will be based on.
26
     *                                Current date if null.
27
     *
28
     * @return string
29
     */
30
    public function setNextFreeIndex(Manager $manager, \DateTime $time = null)
31
    {
32
        if ($time === null) {
33
            $time = new \DateTime();
34
        }
35
36
        $date = $time->format('Y.m.d');
37
        $indexName = $manager->getIndexName();
38
39
        $nameBase = $indexName . '-' . $date;
40
        $name = $nameBase;
41
        $i = 0;
42
        $manager->setIndexName($name);
43
44
        while ($manager->indexExists()) {
45
            $i++;
46
            $name = "{$nameBase}-{$i}";
47
            $manager->setIndexName($name);
48
        }
49
50
        return $name;
51
    }
52
}
53