Completed
Branch 09branch (1e97b6)
by Anton
02:49
created

FileTrait::filename()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 9
nc 6
nop 2
dl 0
loc 18
rs 7.7777
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework, Core Components
4
 *
5
 * @author    Wolfy-J
6
 */
7
8
namespace Spiral\Validation\Checkers\Traits;
9
10
use Psr\Http\Message\UploadedFileInterface;
11
use Spiral\Files\FilesInterface;
12
use Spiral\Files\Streams\StreamableInterface;
13
use Spiral\Files\Streams\StreamWrapper;
14
15
/**
16
 * Provides ability to get filename for uploaded file.
17
 */
18
trait FileTrait
19
{
20
    /**
21
     * @var FilesInterface
22
     */
23
    protected $files;
24
25
    /**
26
     * Internal method to fetch filename using multiple input formats.
27
     *
28
     * @param mixed|UploadedFileInterface|StreamableInterface $file
29
     *
30
     * @return string|null
31
     */
32
    private function resolveFilename($file)
33
    {
34
        if (empty($file)) {
35
            return null;
36
        }
37
38
        if (
39
            ($file instanceof UploadedFileInterface && $file->getError() === 0)
40
            || $file instanceof StreamableInterface
41
        ) {
42
            return StreamWrapper::localFilename($file->getStream());
43
        }
44
45
        if (is_array($file)) {
46
            //Temp filename.
47
            $file = $file['tmp_name'];
48
        }
49
50
        if (!is_string($file) || !$this->files->exists($file)) {
51
            return null;
52
        }
53
54
        return $file;
55
    }
56
57
    /**
58
     * Check if file being uploaded.
59
     *
60
     * @param mixed|UploadedFileInterface $file Filename or file array.
61
     *
62
     * @return bool
63
     */
64
    private function isUploaded($file): bool
65
    {
66
        if (is_string($file)) {
67
            //We can use native method
68
            return is_uploaded_file($file);
69
        }
70
71
        if (is_array($file)) {
72
            return isset($file['tmp_name']) && is_uploaded_file($file['tmp_name']);
73
        }
74
75
        if ($file instanceof UploadedFileInterface) {
76
            return empty($file->getError());
77
        }
78
79
        //Not uploaded
80
        return false;
81
    }
82
}