Skip to content

Instantly share code, notes, and snippets.

@adri
Created Sep 26, 2018
Embed
What would you like to do?
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