public function run() { $this->response = $this->kernel->handle($this->request); $this->response->send(); $this->kernel->terminate($this->request, $this->response); return $this; }
/** * @param null|string $Path * * @return \Symfony\Component\HttpFoundation\Response * @throws \Exception */ public function getRoute($Path = null) { try { return $this->SymfonyHttpKernel->handle(Request::createFromGlobals())->getContent(); } catch (\Exception $E) { throw new ComponentException($E->getMessage(), $E->getCode(), $E); } }
public function getPreprocessorWriterResponse($preprocessorRouteName, array $attributes, Request $currentRequest) { // For localhost, the way is the same as for public to private forward. $attributes['_controller'] = $this->router->getRouteCollection()->get($preprocessorRouteName)->getDefault('_controller'); $subRequest = $currentRequest->duplicate(null, null, $attributes); $response = $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST); /* @var $response \Symfony\Component\HttpFoundation\Response */ $response->setStatusCode($response->getStatusCode(), $response->headers->get('ps_status_text', null)); return $response; }
/** * Handles a Request to convert it to a Response. * * When $catch is true, the implementation must catch all exceptions * and do its best to convert them to a Response instance. * * @param Request $request A Request instance * @param integer $type The type of the request * (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST) * @param Boolean $catch Whether to catch exceptions or not * * @return Response A Response instance * * @throws \Exception When an Exception occurs during processing * * @api * */ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { // for backward compatibility $this->container->set('request', $request); $this->container->get('request.context')->fromRequest($request); $response = parent::handle($request, $type, $catch); return $response; }
/** * run Application */ public function run() { $response = $this->container->get(TwigResponse::class); $response->setTemplate('error/404'); try { $this->eventDispatcher->addSubscriber($this->routerListener); $response = $this->httpKernel->handle($this->request); } catch (ResourceNotFoundException $e) { $response->setContent(['message' => $e->getMessage()]); } catch (\Exception $e) { // $response->setContent(['message' => $e->getMessage()]); throw $e; } finally { $response->send(); $this->httpKernel->terminate($this->request, $response); } }
public function testHandleSetsTheRequest() { $request = Request::create('/'); $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface'); $container->expects($this->exactly(2))->method('set')->with('request', $request); $kernel = new HttpKernel($container, new EventDispatcher(), $this->getResolver()); $kernel->handle($request); }
/** * {@inheritdoc} */ public function __invoke(Request $request) { $context = new RequestContext(); $context->fromRequest($request); $this->eventDispatcher->addSubscriber(new RouterListener(new UrlMatcher($this->routeCollection, $context))); $kernel = new HttpKernel($this->eventDispatcher, new ControllerResolverActionResolverAdapter($this->actionResolver)); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); }
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { $this->container->enterScope('request'); $this->container->set('request', $request, 'request'); try { $response = parent::handle($request, $type, $catch); } catch (\Exception $e) { $this->container->leaveScope('request'); throw $e; } $this->container->leaveScope('request'); return $response; }
public function testUrl() { $routes = new RouteCollection(); $routes->add('hello', new Route('/hello', array('_controller' => function (Request $request) { return new Response("Hello"); }))); $matcher = new UrlMatcher($routes, new RequestContext()); // create the Request object $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new RouterListener($matcher)); $resolver = new ControllerResolver(); $kernel = new HttpKernel($dispatcher, $resolver); $request = Request::create('/hello'); $response = $kernel->handle($request); echo $response->getContent(); // // actually execute the kernel, which turns the request into a response // // by dispatching events, calliwaang a controller, and returning the response // $response = $kernel->handle($request); }
/** @test */ public function it_converts_exception_to_json() { $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface'); $resolver->expects($this->once())->method('getController')->will($this->returnValue(function () { throw new NotFoundHttpException(); })); $resolver->expects($this->once())->method('getArguments')->will($this->returnValue([])); $logger = $this->getMock('Psr\\Log\\LoggerInterface'); $logger->expects($this->once())->method('error'); $dispatcher = new EventDispatcher(); $httpKernel = new HttpKernel($dispatcher, $resolver); $dispatcher->addSubscriber(new RequestFormatNegotiationListener()); $dispatcher->addSubscriber(new RequestFormatValidationListener()); $dispatcher->addSubscriber(new ResponseConversionListener()); $dispatcher->addSubscriber(new ExceptionConversionListener($logger)); $request = Request::create('/exception', 'GET', [], [], [], ['HTTP_ACCEPT' => 'application/json']); $request->attributes->set('_format', 'json'); $response = $httpKernel->handle($request)->prepare($request); $this->assertSame(404, $response->getStatusCode()); $this->assertSame('application/vnd.error+json', $response->headers->get('Content-Type')); $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'Not Found']), $response->getContent()); }
public function __construct() { $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(ROOT_PATH . '/app/config')); $loader->load('services.yml'); $loader = new YamlFileLoader($container, new FileLocator(ROOT_PATH . '/src/config')); $loader->load('services.yml'); $container->compile(); $routes = $container->get('router')->getRoutes(); $request = Request::createFromGlobals(); $matcher = new UrlMatcher($routes, new RequestContext()); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new AuthenticationListener($container)); $dispatcher->addSubscriber(new FirewallListener($container, $matcher)); $dispatcher->addSubscriber(new RouterListener($matcher)); $resolver = new MyControllerResolver($container); $kernel = new HttpKernel($dispatcher, $resolver); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); if (DEV_MODE) { $container->get('profiler')->showProfiler(); } }
public function testVerifyRequestStackPushPopDuringHandle() { $request = new Request(); $stack = $this->getMock('Symfony\\Component\\HttpFoundation\\RequestStack', array('push', 'pop')); $stack->expects($this->at(0))->method('push')->with($this->equalTo($request)); $stack->expects($this->at(1))->method('pop'); $dispatcher = new EventDispatcher(); $kernel = new HttpKernel($dispatcher, $this->getResolver(), $stack); $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST); }
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false) { $this->catch = $catch; $this->backendRequest = $request; return parent::handle($request, $type, $catch); }
require_once __DIR__ . '/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\EventListener\RouterListener; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; $routes = new RouteCollection(); $routes->add('hello', new Route('/add/{param1}', array('_controller' => function (Request $request) { return new Response("asdfasdf" . $request->get("param1")); }))); $routes->add('hello', new Route('/', array('_controller' => function (Request $request) { return new Response("Asdf"); }))); use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ExceptionHandler; ErrorHandler::register(); ExceptionHandler::register(); $request = Request::createFromGlobals(); $matcher = new UrlMatcher($routes, new RequestContext()); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new RouterListener($matcher)); $resolver = new ControllerResolver(); $kernel = new HttpKernel($dispatcher, $resolver); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
/** * @expectedException Symfony\Component\HttpKernel\Exception\BadRequestHttpException */ public function testInconsistentClientIpsOnMasterRequests() { $dispatcher = new EventDispatcher(); $dispatcher->addListener(KernelEvents::REQUEST, function ($event) { $event->getRequest()->getClientIp(); }); $kernel = new HttpKernel($dispatcher, $this->getResolver()); $request = new Request(); $request->setTrustedProxies(array('1.1.1.1')); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $request->headers->set('FORWARDED', '2.2.2.2'); $request->headers->set('X_FORWARDED_FOR', '3.3.3.3'); $kernel->handle($request, $kernel::MASTER_REQUEST, false); }
/** * {@inheritdoc} * * @api */ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { if ($type == HttpKernelInterface::SUB_REQUEST) { $request->query->add(array_merge($_POST, $_GET, $request->query->all())); } else { $this->container['request'] = $request; } return parent::handle($request, $type, $catch); }
/** * Main app dispatcher * * @param Request $request * * @throws \Exception */ public function dispatch(Request $request) { $context = new RequestContext(); $context->fromRequest($request); $matcher = new UrlMatcher($this->routes, $context); $request_stack = new RequestStack(); $dispatcher = new EventDispatcher(); //router $dispatcher->addSubscriber(new RouterListener($matcher, $request_stack, $context)); // IMPLEMENT: logger? //Get the controller $dispatcher->addListener(KernelEvents::CONTROLLER, [$this, 'onKernelController']); //non-response results $dispatcher->addListener(KernelEvents::VIEW, [$this, 'render']); $resolver = new ControllerResolver(); //IMPLEMENT lrogger? $kernel = new HttpKernel($dispatcher, $resolver); //create default response $response = new Response(); try { $response = $kernel->handle($request); } catch (HttpException $e) { if ($e instanceof NotFoundHttpException) { //page not found $response = $this->getPageNotFoundResponse(); } } $response->send(); }
public function testWithBadRequest() { $requestStack = new RequestStack(); $requestMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock(); $requestMatcher->expects($this->never())->method('matchRequest'); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new ValidateRequestListener()); $dispatcher->addSubscriber(new RouterListener($requestMatcher, $requestStack, new RequestContext())); $dispatcher->addSubscriber(new ExceptionListener(function () { return new Response('Exception handled', 400); })); $kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver()); $request = Request::create('http://localhost/'); $request->headers->set('host', '###'); $response = $kernel->handle($request); $this->assertSame(400, $response->getStatusCode()); }
require dirname(__DIR__) . '/vendor/autoload.php'; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; use Symfony\Component\HttpKernel\EventListener\RouterListener; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpKernel\Controller\ControllerResolver; $twigLoader = new Twig_Loader_Filesystem(dirname(__DIR__) . '/templates'); $twig = new Twig_Environment($twigLoader); $template = $twig->loadTemplate('index.html'); $routes = new RouteCollection(); $routes->add('home', new Route('/', array('_controller' => function () use($template) { return new Response($template->render(array('content' => 'Welcome home'))); }))); $routes->add('hello', new Route('/hello/{name}', array('_controller' => function (Request $request) use($template) { return new Response($template->render(array('content' => sprintf("Hello %s", $request->get('name'))))); }, 'name' => ''), array('name' => '.*'))); $request = Request::createFromGlobals(); $context = new RequestContext(); $context->fromRequest($request); $matcher = new UrlMatcher($routes, $context); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new RouterListener($matcher)); $resolver = new ControllerResolver(); $kernel = new HttpKernel($dispatcher, $resolver); $kernel->handle($request)->send();
public function testHandleRestoresThePreviousRequestOnException() { $dispatcher = new EventDispatcher(); $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface'); $kernel = new HttpKernel($dispatcher, $resolver); $request = new Request(); $expected = new \Exception(); $controller = function () use($expected) { throw $expected; }; $resolver->expects($this->once())->method('getController')->with($request)->will($this->returnValue($controller)); $resolver->expects($this->once())->method('getArguments')->with($request, $controller)->will($this->returnValue(array())); try { $kernel->handle($request); $this->fail('->handle() suppresses the controller exception'); } catch (\Exception $actual) { $this->assertSame($expected, $actual, '->handle() throws the controller exception'); } $this->assertNull($kernel->getRequest(), '->handle() restores the parent (null) request when the controller throws an exception'); }
public function handleWeb(Request $request = null) { if ($request === null) { // create the request from the globals if we don't have custom input $request = Request::createFromGlobals(); } $this->container->register('uri', '\\Foolz\\FoolFrame\\Model\\Uri')->addArgument($this)->addArgument($request); $remember_me = $request->cookies->get($this->config->get('foolz/foolframe', 'config', 'config.cookie_prefix') . 'rememberme'); if (!count($this->child_contextes)) { // no app installed, we need to go to the install $this->loadInstallRoutes($this->route_collection); } else { $this->profiler->log('Start Auth rememberme'); /** @var Auth $auth */ $auth = $this->getService('auth'); if ($remember_me) { try { $auth->authenticateWithRememberMe($remember_me); } catch (WrongKeyException $e) { } } $this->profiler->log('Stop Auth rememberme'); Hook::forge('Foolz\\FoolFrame\\Model\\Context::handleWeb#obj.afterAuth')->setObject($this)->setParam('route_collection', $this->route_collection)->execute(); $this->profiler->log('Start Plugins handleWeb'); $this->getService('plugins')->handleWeb(); $this->profiler->log('Stop Plugins handleWeb'); $this->profiler->log('Start language setup'); $available_langs = $this->config->get('foolz/foolframe', 'package', 'preferences.lang.available'); $lang = $request->cookies->get('language'); if (!$lang || !array_key_exists($lang, $available_langs)) { $lang = $this->preferences->get('foolframe.lang.default'); } // HHVM does not support gettext if (function_exists('bindtextdomain')) { $locale = $lang . '.utf8'; putenv('LANG=' . $locale); putenv('LANGUAGE=' . $locale); setlocale(LC_ALL, $locale); bindtextdomain($lang, DOCROOT . 'assets/locale'); bind_textdomain_codeset($lang, 'UTF-8'); textdomain($lang); } $this->profiler->log('Stop language setup'); $this->profiler->log('Start routes setup'); // load the routes from the child contextes first Hook::forge('Foolz\\FoolFrame\\Model\\Context::handleWeb#obj.routing')->setObject($this)->setParam('route_collection', $this->route_collection)->execute(); foreach ($this->child_contextes as $context) { $context->handleWeb($request); $context->loadRoutes($this->route_collection); } $this->profiler->log('Stop routes setup'); $this->profiler->log('Start routes load'); $this->loadRoutes($this->route_collection); $this->profiler->log('Stop routes setup'); } // load the framework routes Hook::forge('Foolz\\FoolFrame\\Model\\Context::handleWeb#obj.context')->setObject($this)->execute(); // this is the first time we know we have a request for sure // hooks that need the request to function must run here Hook::forge('Foolz\\FoolFrame\\Model\\Context::handleWeb#obj.request')->setObject($this)->setParam('request', $request)->execute(); $this->container->register('notices', 'Foolz\\FoolFrame\\Model\\Notices')->addArgument($this)->addArgument($request); $this->profiler->log('Start HttpKernel loading'); $request_context = new RequestContext(); $request_context->fromRequest($request); $matcher = new UrlMatcher($this->route_collection, $request_context); $resolver = new ControllerResolver($this); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new RouterListener($matcher, null, $this->logger)); $dispatcher->addSubscriber(new ResponseListener('UTF-8')); $this->http_kernel = new HttpKernel($dispatcher, $resolver); $this->profiler->log('End HttpKernel loading'); // if this hook is used, it can override the entirety of the request handling $response = Hook::forge('Foolz\\FoolFrame\\Model\\Context::handleWeb#obj.response')->setObject($this)->setParam('request', $request)->execute()->get(false); if (!$response) { try { $this->profiler->log('Request handling start'); $response = $this->http_kernel->handle($request); $this->profiler->log('Request handling end'); } catch (NotFoundHttpException $e) { $controller_404 = $this->route_collection->get('404')->getDefault('_controller'); $request = new Request(); $request->attributes->add(['_controller' => $controller_404]); $response = $this->http_kernel->handle($request); } // stick the html of the profiler at the end if ($request->getRequestFormat() == 'html' && isset($auth) && $auth->hasAccess('maccess.admin')) { $content = explode('</body>', $response->getContent()); if (count($content) == 2) { $this->profiler->log('Execution end'); $response->setContent($content[0] . $this->profiler->getHtml() . '</body>' . $content[1]); } } } $this->getService('security')->updateCsrfToken($response); $response->send(); }
// nested arrays are not supported return $v; } if (strlen($val) === 0) { $escaped[$k] = null; continue; } $escaped[$k] = htmlspecialchars($val, ENT_QUOTES); } return $escaped; } return $v; }); $deserializer = new HTTPQueryStringDeserializer($dispatcher, $mdFactory); $eventDispatcher->addSubscriber(new RequestDeserializer($deserializer)); // application routes ... $stack = new \Symfony\Component\HttpFoundation\RequestStack(); $fl = new FileLocator('config'); $loader = new XmlFileLoader($fl); $collection = $loader->load('routing/routes.xml'); $context = new RequestContext(); $context->fromRequest($request); $matcher = new UrlMatcher($collection, $context); $rResolver = new RouterListener($matcher, $context, null, $stack); $eventDispatcher->addSubscriber($rResolver); // finally create the kernel ... $app = new HttpKernel($eventDispatcher, $conrollerResolver); // ... submit the request ... $response = $app->handle($request); // ... and return the response to the client $response->send();
/** * @param BaseRequest $request * @param integer $type * @param boolean $catch * * @return Response */ public function handle(BaseRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { $this->container['request'] = $request; return parent::handle($request, $type, $catch); }
public function run($group = null, $controller = null, $function = null) { // 注册框架运行的服务. $this->handle(); // 请求参数 $request = Request::capture(); // 设置请求 $this->app['request'] = $request; // 入口文件 $baseUrl = $request->getBaseUrl(); $this->filename = empty($baseUrl) ? $request->getSchemeAndHttpHost() . $request->server('SCRIPT_FILENAME') : $request->getSchemeAndHttpHost() . $baseUrl; if ($path_info = trim($request->getPathInfo(), '/')) { $args = explode('/', $path_info); define('BY_PATH_INFO', true); if (count($args) == 1) { $controller = $controller ?: $args[0]; } elseif (count($args) >= 2) { $controller = $controller ?: $args[0]; $function = $function ?: $args[1]; } } // ======== 开始调度,设置调度那个控制器=============== $group = ucfirst($group) ?: 'Web'; $controller = $controller ?: $request->get('c', 'DefaultController'); $controller = strrpos($controller, 'Controller') !== false ? $controller : $controller . 'Controller'; $function = $function ?: $request->get('m', 'index'); $class = '\\App\\Controllers\\' . $group . '\\' . ucfirst($controller); $load_class = $class . "::" . $function; // ======== 基础控制器设置结束 ======================== // 检查控制器类存在不 if (!class_exists($class)) { $class = '\\App\\Controllers\\' . $group . '\\NoFoundController'; $function = 'index'; $load_class = $class . '::' . $function; } // 如果没有找到类方法,设置为404 if (!is_callable([$class, $function])) { $class = NoFoundController::class; $function = 'index'; $load_class = NoFoundController::class . '::' . $function; } // 事件调度器 $dispatcher = new EventDispatcher(); // 调度控制器参数事件 $dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function ($event) { // 获取调度的参数 $arguments = $event->getArguments(); // 获取调度的控制器 $controller = $event->getController(); // 获取类 $class = $controller[0]; // 获取方法 $function = $controller[1]; // 检查调度方法在不在,在的话转发到调度方法去 if (method_exists($class, '_do_action')) { $controller = [$class, '_do_action']; // 将方法设置为第一个参数 array_unshift($arguments, $function); // 重新调度 $event->setController($controller); $event->setArguments($arguments); } }); // 设置视图事件回调 $dispatcher->addListener(KernelEvents::VIEW, function ($event) { $result = $event->getControllerResult(); // 重置视图的错误报告,忽略掉NOTICE的,视图太多NOTIC了 $error_report = error_reporting(); error_reporting(E_ALL ^ E_NOTICE); $event->setResponse(new Response($result instanceof View ? $result->render() : $result)); // 恢复原来的错误报告 error_reporting($error_report); }); // 设置异常回调 $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) { // 获取异常 $e = $event->getException(); // 如果是自定义异常 if ($e instanceof HttpResponseException) { // 设置成正常响应 $event->setResponse($e->getResponse()); } }); // 以下是Symfony默认HTTP调度,无需修改 $controllerResolver = new ControllerResolver(); $argumentResolver = new ArgumentResolver(); $kernel = new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver); $request->attributes->set('_controller', $load_class); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); }
/** * @param $controller * @param array $path * @param array $query * * @return \Symfony\Component\HttpFoundation\Response * @throws \Exception */ public function forward($controller, array $path = array(), array $query = array()) { $path['_controller'] = $controller; $subRequest = $this->requestStack->getCurrentRequest()->duplicate($query, null, $path); return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST); }
public function testHandleWithAResponseListener() { $dispatcher = new EventDispatcher(); $dispatcher->addListener(KernelEvents::RESPONSE, function ($event) { $event->setResponse(new Response('foo')); }); $kernel = new HttpKernel($dispatcher, $this->getResolver()); $this->assertEquals('foo', $kernel->handle(new Request())->getContent()); }
public function handle() { $resolver = new Resolver(); $kernel = new HttpKernel($this->getDispatcher(), $resolver); $response = $kernel->handle($this->getRequest()); $response->send(); $kernel->terminate($this->getRequest(), $response); }
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false) { return parent::handle($request, $type, $catch); }
public function testHandleWithAResponseListener() { $dispatcher = new EventDispatcher(); $dispatcher->connect('core.response', function ($event, $response) { return new Response('foo'); }); $kernel = new HttpKernel($dispatcher, $this->getResolver()); $this->assertEquals('foo', $kernel->handle(new Request())->getContent()); }