Passed
Push — master ( 1f8075...93e91b )
by Fabien
02:17
created

FileHelper::ensureFileIsWritable()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 18
rs 9.6111
cc 5
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Churn\File;
6
7
use InvalidArgumentException;
8
use Symfony\Component\Filesystem\Filesystem;
9
10
class FileHelper
11
{
12
13
    /**
14
     * @param string $path The path of an item.
15
     * @param string $basePath The absolute base path.
16
     * @return string The absolute path of the given item.
17
     */
18
    public static function toAbsolutePath(string $path, string $basePath): string
19
    {
20
        return (new Filesystem())->isAbsolutePath($path)
21
            ? $path
22
            : $basePath . '/' . $path;
23
    }
24
25
    /**
26
     * Check whether the path is writable and create the missing folders if needed.
27
     *
28
     * @param string $filePath The file path to check.
29
     * @throws InvalidArgumentException If the path is invalid.
30
     */
31
    public static function ensureFileIsWritable(string $filePath): void
32
    {
33
        if ('' === $filePath) {
34
            throw new InvalidArgumentException('Path cannot be empty');
35
        }
36
37
        if (\is_dir($filePath)) {
38
            throw new InvalidArgumentException('Path cannot be a folder');
39
        }
40
41
        if (!\is_file($filePath)) {
42
            (new Filesystem())->mkdir(\dirname($filePath));
43
44
            return;
45
        }
46
47
        if (!\is_writable($filePath)) {
48
            throw new InvalidArgumentException('File is not writable');
49
        }
50
    }
51
}
52