You are here

HijriFormatter.php in Hijri 1.0.x

Namespace

Drupal\hijri

File

src/HijriFormatter.php
View source
<?php

namespace Drupal\hijri;

use Drupal\Core\Datetime\DateFormatter;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use ArUtil\I18N\Date;

/**
 * Provides a service to handle Hijri date related functionality.
 *
 * @ingroup i18n
 */
class HijriFormatter extends DateFormatter {

  /**
   * The list of loaded timezones.
   *
   * @var array
   */
  protected $timezones;

  /**
   * The date format storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $dateFormatStorage;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;
  protected $country = NULL;
  protected $dateFormats = [];

  /**
   * Contains the different date interval units.
   *
   * This array is keyed by strings representing the unit (e.g.
   * '1 year|@count years') and with the amount of values of the unit in
   * seconds.
   *
   * @var array
   */
  protected $units = [
    '1 year|@count years' => 31536000,
    '1 month|@count months' => 2592000,
    '1 week|@count weeks' => 604800,
    '1 day|@count days' => 86400,
    '1 hour|@count hours' => 3600,
    '1 min|@count min' => 60,
    '1 sec|@count sec' => 1,
  ];

  /**
   * Constructs a Hijri object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation
   *   The string translation.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, TranslationInterface $translation, ConfigFactoryInterface $config_factory, RequestStack $request_stack) {
    $this->dateFormatStorage = $entity_type_manager
      ->getStorage('date_format');
    $this->languageManager = $language_manager;
    $this->stringTranslation = $translation;
    $this->configFactory = $config_factory;
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {

    // @todo We have to get the correction value as a parameter.
    $correction = 0;
    if (!isset($timezone)) {
      $timezone = date_default_timezone_get();
      $correction = $this->configFactory
        ->get('hijri.config')
        ->get('correction_value');
    }

    // Store DateTimeZone objects in an array rather than repeatedly
    // constructing identical objects over the life of a request.
    if (!isset($this->timezones[$timezone])) {
      $this->timezones[$timezone] = timezone_open($timezone);
    }
    if (empty($langcode)) {
      $langcode = $this->languageManager
        ->getCurrentLanguage()
        ->getId();
    }

    // If we have a non-custom date format use the provided date format pattern.
    if ($type !== 'custom') {
      if ($date_format = $this
        ->dateFormat($type, $langcode)) {
        $format = $date_format
          ->getPattern();
      }
    }

    // Fall back to the 'medium' date format type if the format string is
    // empty, either from not finding a requested date format or being given an
    // empty custom format string.
    if (empty($format)) {
      $format = $this
        ->dateFormat('fallback', $langcode)
        ->getPattern();
    }

    // Use Ar-php date.
    return $this
      ->hijri($format, $timestamp, $correction);

    // Create a DrupalDateTime object from the timestamp and timezone.
    $create_settings = [
      'langcode' => $langcode,
      'country' => $this
        ->country(),
    ];

    // Call $date->format().
    $settings = [
      'langcode' => $langcode,
    ];
    return $date
      ->format($format, $settings);
  }

  /**
   * Retrive Hijri date from given format and timestamp.
   *
   * @param $format
   * @param null $timestamp
   * @param int $correction
   *
   * @return mixed
   */
  public function hijri($format, $timestamp = NULL, $correction = 0) {
    $timestamp = $timestamp == NULL ? time() : $timestamp;
    $patterns = [];
    $replacements = [];
    array_push($patterns, 'Y');
    array_push($replacements, 'x1');
    array_push($patterns, 'y');
    array_push($replacements, 'x2');
    array_push($patterns, 'M');
    array_push($replacements, 'x3');
    array_push($patterns, 'F');
    array_push($replacements, 'x3');
    array_push($patterns, 'n');
    array_push($replacements, 'x4');
    array_push($patterns, 'm');
    array_push($replacements, 'x5');
    array_push($patterns, 'j');
    array_push($replacements, 'x6');
    array_push($patterns, 'd');
    array_push($replacements, 'x7');
    array_push($patterns, 'S');
    array_push($replacements, '');
    $format = str_replace($patterns, $replacements, $format);

    // 1. Converting user given date before any increment.
    $date_result = \Drupal::service('date.formatter')
      ->format($timestamp, 'custom', $format);

    // 2. Preparing timestamp if there is increments?
    if ($correction != 0) {
      $timestamp = $timestamp + 60 * 60 * 24 * $correction;
    }

    // $calc_hijri_date to retrive Hijri Year.
    // Hijri Month and Hijri day in numbers.
    list($y, $m, $d) = explode(' ', \Drupal::service('date.formatter')
      ->format($timestamp, 'custom', 'Y m d'));
    $calc_hijri_date = (new Date())
      ->hjConvert($y, $m, $d);
    $hijri_month_name = $this
      ->hijriMonthNames();

    // 4. Replacing reserved constants with Hijri results.
    $patterns = [];
    $replacements = [];

    // Y.
    $patterns[] = 'x1';
    $replacements[] = $calc_hijri_date[0];

    // Y.
    $patterns[] = 'x2';
    $replacements[] = substr($calc_hijri_date[0], -2);

    // M .. There is no shortname in Hijri month names.
    $patterns[] = 'x3';
    $replacements[] = $hijri_month_name[$calc_hijri_date[1]];

    // N.
    $patterns[] = 'x4';
    $replacements[] = $calc_hijri_date[1];

    // M.
    $patterns[] = 'x5';
    $replacements[] = sprintf('%02d', $calc_hijri_date[1]);

    // J.
    $patterns[] = 'x6';
    $replacements[] = $calc_hijri_date[2];

    // D.
    $patterns[] = 'x7';
    $replacements[] = sprintf('%02d', $calc_hijri_date[2]);
    return str_replace($patterns, $replacements, $date_result);
  }

  /**
   * Retrive Hijri months names.
   */
  public function hijriMonthNames() {

    // This Arabic names should written in English with t() function.
    return [
      '1' => (string) $this
        ->t('Muharram'),
      '2' => (string) $this
        ->t('Safar'),
      '3' => (string) $this
        ->t('Rabia al-Awwal'),
      '4' => (string) $this
        ->t('Rabia ath-Thani'),
      '5' => (string) $this
        ->t('Jumada al-Ula'),
      '6' => (string) $this
        ->t('Jumada ath-Thaniya'),
      '7' => (string) $this
        ->t('Rajab'),
      '8' => (string) $this
        ->t('Shaban'),
      '9' => (string) $this
        ->t('Ramadan'),
      '10' => (string) $this
        ->t('Shawwal'),
      '11' => (string) $this
        ->t('Dhu al-Qada'),
      '12' => (string) $this
        ->t('Dhu al-Hijja'),
    ];
  }

}

Classes

Namesort descending Description
HijriFormatter Provides a service to handle Hijri date related functionality.