StreamContextFactory.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. /**
  13. * Allows the creation of a basic context supporting http proxy
  14. *
  15. * @author Jordan Alliot <jordan.alliot@gmail.com>
  16. */
  17. final class StreamContextFactory
  18. {
  19. private static $context;
  20. /**
  21. * Creates a context supporting HTTP proxies
  22. *
  23. * @return resource Default context
  24. * @throws \RuntimeException if https proxy required and OpenSSL uninstalled
  25. */
  26. public static function getContext()
  27. {
  28. if (null !== self::$context) {
  29. return self::$context;
  30. }
  31. // Handle system proxy
  32. $params = array('http' => array());
  33. if (isset($_SERVER['HTTP_PROXY']) || isset($_SERVER['http_proxy'])) {
  34. // Some systems seem to rely on a lowercased version instead...
  35. $proxy = isset($_SERVER['HTTP_PROXY']) ? $_SERVER['HTTP_PROXY'] : $_SERVER['http_proxy'];
  36. // http(s):// is not supported in proxy
  37. $proxy = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $proxy);
  38. if (0 === strpos($proxy, 'ssl:') && !extension_loaded('openssl')) {
  39. throw new \RuntimeException('You must enable the openssl extension to use a proxy over https');
  40. }
  41. $params['http'] = array(
  42. 'proxy' => $proxy,
  43. 'request_fulluri' => true,
  44. );
  45. }
  46. return self::$context = stream_context_create($params);
  47. }
  48. }