-
-
Save ybouhjira/e5d168e8cfe6a4ad4741504af0aa57b7 to your computer and use it in GitHub Desktop.
Automatically generate HATEOAS links for doctrine relations
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 | |
namespace Acme\FooBundle\Hateoas; | |
use Doctrine\ORM\EntityManager; | |
use Hateoas\Configuration\Metadata\ClassMetadataInterface; | |
use Hateoas\Configuration as Hateoas; | |
use Symfony\Component\Routing\Route; | |
use Symfony\Component\Routing\RouterInterface; | |
class DoctrineRelationProvider | |
{ | |
protected $entityManager; | |
protected $router; | |
public function __construct(EntityManager $entityManager, RouterInterface $router) | |
{ | |
$this->entityManager = $entityManager; | |
$this->router = $router; | |
} | |
public function addRelations($object, ClassMetadataInterface $classMetadata) | |
{ | |
$relations = array(); | |
$parts = explode('\\', $classMetadata->getName()); | |
$self_route = 'get_' . strtolower(array_pop($parts)); | |
if ($this->routeExists($self_route) ) { | |
$relations[] = new Hateoas\Relation( | |
'self', | |
new Hateoas\Route( | |
$self_route, | |
array('id' => 'expr(object.getId())') | |
) | |
); | |
} | |
$metadata = $this->entityManager->getClassMetadata($classMetadata->getName()); | |
foreach($metadata->getAssociationMappings() as $mapping) { | |
$route_name = $self_route . '_' . strtolower($mapping['fieldName']); | |
if ($this->routeExists($route_name)) { | |
$relations[] = new Hateoas\Relation( | |
$mapping['fieldName'], | |
new Hateoas\Route( | |
$route_name, | |
array('id' => 'expr(object.getId())') | |
) | |
); | |
} | |
} | |
// You need to return the relations | |
// Adding the relations to the $classMetadata won't work | |
return $relations; | |
} | |
protected function routeExists($name) { | |
return $this->router->getRouteCollection()->get($name) instanceof Route; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment