/** * @param FilterControllerEvent $event */ public function onKernelController(FilterControllerEvent $event) { // Skip if we aren't the main request if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) { return; } // Skip if we are a closure if (!is_array($controller = $event->getController())) { return; } // Find the best match $annotations = $event->getRequest()->attributes->get('_x-rate-limit', array()); $rateLimit = $this->findBestMethodMatch($event->getRequest(), $annotations); // No matching annotation found if (!$rateLimit) { return; } $key = $this->getKey($event, $rateLimit, $annotations); // Ratelimit the call $rateLimitInfo = $this->rateLimitService->limitRate($key); if (!$rateLimitInfo) { // Create new rate limit entry for this call $rateLimitInfo = $this->rateLimitService->createRate($key, $rateLimit->getLimit(), $rateLimit->getPeriod()); if (!$rateLimitInfo) { // @codeCoverageIgnoreStart return; // @codeCoverageIgnoreEnd } } // Store the current rating info in the request attributes $request = $event->getRequest(); $request->attributes->set('rate_limit_info', $rateLimitInfo); // When we exceeded our limit, return a custom error response if ($rateLimitInfo->getCalls() > $rateLimitInfo->getLimit()) { // Throw an exception if configured. if ($this->getParameter('rate_response_exception')) { $class = $this->getParameter('rate_response_exception'); throw new $class($this->getParameter('rate_response_message'), $this->getParameter('rate_response_code')); } $message = $this->getParameter('rate_response_message'); $code = $this->getParameter('rate_response_code'); $event->setController(function () use($message, $code) { // @codeCoverageIgnoreStart return new Response($message, $code); // @codeCoverageIgnoreEnd }); } }
public function testcreateRate() { $mockStorage = $this->getMock('Noxlogic\\RateLimitBundle\\Service\\Storage\\StorageInterface'); $mockStorage->expects($this->once())->method('createRate')->with('testkey', 10, 100); $service = new RateLimitService(); $service->setStorage($mockStorage); $service->createRate('testkey', 10, 100); }