<?php
declare(strict_types=1);
namespace App\Decorator;
use App\Component\Configuration\Util\Config;
use App\Entity\ApplicantForm;
use App\Entity\Option;
use App\Entity\OptionValue;
use App\Entity\Vacancy;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityManagerInterface;
use MobileDetectBundle\DeviceDetector\MobileDetector;
class ApplicantFormRetriever implements ApplicantFormRetrieverInterface
{
public function __construct(
private readonly MobileDetector $mobileDetector,
private readonly Config $config,
private readonly EntityManagerInterface $manager
) {
}
public function retrieve(Vacancy $vacancy): ApplicantForm
{
/** @var ApplicantForm|null $mobileForm */
$mobileForm = $this->config->get('site_vacancy_mobile_application_form');
if ($this->mobileDetector->isMobile() && null !== $mobileForm) {
return $mobileForm;
}
$customApplicantForm = $vacancy->getCustomApplicantForm();
if ((bool) $vacancy->isApplicantFormCustom() && null !== $customApplicantForm) {
return $customApplicantForm;
}
$applicantForm = $vacancy->getApplicantForm();
if (null !== $applicantForm) {
return $applicantForm;
}
$applicantForm = $this->findApplicantFormFromOptionValues($vacancy);
if (null !== $applicantForm) {
return $applicantForm;
}
/** @var ApplicantForm $applicantForm */
$applicantForm = $this->manager->getRepository(ApplicantForm::class)->findOneBy(['default' => true]);
return $applicantForm;
}
private function findApplicantFormFromOptionValues(Vacancy $vacancy): ?ApplicantForm
{
/** @var bool $formStrategy */
$formStrategy = $this->config->get('site_vacancy_applicant_form_strategy');
if (!$formStrategy) {
return null;
}
$formOption = $this->config->get('site_vacancy_applicant_form_option');
if (!$formOption instanceof Option) {
return null;
}
/** @var Collection<1, OptionValue> $optionValues */
$optionValues = $vacancy->getOptionValues();
if ($optionValues->isEmpty()) {
return null;
}
$filteredSearchFilters = $optionValues->filter(function (OptionValue $optionValue) use ($formOption) {
/** @var Option $formOption */
if ($optionValue->getOption()?->getId() !== $formOption->getId()) {
return false;
}
return null !== $optionValue->getApplicantForm();
});
if ($filteredSearchFilters->isEmpty()) {
return null;
}
/** @var OptionValue $optionValue */
$optionValue = $filteredSearchFilters->first();
return $optionValue->getApplicantForm();
}
}