%PDF- %PDF-
| Direktori : /www/loslex_o/demo/app/Rules/ |
| Current File : /www/loslex_o/demo/app/Rules/ContestDate.php |
<?php
namespace App\Rules;
use Closure;
use App\Models\Contest;
use App\Models\ContestLevel;
use Illuminate\Support\Carbon;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
class ContestDate implements DataAwareRule, ValidationRule
{
/**
* All of the data under validation.
* @var array<string, mixed>
*/
protected $data = [];
protected $contestId;
/**
* Set the data under validation.
* @param array<string, mixed> $data
*/
public function setData(array $data): static
{
$this->data = $data;
$exploreUrl = explode('/', request()->url());
$this->contestId = end($exploreUrl);
return $this;
}
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$originalDate = intval($this->contestId)
? Contest::select('date')->where('id', $this->contestId)->first()->date
: null;
$updatedDate = Carbon::parse($this->data['date']);
// if contest date was not changed no need to continue validation
if ($originalDate == $updatedDate) { return; }
if ($updatedDate < Carbon::today()) {
$fail('validation.contestdateinpast')->translate();
return;
}
// checking if specific contest types are opened in advance enough
if (!isset($this->data['contest_level_id'])) { return; }
$contestlevel = ContestLevel::where('id', $this->data['contest_level_id'])->first();
$advanceDays = $updatedDate->diff(Carbon::now())->days;
if ($advanceDays < $contestlevel->advance) {
$fail('validation.contestdateadvance')->translate(['value' => $contestlevel->advance]);
}
}
}