DebugAction.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\elasticsearch;
  8. use yii\base\Action;
  9. use yii\base\NotSupportedException;
  10. use yii\helpers\ArrayHelper;
  11. use yii\web\HttpException;
  12. use yii\web\Response;
  13. use Yii;
  14. /**
  15. * Debug Action is used by [[DebugPanel]] to perform Elasticsearch queries using ajax.
  16. *
  17. * @author Carsten Brandt <mail@cebe.cc>
  18. * @since 2.0
  19. */
  20. class DebugAction extends Action
  21. {
  22. /**
  23. * @var string the connection id to use
  24. */
  25. public $db;
  26. /**
  27. * @var DebugPanel
  28. */
  29. public $panel;
  30. /**
  31. * @var \yii\debug\controllers\DefaultController
  32. */
  33. public $controller;
  34. public function run($logId, $tag)
  35. {
  36. $this->controller->loadData($tag);
  37. $timings = $this->panel->calculateTimings();
  38. ArrayHelper::multisort($timings, 3, SORT_DESC);
  39. if (!isset($timings[$logId])) {
  40. throw new HttpException(404, 'Log message not found.');
  41. }
  42. $message = $timings[$logId][1];
  43. if (($pos = mb_strpos($message, "#")) !== false) {
  44. $url = mb_substr($message, 0, $pos);
  45. $body = mb_substr($message, $pos + 1);
  46. } else {
  47. $url = $message;
  48. $body = null;
  49. }
  50. $method = mb_substr($url, 0, $pos = mb_strpos($url, ' '));
  51. $url = mb_substr($url, $pos + 1);
  52. $options = ['pretty' => 'true'];
  53. /* @var $db Connection */
  54. $db = \Yii::$app->get($this->db);
  55. $time = microtime(true);
  56. switch ($method) {
  57. case 'GET': $result = $db->get($url, $options, $body, true); break;
  58. case 'POST': $result = $db->post($url, $options, $body, true); break;
  59. case 'PUT': $result = $db->put($url, $options, $body, true); break;
  60. case 'DELETE': $result = $db->delete($url, $options, $body, true); break;
  61. case 'HEAD': $result = $db->head($url, $options, $body); break;
  62. default:
  63. throw new NotSupportedException("Request method '$method' is not supported by Elasticsearch.");
  64. }
  65. $time = microtime(true) - $time;
  66. if ($result === true) {
  67. $result = '<span class="label label-success">success</span>';
  68. } elseif ($result === false) {
  69. $result = '<span class="label label-danger">no success</span>';
  70. }
  71. Yii::$app->response->format = Response::FORMAT_JSON;
  72. return [
  73. 'time' => sprintf('%.1f ms', $time * 1000),
  74. 'result' => $result,
  75. ];
  76. }
  77. }