Passed
Push — master ( d76e03...3657f2 )
by Andreas
19:39
created

attachment   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 70%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 33
ccs 14
cts 20
cp 0.7
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generate_unique_name() 0 18 3
A create_attachment() 0 8 2
1
<?php
2
/**
3
 * @copyright CONTENT CONTROL GmbH, http://www.contentcontrol-berlin.de
4
 */
5
6
namespace midcom\datamanager\helper;
7
8
use midcom_db_attachment;
9
use midcom_error;
10
use midcom_helper_reflector_nameresolver;
11
12
/**
13
 * Attachment helper
14
 */
15
trait attachment
16
{
17
    /**
18
     * Make sure we have unique filename
19
     */
20 2
    private function generate_unique_name(string $filename, string $parentguid) : string
21
    {
22 2
        $filename = midcom_db_attachment::safe_filename($filename, true);
23 2
        $attachment = new midcom_db_attachment;
24 2
        $attachment->title = $filename;
25 2
        $attachment->name = $filename;
26 2
        $attachment->parentguid = $parentguid;
27
28 2
        $resolver = new midcom_helper_reflector_nameresolver($attachment);
29 2
        if (!$resolver->name_is_unique()) {
30
            debug_add("Name '{$attachment->name}' is not unique, trying to generate", MIDCOM_LOG_INFO);
31
            $ext = '';
32
            if (preg_match('/^(.*)(\..*?)$/', $filename, $ext_matches)) {
33
                $ext = $ext_matches[2];
34
            }
35
            $filename = $resolver->generate_unique_name($ext);
36
        }
37 2
        return $filename;
38
    }
39
40 2
    protected function create_attachment(midcom_db_attachment $attachment, string $filename, string $title, string $mimetype)
41
    {
42 2
        $attachment->name = $this->generate_unique_name($filename, $attachment->parentguid);
43 2
        $attachment->title = $title;
44 2
        $attachment->mimetype = $mimetype;
45
46 2
        if (!$attachment->create()) {
47
            throw new midcom_error('Failed to create attachment: ' . \midcom_connection::get_error_string());
48
        }
49
    }
50
}