NullTransport.php 2.2 KB

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