I created a feature to check if a spreadsheet has the correct layout, before uploading it to the database, it works perfectly for spreadsheets that are outside the requested standard. The problem is, when I upload it to check one that has the correct layout, it gives the same exception message as if it were wrong.
This was the function I created to do the validation:
private function validateFields(string $file): self
{
$fh = fopen($file, 'r');
$header = fgetcsv($fh);
fclose($fh);
foreach ($header as $value) {
if (!in_array(strtoupper($value),
self::MAP) || count(self::MAP) != count($header)) {
throw new \Exception('Invalid archive layout.');
}
}
return $this;
}
And here is where i'm calling this function with a try catch for this exception message:
public function execute()
{
$files = $this->getRequest()->getFiles('files');
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*');
if (empty($files['tmp_name'])) {
$this->messageManager->addWarningMessage(__('No files were uploaded.'));
return $resultRedirect;
}
try {
$file = $this->setExtensionInTemporaryFile($files['tmp_name'], $files['name']);
$fileData = $this->file->readFile($file, self::SPREADSHEET_TAB);
$this->validateFields('$file');
$this->saveCustomerRelatedAttribute->execute($fileData);
$this->messageManager->addSuccessMessage(__('Customer segment attributes save successfuly.'));
} catch (\InvalidArgumentException $e) {
$this->messageManager->addErrorMessage(__('Make sure the file extension refers to a csv.'));
} catch (CouldNotSaveException $e) {
$this->messageManager->addErrorMessage(
__('One or more lines do not contain correct values. Check and try again.')
);
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(__('The csv layout is invalid. Check and try again.')
);
}
return $resultRedirect;
}