PersianDateFormatter.php in Persian Date for Drupal 8 8.4
File
src/Service/Formatter/PersianDateFormatter.php
View source
<?php
namespace Drupal\persian_date\Service\Formatter;
use Drupal\Core\Datetime\DateFormatter;
use Drupal\persian_date\Converter\PersianDateConverter;
use Drupal\persian_date\Converter\PersianDateFactory;
use Drupal\persian_date\PersianLanguageDiscovery;
class PersianDateFormatter extends DateFormatter {
public function format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
if (!PersianLanguageDiscovery::isPersian() || $this
->isForMetaTag()) {
return parent::format($timestamp, $type, $format, $timezone, $langcode);
}
if (!isset($timezone)) {
$timezone = drupal_get_user_timezone();
}
if (!isset($this->timezones[$timezone])) {
$this->timezones[$timezone] = timezone_open($timezone);
}
if (empty($langcode)) {
$langcode = $this->languageManager
->getCurrentLanguage()
->getId();
}
$date = PersianDateFactory::buildFromTimestamp($timestamp, $this->timezones[$timezone]);
if ($type !== 'custom') {
if ($date_format = $this
->dateFormat($type, $langcode)) {
$format = $date_format
->getPattern();
}
}
if ($type === 'custom' & $format === DATETIME_DATETIME_STORAGE_FORMAT) {
$date = parent::format($timestamp, $type, $format, $timezone, $langcode);
$year = explode('-', $date)[0];
if (!is_georgian_year($year)) {
$other = PersianDateConverter::normalizeDate(new \DateTime($date));
$date = parent::format($other
->getTimestamp(), $type, $format, $timezone, $langcode);
}
return $date;
}
if (empty($format)) {
$format = $this
->dateFormat('fallback', $langcode)
->getPattern();
}
return $date
->format($format);
}
private function isForMetaTag() {
foreach (debug_backtrace() as $trace) {
if (!isset($trace['file'])) {
continue;
}
$isMetatagModuleCalling = strpos($trace['file'], '/metatag/') !== FALSE;
$isRdfModuleCalling = strpos($trace['file'], '/rdf/') !== FALSE;
if ($isMetatagModuleCalling || $isRdfModuleCalling) {
return TRUE;
}
}
return FALSE;
}
}