AbstractStorage::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by jensk on 17-3-2017.
4
 */
5
6
namespace CloudControl\Cms\storage\storage;
7
8
9
use CloudControl\Cms\util\StringUtil;
10
use CloudControl\Cms\storage\Repository;
11
12
abstract class AbstractStorage
13
{
14
    /**
15
     * @var Repository
16
     */
17
    protected $repository;
18
19
    public function __construct(Repository $repository)
20
    {
21
        $this->repository = $repository;
22
    }
23
24
    /**
25
     * Converts filename to lowercase, remove non-ascii chars
26
     * And adds "-copy" if the file already exists
27
     *
28
     * @param $filename
29
     * @param $path
30
     *
31
     * @return string
32
     */
33
    protected function validateFilename($filename, $path)
34
    {
35
        $fileParts = explode('.', $filename);
36
        if (count($fileParts) > 1) {
37
            $extension = end($fileParts);
38
            array_pop($fileParts);
39
            $fileNameWithoutExtension = implode('-', $fileParts);
40
            $fileNameWithoutExtension = StringUtil::slugify($fileNameWithoutExtension);
41
            $filename = $fileNameWithoutExtension . '.' . $extension;
42
        } else {
43
            $filename = StringUtil::slugify($filename);
44
        }
45
46
        if (file_exists($path . '/' . $filename)) {
47
            $fileParts = explode('.', $filename);
48
            if (count($fileParts) > 1) {
49
                $extension = end($fileParts);
50
                array_pop($fileParts);
51
                $fileNameWithoutExtension = implode('-', $fileParts);
52
                $fileNameWithoutExtension .= '-copy';
53
                $filename = $fileNameWithoutExtension . '.' . $extension;
54
            } else {
55
                $filename .= '-copy';
56
            }
57
58
            return $this->validateFilename($filename, $path);
59
        }
60
61
        return $filename;
62
    }
63
64
    /**
65
     * Save changes made to the repository
66
     *
67
     * @throws \Exception
68
     */
69
    protected function save()
70
    {
71
        $this->repository->save();
72
    }
73
}