Skip to content

Improve Error Message "Invalid file name" in setValueAfterValidation() Method  #39222

Open
@obsergiu

Description

@obsergiu

Currently, the setValueAfterValidation method in Magento\Config\Model\Config\Backend\File.php throws a generic error message, Invalid file name, when a file name doesn't pass validation(like: default/logo.png). I think it would be better for improving this by including the actual invalid file name in the message to make it more informative.

This validation and function were introduced in Magento 2.4.6-p5, but I don't see it in the current beta version. As such it should be treated more like a reference for others who might encounter similar issues.

The code is located at:

throw new LocalizedException(__('Invalid file name'));

The existing code:

private function setValueAfterValidation(string $value): void
{
    if (preg_match('/[^a-z0-9_\/\\-\\.]+/i', $value)
        // phpcs:ignore Magento2.Functions.DiscouragedFunction
        || !$this->_mediaDirectory->isFile($this->_getUploadDir() . DIRECTORY_SEPARATOR . basename($value))
    ) {
        throw new LocalizedException(__('Invalid file name'));
    }

    $this->setValue($value);
}

Suggested change:

private function setValueAfterValidation(string $value): void
{
    if (preg_match('/[^a-z0-9_\/\\-\\.]+/i', $value)
        // phpcs:ignore Magento2.Functions.DiscouragedFunction
        || !$this->_mediaDirectory->isFile($this->_getUploadDir() . DIRECTORY_SEPARATOR . basename($value))
    ) {
        throw new LocalizedException(__('Invalid file name: "%1".', $value));
    }

    $this->setValue($value);
}

Including the actual file name in the error message will make it easier to understand what went wrong and help debug the issue faster.

Steps to Reproduce:

  1. Try to save a configuration with an invalid file name.
  2. You’ll see a generic error message: Invalid file name.

Expected Result:
The error message should show the exact file name, like: Invalid file name: "default/logo.png".

Actual Result:
Currently, it just says: Invalid file name.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Ready for Grooming

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions