graph_element-1.0.4/src/Utility.php

src/Utility.php
<?php

namespace Drupal\graph_element;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Logger\LoggerChannelTrait;
use Drupal\Core\Render\Markup;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\rest\ResourceResponse;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
 * Utility class for graph_element module functions.
 *
 * @package Drupal\graph_element
 */
class Utility {

  use StringTranslationTrait;
  use LoggerChannelTrait;

  /**
   * Custom function to make API call to external resource.
   *
   * @var string
   * The X key value.
   *
   * @var string
   * The Y key value.
   *
   * @var string
   * The endpoint value.
   *
   * @var string
   * The method value.
   *
   * @return array
   *   The array of api response.
   */
  public function statsApiCall($graphXKey, $graphYKey, $endpoint, $method = 'GET') {
    $client = new Client();
    $response = [];
    $logger = $this->getLogger('graph_element');

    try {
      $request = $client->request(
        $method,
        $endpoint,
        [
          'timeout' => 5,
        ]
      );
      if ($request->getStatusCode() == 200) {
        $res = $request ? $request->getBody() : '{}';
        $data = $res->getContents();
        $decode = Json::decode($data);
        $all_rows = [];

        foreach ($decode[$graphXKey] as $column => $row) {
          if ($column == 'Slice') {
            continue;
          }
          $convertions = 0;
          foreach ($decode[$graphXKey][$column] as $key => $val) {
            if (isset($decode[$graphXKey][$column][$key][$graphYKey])) {
              $convertions = (int) $decode[$graphXKey][$column][$key][$graphYKey] + $convertions;
            }
            else {
              continue;
            }
          }
          $all_rows[$graphXKey][] = $column;
          $all_rows[$graphYKey][] = $convertions;
        }

        $response = new ResourceResponse($all_rows, 200);

        $response = $response->getResponseData();
      }
      return $response;
    }
    catch (RequestException $e) {
      $logger->error('Charts - Error: @error', ['@error' => json_encode($e->getMessage())]);
      return $response;
    }
  }

  /**
   * Custom function to return saved resources.
   */
  public function getGraphResources($form = NULL) {
    $config = $this->config();
    $savedResources = $config->get('stats_types');
    $graphResources = [];
    if ($form) {
      $graphResources['example'] = 'Example';
      if (!empty($savedResources)) {
        foreach ($savedResources as $value) {
          if (isset($value['name']) && $value['name'] != "" && !empty($value['name'])) {
            $graphResources[$this->cleanString($value['name'])] = $value['name'];
          }
        }
      }
    }
    else {
      if (!empty($savedResources)) {
        foreach ($savedResources as $value) {
          if (isset($value['name']) && $value['name'] != "" && !empty($value['name'])) {
            $graphResources[$this->cleanString($value['name'])] = (object) [];
            $graphResources[$this->cleanString($value['name'])]->name = $value['name'];
            $graphResources[$this->cleanString($value['name'])]->endpoint = $value['endpoint'];
            $graphResources[$this->cleanString($value['name'])]->method = $value['method'];
            $graphResources[$this->cleanString($value['name'])]->x_key_name = $value['x_key_name'];
            $graphResources[$this->cleanString($value['name'])]->x_key = $value['x_key'];
            $graphResources[$this->cleanString($value['name'])]->y_key_name = $value['y_key_name'];
            $graphResources[$this->cleanString($value['name'])]->y_key = $value['y_key'];
          }
        }
      }
    }
    return $graphResources;
  }

  /**
   * Custom function to return graphTypes.
   */
  public function getGraphTypes() {
    $graphTypesOptions = [
      'area' => $this->t('Area'),
      'bar' => $this->t('Bar'),
      'column' => $this->t('Column'),
      'line' => $this->t('Lne'),
      'spline' => $this->t('Spline'),
      'pie' => $this->t('Pie'),
      'donut' => $this->t('Donut'),
    ];
    return $graphTypesOptions;
  }

