Completed
Pull Request — master (#10)
by dan
09:38
created

FilenameTransliterator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 61
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B transliterate() 0 26 2
A isUniqueFilename() 0 6 2
1
<?php
2
/**
3
 * This file is part of the IrishDan\ResponsiveImageBundle package.
4
 *
5
 * (c) Daniel Byrne <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source
8
 * code.
9
 */
10
11
namespace IrishDan\ResponsiveImageBundle\File;
12
13
14
/**
15
 * Class FilenameTransliterator
16
 *
17
 * @package IrishDan\ResponsiveImageBundle\File
18
 */
19
class FilenameTransliterator implements FilenameTransliteratorInterface
20
{
21
    /**
22
     * @var FileToObject
23
     */
24
    protected $fileToObject;
25
26
    /**
27
     * FilenameTransliterator constructor.
28
     *
29
     * @param \IrishDan\ResponsiveImageBundle\File\FileToObject $fileToObject
30
     */
31
    public function __construct(FileToObject $fileToObject)
32
    {
33
        $this->fileToObject = $fileToObject;
34
    }
35
36
    /**
37
     * @param $filename
38
     *
39
     * @return mixed|string
40
     */
41
    public function transliterate($filename)
42
    {
43
        // Sanitize and transliterate
44
        $str      = strtolower($filename);
45
        $str      = strip_tags($str);
46
        $str      = str_replace([' ', '-'], '_', $str);
47
        $safeName = preg_replace('/[^a-z0-9-_\.]/', '', $str);
48
49
        // Create unique filename.
50
        $i         = 1;
51
        $nameArray = explode('.', $safeName);
52
53
        while (!$this->isUniqueFilename($safeName)) {
54
            $parts           = $nameArray;
55
            $secondLastIndex = count($parts) - 2;
56
57
            // Add an incremented suffix to the second last part.
58
            $parts[$secondLastIndex] = $parts[$secondLastIndex] . '_' . $i;
59
            // Stick it all back together
60
            $safeName = implode('.', $parts);
61
62
            $i++;
63
        }
64
65
        return $safeName;
66
    }
67
68
    /**
69
     * @param $filename
70
     *
71
     * @return bool
72
     */
73
    protected function isUniqueFilename($filename)
74
    {
75
        $entity = $this->fileToObject->getObjectFromFilename($filename);
76
77
        return empty($entity) ? true : false;
78
    }
79
}