Passed
Push — master ( 893d1e...31005e )
by Kirill
03:35
created

FileTrait::resolveFilename()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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