/** * Inject into the request authentication options * * @param \Guzzle\Common\Event $event */ public function onCreateRequest(Event $event) { $data = $event->toArray(); /** @var $request Request */ $request = $data['request']; $request->setAuth($this->username, $this->password); }
public function testOnRequestBeforeSend() { $requestId = new RequestId(new Generator(), true); $guzzzleAdapter = new Guzzle($requestId); $event = new Event(); $request = new Request('GET', 'test'); $event->offsetSet('request', $request); $guzzzleAdapter->onRequestBeforeSend($event); $this->assertEquals($requestId->getRequestId(), $event['request']->getHeader("X-RequestId")); }
public function it_dispatches_before_send(Event $e, Request $request, Url $url, QueryString $q) { $e->offsetGet('request')->willReturn($request); $request->getUrl(true)->willReturn($url); $url->setHost(sprintf(LegacyUrlPlugin::BASE_URL, 'username'))->willReturn($url); $url->setPath(LegacyUrlPlugin::WEBHOOK_PATH)->willReturn($url); $url->setScheme('https')->willReturn($url); $request->setUrl($url)->shouldBeCalled()->willReturn($request); $request->getQuery()->shouldBeCalled()->willReturn($q); $this->onRequestBeforeSend($e)->shouldReturn(null); }
public function onRequestBeforeSend(Event $event) { if ($this->queue) { $request = $event['request']; $this->received[] = $request; // Detach the filter from the client so it's a one-time use if ($this->temporary && count($this->queue) == 1 && $request->getClient()) { $request->getClient()->getEventDispatcher()->removeSubscriber($this); } $this->dequeue($request); $event->stopPropagation(); } }
/** * curl error * @param \Guzzle\Common\Event $event * @throws KintoneException */ public function onRequestException(Event $event) { $this->request = $event->offsetGet('request'); $this->response = $event->offsetGet('response'); $this->exception = $event->offsetGet('exception'); if ($this->exception instanceof \Guzzle\Http\Exception\CurlException) { $errorNumber = $this->exception->getErrorNo(); switch ($errorNumber) { case 6: throw new KintoneException('kintone.unknown_url'); case 35: throw new KintoneException('kintone.invalid_cert'); default: throw new KintoneException('kintone.invalid_auth'); } } throw new \Exception($this->exception->getMessage()); }
public function onRequestError(Event $event) { if ($event['response']->getStatusCode() == 401) { if ($event['request']->getHeader('X-Retry-Count')) { // We already retried once, give up. return; } // Acquire a new access token, and retry the request. $newAccessToken = $this->acquireAccessToken(); if ($newAccessToken) { $newRequest = clone $event['request']; $newRequest->setHeader('Authorization', 'Bearer ' . $newAccessToken->getToken()); $newRequest->setHeader('X-Retry-Count', '1'); $event['response'] = $newRequest->send(); $event->stopPropagation(); } } }
/** * Map Laravel's soft delete action to Kinvey's user suspend * endpoint. * * @param Guzzle\Common\Event * @return void */ public function beforePrepare(Event $event) { $command = $event['command']; $operation = $command->getOperation(); $client = $command->getClient(); if ($command->getName() !== 'updateEntity') { return; } if ($operation->getParam('collection')->getDefault() !== 'user') { return; } // Attempt to get the model's deleted at value from the array of values passed // to the command. $statusValue = false; if ($command->offsetExists(Model::DELETED_AT)) { $statusValue = $command->offsetGet(Model::DELETED_AT); } elseif ($command->offsetExists('_kmd')) { $_kmd = array_dot($command->offsetGet('_kmd')); $statusField = MODEL::DELETED_AT; $statusField = str_replace('_kmd.', '', MODEL::DELETED_AT); if (array_key_exists($statusField, $_kmd)) { $statusValue = $_kmd[$statusField]; } } // Could not determine the status field. if ($statusValue === false) { return; } elseif (!is_null($statusValue)) { $event->stopPropagation(); $suspendCommand = $client->getCommand('deleteEntity', array('collection' => 'user', '_id' => $command->offsetGet('_id'))); $suspendCommand->execute(); } else { $event->stopPropagation(); $restoreCommand = $client->getCommand('restore', array('_id' => $command->offsetGet('_id'))); $restoreCommand->execute(); } }
public function it_adds_the_token_to_the_command_before_prepare(Event $event, CommandInterface $command) { /** @var EventDispatcher $dispatcher */ $dispatcher = $this->getEventDispatcher(); $event->offsetGet('command')->willReturn($command); $event->setDispatcher($dispatcher)->shouldBeCalled(); $event->setName('command.before_prepare')->shouldBeCalled(); $event->isPropagationStopped()->willReturn(false); $command->offsetSet('token', $this->config['token'])->shouldBeCalled(); $dispatcher->dispatch('command.before_prepare', $event); }
public function onRequestError(Event $event) { if ($event['response']->getStatusCode() == 401) { // The access token has expired. We need to get a new token using the refresh token, // and then sign a new request with the new access token if ($storage = self::$config['storage']['getRefresh']) { $client = new Client(self::URL_STUB); if ($id = self::getConfig('userID')) { $params = array('refresh_token' => $storage($id), 'client_id' => self::$config['clientId'], 'client_secret' => self::$config['clientSecret'], 'grant_type' => 'refresh_token'); } else { $params = array('refresh_token' => $storage(), 'client_id' => self::$config['clientId'], 'client_secret' => self::$config['clientSecret'], 'grant_type' => 'refresh_token'); } try { $response = $client->post('token')->addPostFields($params)->send(); } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) { throw new InvalidRefresh(); } foreach ($response->json() as $key => $val) { if ($key == 'access_token') { $storage = self::$config['storage']['token']; if ($id = self::getConfig('userID')) { $storage($val, $id); } else { $storage($val); } } } $newRequest = clone $event['request']; $newRequest = $newRequest->setHeader('Authorization', $this->_buildAuthorizationHeader())->send(); $event['response'] = $newRequest; } else { throw new KeyExpired(); } $event->stopPropagation(); } }
/** * Throws a more meaningful request exception if available * * @param Event $event Event emitted */ public function onRequestError(Event $event) { $e = $this->factory->fromResponse($event['request'], $event['response']); $event->stopPropagation(); throw $e; }
/** * If possible, set a cache response on a cURL exception * * @param Event $event * * @return null */ public function onRequestException(Event $event) { if (!$event['exception'] instanceof CurlException) { return; } $request = $event['request']; if (!$this->canCache->canCacheRequest($request)) { return; } if ($response = $this->storage->fetch($request)) { $response->setHeader('Age', time() - strtotime($response->getDate() ?: 'now')); if (!$this->canResponseSatisfyFailedRequest($request, $response)) { return; } $request->getParams()->set('cache.hit', 'error'); $request->setResponse($response); $this->addResponseHeaders($request, $response); $event->stopPropagation(); } }
/** * {@inheritdoc} */ public function __construct(array $context = []) { $resolver = new OptionsResolver(); $this->setDefaultOptions($resolver); parent::__construct($resolver->resolve($context)); }
protected function getMockEvent(RequestInterface $request) { // Create a mock curl multi object $multi = $this->getMockBuilder('Guzzle\\Http\\Curl\\CurlMulti')->setMethods(array('remove', 'add'))->getMock(); // Create an event that is expected for the Poll event $event = new Event(array('request' => $request, 'curl_multi' => $multi)); $event->setName(CurlMultiInterface::POLLING_REQUEST); return $event; }
/** * Default method that will throw exceptions if an unsuccessful response is received. * * @param Event $event Received * @throws BadResponseException if the response is not successful */ public static function onRequestError(Event $event) { $e = BadResponseException::factory($event['request'], $event['response']); $event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray()); throw $e; }
/** * @covers Guzzle\Http\Plugin\ExponentialBackoffPlugin::onRequestPoll */ public function testSeeksToBeginningOfRequestBodyWhenRetrying() { // Create a mock curl multi object $multi = $this->getMockBuilder('Guzzle\\Http\\Curl\\CurlMulti')->setMethods(array('remove', 'add'))->getMock(); // Create a request with a body $request = new EntityEnclosingRequest('PUT', 'http://www.example.com'); $request->setBody('abc'); // Set the retry time to be something that will be retried always $request->getParams()->set('plugins.exponential_backoff.retry_time', 2); // Seek to the end of the stream $request->getBody()->seek(3); $this->assertEquals('', $request->getBody()->read(1)); // Create a plugin that does not delay when retrying $plugin = new ExponentialBackoffPlugin(2, null, array($this, 'delayClosure')); // Create an event that is expected for the Poll event $event = new Event(array('request' => $request, 'curl_multi' => $multi)); $event->setName(CurlMultiInterface::POLLING_REQUEST); $plugin->onRequestPoll($event); // Ensure that the stream was seeked to 0 $this->assertEquals('a', $request->getBody()->read(1)); }
/** * Function: refreshToken() * Parameters: * $event = Guzzle\Common\Event * Description: Attempts to reconnect with new token on 401 * Returns: VOID */ public function refreshToken(Event $event) { if ($event['response']->getStatusCode() === 401) { $this->setToken($this->getNewAuthToken()); $event['response'] = $event['request']->send(); $event->stopPropagation(); } }