1<?php
2
3namespace Elastica\Transport;
4
5use Elastica\JSON;
6use Elastica\Request;
7use Elastica\Response;
8
9/**
10 * Elastica Null Transport object.
11 *
12 * This is used in case you just need a test transport that doesn't do any connection to an elasticsearch
13 * host but still returns a valid response object
14 *
15 * @author James Boehmer <james.boehmer@jamesboehmer.com>
16 * @author Jan Domanski <jandom@gmail.com>
17 */
18class NullTransport extends AbstractTransport
19{
20    /**
21     * Response you want to get from the transport.
22     *
23     * @var Response Response
24     */
25    protected $_response = null;
26
27    /**
28     * Set response object the transport returns.
29     *
30     * @param array $params Hostname, port, path, ...
31     *
32     * @return Response
33     */
34    public function getResponse(array $params = []): Response
35    {
36        return $this->_response ?? $this->generateDefaultResponse($params);
37    }
38
39    /**
40     * Set response object the transport returns.
41     *
42     * @param \Elastica\Response $response
43     *
44     * @return $this
45     */
46    public function setResponse(Response $response): NullTransport
47    {
48        $this->_response = $response;
49
50        return $this;
51    }
52
53    /**
54     * Generate an example response object.
55     *
56     * @param array $params Hostname, port, path, ...
57     *
58     * @return Response $response
59     */
60    public function generateDefaultResponse(array $params): Response
61    {
62        $response = [
63            'took' => 0,
64            'timed_out' => false,
65            '_shards' => [
66                'total' => 0,
67                'successful' => 0,
68                'failed' => 0,
69            ],
70            'hits' => [
71                'total' => 0,
72                'max_score' => null,
73                'hits' => [],
74            ],
75            'params' => $params,
76        ];
77
78        return new Response(JSON::stringify($response));
79    }
80
81    /**
82     * Null transport.
83     *
84     * @param Request $request
85     * @param array   $params  Hostname, port, path, ...
86     *
87     * @return Response Response empty object
88     */
89    public function exec(Request $request, array $params): Response
90    {
91        return $this->getResponse($params);
92    }
93}
94