summaryrefslogtreecommitdiff
path: root/vendor/ruflin/elastica/lib/Elastica/Transport/Memcache.php
blob: cf047b583d7093df44b0bc237c86530800bd5b3a (plain)
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
<?php

namespace Elastica\Transport;

use Elastica\Exception\InvalidException;
use Elastica\Exception\PartialShardFailureException;
use Elastica\Exception\ResponseException;
use Elastica\JSON;
use Elastica\Request;
use Elastica\Response;

/**
 * Elastica Memcache Transport object
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Memcache extends AbstractTransport
{
    /**
     * Makes calls to the elasticsearch server
     *
     * @param \Elastica\Request $request
     * @param  array                               $params Host, Port, ...
     * @throws \Elastica\Exception\ResponseException
     * @throws \Elastica\Exception\InvalidException
     * @return \Elastica\Response                   Response object
     */
    public function exec(Request $request, array $params)
    {
        $memcache = new \Memcache();
        $memcache->connect($this->getConnection()->getHost(), $this->getConnection()->getPort());

        // Finds right function name
        $function = strtolower($request->getMethod());

        $data = $request->getData();

        $content = '';

        if (!empty($data) || '0' === $data) {
            if (is_array($data)) {
                $content = JSON::stringify($data);
            } else {
                $content = $data;
            }

            // Escaping of / not necessary. Causes problems in base64 encoding of files
            $content = str_replace('\/', '/', $content);
        }

        $responseString = '';

        switch ($function) {
            case 'post':
            case 'put':
                $memcache->set($request->getPath(), $content);
                break;
            case 'get':
                $responseString = $memcache->get($request->getPath() . '?source=' . $content);
                break;
            case 'delete':
                break;
            default:
                throw new InvalidException('Method ' . $function . ' is not supported in memcache transport');

        }

        $response = new Response($responseString);

        if ($response->hasError()) {
            throw new ResponseException($request, $response);
        }

        if ($response->hasFailedShards()) {
            throw new PartialShardFailureException($request, $response);
        }

        return $response;
    }
}