  /**
   * Custom clean resouce name string.
   */
  public function cleanString($string) {
    // Replaces all spaces with underscores.
    $string = str_replace(' ', '_', $string);
    // Removes special chars.
    $string = preg_replace('/[^A-Za-z0-9\_]/', '', $string);

    // Replaces multiple underscores with single one.
    return preg_replace('/_+/', '_', strtolower($string));
  }

  /**
   * Returns the CSV contents in an array with data organized by column.
   *
   * @return array
   *   The array of rows.
   */
  public function getCsvContents() {
    $file_path = $this->getModulePath();
    $file_name = $file_path . '/fixtures/charts_api_example_file.csv';
    $handle = fopen($file_name, 'r');
    $all_rows = [];
    while ($row = fgetcsv($handle)) {
      $all_rows['Week'][] = $row[0];
      $all_rows['7.x-2.x'][] = (int) $row[4];
      $all_rows['8.x-3.x'][] = (int) $row[6];
      $all_rows['5.0.x'][] = (int) $row[8];
    }
    fclose($handle);

    return $all_rows;
  }

  /**
   * Returns the chart element.
   *
   * @return array
   *   The array of rows.
   */
  public function renderChart($prefix, $configBlock, $gaphDataXKey, $gaphDataYKey, $data, $labels, $idPrefix) {
    // Render the element.
    $chart = [
      '#type' => 'chart',
      '#content_prefix' => [
        '#type' => 'markup',
        '#markup' => Markup::create($prefix),
      ],
      '#id' => isset($configBlock['graph_type']) ? $idPrefix . '_js_' . $configBlock['graph_type'] . '_' . $configBlock['graph_source'] : $idPrefix . '_js_donut_' . $configBlock['graph_source'] . $this->cleanString($gaphDataXKey),
      '#chart_id' => isset($configBlock['graph_type']) ? $idPrefix . $configBlock['graph_type'] . '_' . $configBlock['graph_source'] : $idPrefix . '_donut_' . $configBlock['graph_source'] . $this->cleanString($gaphDataXKey),
      '#chart_type' => $configBlock['graph_type'] ?? 'donut',

    ];
    $chart['series'] = [
      '#type' => 'chart_data',
      '#title' => $gaphDataYKey && $gaphDataXKey ? $gaphDataYKey . ' ' . $this->t('in') . ' ' . $gaphDataXKey : $this->t('Responses'),
      '#data' => $data,
    ];
    $chart['xaxis'] = [
      '#type' => 'chart_xaxis',
      '#title' => $gaphDataXKey ? $gaphDataXKey : $this->t('Month'),
      '#labels' => $labels,
    ];
    $chart['y_axis'] = [
      '#type' => 'chart_yaxis',
      '#title' => $gaphDataYKey && $gaphDataXKey ? $gaphDataYKey . ' ' . $this->t('in') . ' ' . $gaphDataXKey : $this->t('Responses'),
      '#labels' => $data,
    ];
    return $chart;
  }

  /**
   * Retrieves the container.
   *
   * @return mixed
   *   The container.
   */
  public static function getContainer() {
    return \Drupal::getContainer();
  }

  /**
   * Retrieves the configuration settings.
   *
   * @return object
   *   The configuration settings.
   */
  public static function config() {
    return static::getContainer()
      ->get('config.factory')
      ->get('graph_element.settings');
  }

  /**
   * Returns the path of the module.
   *
   * @return string
   *   The path of the module.
   */
  public static function getModulePath() {
    return static::getContainer()
      ->get('extension.list.module')
      ->getPath('graph_element');
  }

  /**
   * Retrieves the specified module by name.
   *
   * @param string $module_name
   *   The name of the module to retrieve.
   *
   * @return mixed|null
   *   The module object if found, null otherwise.
   */
  public static function getModule($module_name) {
    return static::getContainer()
      ->get('extension.list.module')
      ->get($module_name);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc