* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @link http://www.solarium-project.org/ * * @package Solarium * @subpackage Client */ /** * Pecl HTTP adapter * * @author Gasol Wu * @package Solarium * @subpackage Client */ class Solarium_Client_Adapter_PeclHttp extends Solarium_Client_Adapter { /** * Initialization hook * * Checks the availability of pecl_http */ protected function _init() { // @codeCoverageIgnoreStart if (!class_exists('HttpRequest', false)) { throw new Solarium_Exception('Pecl_http is not available, install it to use the PeclHttp adapter'); } parent::_init(); // @codeCoverageIgnoreEnd } /** * Execute a Solr request using the Pecl Http * * @param Solarium_Client_Request $request * @return Solarium_Client_Response */ public function execute($request) { $httpRequest = $this->toHttpRequest($request); try { $httpMessage = $httpRequest->send(); } catch (Exception $e) { throw new Solarium_Client_HttpException($e->getMessage()); } return new Solarium_Client_Response( $httpMessage->getBody(), $this->_toRawHeaders($httpMessage) ); } /** * Convert key/value pair header to raw header. * * * //before * $headers['Content-Type'] = 'text/plain'; * * ... * * //after * $headers[0] = 'Content-Type: text/plain'; * * * @param $message HttpMessage * @return array */ protected function _toRawHeaders($message) { $headers[] = 'HTTP/' . $message->getHttpVersion() . ' ' . $message->getResponseCode() . ' ' . $message->getResponseStatus(); foreach ($message->getHeaders() as $header => $value) { $headers[] = "$header: $value"; } return $headers; } /** * * adapt Solarium_Client_Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * @param Solarium_Client_Request $request * @param HttpRequest */ public function toHttpRequest($request) { $url = $this->getBaseUri() . $request->getUri(); $httpRequest = new HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } switch($request->getMethod()) { case Solarium_Client_Request::METHOD_GET: $method = HTTP_METH_GET; break; case Solarium_Client_Request::METHOD_POST: $method = HTTP_METH_POST; $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } break; case Solarium_Client_Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new Solarium_Exception( 'Unsupported method: ' . $request->getMethod() ); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $this->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; } }