Completed
Branch feature/pre-split (bbd802)
by Anton
02:54
created

FileTrait::filename()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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