You are here

public function ViewsJsonQuery::execute in Views Json Source 8

Same name and namespace in other branches
  1. 1.x src/Plugin/views/query/ViewsJsonQuery.php \Drupal\views_json_source\Plugin\views\query\ViewsJsonQuery::execute()

Executes the query and fills the associated view object with according values.

Values to set: $view->result, $view->total_rows, $view->execute_time, $view->pager['current_page'].

$view->result should contain an array of objects. The array must use a numeric index starting at 0.

Parameters

view $view: The view which is executed.

Overrides QueryPluginBase::execute

File

src/Plugin/views/query/ViewsJsonQuery.php, line 178

Class

ViewsJsonQuery
Base query handler for views_json_source.

Namespace

Drupal\views_json_source\Plugin\views\query

Code

public function execute(ViewExecutable $view) {
  $start = microtime(TRUE);

  // Avoid notices about $view->execute_time being undefined if the query
  // doesn't finish.
  $view->execute_time = NULL;

  // Make sure that an xml file exists.
  // This could happen if you come from the add wizard to the actual views
  // edit page.
  if (empty($this->options['json_file'])) {
    return FALSE;
  }
  $data = new \stdClass();
  try {

    // Replace any dynamic character if any.
    $url = $this->options['json_file'];
    while ($param = $this
      ->getUrlParam()) {
      $url = preg_replace('/' . preg_quote('%', '/') . '/', $param, $url, 1);
    }
    $data->contents = $this
      ->fetchFile($url);
  } catch (\Exception $e) {
    \Drupal::messenger()
      ->addMessage($e
      ->getMessage(), 'error');
    return;
  }

  // When content is empty, parsing it is pointless.
  if (!$data->contents) {
    if ($this->options['show_errors']) {
      \Drupal::messenger()
        ->addMessage($this
        ->t('Views JSON Backend: File is empty.'), 'warning');
    }
    return;
  }

  // Go!
  $ret = $this
    ->parse($view, $data);
  $view->execute_time = microtime(TRUE) - $start;
  if (!$ret) {
    if (version_compare(phpversion(), '5.3.0', '>=')) {
      $tmp = [
        JSON_ERROR_NONE => $this
          ->t('No error has occurred'),
        JSON_ERROR_DEPTH => $this
          ->t('The maximum stack depth has been exceeded'),
        JSON_ERROR_STATE_MISMATCH => $this
          ->t('Invalid or malformed JSON'),
        JSON_ERROR_CTRL_CHAR => $this
          ->t('Control character error, possibly incorrectly encoded'),
        JSON_ERROR_SYNTAX => $this
          ->t('Syntax error'),
        JSON_ERROR_UTF8 => $this
          ->t('Malformed UTF-8 characters, possibly incorrectly encoded'),
      ];
      $msg = $tmp[json_last_error()] . ' - ' . $this->options['json_file'];
      \Drupal::messenger()
        ->addMessage($msg, 'error');
    }
    else {
      \Drupal::messenger()
        ->addMessage($this
        ->t('Views JSON Backend: Parse error') . ' - ' . $this->options['json_file'], 'error');
    }
  }
}