Created
December 14, 2018 13:19
-
-
Save nojimage/8e9ccef4051ba3856db6f17c13a3d0af to your computer and use it in GitHub Desktop.
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 | |
/** | |
* 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