1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Churn\File; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Symfony\Component\Filesystem\Exception\InvalidArgumentException as FilesystemException; |
9
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @internal |
13
|
|
|
*/ |
14
|
|
|
class FileHelper |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param string $path The path of an item. |
19
|
|
|
* @param string $basePath The absolute base path. |
20
|
|
|
* @return string The absolute path of the given item. |
21
|
|
|
*/ |
22
|
|
|
public static function toAbsolutePath(string $path, string $basePath): string |
23
|
|
|
{ |
24
|
|
|
return (new Filesystem())->isAbsolutePath($path) |
25
|
|
|
? $path |
26
|
|
|
: $basePath . '/' . $path; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $path The absolute path of an item. |
31
|
|
|
* @param string $basePath The absolute base path. |
32
|
|
|
* @return string The relative path of the given item. |
33
|
|
|
*/ |
34
|
|
|
public static function toRelativePath(string $path, string $basePath): string |
35
|
|
|
{ |
36
|
|
|
try { |
37
|
|
|
$relativePath = (new Filesystem())->makePathRelative($path, $basePath); |
38
|
|
|
|
39
|
|
|
return \rtrim($relativePath, '/\\'); |
40
|
|
|
} catch (FilesystemException $e) { |
41
|
|
|
return $path; |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Check whether the path is writable and create the missing folders if needed. |
47
|
|
|
* |
48
|
|
|
* @param string $filePath The file path to check. |
49
|
|
|
* @throws InvalidArgumentException If the path is invalid. |
50
|
|
|
*/ |
51
|
|
|
public static function ensureFileIsWritable(string $filePath): void |
52
|
|
|
{ |
53
|
|
|
if ('' === $filePath) { |
54
|
|
|
throw new InvalidArgumentException('Path cannot be empty'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
if (\is_dir($filePath)) { |
58
|
|
|
throw new InvalidArgumentException('Path cannot be a folder'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if (!\is_file($filePath)) { |
62
|
|
|
(new Filesystem())->mkdir(\dirname($filePath)); |
63
|
|
|
|
64
|
|
|
return; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (!\is_writable($filePath)) { |
68
|
|
|
throw new InvalidArgumentException('File is not writable'); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|