Overview

Namespaces

  • Contrib
    • Bundle
      • CoverallsBundle
        • Console
        • Entity
      • CoverallsV1Bundle
        • Api
        • Collector
        • Command
        • Config
        • Entity
          • Git
    • Component
      • File
      • Log
      • System
        • Git
  • Guzzle
    • Batch
      • Exception
    • Cache
    • Common
      • Exception
    • Http
      • Curl
      • Exception
      • Message
      • QueryAggregator
    • Inflection
    • Iterator
    • Log
    • Parser
      • Cookie
      • Message
      • UriTemplate
      • Url
    • Plugin
      • Async
      • Backoff
      • Cache
      • Cookie
        • CookieJar
        • Exception
      • CurlAuth
      • ErrorResponse
        • Exception
      • History
      • Log
      • Md5
      • Mock
      • Oauth
    • Service
      • Builder
      • Command
        • Factory
        • LocationVisitor
          • Request
          • Response
      • Description
      • Exception
      • Resource
    • Stream
  • PHP
  • Psr
    • Log
  • Symfony
    • Component
      • Config
        • Definition
          • Builder
          • Exception
        • Exception
        • Loader
        • Resource
        • Util
      • Console
        • Command
        • Formatter
        • Helper
        • Input
        • Output
        • Tester
      • EventDispatcher
        • Debug
      • Finder
        • Adapter
        • Comparator
        • Exception
        • Expression
        • Iterator
        • Shell
      • Stopwatch
      • Yaml
        • Exception

Classes

  • AbstractEntityBodyDecorator
  • CachingEntityBody
  • Client
  • EntityBody
  • IoEmittingEntityBody
  • Mimetypes
  • QueryString
  • ReadLimitEntityBody
  • RedirectPlugin
  • Url

