*/ final class UpsertShopsPickupExceptionsUsingApiForYear implements Action { private const string CALENDAR_API_URL = 'https://calendrier.api.gouv.fr/jours-feries/metropole/:year.json'; private const int API_CALL_TIMEOUT = 120; /** * @param \App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsUsingApiForYearInput $input */ #[\Override] public function __invoke(ActionInput $input): void { Assert::isInstanceOf($input, UpsertShopsPickupExceptionsUsingApiForYearInput::class); if ( $input->onlyIfMissing && PickupException::query() ->whereYear('date', $input->year) ->where('auto_updated', true) ->exists() ) { return; } $holidayList = $this->getHolidaysForYear($input->year); foreach ($holidayList as $holiday) { $exception = PickupException::query() ->firstOrNew([ 'date' => $holiday->date->format('Y-m-d'), 'label' => $holiday->label, ]); $exception->fill([ 'date' => $holiday->date->format('Y-m-d'), 'repeatable' => true, 'repeat_frequency' => RepeatFrequency::YEARLY, ]); $exception->setAttribute('auto_updated', true); $exception->saveOrFail(); } $repeatablesFromApi = PickupException::query() ->whereYear('date', $input->year) ->whereIn('label', array_map( fn ($v) => $v->label, $holidayList )) ->get(); Shop::query()->get() ->each(fn ($shop) => $shop->pickupExceptions() ->syncWithoutDetaching($repeatablesFromApi)); } /** @return object{date:\DateTimeInterface,label:string}[] */ private function getHolidaysForYear(int $year): array { $url = $this->getCalendarApiUrlFor($year); $response = Http::timeout(self::API_CALL_TIMEOUT)->get($url); throw_unless( $response->successful(), \UnexpectedValueException::class, 'Failed to fetch calendar from api' ); $outputList = $response ->collect() ->map(fn ($label, $date) => [ 'date' => $date, 'label' => $label, ])->all(); $rules = [ '*' => 'array', '*.date' => ['required', 'date'], '*.label' => ['required', 'string'], ]; $validator = Validator::make($outputList, $rules); if ($validator->fails()) { $errors = $validator->errors(); throw new \UnexpectedValueException( 'Invalid response: ' . json_encode($errors->messages()) ); } return array_map(fn (array $entry) => (object) [ 'date' => Date::parse( $entry['date'], new \DateTimeZone('Europe/Paris') ), 'label' => Arr::string($entry, 'label'), ], $outputList); } private function getCalendarApiUrlFor(int $year): string { return str_replace( ':year', strval($year), self::CALENDAR_API_URL ); } }