Skip to content

Commit

Permalink
Merge pull request #37 from Moln/feature/add-file-arg
Browse files Browse the repository at this point in the history
[Feature] Add `$file` argument in `SanitizerCallback`.
  • Loading branch information
adrianmiu committed Sep 22, 2022
2 parents d6db09a + 85eab39 commit b6f37e4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
7 changes: 4 additions & 3 deletions src/Handler.php
Expand Up @@ -228,7 +228,7 @@ protected function processSingleFile(array $file):array
$file['original_name'] = $file['name'];

// sanitize the file name
$file['name'] = $this->sanitizeFileName($file['name']);
$file['name'] = $this->sanitizeFileName($file['name'], $file);

$file = $this->validateFile($file);
// if there are messages the file is not valid
Expand Down Expand Up @@ -289,12 +289,13 @@ protected function validateFile($file)
* and replacing "invalid" characters with underscore _
*
* @param string $name
* @param array $file
* @return string
*/
protected function sanitizeFileName($name)
protected function sanitizeFileName($name, $file)
{
if ($this->sanitizerCallback) {
return call_user_func($this->sanitizerCallback, $name);
return call_user_func($this->sanitizerCallback, $name, $file);
}
return preg_replace('/[^A-Za-z0-9\.]+/', '_', $name);
}
Expand Down
9 changes: 6 additions & 3 deletions tests/src/HandlerTest.php
Expand Up @@ -288,8 +288,11 @@ function testMultiUploadValidation()

function testCustomSanitizationCallback()
{
$this->handler->setSanitizerCallback(function ($name) {
return preg_replace('/[^A-Za-z0-9\.]+/', '-', strtolower($name));
$this->handler->setSanitizerCallback(function ($name, $file) {
return preg_replace(
'/[^A-Za-z0-9\.]+/', '-',
substr(md5_file($file['tmp_name']), 0, 8) . '-' . strtolower($name)
);
});
$this->createTemporaryFile('ABC 123.tmp', 'non image file');

Expand All @@ -300,7 +303,7 @@ function testCustomSanitizationCallback()
)
);

$this->assertTrue(file_exists($this->uploadFolder . '/abc-123.tmp'));
$this->assertTrue(file_exists($this->uploadFolder . '/35d41ded-abc-123.tmp'));
}

function testExceptionThrownForInvalidSanitizationCallback()
Expand Down

0 comments on commit b6f37e4

Please sign in to comment.