View source
<?php
namespace Drupal\charts\Util;
use Drupal\views\ViewExecutable;
class Util {
public static function viewsData(ViewExecutable $view = NULL, array $labelValues = [], $labelField = '', array $color = [], $attachmentChartTypeOption = NULL) {
$data = [];
$style_options = $view
->getStyle()->options['chart_settings'];
foreach ($view->result as $row_number => $row) {
$view->row_index = $row->index;
$numberFields = 0;
$rowData = [];
foreach ($labelValues as $fieldId => $rowDataValue) {
if ($style_options['fields']['allow_advanced_rendering'] == 1 || isset($view->field[$labelField]->options['type']) && $view->field[$labelField]->options['type'] === 'timestamp') {
$renderedLabelField = $view->field[$labelField]
->advancedRender($row);
}
else {
$renderedLabelField = $view->field[$labelField]
->getValue($row);
}
$renderedLabelField = strip_tags($renderedLabelField);
$rowData[$numberFields] = [
'value' => $style_options['fields']['allow_advanced_rendering'] ? $view->field[$fieldId]
->advancedRender($row) : $view->field[$fieldId]
->getValue($row),
'label_field' => $renderedLabelField,
'label' => $view->field[$fieldId]
->label(),
'color' => $color[$fieldId]['color'],
'type' => $attachmentChartTypeOption,
];
$numberFields++;
}
$data[$row_number] = $rowData;
}
return $data;
}
public static function removeUnselectedFields(array $valueField = []) {
$fieldValues = [];
foreach ($valueField as $key => $value) {
if (!empty($value)) {
$fieldValues[$key] = $value;
}
}
return $fieldValues;
}
public static function removeHiddenFields(ViewExecutable $view, array $fieldValues) {
$fields = $view->display_handler
->getOption('fields');
$visibleFields = array_filter($fields, function ($field) {
return !empty($field['exclude']);
});
$visibleFields = array_diff_key($fieldValues, $visibleFields);
return $visibleFields;
}
public static function createChartableData(array $data = []) {
$chartData = [];
$categories = [];
$seriesData = [];
for ($i = 0; $i < count($data[0]); $i++) {
$seriesRowData = [
'name' => '',
'color' => '',
'type' => '',
'data' => [],
];
for ($j = 0; $j < count($data); $j++) {
$categories[$j] = $data[$j][$i]['label_field'];
$seriesRowData['name'] = $data[$j][$i]['label'];
$seriesRowData['type'] = $data[$j][$i]['type'];
$seriesRowData['color'] = $data[$j][$i]['color'];
array_push($seriesRowData['data'], json_decode($data[$j][$i]['value']));
}
array_push($seriesData, $seriesRowData);
}
$chartData[0] = $categories;
$chartData[1] = $seriesData;
return $chartData;
}
public static function checkMissingLibrary($libraryPath = '') {
if (!file_exists(DRUPAL_ROOT . DIRECTORY_SEPARATOR . $libraryPath)) {
\Drupal::service('messenger')
->addMessage(t('Charting libraries might not be installed at the location @libraryPath.', [
'@libraryPath' => $libraryPath,
]), 'error');
}
}
}