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

attachment::generate_unique_name()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.4098

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 13
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 18
ccs 9
cts 14
cp 0.6429
crap 3.4098
rs 9.8333
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
}