Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: Throw exception when entity definition for name is unavailable #67

Merged
merged 1 commit into from
Mar 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Provider/Doctrine/EntityDefinitionUnavailable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace FactoryGirl\Provider\Doctrine;

final class EntityDefinitionUnavailable extends \OutOfRangeException implements Exception
{
public static function for(string $name): self
{
return new self(sprintf(
'An entity definition for name "%s" is not available.',
$name
));
}
}
72 changes: 39 additions & 33 deletions src/Provider/Doctrine/FixtureFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,22 @@ class FixtureFactory
* @var EntityManager
*/
protected $em;

/**
* @var string
*/
protected $entityNamespace;

/**
* @var array<EntityDef>
*/
protected $entityDefs;

/**
* @var array
*/
protected $singletons;

/**
* @var boolean
*/
Expand All @@ -42,70 +42,76 @@ class FixtureFactory
public function __construct(EntityManager $em)
{
$this->em = $em;

$this->entityNamespace = '';

$this->entityDefs = [];

$this->singletons = [];

$this->persist = false;
}

/**
* Sets the namespace to be prefixed to all entity names passed to this class.
*/
public function setEntityNamespace($namespace)
{
$this->entityNamespace = trim($namespace, '\\');
}

public function getEntityNamespace()
{
return $this->entityNamespace;
}


/**
* Get an entity and its dependencies.
*
* Whether the entity is new or not depends on whether you've created
* a singleton with the entity name. See `getAsSingleton()`.
*
* If you've called `persistOnGet()` then the entity is also persisted.
*
* @throws EntityDefinitionUnavailable
*/
public function get($name, array $fieldOverrides = [])
{
if (isset($this->singletons[$name])) {
return $this->singletons[$name];
}


if (!array_key_exists($name, $this->entityDefs)) {
throw EntityDefinitionUnavailable::for($name);
}

$def = $this->entityDefs[$name];
$config = $def->getConfig();

$this->checkFieldOverrides($def, $fieldOverrides);

$ent = $def->getEntityMetadata()->newInstance();
$fieldValues = [];
foreach ($def->getFieldDefs() as $fieldName => $fieldDef) {
$fieldValues[$fieldName] = array_key_exists($fieldName, $fieldOverrides)
? $fieldOverrides[$fieldName]
: $fieldDef($this);
}

foreach ($fieldValues as $fieldName => $fieldValue) {
$this->setField($ent, $def, $fieldName, $fieldValue);
}

if (isset($config['afterCreate'])) {
$config['afterCreate']($ent, $fieldValues);
}


if ($this->persist) {
$this->em->persist($ent);
}

return $ent;
}

Expand Down Expand Up @@ -143,11 +149,11 @@ protected function checkFieldOverrides(EntityDef $def, array $fieldOverrides)
throw new Exception("Field(s) not in " . $def->getEntityType() . ": '" . implode("', '", $extraFields) . "'");
}
}

protected function setField($ent, EntityDef $def, $fieldName, $fieldValue)
{
$metadata = $def->getEntityMetadata();

if ($metadata->isCollectionValuedAssociation($fieldName)) {
$metadata->setFieldValue($ent, $fieldName, $this->createCollectionFrom($fieldValue));
} else {
Expand All @@ -167,7 +173,7 @@ protected function createCollectionFrom($array = [])

return new ArrayCollection();
}

/**
* Sets whether `get()` should automatically persist the entity it creates.
* By default it does not. In any case, you still need to call
Expand All @@ -177,7 +183,7 @@ public function persistOnGet($enabled = true)
{
$this->persist = $enabled;
}

/**
* A shorthand combining `get()` and `setSingleton()`.
*
Expand All @@ -191,7 +197,7 @@ public function getAsSingleton($name, array $fieldOverrides = [])
$this->singletons[$name] = $this->get($name, $fieldOverrides);
return $this->singletons[$name];
}

/**
* Sets `$entity` to be the singleton for `$name`.
*
Expand All @@ -201,7 +207,7 @@ public function setSingleton($name, $entity)
{
$this->singletons[$name] = $entity;
}

/**
* Unsets the singleton for `$name`.
*
Expand All @@ -211,7 +217,7 @@ public function unsetSingleton($name)
{
unset($this->singletons[$name]);
}

/**
* Defines how to create a default entity of type `$name`.
*
Expand All @@ -224,22 +230,22 @@ public function defineEntity($name, array $fieldDefs = [], array $config = [])
if (isset($this->entityDefs[$name])) {
throw new Exception("Entity '$name' already defined in fixture factory");
}

$type = $this->addNamespace($name);
if (!class_exists($type, true)) {
throw new Exception("Not a class: $type");
}

$metadata = $this->em->getClassMetadata($type);
if (!isset($metadata)) {
throw new Exception("Unknown entity type: $type");
}

$this->entityDefs[$name] = new EntityDef($this->em, $name, $type, $fieldDefs, $config);

return $this;
}

/**
* @param string $name
* @return string
Expand All @@ -254,7 +260,7 @@ protected function addNamespace($name)

return $this->entityNamespace . '\\' . $name;
}

protected function updateCollectionSideOfAssocation($entityBeingCreated, $metadata, $fieldName, $value)
{
$assoc = $metadata->getAssociationMapping($fieldName);
Expand Down
30 changes: 30 additions & 0 deletions tests/Provider/Doctrine/EntityDefinitionUnavailableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace FactoryGirl\Tests\Provider\Doctrine;

use FactoryGirl\Provider\Doctrine\EntityDefinitionUnavailable;
use PHPUnit\Framework;

/**
* @covers \FactoryGirl\Provider\Doctrine\EntityDefinitionUnavailable
*/
final class EntityDefinitionUnavailableTest extends Framework\TestCase
{
public function testForReturnsException(): void
{
$name = 'foo';

$exception = EntityDefinitionUnavailable::for($name);

self::assertInstanceOf(\OutOfRangeException::class, $exception);

$message = sprintf(
'An entity definition for name "%s" is not available.',
$name
);

self::assertSame($message, $exception->getMessage());
}
}
28 changes: 28 additions & 0 deletions tests/Provider/Doctrine/FixtureFactoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace FactoryGirl\Tests\Provider\Doctrine;

use Doctrine\ORM\EntityManager;
use FactoryGirl\Provider\Doctrine\EntityDefinitionUnavailable;
use FactoryGirl\Provider\Doctrine\FixtureFactory;

use PHPUnit\Framework;

/**
* @covers \FactoryGirl\Provider\Doctrine\FixtureFactory
*/
final class FixtureFactoryTest extends Framework\TestCase
{
public function testGetThrowsEntityDefinitionUnavailableWhenDefinitionIsUnavailable(): void
{
$entityManager = $this->prophesize(EntityManager::class)->reveal();

$fixtureFactory = new FixtureFactory($entityManager);

$this->expectException(EntityDefinitionUnavailable::class);

$fixtureFactory->get('foo');
}
}