DebugAction.php 2.5 KB
Newer Older
1 2
<?php
/**
3 4 5
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
6 7 8 9 10 11 12 13 14 15
 */

namespace yii\elasticsearch;

use yii\base\Action;
use yii\base\NotSupportedException;
use yii\debug\Panel;
use yii\helpers\ArrayHelper;
use yii\web\HttpException;
use yii\web\Response;
16
use Yii;
17

18 19 20 21 22 23
/**
 * Debug Action is used by [[DebugPanel]] to perform elasticsearch queries using ajax.
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
24 25
class DebugAction extends Action
{
26 27 28 29 30
    /**
     * @var string the connection id to use
     */
    public $db;
    /**
31
     * @var Panel
32 33
     */
    public $panel;
34

35 36 37
    public function run($logId, $tag)
    {
        $this->controller->loadData($tag);
38

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        $timings = $this->panel->calculateTimings();
        ArrayHelper::multisort($timings, 3, SORT_DESC);
        if (!isset($timings[$logId])) {
            throw new HttpException(404, 'Log message not found.');
        }
        $message = $timings[$logId][1];
        if (($pos = mb_strpos($message, "#")) !== false) {
            $url = mb_substr($message, 0, $pos);
            $body = mb_substr($message, $pos + 1);
        } else {
            $url = $message;
            $body = null;
        }
        $method = mb_substr($url, 0, $pos = mb_strpos($url, ' '));
        $url = mb_substr($url, $pos + 1);
54

55
        $options = ['pretty' => true];
56

57
        /** @var Connection $db */
58
        $db = \Yii::$app->get($this->db);
59 60 61 62 63 64 65 66 67 68 69
        $time = microtime(true);
        switch ($method) {
            case 'GET': $result = $db->get($url, $options, $body, true); break;
            case 'POST': $result = $db->post($url, $options, $body, true); break;
            case 'PUT': $result = $db->put($url, $options, $body, true); break;
            case 'DELETE': $result = $db->delete($url, $options, $body, true); break;
            case 'HEAD': $result = $db->head($url, $options, $body); break;
            default:
                throw new NotSupportedException("Request method '$method' is not supported by elasticsearch.");
        }
        $time = microtime(true) - $time;
70

71 72 73 74 75
        if ($result === true) {
            $result = '<span class="label label-success">success</span>';
        } elseif ($result === false) {
            $result = '<span class="label label-danger">no success</span>';
        }
76

77 78 79 80 81 82 83
        Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'time' => sprintf('%.1f ms', $time * 1000),
            'result' => $result,
        ];
    }
84
}