public invoke ( Imbo\EventManager\EventInterface $event ) | ||
$event | Imbo\EventManager\EventInterface | The event instance |
public function invoke(EventInterface $event)
{
$request = $event->getRequest();
$resource = (string) $request->getRoute();
$method = $request->getMethod();
$allowed = $this->params['allowedMethods'];
if (!isset($allowed[$resource]) || !in_array($method, $allowed[$resource])) {
// The listener is not configured for the current method/resource combination
return;
}
$origin = $request->headers->get('Origin');
// Vary on Origin to prevent caching allowed/disallowed requests
$event->getResponse()->setVary('Origin', false);
// Fall back if the passed origin is not allowed
if (!$origin || !$this->originIsAllowed($origin)) {
return;
}
// Flag this as an allowed request
$this->requestAllowed = true;
$event->getResponse()->headers->add(['Access-Control-Allow-Origin' => $origin]);
}
/** * @covers Imbo\EventListener\Cors::invoke */ public function testAddsVaryHeaderContainingOriginRegardlessOfAllowedStatus() { $this->request->expects($this->any())->method('getMethod')->will($this->returnValue('GET')); $route = $this->getMock('Imbo\\Router\\Route'); $route->expects($this->any())->method('__toString')->will($this->returnValue('index')); $this->request->expects($this->any())->method('getRoute')->will($this->returnValue($route)); // Allowed $listener = new Cors(['allowedOrigins' => ['http://imbo-project.org']]); $event = $this->getMock('Imbo\\EventManager\\Event'); $event->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); $response = $this->getMock('Imbo\\Http\\Response\\Response'); $response->expects($this->once())->method('setVary')->with('Origin', false); $event->expects($this->any())->method('getResponse')->will($this->returnValue($response)); $listener->invoke($event); // Disallowed $listener = new Cors(['allowedOrigins' => []]); $event = $this->getMock('Imbo\\EventManager\\Event'); $event->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); $response = $this->getMock('Imbo\\Http\\Response\\Response'); $response->expects($this->once())->method('setVary')->with('Origin', false); $event->expects($this->any())->method('getResponse')->will($this->returnValue($response)); $listener->invoke($event); }