Inheritance: implements Amp\Artax\HttpClient
示例#1
0
 public function render()
 {
     try {
         ob_start();
         $reactor = \Amp\getReactor();
         $client = new Client($reactor);
         $url = sprintf("http://%s/www-status?full&json", $this->domain->getCanonicalDomain());
         $promise = $client->request($url);
         $response = \Amp\wait($promise);
         $headers = ["pool" => "Pool name", "process manager" => "Process manager", "start time" => "Start time", "start since" => "Uptime", "accepted conn" => "Accepted connections", "listen queue" => "Listen queue", "max listen queue" => "Max listen queue", "listen queue len" => "Listen queue length", "idle processes" => "Idle processes", "active processes" => "Active processes", "total processes" => "Total processes", "max active processes" => "Max active processes", "max children reached" => "Max children reached", "slow requests" => "Slow requests"];
         $json = json_decode($response->getBody(), true);
         echo "<table class='table-serverSettings'>";
         echo "<tr><th colspan='2'>Pool info</th></tr>";
         foreach ($headers as $header => $display) {
             echo "<tr><td>";
             echo $display;
             echo "</td><td>";
             echo $json[$header];
             echo "</td></tr>";
         }
         echo "</table>";
         echo "<div style='height: 20px;'></div>";
         echo "<table class='table-serverSettings'>";
         $processHeaders = ["pid", "state", "start since", "requests", "request URI", "content length", "script", "last request cpu", "last request memory"];
         foreach ($processHeaders as $processHeader) {
             echo "<th>";
             echo $processHeader;
             echo "</th>";
         }
         if (isset($json['processes']) && is_array($json['processes'])) {
             foreach ($json['processes'] as $process) {
                 echo "<tr>";
                 foreach ($processHeaders as $processHeader) {
                     echo "<td align='right'>";
                     if (array_key_exists($processHeader, $process)) {
                         $text = $process[$processHeader];
                         $text = str_replace(['/home/github/imagick-demos//imagick-demos', '/home/github/imagick-demos/imagick-demos'], '', $text);
                         $text = ltrim($text, '/');
                         echo $text;
                     } else {
                         echo "-";
                     }
                     echo "</td>";
                 }
                 echo "</tr>";
             }
         }
         echo "</table>";
         echo "<br/>";
         echo "<a href='http://127.0.0.1:9002'>SupervisorD</a>";
         $output = ob_get_contents();
         ob_end_clean();
         return $output;
     } catch (\Exception $e) {
         while (ob_get_level() > 0) {
             ob_end_clean();
         }
         return "Error fetch FPM status: " . $e->getMessage();
     }
 }
示例#2
0
function httpClient() : HttpClient
{
    static $client;
    if (!isset($client)) {
        $client = new HttpClient();
        $client->setAllOptions([HttpClient::OP_DEFAULT_USER_AGENT => Application::USER_AGENT, HttpClient::OP_VERBOSITY => HttpClient::VERBOSE_NONE, HttpClient::OP_AUTO_ENCODING => false]);
    }
    return $client;
}
 private function getReactorAndAPI()
 {
     $reactor = \Amp\reactor();
     $cache = new NullResponseCache();
     $client = new ArtaxClient();
     $client->setOption(ArtaxClient::OP_MS_CONNECT_TIMEOUT, 5000);
     $client->setOption(ArtaxClient::OP_MS_KEEP_ALIVE_TIMEOUT, 1000);
     $githubAPI = new GithubService($client, $reactor, $cache, "Danack/test");
     return [$reactor, $githubAPI];
 }
示例#4
0
 function createResponse()
 {
     ob_start();
     $reactor = \Amp\getReactor();
     $client = new Client($reactor);
     $url = "http://phpimagick.com/www-status?full&json";
     $promise = $client->request($url);
     $response = \Amp\wait($promise);
     //$response = $promise->wait();
     $headers = ["pool" => "Pool name", "process manager" => "Process manager", "start time" => "Start time", "start since" => "Uptime", "accepted conn" => "Accepted connections", "listen queue" => "Listen queue", "max listen queue" => "Max listen queue", "listen queue len" => "Listen queue length", "idle processes" => "Idle processes", "active processes" => "Active processes", "total processes" => "Total processes", "max active processes" => "Max active processes", "max children reached" => "Max children reached", "slow requests" => "Slow requests"];
     $json = json_decode($response->getBody(), true);
     echo "<table>";
     foreach ($headers as $header => $display) {
         echo "<tr><td>";
         echo $display;
         echo "</td><td>";
         echo $json[$header];
         echo "</td></tr>";
     }
     echo "</table>";
     echo "<table>";
     $processHeaders = ["pid", "state", "start time", "start since", "requests", "request duration", "request URI", "content length", "script", "last request cpu", "last request memory"];
     foreach ($processHeaders as $processHeader) {
         echo "<th>";
         echo $processHeader;
         echo "</th>";
     }
     if (isset($json['processes']) && is_array($json['processes'])) {
         foreach ($json['processes'] as $process) {
             echo "<tr>";
             foreach ($processHeaders as $processHeader) {
                 echo "<td align='right'>";
                 if (array_key_exists($processHeader, $process)) {
                     $text = $process[$processHeader];
                     $text = str_replace(['/home/github/imagick-demos//imagick-demos', '/home/github/imagick-demos/imagick-demos'], '', $text);
                     $text = ltrim($text, '/');
                     echo $text;
                 } else {
                     echo "-";
                 }
                 echo "</td>";
             }
             echo "</tr>";
         }
     }
     echo "</table>";
     echo "<br/>";
     echo "<a href='http://127.0.0.1:9002'>SupervisorD</a>";
     $output = ob_get_contents();
     ob_end_clean();
     return new TextResponse($output);
 }
示例#5
0
 public function getAccessTokenFromCode(string $code)
 {
     $body = (new FormBody())->addField("redirect_uri", $this->redirectUri)->addField("client_id", $this->clientId)->addField("client_secret", $this->clientSecret)->addField("code", $code);
     $request = (new Request())->setMethod("POST")->setUri($this->accessTokenUrl)->setBody($body);
     /** @var HttpResponse $response */
     $response = (yield $this->client->request($request));
     $body = $response->getBody();
     parse_str($body, $data);
     if (!isset($data["access_token"])) {
         throw new OAuthException($data["error_description"] ?? $data["error"] ?? "no access token provided");
     }
     return $data["access_token"];
 }
示例#6
0
 /**
  * @param $gauges Gauge[]
  * @param $counters Counter[]
  */
 function send($gauges, $counters)
 {
     $client = new ArtaxClient();
     $client->setAllOptions([ArtaxClient::OP_MS_CONNECT_TIMEOUT => 2000, ArtaxClient::OP_MS_TRANSFER_TIMEOUT => 3000]);
     $request = new Request();
     $request->setUri("https://metrics-api.librato.com/v1/metrics");
     $request->setProtocol('1.1');
     $request->setMethod('POST');
     $request->setHeader("Content-Type", "application/json");
     $auth = base64_encode($this->libratoConfig->getLibratoUsername() . ':' . $this->libratoConfig->getLibratoKey());
     $request->setHeader("Authorization", "Basic {$auth}");
     $data = [];
     //working
     //"{"gauges":[{"name":"Queue.ImagickTaskQueue","value":0,"source":"test.phpimagick.com"}]}"
     if (count($gauges)) {
         $gaugeEntries = [];
         foreach ($gauges as $gauge) {
             $arrayed = $gauge->convertToArray();
             $gaugeEntries = array_merge($gaugeEntries, $arrayed);
         }
         $data["gauges"] = $gaugeEntries;
     }
     if (count($counters)) {
         $counterEntries = [];
         foreach ($counters as $counter) {
             $arrayed = $counter->convertToArray();
             if (is_array($arrayed) == true) {
                 $counterEntries = array_merge($counterEntries, $arrayed);
             } else {
                 $counterEntries[] = $arrayed;
             }
         }
         $data["counters"] = $counterEntries;
     }
     $body = json_encode($data);
     $request->setBody($body);
     var_dump($body);
     try {
         $promise = $client->request($request);
         /** @var $response \Amp\Artax\Response */
         $response = \Amp\wait($promise);
         echo "Status " . $response->getStatus() . "\n";
         echo $response->getBody();
     } catch (SocketException $se) {
         echo "Artax\\SocketExeption" . $se->getMessage();
     }
 }
示例#7
0
 /**
  * @param URLToCheck $urlToCheck
  */
 function fetchURL(URLToCheck $urlToCheck)
 {
     $this->count++;
     $fullURL = $this->siteURL . $urlToCheck->getUrl();
     if ($this->count % 10 == 0) {
         echo "\n";
     }
     echo ".";
     echo "Getting {$fullURL} \n";
     $promise = $this->artaxClient->request($fullURL);
     $analyzeResult = function (\Exception $e = null, Response $response = null) use($urlToCheck, $fullURL) {
         if ($e) {
             echo "Something went wrong for {$fullURL} : " . $e->getMessage() . "\n";
             if ($response) {
                 var_dump($response->getAllHeaders());
             }
             $this->errors++;
             return null;
         }
         $status = $response->getStatus();
         $this->urlsChecked[] = new URLResult($urlToCheck->getUrl(), $status, $urlToCheck->getReferrer(), substr($response->getBody(), 0, 200));
         if ($status != 200 && $status != 202) {
             echo "Status is not ok for " . $urlToCheck->getUrl() . "\n";
             $this->errors++;
             return null;
         }
         $contentTypeHeaders = $response->getHeader('Content-Type');
         if (array_key_exists(0, $contentTypeHeaders) == false) {
             throw new Exception("Content-type header not set.");
         }
         $contentType = $contentTypeHeaders[0];
         $colonPosition = strpos($contentType, ';');
         if ($colonPosition !== false) {
             $contentType = substr($contentType, 0, $colonPosition);
         }
         switch ($contentType) {
             case 'text/html':
                 $body = $response->getBody();
                 $this->analyzeBody($urlToCheck, $body);
                 break;
             case 'application/octet-stream':
             case 'image/gif':
             case 'image/jpeg':
             case 'image/jpg':
             case 'image/vnd.adobe.photoshop':
             case 'image/png':
                 //echo "Image with status - $status\n";
                 //compareImage($urlToCheck, $response->getBody(), $contentType);
                 return null;
             default:
                 throw new \Exception("Unrecognised content-type {$contentType}");
         }
     };
     $promise->when($analyzeResult);
 }
示例#8
0
<?php

use GithubService\GithubArtaxService\GithubService;
use ArtaxServiceBuilder\ResponseCache\NullResponseCache;
use Amp\Artax\Client as ArtaxClient;
use ArtaxServiceBuilder\BadResponseException;
use ArtaxServiceBuilder\Oauth2Token;
use GithubService\Hydrator\HydratorException;
require_once "testBootstrap.php";
$injector = createProvider();
$reactor = \Amp\reactor();
$cache = new NullResponseCache();
$client = new ArtaxClient();
$client->setOption(ArtaxClient::OP_MS_CONNECT_TIMEOUT, 5000);
$client->setOption(ArtaxClient::OP_MS_KEEP_ALIVE_TIMEOUT, 1000);
$githubAPI = new GithubService($client, $reactor, $cache, "Danack/test");
$token = @file_get_contents("../../GithubToken.txt");
$oauthToken = null;
if ($token) {
    $oauthToken = new Oauth2Token($token);
}
try {
    $tagListRequest = $githubAPI->listRepoTags(null, "Danack", "GithubArtaxService");
    $tagList = $tagListRequest->execute();
    foreach ($tagList as $tag) {
        /** @var $tag \GithubService\Model\Tag */
        printf("tag name %s, commmit %s \n", $tag->name, $tag->commit->sha);
    }
    $emojiResult = $githubAPI->listEmojis(null)->execute();
    foreach ($emojiResult->emojis as $emoji) {
        echo $emoji->name . " \n";
示例#9
0
<?php

use Amp\Artax\Client;
require __DIR__ . '/../vendor/autoload.php';
try {
    // Instantiate the HTTP client
    $client = new Client();
    $client->setOption(Client::OP_VERBOSITY, Client::VERBOSE_ALL);
    // Let's build up a custom Request object
    $request = (new Amp\Artax\Request())->setMethod('POST')->setUri('http://httpbin.org/post')->setBody('zanzibar!');
    // Make an asynchronous HTTP request
    $promise = $client->request($request);
    // Client::request() is asynchronous! It doesn't return a response. Instead, it
    // returns a promise to resolve the response at some point in the future when
    // it's finished. Here we use the Amp concurrency framework to synchronously wait
    // for the eventual promise result.
    $response = \Amp\wait($promise);
    // Output the results
    printf("\nHTTP/%s %d %s\n\n------- RESPONSE BODY -------\n%s\n", $response->getProtocol(), $response->getStatus(), $response->getReason(), $response->getBody());
} catch (Amp\Artax\ClientException $e) {
    // If something goes wrong the Promise::wait() call will throw the relevant
    // exception. The Client::request() method itself will never throw.
    echo $e;
}
 public function testMultipartBodyRequest()
 {
     $uri = 'http://httpbin.org/post';
     $client = new Client();
     $field1 = 'test val';
     $file1 = __DIR__ . '/fixture/lorem.txt';
     $file2 = __DIR__ . '/fixture/answer.txt';
     $boundary = 'AaB03x';
     $body = new FormBody($boundary);
     $body->addField('field1', $field1);
     $body->addFile('file1', $file1);
     $body->addFile('file2', $file2);
     $request = (new Request())->setBody($body)->setUri('http://httpbin.org/post')->setMethod('POST');
     $promise = $client->request($request);
     $response = \Amp\wait($promise);
     $this->assertEquals(200, $response->getStatus());
     $result = json_decode($response->getBody(), true);
     $this->assertEquals($field1, $result['form']['field1']);
     $this->assertEquals(file_get_contents($file1), $result['files']['file1']);
     $this->assertEquals(file_get_contents($file2), $result['files']['file2']);
     $this->assertEquals('multipart/form-data; boundary=' . $boundary, $result['headers']['Content-Type']);
 }
示例#11
0
 function prepareArtaxClient(ArtaxClient $client, Injector $provider)
 {
     $client->setOption(ArtaxClient::OP_MS_CONNECT_TIMEOUT, 25);
 }
示例#12
0
 /**
  * Constructs a default HTTP client.
  *
  * @return Client
  */
 private function buildClient()
 {
     $client = new Client(new NullCookieJar());
     $client->setOption(Client::OP_DEFAULT_USER_AGENT, "kelunik/acme");
     return $client;
 }
示例#13
0
 /**
  * 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;
 }
示例#14
0
 /**
  * Handles all hooks.
  *
  * @param Request  $request HTTP request
  * @param Response $response HTTP response
  * @param array    $args URL args
  */
 public function handle(Request $request, Response $response, array $args)
 {
     $response->setHeader("content-type", "text/plain");
     $token = $request->getQueryVars()["token"] ?? "";
     if (!$token || !is_string($token)) {
         $response->setStatus(401);
         $response->send("Failure: No token was provided.");
         return;
     }
     // use @ so we don't have to check for invalid strings manually
     $token = (string) @hex2bin($token);
     $hook = (yield $this->hookRepository->get($args["id"]));
     if (!$hook) {
         $response->setStatus(404);
         $response->send("Failure: Hook does not exist.");
         return;
     }
     if (!hash_equals($hook->token, $token)) {
         $response->setStatus(403);
         $response->send("Failure: Provided token doesn't match.");
         return;
     }
     $name = $args["service"];
     if (!isset($this->services[$name])) {
         $response->setStatus(404);
         $response->send("Failure: Unknown service.");
         return;
     }
     $contentType = strtok($request->getHeader("content-type"), ";");
     $body = (yield $request->getBody());
     switch ($contentType) {
         case "application/json":
             $payload = json_decode($body);
             break;
         case "application/x-www-form-urlencoded":
             parse_str($body, $payload);
             $payload = json_decode(json_encode($payload));
             break;
         default:
             $response->setStatus(415);
             $response->send("Failure: Content-type not supported.");
             return;
     }
     $service = $this->services[$name];
     $headers = $request->getAllHeaders();
     $event = $service->getEventName($headers, $payload);
     if (!isset($this->schemas[$name][$event])) {
         $response->setStatus(400);
         $response->send("Failure: Event not supported.");
         return;
     }
     $schema = $this->schemas[$name][$event];
     $this->validator->reset();
     $this->validator->check($payload, $schema);
     if (!$this->validator->isValid()) {
         $errors = $this->validator->getErrors();
         $errors = array_reduce($errors, function (string $carry, array $item) : string {
             if ($item["property"]) {
                 return $carry . sprintf("\n%s: %s", $item["property"], $item["message"]);
             } else {
                 return $carry . "\n" . $item["message"];
             }
         }, "");
         $response->setStatus(400);
         $response->send("Failure: Payload validation failed." . $errors);
         return;
     }
     $message = $service->handle($headers, $payload);
     try {
         if ($message) {
             $req = (new HttpRequest())->setMethod("PUT")->setUri($this->config["api"] . "/messages")->setHeader("authorization", "Basic " . base64_encode("{$this->config['user_id']}:{$this->config['token']}"))->setBody(json_encode(["room_id" => $hook->room_id, "text" => $message->getText(), "data" => $message->getData()]));
             $resp = (yield $this->http->request($req));
             if (intval($resp->getStatus() / 100) !== 2) {
                 $message = "API request failed: " . $resp->getStatus();
                 if ($resp->getBody()) {
                     $message .= "\n" . $resp->getBody();
                 }
                 throw new Exception($message);
             }
         }
         $response->send("Success: " . ($message ? "Message sent." : "Message skipped."));
     } catch (Exception $e) {
         $response->setStatus(500);
         $response->send("Failure: Couldn't persist message.");
     }
 }
 * to perform HTTP requests in a true parallel (but not multi-threaded) way.
 */
$autoloader = (require __DIR__ . '/../vendor/autoload.php');
use Amp\Artax\Client as ArtaxClient;
use Amp\Artax\Response;
use ArtaxServiceBuilder\ResponseCache\NullResponseCache;
use GithubService\AuthToken\NullToken;
use GithubService\GithubArtaxService\GithubService;
use GithubService\Model\Tags;
// Create the appropriate Amp reactor for your system. This depends on
// which extensions you have loaded:
// uv extension -  UvReactor;
// libevent extension - LibeventReactor;
// otherwise a NativeReactor is used.
$reactor = \Amp\reactor();
$artaxClient = new ArtaxClient();
// The reactor keeps running while the socket is open. Set a short
// timeout to avoid waiting around too long
$artaxClient->setOption(\Amp\Artax\Client::OP_MS_KEEP_ALIVE_TIMEOUT, 1);
// Create the GithubService with the prepared client
$github = new GithubService($artaxClient, $reactor, new NullResponseCache(), 'Danack/GithubArtaxService');
//Get the first page of data
$command = $github->listRepoTags(new NullToken(), 'php', 'php-src');
$listRepoTagsCallback = function (Exception $exception = null, Tags $repoTags, Response $response = null) use($github) {
    if ($exception) {
        echo "An error occurred: " . $exception->getMessage();
        return;
    }
    echo "Tags on first page:\n";
    foreach ($repoTags as $repoTag) {
        echo "Found tag: " . $repoTag->name . "\n";