SmartCane/laravel_app/app/Rules/HarvestFile.php
2024-06-25 13:38:57 +02:00

33 lines
1.1 KiB
PHP

<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Maatwebsite\Excel\Exceptions\NoTypeDetectedException;
use Maatwebsite\Excel\HeadingRowImport;
class HarvestFile implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$toCheck = ["field","sub_field", "year", "season_start","season_end", "age" , "sub_area", "tonnage_ha"];
if(!$value) return;
if(!in_array($value['extension'], ['xlsx', 'xls', 'csv', 'ods'])) {
$fail($value['extension'].' is not a valid file (.xlsx, .xls, .csv, .ods).');
}
try{
$excelHeaderArray = (new HeadingRowImport)->toArray($value['path']);
$header = $excelHeaderArray[0][0];
if($diff = array_diff($toCheck,$header)) $fail("This sheet doesn't contain one of the following: ".implode(', ',$diff));
}catch(NoTypeDetectedException $e){
$fail($e->getMessage());
}
}
}