1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106:
<?php
namespace Net\Bazzline\Component\Curl\Dispatcher;
use Net\Bazzline\Component\Curl\Response\Response;
class Dispatcher implements DispatcherInterface
{
private $headerLines;
public function dispatch($url, array $options = [])
{
$this->reset();
$handler = $this->getHandler($url);
$handler = $this->setOptions($handler, $options);
$response = $this->execute($handler);
return $response;
}
protected function execute($handler)
{
$content = curl_exec($handler);
$contentType = curl_getinfo($handler, CURLINFO_CONTENT_TYPE);
$error = curl_error($handler);
$errorCode = curl_errno($handler);
$statusCode = curl_getinfo($handler, CURLINFO_HTTP_CODE);
curl_close($handler);
return new Response($content, $contentType, $error, $errorCode, $this->headerLines, $statusCode);
}
protected function getHandler($url)
{
$handler = curl_init($url);
return $handler;
}
protected function setOptions($handler, array $options)
{
$options[CURLINFO_HEADER_OUT] = 1;
$options[CURLOPT_HEADERFUNCTION] = [
$this,
'processHeadLine'
];
$options[CURLOPT_RETURNTRANSFER] = true;
curl_setopt_array($handler, $options);
return $handler;
}
private function processHeadLine($handler, $string)
{
$delimiter = ':';
$exploded = explode($delimiter, trim($string));
$isValid = (count($exploded) === 2);
if ($isValid) {
$prefix = array_shift($exploded);
$this->headerLines[$prefix] = implode($delimiter, $exploded);
}
return strlen($string);
}
private function reset()
{
$this->headerLines = [];
}
}