MultiRequest.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Jaeger <JaegerCode@gmail.com>
  5. * Date: 18/12/10
  6. * Time: 下午6:04
  7. */
  8. namespace Jaeger;
  9. use GuzzleHttp\Client;
  10. use Closure;
  11. use GuzzleHttp\Pool;
  12. use GuzzleHttp\Psr7\Request;
  13. class MultiRequest
  14. {
  15. protected $client;
  16. protected $headers = [];
  17. protected $options = [];
  18. protected $successCallback;
  19. protected $errorCallback;
  20. protected $urls = [];
  21. protected $method;
  22. protected $concurrency = 5;
  23. public function __construct(Client $client)
  24. {
  25. $this->client = $client;
  26. $this->headers = [
  27. 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
  28. ];
  29. }
  30. public static function newRequest(Client $client)
  31. {
  32. $request = new self($client);
  33. return $request;
  34. }
  35. public function withHeaders($headers)
  36. {
  37. $this->headers = array_merge($this->headers,$headers);
  38. return $this;
  39. }
  40. public function withOptions($options)
  41. {
  42. $this->options = $options;
  43. return $this;
  44. }
  45. public function concurrency($concurrency)
  46. {
  47. $this->concurrency = $concurrency;
  48. return $this;
  49. }
  50. public function success(Closure $success)
  51. {
  52. $this->successCallback = $success;
  53. return $this;
  54. }
  55. public function error(Closure $error)
  56. {
  57. $this->errorCallback = $error;
  58. return $this;
  59. }
  60. public function urls(array $urls)
  61. {
  62. $this->urls = $urls;
  63. return $this;
  64. }
  65. public function get()
  66. {
  67. $this->method = 'GET';
  68. $this->send();
  69. }
  70. public function post()
  71. {
  72. $this->method = 'POST';
  73. $this->send();
  74. }
  75. protected function send()
  76. {
  77. $client = $this->client;
  78. $requests = function ($urls) use($client){
  79. foreach ($urls as $url) {
  80. if (is_string($url)) {
  81. yield new Request($this->method,$url,$this->headers);
  82. } else {
  83. yield $url;
  84. }
  85. }
  86. };
  87. $pool = new Pool($client, $requests($this->urls), [
  88. 'concurrency' => $this->concurrency,
  89. 'fulfilled' => $this->successCallback,
  90. 'rejected' => $this->errorCallback,
  91. 'options' => $this->options
  92. ]);
  93. $promise = $pool->promise();
  94. $promise->wait();
  95. }
  96. }