Test Failed
Pull Request — master (#38)
by Maximo
04:24
created

Helper::generateUniqueName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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