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
<?php
namespace Basho\Riak\Api\Http\Translator;
use Basho\Riak\Api\Http;
use Basho\Riak\Command;
use Basho\Riak\Object;
class ObjectResponse
{
protected $command;
protected $code;
public function __construct(Command\Object $command, $code)
{
$this->command = $command;
$this->code = $code;
}
public function parseResponse($response, $headers = [])
{
$objects = [];
if ($this->code == '300') {
$position = strpos($headers[Http::CONTENT_TYPE_KEY], 'boundary=');
$boundary = '--' . substr($headers[Http::CONTENT_TYPE_KEY], $position + 9);
$objects = $this->parseSiblings($response, $boundary, $headers[Http::VCLOCK_KEY]);
} elseif (in_array($this->code, ['200','201','204'])) {
$objects[] = $this->parseObject($response, $headers);
}
return $objects;
}
public function parseSiblings($response, $boundary, $vclock = '')
{
$siblings = [];
$parts = explode($boundary, $response);
foreach ($parts as $part) {
$headers = [Http::VCLOCK_KEY => $vclock];
$slice_point = 0;
$empties = 0;
$lines = preg_split('/\n\r|\n|\r/', trim($part));
foreach ($lines as $key => $line) {
if (strpos($line, ':')) {
$empties = 0;
list ($key, $value) = explode(':', $line);
$value = trim($value);
if (!empty($value)) {
if (!isset($headers[$key])) {
$headers[$key] = $value;
} elseif (is_array($headers[$key])) {
$headers[$key] = array_merge($headers[$key], [$value]);
} else {
$headers[$key] = array_merge([$headers[$key]], [$value]);
}
}
} elseif ($line == '') {
if ($empties) {
$slice_point = $key + 1;
break;
} else {
$empties++;
}
}
}
$data = implode(PHP_EOL, array_slice($lines, $slice_point));
$siblings[] = $this->parseObject($data, $headers);
}
return $siblings;
}
public function parseObject($response, $headers = [])
{
$contentType = !empty($headers[Http::CONTENT_TYPE_KEY]) ? $headers[Http::CONTENT_TYPE_KEY] : '';
$data = $this->command->getDecodedData($response, $contentType);
return new Object($data, $headers);
}
}