我不得不放弃UnauthorizedStrategy
上课。onError
基本上,我从类的方法中复制了代码UnauthorizedStrategy
并进行了修改以满足我的需要。
public function onBootstrap(MvcEvent $e)
{
/** @var EventManager $eventManager */
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'onError'], 100);
}
public function onError(MvcEvent $event) {
// Do nothing if no error or if response is not HTTP response
if (($event->getResult() instanceof HttpResponse)
|| !($event->getResponse() instanceof HttpResponse)
) {
return;
}
$baseModel = new ViewModel();
$baseModel->setTemplate('layout/layout');
$model = new ViewModel();
$model->setTemplate('error/403');
switch ($event->getError()) {
case GuardInterface::GUARD_UNAUTHORIZED:
$model->setVariable('error', GuardInterface::GUARD_UNAUTHORIZED);
break;
default:
return; // If it is not unauthorized error, skip it so it will show the more appropriate errors.
}
$baseModel->addChild($model);
$baseModel->setTerminal(true);
$event->setViewModel($baseModel);
$response = $event->getResponse() ?: new HttpResponse();
$response->setStatusCode(403);
$event->setResponse($response);
$event->setResult($baseModel);
$event->stopPropagation();
}