Interfaces

  • ClientInterface
  • EntityBodyInterface
  • Overview
  • Namespace
  • Class
  • Tree
  • Todo
  1: <?php
  2: 
  3: namespace Guzzle\Http;
  4: 
  5: use Guzzle\Common\Collection;
  6: use Guzzle\Common\AbstractHasDispatcher;
  7: use Guzzle\Common\Exception\ExceptionCollection;
  8: use Guzzle\Common\Exception\InvalidArgumentException;
  9: use Guzzle\Common\Exception\RuntimeException;
 10: use Guzzle\Common\Version;
 11: use Guzzle\Parser\ParserRegistry;
 12: use Guzzle\Parser\UriTemplate\UriTemplateInterface;
 13: use Guzzle\Http\Message\RequestInterface;
 14: use Guzzle\Http\Message\RequestFactory;
 15: use Guzzle\Http\Message\RequestFactoryInterface;
 16: use Guzzle\Http\Curl\CurlMultiInterface;
 17: use Guzzle\Http\Curl\CurlMultiProxy;
 18: use Guzzle\Http\Curl\CurlHandle;
 19: use Guzzle\Http\Curl\CurlVersion;
 20: 
 21: /**
 22:  * HTTP client
 23:  */
 24: class Client extends AbstractHasDispatcher implements ClientInterface
 25: {
 26:     const REQUEST_PARAMS = 'request.params';
 27:     const CURL_OPTIONS = 'curl.options';
 28:     const SSL_CERT_AUTHORITY = 'ssl.certificate_authority';
 29:     const DISABLE_REDIRECTS = RedirectPlugin::DISABLE;
 30: 
 31:     /**
 32:      * @var Collection Default HTTP headers to set on each request
 33:      */
 34:     protected $defaultHeaders;
 35: 
 36:     /**
 37:      * @var string The user agent string to set on each request
 38:      */
 39:     protected $userAgent;
 40: 
 41:     /**
 42:      * @var Collection Parameter object holding configuration data
 43:      */
 44:     private $config;
 45: 
 46:     /**
 47:      * @var Url Base URL of the client
 48:      */
 49:     private $baseUrl;
 50: 
 51:     /**
 52:      * @var CurlMultiInterface CurlMulti object used internally
 53:      */
 54:     private $curlMulti;
 55: 
 56:     /**
 57:      * @var UriTemplateInterface URI template owned by the client
 58:      */
 59:     private $uriTemplate;
 60: 
 61:     /**
 62:      * @var RequestFactoryInterface Request factory used by the client
 63:      */
 64:     protected $requestFactory;
 65: 
 66:     /**
 67:      * {@inheritdoc}
 68:      */
 69:     public static function getAllEvents()
 70:     {
 71:         return array(self::CREATE_REQUEST);
 72:     }
 73: 
 74:     /**
 75:      * Client constructor
 76:      *
 77:      * @param string           $baseUrl Base URL of the web service
 78:      * @param array|Collection $config  Configuration settings
 79:      */
 80:     public function __construct($baseUrl = '', $config = null)
 81:     {
 82:         $this->setConfig($config ?: new Collection());
 83:         $this->initSsl();
 84:         $this->setBaseUrl($baseUrl);
 85:         $this->defaultHeaders = new Collection();
 86:         $this->setRequestFactory(RequestFactory::getInstance());
 87: 
 88:         // Redirect by default, but allow for redirects to be globally disabled on a client
 89:         if (!$this->config->get(self::DISABLE_REDIRECTS)) {
 90:             $this->addSubscriber(new RedirectPlugin());
 91:         }
 92: 
 93:         // Set the default User-Agent on the client
 94:         $this->userAgent = $this->getDefaultUserAgent();
 95:     }
 96: 
 97:     /**
 98:      * {@inheritdoc}
 99:      */
100:     final public function setConfig($config)
101:     {
102:         // Set the configuration object
103:         if ($config instanceof Collection) {
104:             $this->config = $config;
105:         } elseif (is_array($config)) {
106:             $this->config = new Collection($config);
107:         } else {
108:             throw new InvalidArgumentException(
109:                 'Config must be an array or Collection'
110:             );
111:         }
112: 
113:         return $this;
114:     }
115: 
116:     /**
117:      * {@inheritdoc}
118:      */
119:     final public function getConfig($key = false)
120:     {
121:         return $key ? $this->config->get($key) : $this->config;
122:     }
123: 
124:     /**
125:      * {@inheritdoc}
126:      */
127:     final public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2)
128:     {
129:         $opts = $this->config->get(self::CURL_OPTIONS) ?: array();
130: 
131:         if ($certificateAuthority === true) {
132:             // use bundled CA bundle, set secure defaults
133:             $opts[CURLOPT_CAINFO] = __DIR__ . '/Resources/cacert.pem';
134:             $opts[CURLOPT_SSL_VERIFYPEER] = true;
135:             $opts[CURLOPT_SSL_VERIFYHOST] = 2;
136:         } elseif ($certificateAuthority === false) {
137:             unset($opts[CURLOPT_CAINFO]);
138:             $opts[CURLOPT_SSL_VERIFYPEER] = false;
139:             $opts[CURLOPT_SSL_VERIFYHOST] = 2;
140:         } elseif ($verifyPeer !== true && $verifyPeer !== false && $verifyPeer !== 1 && $verifyPeer !== 0) {
141:             throw new InvalidArgumentException('verifyPeer must be 1, 0 or boolean');
142:         } elseif ($verifyHost !== 0 && $verifyHost !== 1 && $verifyHost !== 2) {
143:             throw new InvalidArgumentException('verifyHost must be 0, 1 or 2');
144:         } else {
145:             $opts[CURLOPT_SSL_VERIFYPEER] = $verifyPeer;
146:             $opts[CURLOPT_SSL_VERIFYHOST] = $verifyHost;
147:             if (is_file($certificateAuthority)) {
148:                 unset($opts[CURLOPT_CAPATH]);
149:                 $opts[CURLOPT_CAINFO] = $certificateAuthority;
150:             } elseif (is_dir($certificateAuthority)) {
151:                 unset($opts[CURLOPT_CAINFO]);
152:                 $opts[CURLOPT_CAPATH] = $certificateAuthority;
153:             } else {
154:                 throw new RuntimeException(
155:                     'Invalid option passed to ' . self::SSL_CERT_AUTHORITY . ': ' . $certificateAuthority
156:                 );
157:             }
158:         }
159: 
160:         $this->config->set(self::CURL_OPTIONS, $opts);
161: 
162:         return $this;
163:     }
164: 
165:     /**
166:      * {@inheritdoc}
167:      */
168:     public function getDefaultHeaders()
169:     {
170:         return $this->defaultHeaders;
171:     }
172: 
173:     /**
174:      * {@inheritdoc}
175:      */
176:     public function setDefaultHeaders($headers)
177:     {
178:         if ($headers instanceof Collection) {
179:             $this->defaultHeaders = $headers;
180:         } elseif (is_array($headers)) {
181:             $this->defaultHeaders = new Collection($headers);
182:         } else {
183:             throw new InvalidArgumentException('Headers must be an array or Collection');
184:         }
185: 
186:         return $this;
187:     }
188: 
189:     /**
190:      * {@inheritdoc}
191:      */
192:     public function expandTemplate($template, array $variables = null)
193:     {
194:         $expansionVars = $this->getConfig()->getAll();
195:         if ($variables) {
196:             $expansionVars = array_merge($expansionVars, $variables);
197:         }
198: 
199:         return $this->getUriTemplate()->expand($template, $expansionVars);
200:     }
201: 
202:     /**
203:      * {@inheritdoc}
204:      */
205:     public function setUriTemplate(UriTemplateInterface $uriTemplate)
206:     {
207:         $this->uriTemplate = $uriTemplate;
208: 
209:         return $this;
210:     }
211: 
212:     /**
213:      * {@inheritdoc}
214:      */
215:     public function getUriTemplate()
216:     {
217:         if (!$this->uriTemplate) {
218:             $this->uriTemplate = ParserRegistry::getInstance()->getParser('uri_template');
219:         }
220: 
221:         return $this->uriTemplate;
222:     }
223: 
224:     /**
225:      * {@inheritdoc}
226:      */
227:     public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null)
228:     {
229:         if (!is_array($uri)) {
230:             $templateVars = null;
231:         } else {
232:             if (count($uri) != 2 || !isset($uri[1]) || !is_array($uri[1])) {
233:                 throw new InvalidArgumentException(
234:                     'You must provide a URI template followed by an array of template variables '
235:                     . 'when using an array for a URI template'
236:                 );
237:             }
238:             list($uri, $templateVars) = $uri;
239:         }
240: 
241:         if (!$uri) {
242:             $url = $this->getBaseUrl();
243:         } elseif (substr($uri, 0, 4) === 'http') {
244:             // Use absolute URLs as-is
245:             $url = $this->expandTemplate($uri, $templateVars);
246:         } else {
247:             $url = Url::factory($this->getBaseUrl())->combine($this->expandTemplate($uri, $templateVars));
248:         }
249: 
250:         // If default headers are provided, then merge them into existing headers
251:         // If a collision occurs, the header is completely replaced
252:         if (count($this->defaultHeaders)) {
253:             if (is_array($headers)) {
254:                 $headers = array_merge($this->defaultHeaders->getAll(), $headers);
255:             } elseif ($headers instanceof Collection) {
256:                 $headers = array_merge($this->defaultHeaders->getAll(), $headers->getAll());
257:             } else {
258:                 $headers = $this->defaultHeaders;
259:             }
260:         }
261: 
262:         return $this->prepareRequest(
263:             $this->requestFactory->create($method, (string) $url, $headers, $body)
264:         );
265:     }
266: 
267:     /**
268:      * {@inheritdoc}
269:      */
270:     public function getBaseUrl($expand = true)
271:     {
272:         return $expand ? $this->expandTemplate($this->baseUrl) : $this->baseUrl;
273:     }
274: 
275:     /**
276:      * {@inheritdoc}
277:      */
278:     public function setBaseUrl($url)
279:     {
280:         $this->baseUrl = $url;
281: 
282:         return $this;
283:     }
284: 
285:     /**
286:      * {@inheritdoc}
287:      */
288:     public function setUserAgent($userAgent, $includeDefault = false)
289:     {
290:         if ($includeDefault) {
291:             $userAgent .= ' ' . $this->getDefaultUserAgent();
292:         }
293:         $this->userAgent = $userAgent;
294: 
295:         return $this;
296:     }
297: 
298:     /**
299:      * Get the default User-Agent string to use with Guzzle
300:      *
301:      * @return string
302:      */
303:     public function getDefaultUserAgent()
304:     {
305:         return 'Guzzle/' . Version::VERSION
306:             . ' curl/' . CurlVersion::getInstance()->get('version')
307:             . ' PHP/' . PHP_VERSION;
308:     }
309: 
310:     /**
311:      * {@inheritdoc}
312:      */
313:     public function get($uri = null, $headers = null, $body = null)
314:     {
315:         return $this->createRequest('GET', $uri, $headers, $body);
316:     }
317: 
318:     /**
319:      * {@inheritdoc}
320:      */
321:     public function head($uri = null, $headers = null)
322:     {
323:         return $this->createRequest('HEAD', $uri, $headers);
324:     }
325: 
326:     /**
327:      * {@inheritdoc}
328:      */
329:     public function delete($uri = null, $headers = null, $body = null)
330:     {
331:         return $this->createRequest('DELETE', $uri, $headers, $body);
332:     }
333: 
334:     /**
335:      * {@inheritdoc}
336:      */
337:     public function put($uri = null, $headers = null, $body = null)
338:     {
339:         return $this->createRequest('PUT', $uri, $headers, $body);
340:     }
341: 
342:     /**
343:      * {@inheritdoc}
344:      */
345:     public function patch($uri = null, $headers = null, $body = null)
346:     {
347:         return $this->createRequest('PATCH', $uri, $headers, $body);
348:     }
349: 
350:     /**
351:      * {@inheritdoc}
352:      */
353:     public function post($uri = null, $headers = null, $postBody = null)
354:     {
355:         return $this->createRequest('POST', $uri, $headers, $postBody);
356:     }
357: 
358:     /**
359:      * {@inheritdoc}
360:      */
361:     public function options($uri = null)
362:     {
363:         return $this->createRequest('OPTIONS', $uri);
364:     }
365: 
366:     /**
367:      * {@inheritdoc}
368:      */
369:     public function send($requests)
370:     {
371:         $curlMulti = $this->getCurlMulti();
372:         $multipleRequests = !($requests instanceof RequestInterface);
373:         if (!$multipleRequests) {
374:             $requests = array($requests);
375:         }
376: 
377:         foreach ($requests as $request) {
378:             $curlMulti->add($request);
379:         }
380: 
381:         try {
382:             $curlMulti->send();
383:         } catch (ExceptionCollection $e) {
384:             throw $multipleRequests ? $e : $e->getFirst();
385:         }
386: 
387:         if (!$multipleRequests) {
388:             return end($requests)->getResponse();
389:         } else {
390:             return array_map(function ($request) { return $request->getResponse(); }, $requests);
391:         }
392:     }
393: 
394:     /**
395:      * {@inheritdoc}
396:      */
397:     public function setCurlMulti(CurlMultiInterface $curlMulti)
398:     {
399:         $this->curlMulti = $curlMulti;
400: 
401:         return $this;
402:     }
403: 
404:     /**
405:      * {@inheritdoc}
406:      */
407:     public function getCurlMulti()
408:     {
409:         if (!$this->curlMulti) {
410:             $this->curlMulti = new CurlMultiProxy();
411:         }
412: 
413:         return $this->curlMulti;
414:     }
415: 
416:     /**
417:      * {@inheritdoc}
418:      */
419:     public function setRequestFactory(RequestFactoryInterface $factory)
420:     {
421:         $this->requestFactory = $factory;
422: 
423:         return $this;
424:     }
425: 
426:     /**
427:      * Copy the cacert.pem file from the phar if it is not in the temp folder and validate the MD5 checksum
428:      *
429:      * @param bool $md5Check Set to false to not perform the MD5 validation
430:      *
431:      * @return string Returns the path to the extracted cacert
432:      * @throws RuntimeException if the file cannot be copied or there is a MD5 mismatch
433:      */
434:     public function preparePharCacert($md5Check = true)
435:     {
436:         $from = __DIR__ . '/Resources/cacert.pem';
437:         $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem';
438:         if (!file_exists($certFile) && !copy($from, $certFile)) {
439:             throw new RuntimeException("Could not copy {$from} to {$certFile}: " . var_export(error_get_last(), true));
440:         } elseif ($md5Check) {
441:             $actualMd5 = md5_file($certFile);
442:             $expectedMd5 = trim(file_get_contents("{$from}.md5"));
443:             if ($actualMd5 != $expectedMd5) {
444:                 throw new RuntimeException("{$certFile} MD5 mismatch: expected {$expectedMd5} but got {$actualMd5}");
445:             }
446:         }
447: 
448:         return $certFile;
449:     }
450: 
451:     /**
452:      * Prepare a request to be sent from the Client by adding client specific behaviors and properties to the request.
453:      *
454:      * @param RequestInterface $request Request to prepare for the client
455:      *
456:      * @return RequestInterface
457:      */
458:     protected function prepareRequest(RequestInterface $request)
459:     {
460:         $request->setClient($this);
461: 
462:         // Add any curl options to the request
463:         if ($options = $this->config->get(self::CURL_OPTIONS)) {
464:             $request->getCurlOptions()->merge(CurlHandle::parseCurlConfig($options));
465:         }
466: 
467:         // Add request parameters to the request
468:         if ($options = $this->config->get(self::REQUEST_PARAMS)) {
469:             $request->getParams()->merge($options);
470:         }
471: 
472:         // Attach client observers to the request
473:         $request->setEventDispatcher(clone $this->getEventDispatcher());
474: 
475:         // Set the User-Agent if one is specified on the client but not explicitly on the request
476:         if ($this->userAgent && !$request->hasHeader('User-Agent')) {
477:             $request->setHeader('User-Agent', $this->userAgent);
478:         }
479: 
480:         $this->dispatch(
481:             'client.create_request',
482:             array(
483:                 'client'  => $this,
484:                 'request' => $request
485:             )
486:         );
487: 
488:         return $request;
489:     }
490: 
491:     /**
492:      * Initializes SSL settings
493:      */
494:     protected function initSsl()
495:     {
496:         // Allow ssl.certificate_authority config setting to control the certificate authority used by curl
497:         $authority = $this->config->get(self::SSL_CERT_AUTHORITY);
498: 
499:         // Set the SSL certificate
500:         if ($authority !== 'system') {
501: 
502:             if ($authority === null) {
503:                 $authority = true;
504:             }
505: 
506:             if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') {
507:                 $authority = $this->preparePharCacert();
508:                 $that = $this;
509:                 $this->getEventDispatcher()->addListener(
510:                     'request.before_send',
511:                     function ($event) use ($authority, $that) {
512:                         if ($authority == $event['request']->getCurlOptions()->get(CURLOPT_CAINFO)) {
513:                             $that->preparePharCacert(false);
514:                         }
515:                     }
516:                 );
517:             }
518: 
519:             $this->setSslVerification($authority);
520:         }
521:     }
522: }
523: 
php-coveralls API documentation generated by ApiGen 2.8.0