Test Failed
Pull Request — master (#38)
by Rafael
04:40
created

Helper::pathToFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 2
rs 10
c 0
b 0
f 0
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
The type Gewaer\Filesystem\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
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