Official Riak Client for PHP
  • Namespace
  • Class
  • Tree

Namespaces

  • Basho
    • Riak
      • Api
        • Http
          • Translator
      • Command
        • Bucket
        • Builder
          • MapReduce
          • Search
          • TimeSeries
        • DataType
          • Counter
          • Map
          • Set
        • Indexes
        • MapReduce
        • Object
        • Search
          • Index
          • Schema
        • Stats
        • TimeSeries
          • Query
      • DataType
      • Node
        • Builder
      • Search
      • TimeSeries

Classes

  • Basho\Riak
  • Basho\Riak\Api
  • Basho\Riak\Api\Http
  • Basho\Riak\Api\Http\Translator\ObjectResponse
  • Basho\Riak\Api\Http\Translator\SecondaryIndex
  • Basho\Riak\Bucket
  • Basho\Riak\Command
  • Basho\Riak\Command\Bucket\Delete
  • Basho\Riak\Command\Bucket\Fetch
  • Basho\Riak\Command\Bucket\Response
  • Basho\Riak\Command\Bucket\Store
  • Basho\Riak\Command\Builder
  • Basho\Riak\Command\Builder\DeleteObject
  • Basho\Riak\Command\Builder\FetchBucketProperties
  • Basho\Riak\Command\Builder\FetchCounter
  • Basho\Riak\Command\Builder\FetchMap
  • Basho\Riak\Command\Builder\FetchObject
  • Basho\Riak\Command\Builder\FetchPreflist
  • Basho\Riak\Command\Builder\FetchSet
  • Basho\Riak\Command\Builder\FetchStats
  • Basho\Riak\Command\Builder\IncrementCounter
  • Basho\Riak\Command\Builder\MapReduce\FetchObjects
  • Basho\Riak\Command\Builder\Ping
  • Basho\Riak\Command\Builder\QueryIndex
  • Basho\Riak\Command\Builder\Search\AssociateIndex
  • Basho\Riak\Command\Builder\Search\DeleteIndex
  • Basho\Riak\Command\Builder\Search\DissociateIndex
  • Basho\Riak\Command\Builder\Search\FetchIndex
  • Basho\Riak\Command\Builder\Search\FetchObjects
  • Basho\Riak\Command\Builder\Search\FetchSchema
  • Basho\Riak\Command\Builder\Search\StoreIndex
  • Basho\Riak\Command\Builder\Search\StoreSchema
  • Basho\Riak\Command\Builder\SetBucketProperties
  • Basho\Riak\Command\Builder\StoreObject
  • Basho\Riak\Command\Builder\TimeSeries\DeleteRow
  • Basho\Riak\Command\Builder\TimeSeries\DescribeTable
  • Basho\Riak\Command\Builder\TimeSeries\FetchRow
  • Basho\Riak\Command\Builder\TimeSeries\Query
  • Basho\Riak\Command\Builder\TimeSeries\StoreRows
  • Basho\Riak\Command\Builder\UpdateMap
  • Basho\Riak\Command\Builder\UpdateSet
  • Basho\Riak\Command\DataType\Counter\Fetch
  • Basho\Riak\Command\DataType\Counter\Response
  • Basho\Riak\Command\DataType\Counter\Store
  • Basho\Riak\Command\DataType\Map\Fetch
  • Basho\Riak\Command\DataType\Map\Response
  • Basho\Riak\Command\DataType\Map\Store
  • Basho\Riak\Command\DataType\Set\Fetch
  • Basho\Riak\Command\DataType\Set\Response
  • Basho\Riak\Command\DataType\Set\Store
  • Basho\Riak\Command\Indexes\Query
  • Basho\Riak\Command\Indexes\Response
  • Basho\Riak\Command\MapReduce\Fetch
  • Basho\Riak\Command\MapReduce\Response
  • Basho\Riak\Command\Object
  • Basho\Riak\Command\Object\Delete
  • Basho\Riak\Command\Object\Fetch
  • Basho\Riak\Command\Object\FetchPreflist
  • Basho\Riak\Command\Object\Response
  • Basho\Riak\Command\Object\Store
  • Basho\Riak\Command\Ping
  • Basho\Riak\Command\Response
  • Basho\Riak\Command\Search\Fetch
  • Basho\Riak\Command\Search\Index\Delete
  • Basho\Riak\Command\Search\Index\Fetch
  • Basho\Riak\Command\Search\Index\Response
  • Basho\Riak\Command\Search\Index\Store
  • Basho\Riak\Command\Search\Response
  • Basho\Riak\Command\Search\Schema\Fetch
  • Basho\Riak\Command\Search\Schema\Response
  • Basho\Riak\Command\Search\Schema\Store
  • Basho\Riak\Command\Stats
  • Basho\Riak\Command\Stats\Response
  • Basho\Riak\Command\TimeSeries\Delete
  • Basho\Riak\Command\TimeSeries\Fetch
  • Basho\Riak\Command\TimeSeries\Query\Fetch
  • Basho\Riak\Command\TimeSeries\Query\Response
  • Basho\Riak\Command\TimeSeries\Response
  • Basho\Riak\Command\TimeSeries\Store
  • Basho\Riak\DataType
  • Basho\Riak\DataType\Counter
  • Basho\Riak\DataType\Map
  • Basho\Riak\DataType\Set
  • Basho\Riak\Location
  • Basho\Riak\Node
  • Basho\Riak\Node\Builder
  • Basho\Riak\Node\Config
  • Basho\Riak\Object
  • Basho\Riak\Search\Doc
  • Basho\Riak\TimeSeries\Cell

Interfaces

  • Basho\Riak\ApiInterface
  • Basho\Riak\Command\BuilderInterface
  • Basho\Riak\CommandInterface

Traits

  • Basho\Riak\Command\Builder\BucketTrait
  • Basho\Riak\Command\Builder\IndexTrait
  • Basho\Riak\Command\Builder\LocationTrait
  • Basho\Riak\Command\Builder\ObjectTrait
  • Basho\Riak\Command\Builder\TimeSeries\KeyTrait
  • Basho\Riak\Command\Builder\TimeSeries\RowsTrait
  • Basho\Riak\Command\Builder\TimeSeries\TableTrait
  • Basho\Riak\HeadersTrait

Exceptions

  • Basho\Riak\Api\Exception
  • Basho\Riak\Command\Builder\Exception
  • Basho\Riak\Command\Exception
  • Basho\Riak\DataType\Exception
  • Basho\Riak\Exception
  • Basho\Riak\Node\Builder\Exception
  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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 
<?php

namespace Basho\Riak\Api;

use Basho\Riak\Api;
use Basho\Riak\ApiInterface;
use Basho\Riak\Bucket;
use Basho\Riak\Command;
use Basho\Riak\DataType\Counter;
use Basho\Riak\DataType\Map;
use Basho\Riak\DataType\Set;
use Basho\Riak\Location;
use Basho\Riak\Node;
use Basho\Riak\Object;
use Basho\Riak\Search\Doc;

/**
 * Handles communications between end user app & Riak via Riak HTTP API using cURL
 *
 * @author Christopher Mancini <cmancini at basho d0t com>
 */
class Http extends Api implements ApiInterface
{
    // Header keys
    const VCLOCK_KEY = 'X-Riak-Vclock';
    const CONTENT_TYPE_KEY = 'Content-Type';
    const METADATA_PREFIX = 'X-Riak-Meta-';
    const LAST_MODIFIED_KEY = 'Last-Modified';

    // Content Types
    const CONTENT_TYPE_JSON = 'application/json';
    const CONTENT_TYPE_XML = 'application/xml';

    const TS_API_PREFIX = '/ts/v1/';

    /**
     * Request body to be sent
     *
     * @var string
     */
    protected $requestBody = '';

    /**
     * Response headers returned from request
     *
     * @var array
     */
    protected $responseHeaders = [];

    /**
     * Response body returned from request
     *
     * @var string
     */
    protected $responseBody = '';

    /**
     * HTTP Status Code from response
     *
     * @var int
     */
    protected $statusCode = 0;

    /**
     * cURL connection handle
     *
     * @var null
     */
    protected $connection = null;

    /**
     * API path
     *
     * @var string
     */
    protected $path = '';

    /**
     * Query string
     *
     * @var string
     */
    protected $query = '';

    private $options = [];

    protected $headers = [];

    /**
     * @return int
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }

    /**
     * @return string
     */
    public function getResponseBody()
    {
        return $this->responseBody;
    }

    /**
     * @return array
     */
    public function getResponseHeaders()
    {
        return $this->responseHeaders;
    }

