Last active
August 29, 2015 14:07
-
-
Save zburgermeiszter/9a88a54609ed5e42665f to your computer and use it in GitHub Desktop.
API core controller with route listing
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 InstantWater\AdminApiBundle\Controller; | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; | |
/** | |
* Class AbstractApiCoreController | |
* @package InstantWater\ApiBundle\Controller | |
*/ | |
abstract class AbstractApiCoreController extends Controller | |
{ | |
/** | |
* It will implement the empty route for each routed controller | |
* @Route("", name="api-core-controller-route-list") | |
* @Method("GET") | |
* @param Request $request | |
* @return Response | |
*/ | |
public function apiControllerRouteListAction(Request $request) { | |
return new JsonResponse($this->getControllerRoutes(), 200); | |
} | |
/** | |
* Return route names and details provided by the controller. | |
* Source: http://stackoverflow.com/questions/15943780/symfony2-get-list-of-all-routes-of-a-controller/15950365#15950365 | |
* @return null | |
*/ | |
protected function getControllerRoutes() { | |
/** | |
* @var $router \Symfony\Component\Routing\Router | |
* @var $collection \Symfony\Component\Routing\RouteCollection | |
* @var $params \Symfony\Component\Routing\Route | |
*/ | |
$schemeAndHttpHost = $this->getRequest()->getSchemeAndHttpHost(); | |
$router = $this->container->get('router'); | |
$collection = $router->getRouteCollection(); | |
$allRoutes = $collection->all(); | |
$routes = array(); | |
foreach ($allRoutes as $route => $params) | |
{ | |
$defaults = $params->getDefaults(); | |
if (isset($defaults['_controller'])) | |
{ | |
$controllerAction = explode(':', $defaults['_controller']); | |
$controller = $controllerAction[0]; | |
if (!isset($routes[$controller])) { | |
$routes[$controller] = array(); | |
} | |
$routes[$controller][$route]= array( | |
'url' => $schemeAndHttpHost.$params->getPath(), | |
'methods' => $params->getMethods(), | |
'schemes' => $params->getSchemes(), | |
); | |
} | |
} | |
return isset($routes[get_class($this)]) ? | |
$routes[get_class($this)] : null ; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment