Passed
Push — master ( 983377...eb5b2a )
by Petr
08:18
created

FindFreeName::__construct()   A

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
9
10
/**
11
 * Class FindFreeName
12
 * @package kalanis\kw_files\Extended
13
 * Work with files - find which name is free for use (either for dir and file)
14
 */
15
class FindFreeName
16
{
17
    const FREE_NAME_SEPARATOR = '_';
18
19
    /** @var Interfaces\IProcessNodes */
20
    protected $nodes = null;
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
     * @return string
33
     */
34 10
    public function findFreeName(array $path, string $name, string $suffix): string
35
    {
36 10
        if (!$this->targetExists($path, $name . $suffix)) {
37 4
            return $name . $suffix;
38
        }
39 6
        $i = 0;
40 6
        while ($this->targetExists($path, $name . $this->getNameSeparator() . strval($i) . $suffix)) {
41 2
            $i++;
42
        }
43 6
        return $name . $this->getNameSeparator() . strval($i) . $suffix;
44
    }
45
46
    /**
47
     * @param array<string> $path
48
     * @param string $name
49
     * @throws FilesException
50
     * @return bool
51
     */
52 10
    protected function targetExists(array $path, string $name): bool
53
    {
54 10
        return $this->nodes->exists(array_merge($path, [$name]));
55
    }
56
57 3
    protected function getNameSeparator(): string
58
    {
59 3
        return static::FREE_NAME_SEPARATOR;
60
    }
61
}
62