Last active
August 7, 2020 06:03
-
-
Save jelen07/ea13e57bcd71afd3e6b8e9d686c7f15a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* What pattern is this class? | |
*/ | |
declare(strict_types=1); | |
namespace Vendor\Package\Bundle\PickupPointBundle\Pattern; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Doctrine\Common\Collections\Collection; | |
use Doctrine\ORM\EntityManagerInterface; | |
use Vendor\Package\Bundle\PickupPointBundle\Doctrine\ORM\PickupPointRepositoryInterface; | |
use Vendor\Package\Bundle\PickupPointBundle\Entity\PickupPointInterface; | |
use Vendor\Package\Bundle\PickupPointBundle\Factory\PickupPointFactoryInterface; | |
final class PickupPointPattern implements PickupPointPatternInterface | |
{ | |
/** @var PickupPointRepositoryInterface */ | |
private $providerRepository; | |
/** @var PickupPointFactoryInterface */ | |
private $providerFactory; | |
/** @var EntityManagerInterface */ | |
private $entityManager; | |
/** @var Collection */ | |
private $providers; | |
public function __construct( | |
PickupPointRepositoryInterface $providerRepository, | |
PickupPointFactoryInterface $providerFactory, | |
EntityManagerInterface $entityManager | |
) { | |
$this->providerRepository = $providerRepository; | |
$this->providerFactory = $providerFactory; | |
$this->entityManager = $entityManager; | |
} | |
public function getProviderByCode(string $code): PickupPointInterface | |
{ | |
if (null === $this->providers) { | |
$this->providers = $this->getProviders(); | |
} | |
$provider = $this->providers->filter(static function (PickupPointInterface $PickupPoint) use ($code) { | |
if ($code === $PickupPoint->getCode()) { | |
return $PickupPoint; | |
} | |
return null; | |
})->first(); | |
if (false === $provider) { | |
$provider = $this->createNew($code); | |
$this->providers->add($provider); | |
} | |
return $provider; | |
} | |
private function getProviders(): ArrayCollection | |
{ | |
$providers = $this->providerRepository->findAll(); | |
return new ArrayCollection($providers); | |
} | |
private function createNew(string $providerCode): PickupPointInterface | |
{ | |
/** @var PickupPointInterface $provider */ | |
$provider = $this->providerFactory->createNew(); | |
$provider->setCode($providerCode); | |
$this->entityManager->persist($provider); | |
$this->entityManager->flush(); | |
return $provider; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment