Created
March 28, 2012 14:05
-
-
Save uwej711/2226457 to your computer and use it in GitHub Desktop.
EntityRouter
This file contains hidden or 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 | |
| use Symfony\Component\Routing\RouterInterface; | |
| use Symfony\Component\Routing\RequestContext; | |
| use Symfony\Component\Routing\RouteCollection; | |
| use Symfony\Component\Routing\Exception\RouteNotFoundException; | |
| use Symfony\Component\Routing\Exception\ResourceNotFoundException; | |
| use Symfony\Component\Routing\Exception\MethodNotAllowedException; | |
| use Symfony\Component\Routing\Route; | |
| use Symfony\Component\Routing\Generator\UrlGenerator; | |
| class EntityRouter implements RouterInterface | |
| { | |
| const NAME = 'entity'; | |
| protected $context; | |
| protected $service; | |
| protected $route; | |
| protected $collection; | |
| protected $generator; | |
| public function __construct(ServiceInterface $service, RequestContext $context) | |
| { | |
| $this->service = $service; | |
| $this->context = $context; | |
| $this->route = new Route('/{slug}', array('_controller' => '<put a default here>'),array('slug' => '.+')); | |
| $this->collection = new RouteCollection(); | |
| $this->collection->add(self::NAME, $this->route); | |
| $this->generator = new UrlGenerator($this->collection, $this->context); | |
| } | |
| public function setContext(RequestContext $context) | |
| { | |
| $this->context = $context; | |
| $this->generator->setContext($context); | |
| } | |
| public function getContext() | |
| { | |
| return $this->context; | |
| } | |
| public function getRouteCollection() | |
| { | |
| return $this->collection; | |
| } | |
| public function generate($name, $parameters = array(), $absolute = false) | |
| { | |
| return $this->generator->generate($name, $parameters, $absolute); | |
| } | |
| public function match($pathinfo) | |
| { | |
| $slug = substr($pathinfo, 1); | |
| $entity = $this->service->getEntityBySlug($slug); | |
| if (null === $entity) { | |
| throw new ResourceNotFoundException("No entity for slug $slug found"); | |
| } | |
| return array_merge($this->route->getDefaults(), array('_route' => self::NAME, 'entity' => $entity)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really nice work. I think I could use that! Thanks.