Passed
Push — master ( d69110...dabd68 )
by Andreas
25:25
created

write_the_file()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.1406

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 10
ccs 6
cts 8
cp 0.75
crap 3.1406
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author lukasz chalat
4
 * @package midcom.helper.imagepopup
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\File\UploadedFile;
11
12
/**
13
 * This handler get uploaded file and save it in database and write to file.
14
 *
15
 * @package midcom.helper.imagepopup
16
 */
17
class midcom_helper_imagepopup_handler_upload extends midcom_baseclasses_components_handler
18
{
19 2
    public function _handler_upload(Request $request, string $guid = null)
20
    {
21
        // Get the file
22 2
        $temp = $request->files->get('file');
23
24
        // Verify file extension
25 2
        if (   !$temp instanceof UploadedFile
26 2
            || !in_array(strtolower($temp->getClientOriginalExtension()), ["gif", "jpg", "png"])) {
27
                throw new midcom_error('Invalid extension.');
28
        }
29
30
        // Get the data
31 2
        $parentguid = $guid ?: $this->_topic->guid;
32
33
        // Set modified filename
34 2
        $filename = $this->get_modify_filename($temp->getClientOriginalName());
35
36
        // Insert the image into database
37 2
        $attachment = $this->insert_database($filename, $temp->getClientMimeType(), $parentguid);
38
39
        // Get target to write the file
40 2
        $target = $this->get_data_from_database($filename, $parentguid);
41
42
        // Write the file
43 2
        $this->write_the_file($temp->getRealPath(), $target);
44
45
        // Make a response for editor.uploadImages() function
46 2
        $location = midcom_db_attachment::get_url($attachment);
47
48
        // Return image location as JSON
49 2
        return new midcom_response_json(['location' => $location]);
50
    }
51
52 2
    private function get_modify_filename(string $filename) : string
53
    {
54 2
        $filename = midcom_db_attachment::safe_filename($filename);
55 2
        $pieces = explode('.', $filename);
56 2
        $core = array_shift($pieces);
57 2
        $split = preg_split("/-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})/", $core);
58 2
        $core = array_shift($split);
59 2
        $extension = array_pop($pieces);
60 2
        return $core . "-" . date('Y-m-d-H-i-s', time()) . "." . $extension;
61
    }
62
63 2
    private function get_data_from_database(string $filename, string $parentguid) : midcom_db_attachment
64
    {
65 2
        $query = midcom_db_attachment::new_query_builder();
66 2
        $query->add_constraint('name', '=', $filename);
67 2
        $query->add_constraint('parentguid', '=', $parentguid);
68 2
        $entry = $query->execute();
69
70 2
        if (empty($entry)) {
71
            throw new midcom_error_notfound("There is no match in database " . midcom_connection::get_error_string());
72
        }
73 2
        if (count($entry) == 1) {
74 2
            return $entry[0];
75
        }
76
        throw new midcom_error('There is more than just one object' . midcom_connection::get_error_string());
77
    }
78
79
    /**
80
     * @param string $tmp The temporary location of file
81
     * @param midcom_db_attachment $target The final destination for file
82
     */
83 2
    private function write_the_file(string $tmp, midcom_db_attachment $target)
84
    {
85 2
        $source = fopen($tmp, 'r');
86 2
        if (!$source) {
0 ignored issues
show
introduced by
$source is of type resource, thus it always evaluated to false.
Loading history...
87
            throw new midcom_error("Could not open file " . $tmp . " for reading.");
88
        }
89 2
        $stat = $target->copy_from_handle($source);
90 2
        fclose($source);
91 2
        if (!$stat) {
92
            throw new midcom_error('Failed to copy from handle: ' . midcom_connection::get_error_string());
93
        }
94 2
    }
95
96 2
    private function insert_database(string $filename, string $mimetype, string $parentguid) : midcom_db_attachment
97
    {
98 2
        $attachment = new midcom_db_attachment();
99 2
        $attachment->name = $filename;
100 2
        $attachment->title = $filename;
101 2
        $attachment->mimetype = $mimetype;
102 2
        $attachment->parentguid = $parentguid;
103 2
        if (!$attachment->create()) {
104
            throw new midcom_error('Failed to create derived image: ' . midcom_connection::get_error_string());
105
        }
106
107 2
        return $attachment;
108
    }
109
}
110