Skip to content

Commit

Permalink
Add Additional Filename Sanitization (#3105)
Browse files Browse the repository at this point in the history
* Update FileAdder.php

Update the default filename sanitizer to handle funky whitespace characters in files - I had a case where a file was being uploaded, and it kepts throwing Flysystems `CorruptedPathDetected` exception. Not sure if copy-pasting the filename to github keeps the characters there: `Scan-‎9‎.‎14‎.‎2022-‎7‎.‎23‎.‎28.pdf`

* add unit tests for PR #3031

* Fix styling

Co-authored-by: Tommi Carleman <[email protected]>
  • Loading branch information
patinthehat and tommica authored Nov 22, 2022
1 parent 9e34cb2 commit 40cf0c6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/MediaCollections/FileAdder.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,8 @@ protected function ensureDiskExists(string $diskName)

public function defaultSanitizer(string $fileName): string
{
$fileName = preg_replace('#\p{C}+#u', '', $fileName);

return str_replace(['#', '/', '\\', ' '], '-', $fileName);
}

Expand Down
25 changes: 25 additions & 0 deletions tests/MediaCollections/FileAdderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Spatie\MediaLibrary\Tests\MediaCollections;

use Spatie\MediaLibrary\MediaCollections\FileAdder;

it('sanitizes filenames correctly', function () {
/** @var FileAdder $adder */
$adder = app(FileAdder::class);

expect($adder->defaultSanitizer('valid-filename.jpg'))
->toEqual('valid-filename.jpg');

expect($adder->defaultSanitizer('test one.pdf'))
->toEqual('test-one.pdf');

expect($adder->defaultSanitizer('test#one.pdf'))
->toEqual('test-one.pdf');

expect($adder->defaultSanitizer('some/test/file.pdf'))
->toEqual('some-test-file.pdf');

expect($adder->defaultSanitizer('Scan-‎9‎.‎14‎.‎2022-‎7‎.‎23‎.‎28.pdf'))
->toEqual('Scan-9.14.2022-7.23.28.pdf');
});

0 comments on commit 40cf0c6

Please sign in to comment.