Exemple #1
0
 public function fetch(string $screenName)
 {
     $params = ['screen_name' => $screenName, 'include_entities' => 'false'];
     $request = (new Request())->setMethod('GET')->setUri('https://api.twitter.com/1.1/users/show.json?' . http_build_query($params));
     $authorizedHeader = $this->oauthHeaderGenerator->generateHeader($request);
     $request->setHeader('Authorization', $authorizedHeader);
     $responsePromise = httpClient()->request($request);
     /** @var Response $response */
     // TODO handle scenario when reactor is already running when this is called
     $response = wait($responsePromise);
     if ($response->getStatus() === 200) {
         $data = json_decode($response->getBody(), true);
         return $data['id_str'];
     } else {
         return false;
     }
 }
 public function testHandleCommandWhenMatches()
 {
     $event = $this->getMockBuilder(MessageEvent::class)->disableOriginalConstructor()->getMock();
     $event->expects($this->once())->method('getId')->willReturn(721);
     $userCommand = $this->getMockBuilder(Command::class)->disableOriginalConstructor()->getMock();
     $userCommand->expects($this->once())->method('getCommandName')->will($this->returnValue('foo'));
     $userCommand->expects($this->once())->method('getEvent')->willReturn($event);
     $userCommand->expects($this->once())->method('getUserId')->willReturn(14);
     $registeredCommand = $this->getMock(BuiltInCommand::class);
     $registeredCommand->expects($this->once())->method('getCommandNames')->will($this->returnValue(['foo']));
     $registeredCommand->expects($this->once())->method('handleCommand')->with($this->isInstanceOf($userCommand))->willReturn(new Success());
     $logger = $this->getMock(Logger::class);
     $logger->expects($this->exactly(2))->method('log')->withConsecutive([Level::DEBUG, 'Registering command name \'foo\' with built in command ' . get_class($registeredCommand)], [Level::DEBUG, 'Passing event #721 to built in command handler ' . get_class($registeredCommand)]);
     $banStorage = $this->getMock(BanStorage::class);
     $banStorage->expects($this->once())->method('isBanned')->willReturn(new Success(false));
     $builtInCommandManager = new BuiltInActionManager($banStorage, $logger);
     $builtInCommandManager->registerCommand($registeredCommand);
     $this->assertNull(wait($builtInCommandManager->handleCommand($userCommand)));
 }
 /**
  * Helper method to facilitate json rpc requests using the Amp\Artax client
  *
  * @param string $method    The rpc method to call
  * @param array  $params Associative array of rpc method arguments to send in the header (not auth arguments)
  *
  * @throws HTTPException When something goes wrong with the HTTP call
  *
  * @return Response The HTTP response containing headers / body ready for validation / parsing
  */
 private function performRPCRequest($method, array $params)
 {
     $client = $this->client;
     $request = new Request();
     if (empty($this->sessionCookie)) {
         $request->setUri(sprintf('%s:%s/json', $this->connectionArgs['host'], $this->connectionArgs['port']));
         $request->setMethod('POST');
         $request->setAllHeaders(array('Content-Type' => 'application/json; charset=utf-8'));
         $request->setBody(json_encode(array('method' => self::METHOD_AUTH, 'params' => array($this->connectionArgs['password']), 'id' => rand())));
         $promise = $client->request($request);
         /** @var Amp\Artax\Response $response */
         $response = Amp\wait($promise);
         if ($response->hasHeader('Set-Cookie')) {
             $cookieHeader = $response->getHeader('Set-Cookie');
             preg_match_all('/_session_id=(.*?);/', $cookieHeader[0], $matches);
             $this->sessionCookie = isset($matches[0][0]) ? $matches[0][0] : '';
         } else {
             throw new HTTPException("Response from torrent client did not return a Set-Cookie header");
         }
     }
     $request = new Request();
     $request->setUri(sprintf('%s:%s/json', $this->connectionArgs['host'], $this->connectionArgs['port']));
     $request->setMethod('POST');
     $request->setAllHeaders(array('Content-Type' => 'application/json; charset=utf-8', 'Cookie' => $this->sessionCookie));
     $body = array('method' => $method, 'params' => $params, 'id' => rand());
     $request->setBody(json_encode($body));
     $promise = $client->request($request);
     /** @var Amp\Artax\Response $response */
     $response = Amp\wait($promise);
     if ($response->getStatus() === 200) {
         $body = $response->getBody();
         $isJson = function () use($body) {
             json_decode($body);
             return json_last_error() === JSON_ERROR_NONE;
         };
         if ($isJson()) {
             return $response;
         } else {
             throw new HTTPException(sprintf('"%s" did not get back a JSON response body, got "%s" instead', $method, print_r($response->getBody(), true)));
         }
     } else {
         throw new HTTPException(sprintf('"%s" expected 200 response, got "%s" instead, reason: "%s"', $method, $response->getStatus(), $response->getReason()));
     }
 }
 /**
  * Do the request (enabled multiple attempts)
  *
  * @param ArtaxMessage $request
  * @param int          $attempt
  *
  * @return ArtaxResponse|mixed
  * @throws AmpSocketException
  * @throws NbsockSocketException
  * @throws null
  */
 private function doRequest(ArtaxMessage $request, $attempt = 1)
 {
     $artaxClient = new ArtaxClient();
     $artaxClient->setOption(ArtaxClient::OP_MS_CONNECT_TIMEOUT, self::OP_MS_CONNECT_TIMEOUT);
     // connection timeout
     try {
         /** @var ArtaxResponse $ampResponse */
         $ampResponse = Amp\wait($artaxClient->request($request));
     } catch (\Exception $exception) {
         if ($exception instanceof AmpSocketException || $exception instanceof AmpResolutionException || $exception instanceof NbsockSocketException) {
             // try a second attempt
             if ($attempt < self::REQUEST_MAX_ATTEMPTS) {
                 return $this->doRequest($request, $attempt + 1);
             }
             // use seeds if we are offline (SocketException mean that we are offline)
             if ($seeds = $this->findSeeds()) {
                 return $seeds;
             }
         }
         throw $exception;
     }
     return $ampResponse;
 }