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|null Response
24     */
25    protected $_response;
26
27    /**
28     * Set response object the transport returns.
29     *
30     * @param array<string, mixed> $params Hostname, port, path, ...
31     */
32    public function getResponse(array $params = []): Response
33    {
34        return $this->_response ?? $this->generateDefaultResponse($params);
35    }
36
37    /**
38     * Set response object the transport returns.
39     *
40     * @return $this
41     */
42    public function setResponse(Response $response): NullTransport
43    {
44        $this->_response = $response;
45
46        return $this;
47    }
48
49    /**
50     * Generate an example response object.
51     *
52     * @param array<string, mixed> $params Hostname, port, path, ...
53     *
54     * @return Response $response
55     */
56    public function generateDefaultResponse(array $params): Response
57    {
58        $response = [
59            'took' => 0,
60            'timed_out' => false,
61            '_shards' => [
62                'total' => 0,
63                'successful' => 0,
64                'failed' => 0,
65            ],
66            'hits' => [
67                'total' => [
68                    'value' => 0,
69                ],
70                'max_score' => null,
71                'hits' => [],
72            ],
73            'params' => $params,
74        ];
75
76        return new Response(JSON::stringify($response));
77    }
78
79    /**
80     * Null transport.
81     *
82     * @param array<string, mixed> $params Hostname, port, path, ...
83     *
84     * @return Response Response empty object
85     */
86    public function exec(Request $request, array $params): Response
87    {
88        return $this->getResponse($params);
89    }
90}
91