/** * Construct controller. * * @throws Controller_API_Exception on invalid version, rate limit exceeded, invalid format */ public function before() { // Log request $api_request = Model_API_Request::factory(); $api_request->ip = Request::$client_ip; $api_request->request = $this->request->uri() . (empty($_REQUEST) ? '' : '?' . http_build_query($_REQUEST)); $api_request->created = time(); $api_request->save(); // Check version $this->version = $this->request->param('version'); if (!in_array($this->version, self::$_versions)) { throw new Controller_API_Exception('Invalid version'); } $this->data['version'] = $this->version; // Rate limit $rate_limit = (int) Kohana::$config->load('api.rate_limit'); $rate_span = (int) Kohana::$config->load('api.rate_span'); if ($rate_limit) { $requests = Model_API_Request::request_count(time() - $rate_span, Request::$client_ip); $requests_left = $rate_limit - $requests; if ($requests_left < 0) { throw new Controller_API_Exception('Request limit reached'); } $this->data['requests'] = $requests; $this->data['requests_left'] = $requests_left; $this->data['request_window'] = $rate_span; } // Check format $this->format = $this->request->param('format'); !$this->format and $this->format = self::FORMAT_JSON; if (!in_array($this->format, self::$_formats)) { throw new Controller_API_Exception('Invalid format'); } parent::before(); }
/** * Construct controller */ public function before() { // Log request Jelly::factory('api_request')->set(array('ip' => Request::$client_ip, 'request' => $this->request->uri . (empty($_GET) ? '' : '?' . http_build_query($_GET))))->save(); // Rate limit $rate_span = Kohana::config('api.rate_span'); $rate_limit = Kohana::config('api.rate_limit'); $requests = Model_API_Request::request_count(time() - $rate_span, Request::$client_ip); $requests_left = $rate_limit - $requests; if ($requests_left < 0) { throw new Controller_API_Exception('Request limit reached'); } // Check version $this->version = $this->request->param('version'); if (!in_array($this->version, self::$_versions)) { throw new Controller_API_Exception('Invalid version'); } // Check format $this->format = $this->request->param('format'); !$this->format and $this->format = self::FORMAT_JSON; if (!in_array($this->format, self::$_formats)) { throw new Controller_API_Exception('Invalid format'); } // Set result defaults $this->data = array('version' => $this->version, 'requests' => $requests, 'requests_left' => $requests_left, 'request_window' => $rate_span); return parent::before(); }