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

92 lines
2.8 KiB
PHP
Raw Permalink Normal View History

2021-06-09 11:43:25 +02:00
<?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'),
2021-06-09 11:43:25 +02:00
'ean' => [
'required',
'numeric',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
function ($attribute, $value, $fail) {
2021-07-06 10:19:57 +02:00
if (strlen((string)$value) !== 13 and strlen((string)$value) !== 7) {
2021-07-06 10:06:35 +02:00
$fail(trans('Le code ean doit être de 7 ou 13 chiffres'));
2021-06-09 11:43:25 +02:00
}
},
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
function ($attribute, $value, $fail) {
2021-07-05 16:29:45 +02:00
// Test EAN13
2021-06-09 11:43:25 +02:00
$ean = EanCode::where('ean', $value)->first();
2021-07-05 16:29:45 +02:00
// 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"));
2021-06-09 11:43:25 +02:00
}
},
]
];
}
public function messages()
{
return [
'buydate.before' => 'Marty dit: Vous ne pouvez indiquer une date dans le futur',
];
}
2021-07-05 16:29:45 +02:00
/**
* 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
]);
}
2021-06-09 11:43:25 +02:00
}