FindFreeName   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 46
ccs 13
cts 13
cp 1
rs 10
c 1
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A targetExists() 0 3 1
A getNameSeparator() 0 3 1
A findFreeName() 0 10 3
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