Completed
Push — master ( 74d877...da503e )
by Oscar
02:36
created

File::getDirectory()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace SimpleCrud\Fields;
4
5
use Psr\Http\Message\UploadedFileInterface;
6
use SimpleCrud\SimpleCrud;
7
use SimpleCrud\SimpleCrudException;
8
9
/**
10
 * To save files.
11
 */
12
class File extends Field
13
{
14
    protected $directory;
15
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function dataToDatabase($data)
20
    {
21
        if ($data instanceof UploadedFileInterface) {
22
            return $this->upload($data);
23
        }
24
25
        return $data;
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function dataFromDatabase($data)
32
    {
33
        if (!empty($data)) {
34
            return $this->getDirectory().$data;
35
        }
36
37
        return $data;
38
    }
39
40
    /**
41
     * Upload the file and return the value.
42
     * 
43
     * @param UploadedFileInterface $file
44
     * 
45
     * @return string
46
     */
47
    private function upload(UploadedFileInterface $file)
48
    {
49
        $root = $this->table->getDatabase()->getAttribute(SimpleCrud::ATTR_UPLOADS);
50
51
        if (empty($root)) {
52
            throw new SimpleCrudException('No ATTR_UPLOADS attribute found to upload files');
53
        }
54
55
        $filename = $this->getFilename($file);
56
        $targetPath = $root.$this->getDirectory();
57
58
        if (!is_dir($targetPath)) {
59
            mkdir($targetPath, 0777, true);
60
        }
61
62
        $file->moveTo($targetPath.$filename);
63
64
        return $filename;
65
    }
66
67
    /**
68
     * Get the name used to save the file in lowercase and without spaces.
69
     * 
70
     * @param UploadedFilenameInterface $file
71
     * 
72
     * @return string
73
     */
74
    protected function getFilename(UploadedFileInterface $file)
75
    {
76
        $name = $file->getClientFilename();
77
78
        if ($name === '') {
79
            return uniqid();
80
        }
81
82
        return preg_replace(['/[^\w\.]/', '/[\-]{2,}/'], '-', strtolower($name));
83
    }
84
85
    /**
86
     * Get the relative directory where the file will be saved.
87
     * 
88
     * @return string
89
     */
90
    protected function getDirectory()
91
    {
92
        if ($this->directory === null) {
93
            return $this->directory = "/{$this->table->name}/{$this->name}/";
94
        }
95
96
        return $this->directory;
97
    }
98
}
99