Using Symfony and Doctrine, I am writing a component that populates the database with elements of arbitrary objects during application deployment.
I want this component to be shared, so I'm trying to automatically resolve dependencies between objects and insert them in the correct order.
Currently, I get the dependencies of each individual object through the metadata of the object, recursively:
public function getEntityDeps($eName) { $deps = []; foreach ($this->entityManager->getClassMetadata($eName)->getAssociationMappings() as $mapping) { $deps[] = $mapping['targetEntity']; $deps = array_merge($deps, $this->getEntityDeps($mapping['targetEntity'])); } return $deps; }
The result is obviously a list of the following form:
// NOTE: The real list of course contains class names instead of entity aliases. [ "FooBundle:EntityA" => [], "FooBundle:EntityB" => ["FooBundle:EntityA", "FooBundle:EntityC"], "FooBundle:EntityC" => ["FooBundle:EntityA"], "BarBundle:EntityA" => ["BarBundle:EntityB"], "BarBundle:EntityB" => [] ]
The next step, I think, will apply some type of topological sorting to the list.
However, I am not sure if I can use the general algorithm here or if I forgot something. Moreover, the entities are not necessarily connected (so in fact we can have more than one dependency graph).
Also, I hope they have Doctrine internal functionality that can sort for me.
So, what would be the most reliable way to sort an arbitrary set of Doctrine objects? Is it possible to reuse Doctrine?