1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Gewaer\Filesystem; |
||
6 | |||
7 | use Phalcon\Http\Request\File; |
||
8 | |||
9 | class Helper |
||
10 | { |
||
11 | /** |
||
12 | * Generate a unique name in a specific dir |
||
13 | * |
||
14 | * @param string $dir the especific dir where the file will be saved |
||
15 | * @param bool $withPath |
||
16 | * |
||
17 | * @return string |
||
18 | */ |
||
19 | public static function generateUniqueName(File $file, string $dir, $withPath = false) : string |
||
20 | { |
||
21 | // the provided path has to be a dir |
||
22 | if (!is_dir($dir)) { |
||
23 | throw new Exception("The dir provided: '{$dir}' isn't a valid one."); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
24 | } |
||
25 | |||
26 | $path = tempnam($dir . '/', ''); |
||
27 | |||
28 | //this function creates a file (like touch) so, we have to delete it. |
||
29 | unlink($path); |
||
30 | $uniqueName = $path; |
||
31 | if (!$withPath) { |
||
32 | $uniqueName = str_replace($dir, '', $path); |
||
33 | } |
||
34 | |||
35 | return $uniqueName . '.' . strtolower($file->getExtension()); |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * Create a File instance from a given path |
||
40 | * |
||
41 | * @param string $path Path of the file to be used |
||
42 | * |
||
43 | * @return File |
||
44 | */ |
||
45 | public static function pathToFile(string $path) : File |
||
46 | { |
||
47 | //Simulate the body of a Phalcon\Request\File class |
||
48 | return new File([ |
||
49 | 'name' => basename($path), |
||
50 | 'type' => mime_content_type($path), |
||
51 | 'tmp_name' => $path, |
||
52 | 'error' => 0, |
||
53 | 'size' => filesize($path), |
||
54 | ]); |
||
55 | } |
||
56 | } |
||
57 |