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
|
|
|
} |