ldc-tousenselle/app/Http/Requests/ParticipationRequest.php

91 lines
2.8 KiB
PHP

<?php
namespace App\Http\Requests;
use App\Models\EanCode;
use App\Models\Participation;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Carbon;
class ParticipationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'magasin' => 'required|exists:magasins,id',
'buydate' => 'required|date_format:Y-m-d|after:2020-01-01|before:' . Carbon::now()->addDay()->format('Y-m-d'),
'ean' => [
'required',
'numeric',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
function ($attribute, $value, $fail) {
if (strlen((string)$value) !== 13 and strlen((string)$value) !== 7) {
$fail(trans('Le code ean doit être de 7 ou 13 chiffres'));
}
},
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
function ($attribute, $value, $fail) {
// Test EAN13
$ean = EanCode::where('ean', $value)->first();
// Test EAN8
if (!$ean || empty($ean)) {
$ean = EanCode::where('ean', 'LIKE', substr($value, 0, 7) . "%")->first();
}
// Test EAN7
if (!$ean || empty($ean)) {
$ean = EanCode::where('ean', 'LIKE', substr($value, 0, 6) . "%")->first();
}
// Error
if (!$ean || empty($ean)) {
$fail(trans("Le produit donné n'est pas éligible pour participer à ce jeu"));
}
},
]
];
}
public function messages()
{
return [
'buydate.before' => 'Marty dit: Vous ne pouvez indiquer une date dans le futur',
];
}
/**
* Handle a passed validation attempt.
*
* @return void
*/
protected function passedValidation()
{
// Test EAN13
$ean = EanCode::where('ean', $this->ean)->first();
// Test EAN8
if (!$ean || empty($ean)) {
$ean = EanCode::where('ean', 'LIKE', substr($this->ean, 0, 7) . "%")->first();
}
// Test EAN7
if (!$ean || empty($ean)) {
$ean = EanCode::where('ean', 'LIKE', substr($this->ean, 0, 6) . "%")->first();
}
$this->merge([
'ean' => $ean
]);
}
}