    /**
     * @return string
     */
    public function getRequest()
    {
        return $this->request . $this->requestBody;
    }

    public function closeConnection()
    {
        if ($this->connection) {
            curl_close($this->connection);
            $this->connection = null;
        }
    }

    /**
     * Prepare request to be sent
     *
     * @param Command $command
     * @param Node $node
     *
     * @return $this
     */
    public function prepare(Command $command, Node $node)
    {
        if ($this->connection) {
            $this->resetConnection();
        }

        // call parent prepare method to setup object members
        parent::prepare($command, $node);

        // set the API path to be used
        $this->buildPath();

        // general connection preparation
        $this->prepareConnection();

        // request specific connection preparation
        $this->prepareRequest();

        return $this;
    }

    public function resetConnection()
    {
        $this->command = null;
        $this->options = [];
        $this->path = '';
        $this->query = '';
        $this->requestBody = '';
        $this->responseHeaders = [];
        $this->responseBody = '';

        if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
            curl_reset($this->connection);
        } else {
            curl_close($this->connection);
            $this->connection = null;
        }
    }

    /**
     * Sets the API path for the command
     *
     * @return $this
     */
    protected function buildPath()
    {
        $bucket = null;
        $key = '';

        $bucket = $this->command->getBucket();

        $location = $this->command->getLocation();
        if (!empty($location) && $location instanceof Location) {
            $key = $location->getKey();
        }
        switch (get_class($this->command)) {
            case 'Basho\Riak\Command\Bucket\List':
                $this->path = sprintf('/types/%s/buckets/%s', $bucket->getType(), $bucket->getName());
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'Basho\Riak\Command\Bucket\Store':
                $this->headers[static::CONTENT_TYPE_KEY] = static::CONTENT_TYPE_JSON;
            case 'Basho\Riak\Command\Bucket\Fetch':
            case 'Basho\Riak\Command\Bucket\Delete':
                $this->path = sprintf('/types/%s/buckets/%s/props', $bucket->getType(), $bucket->getName());
                break;
            case 'Basho\Riak\Command\Bucket\Keys':
                $this->path = sprintf('/types/%s/buckets/%s/keys', $bucket->getType(), $bucket->getName());
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'Basho\Riak\Command\Object\Fetch':
                $this->headers['Accept'] = '*/*, multipart/mixed';
            case 'Basho\Riak\Command\Object\Store':
            case 'Basho\Riak\Command\Object\Delete':
                $this->path = sprintf('/types/%s/buckets/%s/keys/%s', $bucket->getType(), $bucket->getName(), $key);
                break;
            case 'Basho\Riak\Command\DataType\Counter\Store':
            case 'Basho\Riak\Command\DataType\Set\Store':
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'Basho\Riak\Command\DataType\Map\Store':
                $this->headers[static::CONTENT_TYPE_KEY] = static::CONTENT_TYPE_JSON;
            case 'Basho\Riak\Command\DataType\Counter\Fetch':
            case 'Basho\Riak\Command\DataType\Set\Fetch':
            case 'Basho\Riak\Command\DataType\Map\Fetch':
                $this->path = sprintf('/types/%s/buckets/%s/datatypes/%s', $bucket->getType(), $bucket->getName(), $key);
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'Basho\Riak\Command\Search\Index\Store':
                $this->headers[static::CONTENT_TYPE_KEY] = static::CONTENT_TYPE_JSON;
            case 'Basho\Riak\Command\Search\Index\Fetch':
            case 'Basho\Riak\Command\Search\Index\Delete':
                $this->path = sprintf('/search/index/%s', $this->command);
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'Basho\Riak\Command\Search\Schema\Store':
                $this->headers[static::CONTENT_TYPE_KEY] = static::CONTENT_TYPE_XML;
            case 'Basho\Riak\Command\Search\Schema\Fetch':
                $this->path = sprintf('/search/schema/%s', $this->command);
                break;
            case 'Basho\Riak\Command\Search\Fetch':
                $this->path = sprintf('/search/query/%s', $this->command);
                break;
            case 'Basho\Riak\Command\MapReduce\Fetch':
                $this->headers[static::CONTENT_TYPE_KEY] = static::CONTENT_TYPE_JSON;
                $this->path = sprintf('/%s', $this->config['mapred_prefix']);
                break;
            case 'Basho\Riak\Command\Indexes\Query':
                $this->path = $this->createIndexQueryPath($bucket);
                break;
            case 'Basho\Riak\Command\Ping':
                $this->path = '/ping';
                break;
            case 'Basho\Riak\Command\Stats':
                $this->path = '/stats';
                break;
            case 'Basho\Riak\Command\Object\FetchPreflist':
                $this->path = sprintf('/types/%s/buckets/%s/keys/%s/preflist', $bucket->getType(), $bucket->getName(), $key);
                break;
            case 'Basho\Riak\Command\TimeSeries\Fetch':
            case 'Basho\Riak\Command\TimeSeries\Delete':
                /** @var $command Command\TimeSeries\Fetch */
                $command = $this->command;
                $this->path = sprintf('%s/table/%s/%s', static::TS_API_PREFIX, $command->getTable(), implode("/", $command->getData()));
                break;
            case 'Basho\Riak\Command\TimeSeries\Store':
                /** @var $command Command\TimeSeries\Store */
                $command = $this->command;
                $this->path = sprintf('%s/table/%s', static::TS_API_PREFIX, $command->getTable());
                break;
            case 'Basho\Riak\Command\TimeSeries\Query\Fetch':
                $this->path = sprintf('%s/query', static::TS_API_PREFIX);
                break;
            default:
                $this->path = '';
        }

        return $this;
    }

    /**
     * Generates the URL path for a 2i Query
     *
     * @param Bucket $bucket
     * @return string
     * @throws Api\Exception if 2i query is invalid.
     */
    private function createIndexQueryPath(Bucket $bucket)
    {
        /**  @var Command\Indexes\Query $command */
        $command = $this->command;

        if($command->isMatchQuery()) {
            $path =  sprintf('/types/%s/buckets/%s/index/%s/%s', $bucket->getType(),
                        $bucket->getName(),
                        $command->getIndexName(),
                        $command->getMatchValue());
        }
        elseif($command->isRangeQuery()) {
            $path =  sprintf('/types/%s/buckets/%s/index/%s/%s/%s', $bucket->getType(),
                        $bucket->getName(),
                        $command->getIndexName(),
                        $command->getLowerBound(),
                        $command->getUpperBound());
        }
        else
        {
            throw new Api\Exception("Invalid Secondary Index Query.");
        }

        return $path;
    }

    /**
     * Prepare Connection
     *
     * Sets general connection options that are used with every request
     *
     * @return $this
     * @throws Api\Exception
     */
    protected function prepareConnection()
    {
        // record outgoing headers
        $this->options[CURLINFO_HEADER_OUT] = 1;

        if ($this->node->useTls()) {
            // CA File
            if ($this->node->getCaFile()) {
                $this->options[CURLOPT_CAINFO] = $this->node->getCaFile();
            } elseif ($this->node->getCaDirectory()) {
                $this->options[CURLOPT_CAPATH] = $this->node->getCaDirectory();
            } else {
                throw new Api\Exception('A Certificate Authority file is required for secure connections.');
            }

            // verify CA file
            $this->options[CURLOPT_SSL_VERIFYPEER] = true;

            // verify host common name
            $this->options[CURLOPT_SSL_VERIFYHOST] = 0;

            if ($this->node->getUserName()) {
                $this->options[CURLOPT_USERPWD] = sprintf('%s:%s', $this->node->getUserName(),
                    $this->node->getPassword());
            } elseif ($this->node->getCertificate()) {
                /*
                 * NOT CURRENTLY SUPPORTED ON HTTP
                 *
                $this->options[CURLOPT_SSLCERT] = $this->node->getCertificate();
                $this->options[CURLOPT_SSLCERTTYPE] = 'P12';
                if ($this->node->getCertificatePassword()) {
                    $this->options[CURLOPT_SSLCERTPASSWD] = $this->node->getCertificatePassword();
                }
                if ($this->node->getPrivateKey()) {
                    $this->options[CURLOPT_SSLKEY] = $this->node->getPrivateKey();
                    if ($this->node->getPrivateKeyPassword()) {
                        $this->options[CURLOPT_SSLKEYPASSWD] = $this->node->getPrivateKeyPassword();
                    }
                }
                */
            }
        }

        return $this;
    }

    /**
     * Prepare request
     *
     * Sets connection options that are specific to this request
     *
     * @return $this
     */
    protected function prepareRequest()
    {
        return $this->prepareRequestMethod()
            ->prepareRequestHeaders()
            ->prepareRequestParameters()
            ->prepareRequestUrl()
            ->prepareRequestData();
    }

    /**
     * Prepare request data
     *
     * @return $this
     */
    protected function prepareRequestData()
    {
        // if POST or PUT, add parameters to post data, else add to uri
        if (in_array($this->command->getMethod(), ['POST', 'PUT'])) {
            $this->requestBody = $this->command->getEncodedData();
            $this->options[CURLOPT_POSTFIELDS] = $this->requestBody;
        }

        return $this;
    }

    /**
     * Prepares the complete request URL
     *
     * @return $this
     */
    protected function prepareRequestUrl()
    {
        $protocol = $this->node->useTls() ? 'https' : 'http';
        $url = sprintf('%s://%s%s?%s', $protocol, $this->node->getUri(), $this->path, $this->query);

        // set the built request URL on the connection
        $this->options[CURLOPT_URL] = $url;

        return $this;
    }

    /**
     * Prepare request parameters
     *
     * @return $this
     */
    protected function prepareRequestParameters()
    {
        if ($this->command->hasParameters()) {
            // build query using RFC 3986 (spaces become %20 instead of '+')
            $this->query = http_build_query($this->command->getParameters(), '', '&', PHP_QUERY_RFC3986);
        }

        return $this;
    }

    /**
     * Prepares the request headers
     *
     * @return $this
     */
    protected function prepareRequestHeaders()
    {
        $curl_headers = [];

        foreach ($this->headers as $key => $value) {
            $curl_headers[] = sprintf('%s: %s', $key, $value);
        }

        // if we have an object, set appropriate object headers
        $object = $this->command->getObject();
        if ($object) {
            if ($object->getVclock()) {
                $curl_headers[] = sprintf('%s: %s', static::VCLOCK_KEY, $object->getVclock());
            }

            if ($object->getContentType()) {
                $charset = '';
                if ($object->getCharset()) {
                    $charset = sprintf('; charset=%s', $object->getCharset());
                }
                $curl_headers[] = sprintf('%s: %s', static::CONTENT_TYPE_KEY, $object->getContentType(), $charset);
            }

            // setup index headers
            $translator = new Api\Http\Translator\SecondaryIndex();
            $indexHeaders = $translator->createHeadersFromIndexes($object->getIndexes());
            foreach ($indexHeaders as $value) {
                $curl_headers[] = sprintf('%s: %s', $value[0], $value[1]);
            }

            // setup metadata headers
            foreach($object->getMetaData() as $key => $value) {
                $curl_headers[] = sprintf('%s%s: %s', static::METADATA_PREFIX, $key, $value);
            }
        }

        // set the request headers on the connection
        $this->options[CURLOPT_HTTPHEADER] = $curl_headers;

        // dump local headers to start fresh
        $this->headers = [];

        return $this;
    }

    /**
     * Prepare the request method
     *
     * @return $this
     */
    protected function prepareRequestMethod()
    {
        switch ($this->command->getMethod()) {
            case "POST":
                $this->options[CURLOPT_POST] = 1;
                break;
            case "PUT":
                $this->options[CURLOPT_CUSTOMREQUEST] = 'PUT';
                break;
            case "DELETE":
                $this->options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
                break;
            case "HEAD":
                $this->options[CURLOPT_NOBODY] = 1;
                break;
            default:
                // reset http method to get in case its changed
                $this->options[CURLOPT_HTTPGET] = 1;
        }

        return $this;
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @return string
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * @return bool
     */
    public function send()
    {
        // set the response header and body callback functions
        $this->options[CURLOPT_HEADERFUNCTION] = [$this, 'responseHeaderCallback'];
        $this->options[CURLOPT_WRITEFUNCTION] = [$this, 'responseBodyCallback'];

        if ($this->command->isVerbose()) {
            // set curls output to be the output buffer stream
            $this->options[CURLOPT_STDERR] = fopen('php://stdout', 'w+');
            $this->options[CURLOPT_VERBOSE] = 1;

            // there is a bug when verbose is enabled, header out causes no output
            // @see https://bugs.php.net/bug.php?id=65348
            unset($this->options[CURLINFO_HEADER_OUT]);
        }

        // set all options on the resource
        curl_setopt_array($this->getConnection(), $this->options);

        // execute the request
        $this->success = curl_exec($this->getConnection());
        if ($this->success === false) {
            $this->error = curl_error($this->getConnection());
        } elseif ($this->success === true) {
            $this->error = '';
        }

        $this->request = curl_getinfo($this->getConnection(), CURLINFO_HEADER_OUT);

        // set the response http code
        $this->statusCode = curl_getinfo($this->getConnection(), CURLINFO_HTTP_CODE);

        $this->parseResponse();

        return $this->success;
    }

    /**
     * Add a custom header to the request
     *
     * @param $key
     * @param $value
     */
    public function addHeader($key, $value)
    {
        $this->headers[$key] = $value;
    }

    /**
     * @return resource
     */
    public function getConnection()
    {
        if (!$this->connection) {
            $this->openConnection();
        }

        return $this->connection;
    }

    public function openConnection()
    {
        $this->connection = curl_init();

        return $this;
    }

    /**
     * Response header callback
     *
     * Handles callback from curl when the response is received, it parses the headers into an array sets them as
     * member of the class.
     *
     * Has to be public for curl to be able to access it.
     *
     * @param $ch
     * @param $header
     *
     * @return int
     */
    public function responseHeaderCallback($ch, $header)
    {
        if (strpos($header, ':')) {
            list ($key, $value) = explode(':', $header);

            $value = trim($value);

            if (!empty($value)) {
                if (!isset($this->responseHeaders[$key])) {
                    $this->responseHeaders[$key] = $value;
                } elseif (is_array($this->responseHeaders[$key])) {
                    $this->responseHeaders[$key] = array_merge($this->responseHeaders[$key], [$value]);
                } else {
                    $this->responseHeaders[$key] = array_merge([$this->responseHeaders[$key]], [$value]);
                }
            }
        }

        return strlen($header);
    }

    /**
     * Response body callback
     *
     * Handles callback from curl when the response is received, it sets the response body as a member of the class.
     *
     * Has to be public for curl to be able to access it.
     *
     * @param $ch
     * @param $body
     *
     * @return int
     */
    public function responseBodyCallback($ch, $body)
    {
        $this->responseBody .= $body;

        return strlen($body);
    }

    protected function parseResponse()
    {
        // trim leading / trailing whitespace
        $body = $this->responseBody;
        $location = null;
        if ($this->getResponseHeader('Location')) {
            $location = Location::fromString($this->getResponseHeader('Location'));
        }

        switch (get_class($this->command)) {
            case 'Basho\Riak\Command\Bucket\Store':
            case 'Basho\Riak\Command\Bucket\Fetch':
                $bucket = null;
                $modified = $this->getResponseHeader(static::LAST_MODIFIED_KEY, '');
                $properties = json_decode($body, true);
                if ($properties && $this->command->getBucket()) {
                    $bucket = new Bucket($this->command->getBucket()->getName(), $this->command->getBucket()->getType(), $properties['props']);
                }
                $response = new Command\Bucket\Response($this->success, $this->statusCode, $this->error, $bucket, $modified);
                break;

            case 'Basho\Riak\Command\Object\Fetch':
            case 'Basho\Riak\Command\Object\Store':
                /** @var Command\Object $command */
                $command = $this->command;
                $objects = (new Api\Http\Translator\ObjectResponse($command, $this->statusCode))
                    ->parseResponse($body, $this->responseHeaders);
                $response = new Command\Object\Response($this->success, $this->statusCode, $this->error, $location, $objects);
                break;

            case 'Basho\Riak\Command\Object\FetchPreflist':
                $response = new Command\Object\Response($this->success, $this->statusCode, $this->error, $location, [new Object(json_decode($body))]);
                break;

            case 'Basho\Riak\Command\DataType\Counter\Store':
            case 'Basho\Riak\Command\DataType\Counter\Fetch':
                $counter = null;
                $json_object = json_decode($body);
                if ($json_object && isset($json_object->value)) {
                    $counter = new Counter($json_object->value);
                }
                $response = new Command\DataType\Counter\Response(
                    $this->success, $this->statusCode, $this->error, $location, $counter, $this->getResponseHeader('Date')
                );
                break;

            case 'Basho\Riak\Command\DataType\Set\Store':
            case 'Basho\Riak\Command\DataType\Set\Fetch':
                $set = null;
                $json_object = json_decode($body);
                if ($json_object && isset($json_object->value)) {
                    $set = new Set($json_object->value, $json_object->context);
                }
                $response = new Command\DataType\Set\Response(
                    $this->success, $this->statusCode, $this->error, $location, $set, $this->getResponseHeader('Date')
                );
                break;

            case 'Basho\Riak\Command\DataType\Map\Store':
            case 'Basho\Riak\Command\DataType\Map\Fetch':
                $map = null;
                $json_object = json_decode($body, true);
                if ($json_object && isset($json_object['value'])) {
                    $map = new Map($json_object['value'], $json_object['context']);
                }
                $response = new Command\DataType\Map\Response(
                    $this->success, $this->statusCode, $this->error, $location, $map, $this->getResponseHeader('Date')
                );
                break;

            case 'Basho\Riak\Command\Search\Fetch':
                $results = in_array($this->statusCode, [200,204]) ? json_decode($body) : null;
                $docs = [];
                if (!empty($results->response->docs)) {
                    foreach ($results->response->docs as $doc) {
                        $docs[] = new Doc($doc);
                    }
                }
                $numFound = !empty($results->response->numFound) ? $results->response->numFound : 0;

                $response = new Command\Search\Response($this->success, $this->statusCode, $this->error, $numFound, $docs);
                break;
            case 'Basho\Riak\Command\Search\Index\Store':
            case 'Basho\Riak\Command\Search\Index\Fetch':
                $index = json_decode($body);
                $response = new Command\Search\Index\Response($this->success, $this->statusCode, $this->error, $index);
                break;

            case 'Basho\Riak\Command\Search\Schema\Store':
            case 'Basho\Riak\Command\Search\Schema\Fetch':
                $response = new Command\Search\Schema\Response(
                    $this->success, $this->statusCode, $this->error, $body, $this->getResponseHeader(static::CONTENT_TYPE_KEY)
                );
                break;

            case 'Basho\Riak\Command\MapReduce\Fetch':
                $results = in_array($this->statusCode, [200,204]) ? json_decode($body) : null;
                $response = new Command\MapReduce\Response($this->success, $this->statusCode, $this->error, $results);
                break;
            case 'Basho\Riak\Command\Indexes\Query':
                $json_object = in_array($this->statusCode, [200,204]) ? json_decode($body, true) : null;
                $results = [];
                $termsReturned = false;
                $continuation = null;
                $done = true;

                if (isset($json_object['keys'])) {
                    $results = $json_object['keys'];
                }

                if (isset($json_object['results'])) {
                    $results = $json_object['results'];
                    $termsReturned = true;
                }

                if (isset($json_object['continuation'])) {
                    $continuation = $json_object['continuation'];
                    $done = false;
                }

                $response = new Command\Indexes\Response(
                    $this->success, $this->statusCode, $this->error, $results, $termsReturned, $continuation, $done, $this->getResponseHeader('Date')
                );
                break;
            case 'Basho\Riak\Command\Stats':
                $response = new Command\Stats\Response($this->success, $this->statusCode, $this->error, json_decode($body, true));
                break;
            case 'Basho\Riak\Command\TimeSeries\Store':
            case 'Basho\Riak\Command\TimeSeries\Fetch':
                $rows = in_array($this->statusCode, ['200','201','204']) ? json_decode($body) : [];
                $response = new Command\TimeSeries\Response($this->success, $this->statusCode, $this->error, $rows);
                break;
            case 'Basho\Riak\Command\TimeSeries\Query':
                $results = in_array($this->statusCode, ['200','204']) ? json_decode($body) : [];
                $response = new Command\TimeSeries\Response($this->success, $this->statusCode, $this->error, $results);
                break;
            case 'Basho\Riak\Command\TimeSeries\Delete':
            case 'Basho\Riak\Command\Object\Delete':
            case 'Basho\Riak\Command\Bucket\Delete':
            case 'Basho\Riak\Command\Search\Index\Delete':
            case 'Basho\Riak\Command\Ping':
            default:
                $response = new Command\Response($this->success, $this->statusCode, $this->error);
                break;
        }

        $this->response = $response;
    }

    protected function getResponseHeader($key, $default = '')
    {
        if (!empty($this->responseHeaders[$key])) {
            return $this->responseHeaders[$key];
        } else {
            return $default;
        }
    }
}
Official Riak Client for PHP API documentation generated by ApiGen