/sql/couchdb
[return to app]1
<?php
2 /**
3 * CouchDB helper class
4 */
5 class vorkCouchdb {
6 /**
7 * Configurable connection-related settings
8 */
9 public $host = 'localhost', $port = 5984, $user = null, $pass = null, $DB_NAME = null;
10
11 /**
12 * Cache of last header and object recieved
13 * @var array
14 */
15 public $header = null, $object = null;
16
17 /**
18 * Name used as the array-key upon an attempt to insert a string/int instead of an array or object
19 */
20 const SCALAR = 'scalar';
21
22 /**
23 * Base class to communicate with CouchDB
24 *
25 * @param string $method This is the method of communication (get, post, etc.)
26 * @param string $cmd The command transmitted to CouchDB
27 * @param string $data Data to be inserted into CouchDB
28 * @return object
29 */
30 public function couchdb($method, $cmd, $data = null) {
31 if (substr($cmd, 0, 1) != '/') {
32 $cmd = '/' . $this->DB_NAME . '/' . $cmd;
33 }
34 $socket = fsockopen($this->host, $this->port, $errno, $errstr);
35 if (!$socket && DEBUG_MODE) {
36 debug::log($errno . ': ' . $errstr, 'error');
37 return false;
38 }
39 $request = $method . ' ' . $cmd . " HTTP/1.0\r\nHost: " . $this->host . "\r\n";
40 if ($this->user) {
41 $request .= 'Authorization: Basic ' . base64_encode($this->user . ':' . $this->pass) . "\r\n";
42 }
43 if ($data) {
44 $request .= 'Content-Length: ' . strlen($data) . "\r\n\r\n" . $data;
45 }
46 $request .= "\r\n";
47 fwrite($socket, $request);
48
49 $response = '';
50 while (!feof($socket)) {
51 $response .= fgets($socket);
52 }
53 fclose($socket);
54 unset($socket);
55
56 list($this->header, $this->object) = explode("\r\n\r\n", $response);
57 return $this->object;
58 }
59
60 /**
61 * Wrapper around the couchdb method that aids in ease-of-use
62 *
63 * @param string $method This is the method of communication (get, post, etc.)
64 * @param string $cmd The command transmitted to CouchDB
65 * @param string $data Data to be inserted into CouchDB - can be a scalar string, JSON-string or array
66 * @return mixed Returns an array or string
67 */
68 public function send($method, $cmd, $data = null) {
69 if ($data) {
70 if (is_array($data)) {
71 $data = json_encode($data);
72 } else {
73 $data = trim($data);
74 if (substr($data, 0, 1) != '{' || substr($data, -1) != '}') {
75 $data = json_encode(array(self::SCALAR => $data));
76 }
77 }
78 }
79 $body = $this->couchdb($method, $cmd, $data);
80 $return = json_decode($body);
81 if (is_object($return) && property_exists($return, self::SCALAR) && count(get_object_vars($return)) == 3)
{
82 return $return->{self::SCALAR};
83 }
84 return $return;
85 }
86
87 /**
88 * Enables use of $couchdb->get(), $couchdb->delete(), etc.
89 *
90 * @param string $name
91 * @param array $args
92 * @return mixed
93 */
94 public function __call($name, array $args) {
95 if (in_array($name, array('get', 'put', 'post', 'delete', 'head'))) {
96 return $this->send(strtoupper($name), $args[0], (isset($args[1]) ? $args[1] : null));
97 }
98 }
99 }