ClientFactory.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Drupal\Core\Http;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Site\Settings;
  5. use GuzzleHttp\Client;
  6. use GuzzleHttp\HandlerStack;
  7. /**
  8. * Helper class to construct a HTTP client with Drupal specific config.
  9. */
  10. class ClientFactory {
  11. /**
  12. * The handler stack.
  13. *
  14. * @var \GuzzleHttp\HandlerStack
  15. */
  16. protected $stack;
  17. /**
  18. * Constructs a new ClientFactory instance.
  19. *
  20. * @param \GuzzleHttp\HandlerStack $stack
  21. * The handler stack.
  22. */
  23. public function __construct(HandlerStack $stack) {
  24. $this->stack = $stack;
  25. }
  26. /**
  27. * Constructs a new client object from some configuration.
  28. *
  29. * @param array $config
  30. * The config for the client.
  31. *
  32. * @return \GuzzleHttp\Client
  33. * The HTTP client.
  34. */
  35. public function fromOptions(array $config = []) {
  36. $default_config = [
  37. // Security consideration: we must not use the certificate authority
  38. // file shipped with Guzzle because it can easily get outdated if a
  39. // certificate authority is hacked. Instead, we rely on the certificate
  40. // authority file provided by the operating system which is more likely
  41. // going to be updated in a timely fashion. This overrides the default
  42. // path to the pem file bundled with Guzzle.
  43. 'verify' => TRUE,
  44. 'timeout' => 30,
  45. 'headers' => [
  46. 'User-Agent' => 'Drupal/' . \Drupal::VERSION . ' (+https://www.drupal.org/) ' . \GuzzleHttp\default_user_agent(),
  47. ],
  48. 'handler' => $this->stack,
  49. // Security consideration: prevent Guzzle from using environment variables
  50. // to configure the outbound proxy.
  51. 'proxy' => [
  52. 'http' => NULL,
  53. 'https' => NULL,
  54. 'no' => [],
  55. ],
  56. ];
  57. $config = NestedArray::mergeDeep($default_config, Settings::get('http_client_config', []), $config);
  58. return new Client($config);
  59. }
  60. }