Drupal – Print view query (formatted)
     发布在:PHP      浏览:5      评论:0 条评论

在进行上一篇 《Drupal – Preprocess for View in Block》 功能实现的时候遇到了各种 View Query 的问题。

为了查看 View Query 语句的结构,于是就有了这份调试用的代码,用于格式化打印 View Query 语句

<?php
/**
 * Print view query
 */
function _print_view_query(ViewExecutable &$view) {
    /* Magic Below Here */
    // Get query from the view.
    $query = $view -> query -> query();

    // Format SelectQueryInterface into a string.
    $string = (string)$query;

    // Replace arguments.
    $arguments = $query -> arguments();
    if (!empty($arguments) && is_array($arguments)) {
        foreach ($arguments as &$value) {
            if (is_string($value)) {
                $value = "'$value'";
            }
        }
        $string = strtr($string, $arguments);
    }

    // Format the query string for more readable output.
    $string = str_replace(array(' {', "\n{"), ' ', $string);
    $string = str_replace(array('} ', "}\n"), ' AS ', $string);
    $string = str_replace(', ', ",\n  ", $string);
    $string = str_replace(' AND ', "\n  AND ", $string);
    $string = str_replace(' ON ', "\n  ON ", $string);
    $string = str_replace('SELECT ', "SELECT\n  ", $string);
    $string = str_replace('ORDER BY ', "ORDER BY\n  ", $string);

    dump($string);
}
    Responses