You are here

class HijriFormatter in Hijri 3.0.x

Same name in this branch
  1. 3.0.x src/HijriFormatter.php \Drupal\hijri\HijriFormatter
  2. 3.0.x src/Plugin/Field/FieldFormatter/HijriFormatter.php \Drupal\hijri\Plugin\Field\FieldFormatter\HijriFormatter
Same name and namespace in other branches
  1. 8.2 src/HijriFormatter.php \Drupal\hijri\HijriFormatter
  2. 1.0.x src/HijriFormatter.php \Drupal\hijri\HijriFormatter

Provides a service to handle Hijri date related functionality.

Hierarchy

Expanded class hierarchy of HijriFormatter

1 string reference to 'HijriFormatter'
hijri.services.yml in ./hijri.services.yml
hijri.services.yml
1 service uses HijriFormatter
hijri.formatter in ./hijri.services.yml
Drupal\hijri\HijriFormatter

File

src/HijriFormatter.php, line 18

Namespace

Drupal\hijri
View source
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);
  }

  /**
   * 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'),
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DateFormatter::country protected function Returns the default country from config.
DateFormatter::dateFormat protected function Loads the given format pattern for the given langcode.
DateFormatter::formatDiff public function Formats a time interval between two timestamps. Overrides DateFormatterInterface::formatDiff
DateFormatter::formatInterval public function Formats a time interval with the requested granularity. Overrides DateFormatterInterface::formatInterval
DateFormatter::formatTimeDiffSince public function Formats the time difference from a timestamp to the current request time. Overrides DateFormatterInterface::formatTimeDiffSince
DateFormatter::formatTimeDiffUntil public function Formats the time difference from the current request time to a timestamp. Overrides DateFormatterInterface::formatTimeDiffUntil
DateFormatter::getSampleDateFormats public function Provides values for all date formatting characters for a given timestamp. Overrides DateFormatterInterface::getSampleDateFormats
HijriFormatter::$configFactory protected property The configuration factory. Overrides DateFormatter::$configFactory
HijriFormatter::$country protected property Overrides DateFormatter::$country
HijriFormatter::$dateFormats protected property Overrides DateFormatter::$dateFormats
HijriFormatter::$dateFormatStorage protected property The date format storage. Overrides DateFormatter::$dateFormatStorage
HijriFormatter::$languageManager protected property The language manager. Overrides DateFormatter::$languageManager
HijriFormatter::$requestStack protected property The request stack. Overrides DateFormatter::$requestStack
HijriFormatter::$timezones protected property The list of loaded timezones. Overrides DateFormatter::$timezones
HijriFormatter::$units protected property Contains the different date interval units. Overrides DateFormatter::$units
HijriFormatter::format public function Formats a date, using a date type or a custom date format string. Overrides DateFormatter::format
HijriFormatter::hijri public function Retrive Hijri date from given format and timestamp.
HijriFormatter::hijriMonthNames public function Retrive Hijri months names.
HijriFormatter::__construct public function Constructs a Hijri object. Overrides DateFormatter::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.