Skip to content

Instantly share code, notes, and snippets.

@adri
Created September 26, 2018 13:40
Show Gist options
  • Save adri/1357c9842c8d16d4664341cc54913bc7 to your computer and use it in GitHub Desktop.
Save adri/1357c9842c8d16d4664341cc54913bc7 to your computer and use it in GitHub Desktop.
Factory that resolves dependent objects using contexts.
<?php
class Factory
{
/**
* @var array
*/
private $contexts = [];
/**
* @var ObjectManager|null
*/
private $manager;
private function __construct(?ObjectManager $manager = null)
{
$this->manager = $manager;
}
public static function create(?ObjectManager $manager = null) : self
{
return new self($manager);
}
public function payout(callable $customize = null) : Payout
{
return $this->insertFixture(PayoutContext::class, $customize);
}
public function payment(callable $customize = null) : Payment
{
return $this->insertFixture(PaymentContext::class, $customize);
}
public function withPayment(callable $customize) : self
{
return $this->withFixture(PaymentContext::class, $customize);
}
/**
* Creates and inserts entities into the database
*/
private function insertFixture(string $contextClass, ?callable $customize = null)
{
$fixture = $this->createFixture($contextClass, $customize);
if (null !== $this->manager) {
$this->manager->persist($fixture);
$this->manager->flush();
}
return $fixture;
}
/**
* Creates entities
*/
private function createFixture(string $contextClass, ?callable $customize)
{
$context = $this->contexts[$contextClass] ?? new $contextClass();
if (null !== $customize) {
$customize($context);
}
return $context->create($this);
}
/**
* Sets a context without creating any entities
*/
private function withFixture(string $contextClass, ?callable $customize = null) : self
{
$context = new $contextClass();
if (null !== $customize) {
$customize($context);
}
$this->contexts[$contextClass] = $context;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment