[ Index ]

PHP Cross Reference of phpBB-3.2.11-deutsch

title

Body

[close]

/vendor/guzzlehttp/guzzle/src/ -> Client.php (source)

   1  <?php
   2  namespace GuzzleHttp;
   3  
   4  use GuzzleHttp\Event\HasEmitterTrait;
   5  use GuzzleHttp\Message\MessageFactory;
   6  use GuzzleHttp\Message\MessageFactoryInterface;
   7  use GuzzleHttp\Message\RequestInterface;
   8  use GuzzleHttp\Message\FutureResponse;
   9  use GuzzleHttp\Ring\Core;
  10  use GuzzleHttp\Ring\Future\FutureInterface;
  11  use GuzzleHttp\Exception\RequestException;
  12  use React\Promise\FulfilledPromise;
  13  use React\Promise\RejectedPromise;
  14  
  15  /**
  16   * HTTP client
  17   */
  18  class Client implements ClientInterface
  19  {
  20      use HasEmitterTrait;
  21  
  22      /** @var MessageFactoryInterface Request factory used by the client */
  23      private $messageFactory;
  24  
  25      /** @var Url Base URL of the client */
  26      private $baseUrl;
  27  
  28      /** @var array Default request options */
  29      private $defaults;
  30  
  31      /** @var callable Request state machine */
  32      private $fsm;
  33  
  34      /**
  35       * Clients accept an array of constructor parameters.
  36       *
  37       * Here's an example of creating a client using an URI template for the
  38       * client's base_url and an array of default request options to apply
  39       * to each request:
  40       *
  41       *     $client = new Client([
  42       *         'base_url' => [
  43       *              'http://www.foo.com/{version}/',
  44       *              ['version' => '123']
  45       *          ],
  46       *         'defaults' => [
  47       *             'timeout'         => 10,
  48       *             'allow_redirects' => false,
  49       *             'proxy'           => '192.168.16.1:10'
  50       *         ]
  51       *     ]);
  52       *
  53       * @param array $config Client configuration settings
  54       *     - base_url: Base URL of the client that is merged into relative URLs.
  55       *       Can be a string or an array that contains a URI template followed
  56       *       by an associative array of expansion variables to inject into the
  57       *       URI template.
  58       *     - handler: callable RingPHP handler used to transfer requests
  59       *     - message_factory: Factory used to create request and response object
  60       *     - defaults: Default request options to apply to each request
  61       *     - emitter: Event emitter used for request events
  62       *     - fsm: (internal use only) The request finite state machine. A
  63       *       function that accepts a transaction and optional final state. The
  64       *       function is responsible for transitioning a request through its
  65       *       lifecycle events.
  66       */
  67      public function __construct(array $config = [])
  68      {
  69          $this->configureBaseUrl($config);
  70          $this->configureDefaults($config);
  71  
  72          if (isset($config['emitter'])) {
  73              $this->emitter = $config['emitter'];
  74          }
  75  
  76          $this->messageFactory = isset($config['message_factory'])
  77              ? $config['message_factory']
  78              : new MessageFactory();
  79  
  80          if (isset($config['fsm'])) {
  81              $this->fsm = $config['fsm'];
  82          } else {
  83              if (isset($config['handler'])) {
  84                  $handler = $config['handler'];
  85              } elseif (isset($config['adapter'])) {
  86                  $handler = $config['adapter'];
  87              } else {
  88                  $handler = Utils::getDefaultHandler();
  89              }
  90              $this->fsm = new RequestFsm($handler, $this->messageFactory);
  91          }
  92      }
  93  
  94      public function getDefaultOption($keyOrPath = null)
  95      {
  96          return $keyOrPath === null
  97              ? $this->defaults
  98              : Utils::getPath($this->defaults, $keyOrPath);
  99      }
 100  
 101      public function setDefaultOption($keyOrPath, $value)
 102      {
 103          Utils::setPath($this->defaults, $keyOrPath, $value);
 104      }
 105  
 106      public function getBaseUrl()
 107      {
 108          return (string) $this->baseUrl;
 109      }
 110  
 111      public function createRequest($method, $url = null, array $options = [])
 112      {
 113          $options = $this->mergeDefaults($options);
 114          // Use a clone of the client's emitter
 115          $options['config']['emitter'] = clone $this->getEmitter();
 116          $url = $url || (is_string($url) && strlen($url))
 117              ? $this->buildUrl($url)
 118              : (string) $this->baseUrl;
 119  
 120          return $this->messageFactory->createRequest($method, $url, $options);
 121      }
 122  
 123      public function get($url = null, $options = [])
 124      {
 125          return $this->send($this->createRequest('GET', $url, $options));
 126      }
 127  
 128      public function head($url = null, array $options = [])
 129      {
 130          return $this->send($this->createRequest('HEAD', $url, $options));
 131      }
 132  
 133      public function delete($url = null, array $options = [])
 134      {
 135          return $this->send($this->createRequest('DELETE', $url, $options));
 136      }
 137  
 138      public function put($url = null, array $options = [])
 139      {
 140          return $this->send($this->createRequest('PUT', $url, $options));
 141      }
 142  
 143      public function patch($url = null, array $options = [])
 144      {
 145          return $this->send($this->createRequest('PATCH', $url, $options));
 146      }
 147  
 148      public function post($url = null, array $options = [])
 149      {
 150          return $this->send($this->createRequest('POST', $url, $options));
 151      }
 152  
 153      public function options($url = null, array $options = [])
 154      {
 155          return $this->send($this->createRequest('OPTIONS', $url, $options));
 156      }
 157  
 158      public function send(RequestInterface $request)
 159      {
 160          $isFuture = $request->getConfig()->get('future');
 161          $trans = new Transaction($this, $request, $isFuture);
 162          $fn = $this->fsm;
 163  
 164          try {
 165              $fn($trans);
 166              if ($isFuture) {
 167                  // Turn the normal response into a future if needed.
 168                  return $trans->response instanceof FutureInterface
 169                      ? $trans->response
 170                      : new FutureResponse(new FulfilledPromise($trans->response));
 171              }
 172              // Resolve deep futures if this is not a future
 173              // transaction. This accounts for things like retries
 174              // that do not have an immediate side-effect.
 175              while ($trans->response instanceof FutureInterface) {
 176                  $trans->response = $trans->response->wait();
 177              }
 178              return $trans->response;
 179          } catch (\Exception $e) {
 180              if ($isFuture) {
 181                  // Wrap the exception in a promise
 182                  return new FutureResponse(new RejectedPromise($e));
 183              }
 184              throw RequestException::wrapException($trans->request, $e);
 185          } catch (\TypeError $error) {
 186              $exception = new \Exception($error->getMessage(), $error->getCode(), $error);
 187              if ($isFuture) {
 188                  // Wrap the exception in a promise
 189                  return new FutureResponse(new RejectedPromise($exception));
 190              }
 191              throw RequestException::wrapException($trans->request, $exception);
 192          }
 193      }
 194  
 195      /**
 196       * Get an array of default options to apply to the client
 197       *
 198       * @return array
 199       */
 200      protected function getDefaultOptions()
 201      {
 202          $settings = [
 203              'allow_redirects' => true,
 204              'exceptions'      => true,
 205              'decode_content'  => true,
 206              'verify'          => true
 207          ];
 208  
 209          // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
 210          // We can only trust the HTTP_PROXY environment variable in a CLI
 211          // process due to the fact that PHP has no reliable mechanism to
 212          // get environment variables that start with "HTTP_".
 213          if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) {
 214              $settings['proxy']['http'] = getenv('HTTP_PROXY');
 215          }
 216  
 217          if ($proxy = getenv('HTTPS_PROXY')) {
 218              $settings['proxy']['https'] = $proxy;
 219          }
 220  
 221          return $settings;
 222      }
 223  
 224      /**
 225       * Expand a URI template and inherit from the base URL if it's relative
 226       *
 227       * @param string|array $url URL or an array of the URI template to expand
 228       *                          followed by a hash of template varnames.
 229       * @return string
 230       * @throws \InvalidArgumentException
 231       */
 232      private function buildUrl($url)
 233      {
 234          // URI template (absolute or relative)
 235          if (!is_array($url)) {
 236              return strpos($url, '://')
 237                  ? (string) $url
 238                  : (string) $this->baseUrl->combine($url);
 239          }
 240  
 241          if (!isset($url[1])) {
 242              throw new \InvalidArgumentException('You must provide a hash of '
 243                  . 'varname options in the second element of a URL array.');
 244          }
 245  
 246          // Absolute URL
 247          if (strpos($url[0], '://')) {
 248              return Utils::uriTemplate($url[0], $url[1]);
 249          }
 250  
 251          // Combine the relative URL with the base URL
 252          return (string) $this->baseUrl->combine(
 253              Utils::uriTemplate($url[0], $url[1])
 254          );
 255      }
 256  
 257      private function configureBaseUrl(&$config)
 258      {
 259          if (!isset($config['base_url'])) {
 260              $this->baseUrl = new Url('', '');
 261          } elseif (!is_array($config['base_url'])) {
 262              $this->baseUrl = Url::fromString($config['base_url']);
 263          } elseif (count($config['base_url']) < 2) {
 264              throw new \InvalidArgumentException('You must provide a hash of '
 265                  . 'varname options in the second element of a base_url array.');
 266          } else {
 267              $this->baseUrl = Url::fromString(
 268                  Utils::uriTemplate(
 269                      $config['base_url'][0],
 270                      $config['base_url'][1]
 271                  )
 272              );
 273              $config['base_url'] = (string) $this->baseUrl;
 274          }
 275      }
 276  
 277      private function configureDefaults($config)
 278      {
 279          if (!isset($config['defaults'])) {
 280              $this->defaults = $this->getDefaultOptions();
 281          } else {
 282              $this->defaults = array_replace(
 283                  $this->getDefaultOptions(),
 284                  $config['defaults']
 285              );
 286          }
 287  
 288          // Add the default user-agent header
 289          if (!isset($this->defaults['headers'])) {
 290              $this->defaults['headers'] = [
 291                  'User-Agent' => Utils::getDefaultUserAgent()
 292              ];
 293          } elseif (!Core::hasHeader($this->defaults, 'User-Agent')) {
 294              // Add the User-Agent header if one was not already set
 295              $this->defaults['headers']['User-Agent'] = Utils::getDefaultUserAgent();
 296          }
 297      }
 298  
 299      /**
 300       * Merges default options into the array passed by reference.
 301       *
 302       * @param array $options Options to modify by reference
 303       *
 304       * @return array
 305       */
 306      private function mergeDefaults($options)
 307      {
 308          $defaults = $this->defaults;
 309  
 310          // Case-insensitively merge in default headers if both defaults and
 311          // options have headers specified.
 312          if (!empty($defaults['headers']) && !empty($options['headers'])) {
 313              // Create a set of lowercased keys that are present.
 314              $lkeys = [];
 315              foreach (array_keys($options['headers']) as $k) {
 316                  $lkeys[strtolower($k)] = true;
 317              }
 318              // Merge in lowercase default keys when not present in above set.
 319              foreach ($defaults['headers'] as $key => $value) {
 320                  if (!isset($lkeys[strtolower($key)])) {
 321                      $options['headers'][$key] = $value;
 322                  }
 323              }
 324              // No longer need to merge in headers.
 325              unset($defaults['headers']);
 326          }
 327  
 328          $result = array_replace_recursive($defaults, $options);
 329          foreach ($options as $k => $v) {
 330              if ($v === null) {
 331                  unset($result[$k]);
 332              }
 333          }
 334  
 335          return $result;
 336      }
 337  
 338      /**
 339       * @deprecated Use {@see GuzzleHttp\Pool} instead.
 340       * @see GuzzleHttp\Pool
 341       */
 342      public function sendAll($requests, array $options = [])
 343      {
 344          Pool::send($this, $requests, $options);
 345      }
 346  
 347      /**
 348       * @deprecated Use GuzzleHttp\Utils::getDefaultHandler
 349       */
 350      public static function getDefaultHandler()
 351      {
 352          return Utils::getDefaultHandler();
 353      }
 354  
 355      /**
 356       * @deprecated Use GuzzleHttp\Utils::getDefaultUserAgent
 357       */
 358      public static function getDefaultUserAgent()
 359      {
 360          return Utils::getDefaultUserAgent();
 361      }
 362  }


Generated: Wed Nov 11 20:33:01 2020 Cross-referenced by PHPXref 0.7.1