PageRenderTime 10ms CodeModel.GetById 2ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/experimental/couch/CouchHttp.php

http://zoop.googlecode.com/
PHP | 65 lines | 45 code | 13 blank | 7 comment | 5 complexity | 0e754da154f2b42bb70e3c5d86b58038 MD5 | raw file
 1<?php
 2class CouchHttp
 3{
 4	private $host;
 5	private $port;
 6	
 7	function __construct($host = 'localhost', $port = 5984)
 8	{
 9		$this->host = $host;
10		$this->port = $port;
11	}
12
13	function send($method, $url, $postData = NULL)
14	{
15		$method = strtoupper($method);
16		// var_dump($postData);
17		$s = fsockopen($this->host, $this->port, $errno, $errstr);
18
19		if(!$s)
20			trigger_error("socket error: $errno, message: $errstr");
21		
22		$request = "$method $url HTTP/1.0\r\nHost: {$this->host}\r\n";
23
24		if($postData)
25		{
26			$request .= "Content-Length: ".strlen($postData)."\r\n";
27			// if(strtolower($method) == 'post')
28			// 	$request .= 'Content-Type: text/javascript'."\r\n";
29			// else
30			// 	$request .= 'Content-Type: application/json'."\r\n";
31			$request .= "\r\n";
32			$request .= "$postData\r\n";
33		}
34		else
35		{
36			$request .= "\r\n";
37		}
38		
39		// var_dump($request);
40		
41		fwrite($s, $request);
42
43		$response = "";
44		while(!feof($s))
45		{
46			$response .= fgets($s);
47		}
48		
49		if(!$response)
50		{
51			// var_dump($response);
52			trigger_error("request failed");
53			return false;
54		}
55		
56		list($headers, $body) = explode("\r\n\r\n", $response);
57		
58		$bodyObject = json_decode($body);
59		
60		if(isset($bodyObject->error) && $bodyObject->error)
61			trigger_error("couchdb: {$bodyObject->error}: {$bodyObject->reason}");
62		
63		return $bodyObject;
64	}
65}