View source
<?php
namespace Drupal\views_test_data\Plugin\views\query;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Plugin\views\join\JoinPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
class QueryTest extends QueryPluginBase {
protected $conditions = [];
protected $fields = [];
protected $allItems = [];
protected $orderBy = [];
protected function defineOptions() {
$options = parent::defineOptions();
$options['test_setting'] = [
'default' => '',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['test_setting'] = [
'#title' => $this
->t('Test setting'),
'#type' => 'textfield',
'#default_value' => $this->options['test_setting'],
];
}
public function setAllItems($allItems) {
$this->allItems = $allItems;
}
public function addWhere($group, $field, $value = NULL, $operator = NULL) {
$this->conditions[] = [
'field' => $field,
'value' => $value,
'operator' => $operator,
];
}
public function addField($table, $field, $alias = '', $params = []) {
$this->fields[$field] = $field;
return $field;
}
public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = []) {
$this->orderBy = [
'field' => $field,
'order' => $order,
];
}
public function ensureTable($table, $relationship = NULL, JoinPluginBase $join = NULL) {
}
public function build(ViewExecutable $view) {
$this->view = $view;
$this->view->build_info['query'] = "";
$this->view->build_info['count_query'] = "";
}
public function execute(ViewExecutable $view) {
$result = [];
foreach ($this->allItems as $element) {
$match = TRUE;
foreach ($this->conditions as $condition) {
$match &= $this
->match($element, $condition);
}
if ($match) {
if ($this->fields) {
$element = array_intersect_key($element, $this->fields);
}
$result[] = new ResultRow($element);
}
}
$this->view->result = $result;
}
public function match($element, $condition) {
$value = $element[$condition['field']];
switch ($condition['operator']) {
case '=':
return $value == $condition['value'];
case 'IN':
return in_array($value, $condition['value']);
}
return FALSE;
}
public function calculateDependencies() {
return parent::calculateDependencies() + [
'content' => [
'QueryTest',
],
];
}
public function setFieldTimezoneOffset(&$field, $offset) {
}
}