Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion Tests/FileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,22 @@ public function dataTestMakeSafe(): \Generator
'.gitignore',
'Files starting with a fullstop should be allowed when strip chars parameter is empty',
];

if (function_exists('transliterator_transliterate') && function_exists('iconv')) {
yield [
'Änderüng_âsceñt.txt',
[],
'Anderung_ascent.txt',
'Files with non-ascii characters should be transliterated',
];
} else {
yield [
'Änderüng_âsceñt.txt',
[],
'nderng_scet.txt',
'Files with non-ascii characters should be removed when transliteration is not possible',
];
}
}

/**
Expand All @@ -117,7 +133,7 @@ public function dataTestMakeSafe(): \Generator
*/
public function testMakeSafe($name, $stripChars, $expected, $message)
{
$this->assertEquals(File::makeSafe($name, $stripChars), $expected, $message);
$this->assertEquals($expected, File::makeSafe($name, $stripChars), $message);
}

/**
Expand Down
11 changes: 8 additions & 3 deletions src/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,19 @@ public static function stripExt($file)
*/
public static function makeSafe($file, array $stripChars = ['#^\.#'])
{
$regex = array_merge(['#(\.){2,}#', '#[^A-Za-z0-9\.\_\- ]#'], $stripChars);
// Try transliterating the file name using the native php function
if (function_exists('transliterator_transliterate') && function_exists('iconv')) {
// Using iconv to ignore characters that can't be transliterated
$file = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", transliterator_transliterate('Any-Latin; Latin-ASCII', $file));
}

$file = preg_replace($regex, '', $file);
$regex = array_merge(['#(\.){2,}#', '#[^A-Za-z0-9\.\_\- ]#'], $stripChars);
$file = preg_replace($regex, '', $file);

// Remove any trailing dots, as those aren't ever valid file names.
$file = rtrim($file, '.');

return $file;
return trim($file);
}

/**
Expand Down