Skip to content

Instantly share code, notes, and snippets.

@nojimage
Created December 14, 2018 13:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nojimage/8e9ccef4051ba3856db6f17c13a3d0af to your computer and use it in GitHub Desktop.
<?php
/**
* Copyright 2018 Takashi Nojima.
*/
namespace App\Routing;
use Cake\Controller\Controller;
use Cake\Http\ControllerFactory;
use Cake\Http\Response;
use Cake\Http\ServerRequest;
use Cake\Routing\Exception\MissingControllerException;
use Cake\Routing\Router;
/**
* URLからコントローラーの取得
*/
class ControllerResolver
{
/**
* @var ControllerFactory
*/
private $factory;
/**
* ControllerFactory constructor.
*
* @param ControllerFactory|null $factory CakePHP Controller Factory
*/
public function __construct($factory = null)
{
if ($factory === null) {
$factory = new ControllerFactory();
}
$this->factory = $factory;
}
/**
* Get Controller from url
*
* @param array|string $url The parse url
* @param string $method The Request Method
* @return Controller
* @throws MissingControllerException
*/
public function getFromUrl($url, $method = 'GET')
{
$urlString = Router::url($url);
$request = (new ServerRequest($urlString))->withMethod(strtoupper($method));
$params = Router::parseRequest($request);
$controller = null;
try {
$controller = $this->factory->create($request->withAttribute('params', $params), new Response());
} catch (MissingControllerException $e) {
// nothing to do
}
if ($controller === null || get_class($controller) === Controller::class) {
throw new MissingControllerException(sprintf('Can\'t resolve Controller from url. %s %s', $method, $urlString));
}
return $controller;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment