本文整理汇总了PHP中Zend\Mvc\MvcEvent::setResponse方法的典型用法代码示例。如果您正苦于以下问题:PHP MvcEvent::setResponse方法的具体用法?PHP MvcEvent::setResponse怎么用?PHP MvcEvent::setResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Zend\Mvc\MvcEvent
的用法示例。
在下文中一共展示了MvcEvent::setResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: onRoute
public function onRoute(MvcEvent $e)
{
$request = $e->getRequest();
if (!$request instanceof HttpRequest) {
return;
}
$application = $e->getApplication();
$serviceLocator = $application->getServiceManager();
// Load the configuration for maintenance mode
if ($serviceLocator->has('MaintenanceConfig')) {
$config = $serviceLocator->get('MaintenanceConfig');
} else {
$config = new Config();
}
if (!$config->isEnabled()) {
// Maintenance mode is disabled.
return;
}
// Check the white list
if ($request instanceof PhpRequest) {
$address = $request->getServer('REMOTE_ADDR', null);
} else {
$address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
}
if (!empty($address)) {
if (in_array($address, $config->getWhitelist())) {
return;
}
}
// Render the maintenance layout
$renderer = new PhpRenderer();
if ($serviceLocator->has('ViewHelperManager')) {
$renderer->setHelperPluginManager($serviceLocator->get('ViewHelperManager'));
}
$resolver = new TemplateMapResolver();
$resolver->add('maintenance', $config->getTemplate());
$renderer->setResolver($resolver);
$content = $renderer->render('maintenance');
// Set the response
$response = $e->getResponse();
if (!$response instanceof HttpResponse) {
$response = new HttpResponse();
}
$statusCode = $config->getStatusCode();
$response->setStatusCode($statusCode);
if ($statusCode === 503 && !$response->getHeaders()->has('Retry-After')) {
$retryDate = $config->getRetryAfter();
if ($retryDate instanceof DateTime) {
$retryAfter = new RetryAfter();
$retryAfter->setDate($retryDate);
$response->getHeaders()->addHeader($retryAfter);
}
}
$response->setContent($content);
$e->setResponse($response);
// Return the response
return $response;
}
示例2: testReturnIfNotHttpResponse
public function testReturnIfNotHttpResponse()
{
$response = $this->getMock(ResponseInterface::class);
$response->expects($this->never())->method('setStatusCode');
$this->event->setResponse($response);
$this->assertNull($this->resourceResponseListener->finishResponse($this->event));
}
示例3: setUp
/**
* Set up
*/
public function setUp()
{
parent::setUp();
$this->httpExceptionListener = new HttpExceptionListener();
// Init the MvcEvent object
$this->response = new HttpResponse();
$this->event = new MvcEvent();
$this->event->setResponse($this->response);
}
示例4: displayError
protected function displayError($template, $status = 403)
{
$model = new ViewModel();
$model->setTerminal(false);
$model->setTemplate($template);
/** @var $response \Zend\Http\PhpEnvironment\Response */
$response = $this->_event->getResponse();
$response->setStatusCode($status);
$this->_event->setResponse($response);
$this->_event->setResult($model);
return;
}
示例5: setUp
protected function setUp()
{
$this->console = $this->getMockOfConsole();
$this->controller = new IndexController();
$this->event = new MvcEvent();
$this->request = new Request();
$this->response = new Response();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->controller->setConsole($this->console);
$this->controller->setEvent($this->event);
$this->event->setRequest($this->request);
$this->event->setResponse($this->response);
$this->event->setRouteMatch($this->routeMatch);
}
示例6: testOnResponseWithoutAutoInstrument
public function testOnResponseWithoutAutoInstrument()
{
$this->moduleOptions->setBrowserTimingEnabled(true)->setBrowserTimingAutoInstrument(false);
$this->client->expects($this->once())->method('getBrowserTimingHeader')->will($this->returnValue('<div class="browser-timing-header"></div>'));
$this->client->expects($this->once())->method('getBrowserTimingFooter')->will($this->returnValue('<div class="browser-timing-footer"></div>'));
$request = new HttpRequest();
$this->event->setRequest($request);
$response = new Response();
$response->setContent('<html><head></head><body></body></html>');
$this->event->setResponse($response);
$this->listener->onResponse($this->event);
$content = $response->getContent();
$this->assertContains('<head><div class="browser-timing-header"></div></head>', $content);
$this->assertContains('<body><div class="browser-timing-footer"></div></body>', $content);
}
示例7: __invoke
public function __invoke(MvcEvent $e)
{
$response = $e->getResponse();
$this->rateLimitService->consume($e->getRouteMatch(), $e->getRequest());
//var_dump($this->rateLimitService->getTopMeters('daily_limits'));exit;
$status = $this->rateLimitService->getLimitStatus($e->getRouteMatch(), $e->getRequest(), 'daily_limits');
if (!empty($status)) {
//add info headers
$headers = $response->getHeaders();
$headers->addHeaderLine('X-RateLimit-Limit', $status['limit']);
$headers->addHeaderLine('X-RateLimit-Remaining', $status['remaining']);
$headers->addHeaderLine('X-RateLimit-Reset', $status['reset']);
$response->setHeaders($headers);
}
if ($this->rateLimitService->isLimitExceeded()) {
//trigger the ratelimit exceeded event
$mvcLimitEvent = $this->mvcLimitEvent;
$response = $this->eventManager->trigger(MvcLimitEvent::EVENT_RATELIMIT_EXCEEDED, $mvcLimitEvent, function ($r) {
return $r instanceof Response;
});
$response = $response->last();
return $response;
} elseif ($this->rateLimitService->isLimitWarning()) {
//trigger the ratelimit warning event
$mvcLimitEvent = $this->mvcLimitEvent;
$response = $this->eventManager->trigger(MvcLimitEvent::EVENT_RATELIMIT_WARN, $mvcLimitEvent, function ($r) {
return $r instanceof Response;
});
$response = $response->last();
$e->setResponse($response);
}
}
示例8: preDispatch
/**
* preDispatch Event Handler
* Handle authentication process
* Decide where user should be redirected to when logged in or not
*
*
* @access public
* @uses AuthenticationService
* @uses Response
*
* @param \Zend\Mvc\MvcEvent $event
* @throws \Exception
*/
public function preDispatch(MvcEvent $event)
{
// ACL dispatcher is used only in HTTP requests not console requests
if (!$event->getRequest() instanceof HttpRequest) {
return;
}
$userAuth = new AuthenticationService();
$user = array();
$signInController = 'DefaultModule\\Controller\\Sign';
if ($userAuth->hasIdentity()) {
$user = $userAuth->getIdentity();
}
$routeMatch = $event->getRouteMatch();
$controller = $routeMatch->getParam('controller');
$action = $routeMatch->getParam('action');
if ($userAuth->hasIdentity() && isset($user['status']) && $user['status'] == 2) {
$userAuth->clearIdentity();
// redirect to sign/out
$url = $event->getRouter()->assemble(array('action' => 'out'), array('name' => 'defaultSign'));
} else {
if ($userAuth->hasIdentity() && $controller == $signInController && $action == 'in') {
// redirect to index
$url = $event->getRouter()->assemble(array('action' => 'index'), array('name' => 'home'));
}
}
if (isset($url)) {
$event->setResponse(new Response());
$this->redirect()->getController()->setEvent($event);
$response = $this->redirect()->toUrl($url);
return $response;
}
}
示例9: onError
/**
* @private
* @param MvcEvent $event
* @return void
*/
public function onError(MvcEvent $event)
{
// Do nothing if no error or if response is not HTTP response
if (!$event->getParam('exception') instanceof UnauthorizedExceptionInterface || $event->getResult() instanceof HttpResponse || !$event->getResponse() instanceof HttpResponse) {
return;
}
$router = $event->getRouter();
if ($this->authenticationService->hasIdentity()) {
if (!$this->options->getRedirectWhenConnected()) {
return;
}
$redirectRoute = $this->options->getRedirectToRouteConnected();
} else {
$redirectRoute = $this->options->getRedirectToRouteDisconnected();
}
$uri = $router->assemble([], ['name' => $redirectRoute]);
if ($this->options->getAppendPreviousUri()) {
$redirectKey = $this->options->getPreviousUriQueryKey();
$previousUri = $event->getRequest()->getUriString();
$uri = $router->assemble([], ['name' => $redirectRoute, 'query' => [$redirectKey => $previousUri]]);
}
$response = $event->getResponse() ?: new HttpResponse();
$response->getHeaders()->addHeaderLine('Location', $uri);
$response->setStatusCode(302);
$event->setResponse($response);
$event->setResult($response);
}
示例10: testOnRenderErrorCreatesAnApiProblemResponse
public function testOnRenderErrorCreatesAnApiProblemResponse()
{
$response = new Response();
$request = new Request();
$request->getHeaders()->addHeaderLine('Accept', 'application/json');
$event = new MvcEvent();
$event->setError(Application::ERROR_EXCEPTION);
$event->setRequest($request);
$event->setResponse($response);
$this->listener->onRenderError($event);
$this->assertTrue($event->propagationIsStopped());
$this->assertSame($response, $event->getResponse());
$this->assertEquals(406, $response->getStatusCode());
$headers = $response->getHeaders();
$this->assertTrue($headers->has('Content-Type'));
$this->assertEquals('application/problem+json', $headers->get('content-type')->getFieldValue());
$content = json_decode($response->getContent(), true);
$this->assertArrayHasKey('status', $content);
$this->assertArrayHasKey('title', $content);
$this->assertArrayHasKey('describedBy', $content);
$this->assertArrayHasKey('detail', $content);
$this->assertEquals(406, $content['status']);
$this->assertEquals('Not Acceptable', $content['title']);
$this->assertContains('www.w3.org', $content['describedBy']);
$this->assertContains('accept', $content['detail']);
}
示例11: onDispatchError
/**
* Get the exception and optionally set status code, reason message and additional errors
*
* @internal
* @param MvcEvent $event
* @return void
*/
public function onDispatchError(MvcEvent $event)
{
$exception = $event->getParam('exception');
if (isset($this->exceptionMap[get_class($exception)])) {
$exception = $this->createHttpException($exception);
}
// We just deal with our Http error codes here !
if (!$exception instanceof HttpExceptionInterface || $event->getResult() instanceof HttpResponse) {
return;
}
// We clear the response for security purpose
$response = new HttpResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
$exception->prepareResponse($response);
// NOTE: I'd like to return a JsonModel instead, and let ZF handle the request, but I couldn't make
// it work because for unknown reasons, the Response get replaced "somewhere" in the MVC workflow,
// so the simplest is simply to do that
$content = ['status_code' => $response->getStatusCode(), 'message' => $response->getReasonPhrase()];
if ($errors = $exception->getErrors()) {
$content['errors'] = $errors;
}
$response->setContent(json_encode($content));
$event->setResponse($response);
$event->setResult($response);
$event->stopPropagation(true);
}
示例12: onDispatch
/**
* @param MvcEvent $event
*
* @return parent::onDispatch
*/
public function onDispatch(MvcEvent $event)
{
$request = $event->getRequest();
$remoteAddr = $request->getServer('REMOTE_ADDR');
// check IP address is allowed
$application = $event->getApplication();
$config = $application->getConfig();
$autoDeployConfig = $config['auto_deploy'];
$allowedIpAddresses = $autoDeployConfig['ipAddresses'];
// error if ip is not allowed
if (!in_array($remoteAddr, $allowedIpAddresses, true)) {
$baseModel = new \Zend\View\Model\ViewModel();
$baseModel->setTemplate('layout/output');
$model = new \Zend\View\Model\ViewModel();
$model->setTemplate('error/403');
$baseModel->addChild($model);
$baseModel->setTerminal(true);
$event->setViewModel($baseModel);
$response = $event->getResponse();
$response->setStatusCode(403);
$response->sendHeaders();
$event->setResponse($response);
exit;
}
return parent::onDispatch($event);
}
示例13: handleError
/**
* @param MvcEvent $e
*/
protected function handleError(MvcEvent $e)
{
$router = $e->getRouter();
if ($this->authenticationService->hasIdentity()) {
if (!$this->options->getRedirectWhenConnected()) {
return;
}
$redirectRoute = $this->options->getRedirectToRouteConnected();
} else {
$redirectRoute = $this->options->getRedirectToRouteDisconnected();
}
$params = array();
$options = array('name' => $redirectRoute);
if ($this->options->getAppendPreviousUri()) {
$redirectKey = $this->options->getPreviousUriRouteKey();
$previousUri = $e->getRequest()->getUriString();
$params = array($redirectKey => $previousUri);
}
$uri = $router->assemble($params, $options);
$response = $e->getResponse() ?: new HttpResponse();
$response->getHeaders()->addHeaderLine('Location', $uri);
$response->setStatusCode(302);
$e->setResponse($response);
$e->setResult($response);
}
示例14: testInjectTagsHeader
public function testInjectTagsHeader()
{
$tag = InjectTagsHeaderListener::OPTION_CACHE_TAGS;
$event = new MvcEvent();
$response = new Response();
$event->setResponse($response);
$layout = new ViewModel();
$child1 = new ViewModel();
$child1->setOption($tag, ['tag1', 'tag2']);
$layout->addChild($child1);
$child2 = new ViewModel();
$child21 = new ViewModel();
$child21->setOption($tag, ['tag3', null]);
$child2->addChild($child21);
$layout->addChild($child2);
$child3 = new ViewModel();
$child3->setOption('esi', ['ttl' => 120]);
$child3->setOption($tag, 'tag4');
$layout->addChild($child3);
$event->setViewModel($layout);
$this->listener->injectTagsHeader($event);
$this->assertSame(['tag1', 'tag2', 'tag3'], $this->listener->getCacheTags());
$headers = $response->getHeaders();
$this->assertEquals('tag1,tag2,tag3', $headers->get(VarnishService::VARNISH_HEADER_TAGS)->getFieldValue());
}
示例15: setUp
public function setUp()
{
StaticEventManager::resetInstance();
$mockSharedEventManager = $this->getMock('Zend\EventManager\SharedEventManagerInterface');
$mockSharedEventManager->expects($this->any())->method('getListeners')->will($this->returnValue(array()));
$mockEventManager = $this->getMock('Zend\EventManager\EventManagerInterface');
$mockEventManager->expects($this->any())->method('getSharedManager')->will($this->returnValue($mockSharedEventManager));
$mockApplication = $this->getMock('Zend\Mvc\ApplicationInterface');
$mockApplication->expects($this->any())->method('getEventManager')->will($this->returnValue($mockEventManager));
$event = new MvcEvent();
$event->setApplication($mockApplication);
$event->setRequest(new Request());
$event->setResponse(new Response());
$routeMatch = new RouteMatch(array('action' => 'test'));
$routeMatch->setMatchedRouteName('some-route');
$event->setRouteMatch($routeMatch);
$locator = new Locator;
$locator->add('forward', function () {
return new ForwardController();
});
$this->controller = new SampleController();
$this->controller->setEvent($event);
$this->controller->setServiceLocator($locator);
$this->plugin = $this->controller->plugin('forward');
}