FindFreeName::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace kalanis\kw_files\Extended;
4
5
6
use kalanis\kw_files\FilesException;
7
use kalanis\kw_files\Interfaces;
8
use kalanis\kw_paths\PathsException;
9
10
11
/**
12
 * Class FindFreeName
13
 * @package kalanis\kw_files\Extended
14
 * Work with files - find which name is free for use (either for dir and file)
15
 */
16
class FindFreeName
17
{
18
    protected const FREE_NAME_SEPARATOR = '_';
19
20
    protected Interfaces\IProcessNodes $nodes;
21
22 10
    public function __construct(Interfaces\IProcessNodes $nodes)
23
    {
24 10
        $this->nodes = $nodes;
25
    }
26
27
    /**
28
     * @param string[] $path
29
     * @param string $name
30
     * @param string $suffix
31
     * @throws FilesException
32
     * @throws PathsException
33
     * @return string
34
     */
35 10
    public function findFreeName(array $path, string $name, string $suffix): string
36
    {
37 10
        if (!$this->targetExists($path, $name . $suffix)) {
38 4
            return $name . $suffix;
39
        }
40 6
        $i = 0;
41 6
        while ($this->targetExists($path, $name . $this->getNameSeparator() . strval($i) . $suffix)) {
42 2
            $i++;
43
        }
44 6
        return $name . $this->getNameSeparator() . strval($i) . $suffix;
45
    }
46
47
    /**
48
     * @param array<string> $path
49
     * @param string $name
50
     * @throws FilesException
51
     * @throws PathsException
52
     * @return bool
53
     */
54 10
    protected function targetExists(array $path, string $name): bool
55
    {
56 10
        return $this->nodes->exists(array_merge($path, [$name]));
57
    }
58
59 3
    protected function getNameSeparator(): string
60
    {
61 3
        return static::FREE_NAME_SEPARATOR;
62
    }
63
}
64