Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.