Issue #2149197 by penyaskito, mikey_p, vijaycs85, herom: Replace format_interval with \Drupal::service('date')->formatInterval().

8.0.x
Alex Pott 2014-07-24 15:54:28 +01:00
parent 0872feb107
commit 5783e08f16
41 changed files with 361 additions and 152 deletions

View File

@ -319,9 +319,9 @@ function _batch_process() {
'@total' => $total,
'@current' => floor($current),
'@percentage' => $percentage,
'@elapsed' => format_interval($elapsed / 1000),
'@elapsed' => \Drupal::service('date')->formatInterval($elapsed / 1000),
// If possible, estimate remaining processing time.
'@estimate' => ($current > 0) ? format_interval(($elapsed * ($total - $current) / $current) / 1000) : '-',
'@estimate' => ($current > 0) ? \Drupal::service('date')->formatInterval(($elapsed * ($total - $current) / $current) / 1000) : '-',
);
$message = strtr($progress_message, $values);
if (!empty($task_message)) {
@ -410,7 +410,7 @@ function _batch_finished() {
if (is_callable($batch_set['finished'])) {
$queue = _batch_queue($batch_set);
$operations = $queue->getAllItems();
call_user_func_array($batch_set['finished'], array($batch_set['success'], $batch_set['results'], $operations, format_interval($batch_set['elapsed'] / 1000)));
call_user_func_array($batch_set['finished'], array($batch_set['success'], $batch_set['results'], $operations, \Drupal::service('date')->formatInterval($batch_set['elapsed'] / 1000)));
}
}
}

View File

@ -33,7 +33,7 @@ function template_preprocess_aggregator_item(&$variables) {
$variables['source_title'] = String::checkPlain($item->ftitle);
}
if (date('Ymd', $item->getPostedTime()) == date('Ymd')) {
$variables['source_date'] = t('%ago ago', array('%ago' => format_interval(REQUEST_TIME - $item->getPostedTime())));
$variables['source_date'] = t('%ago ago', array('%ago' => \Drupal::service('date')->formatInterval(REQUEST_TIME - $item->getPostedTime())));
}
else {
$variables['source_date'] = format_date($item->getPostedTime(), 'medium');
@ -121,7 +121,7 @@ function template_preprocess_aggregator_summary_item(&$variables) {
'datetime' => format_date($item->getPostedTime(), 'html_datetime', '', 'UTC'),
'class' => array('feed-item-age',),
),
'#text' => t('%age old', array('%age' => format_interval(REQUEST_TIME - $item->getPostedTime()))),
'#text' => t('%age old', array('%age' => \Drupal::service('date')->formatInterval(REQUEST_TIME - $item->getPostedTime()))),
'#html' => TRUE,
);
}
@ -161,7 +161,7 @@ function template_preprocess_aggregator_feed_source(&$variables) {
$variables['source_url'] = check_url(url($feed->getWebsiteUrl(), array('absolute' => TRUE)));
if ($feed->checked) {
$variables['last_checked'] = t('@time ago', array('@time' => format_interval(REQUEST_TIME - $feed->getLastCheckedTime())));
$variables['last_checked'] = t('@time ago', array('@time' => \Drupal::service('date')->formatInterval(REQUEST_TIME - $feed->getLastCheckedTime())));
}
else {
$variables['last_checked'] = t('never');

View File

@ -9,15 +9,43 @@ namespace Drupal\aggregator\Controller;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\aggregator\FeedInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for aggregator module routes.
*/
class AggregatorController extends ControllerBase {
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a \Drupal\aggregator\Controller\AggregatorController object.
*
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(DateFormatter $date_formatter) {
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('date')
);
}
/**
* Presents the aggregator feed creation form.
*
@ -114,11 +142,11 @@ class AggregatorController extends ControllerBase {
foreach ($feeds as $feed) {
$row = array();
$row[] = l($feed->label(), "aggregator/sources/" . $feed->id());
$row[] = format_plural($entity_manager->getStorage('aggregator_item')->getItemCount($feed), '1 item', '@count items');
$row[] = $this->dateFormatter->formatInterval($entity_manager->getStorage('aggregator_item')->getItemCount($feed), '1 item', '@count items');
$last_checked = $feed->getLastCheckedTime();
$refresh_rate = $feed->getRefreshRate();
$row[] = ($last_checked ? $this->t('@time ago', array('@time' => format_interval(REQUEST_TIME - $last_checked))) : $this->t('never'));
$row[] = ($last_checked && $refresh_rate ? $this->t('%time left', array('%time' => format_interval($last_checked + $refresh_rate - REQUEST_TIME))) : $this->t('never'));
$row[] = ($last_checked ? $this->t('@time ago', array('@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked))) : $this->t('never'));
$row[] = ($last_checked && $refresh_rate ? $this->t('%time left', array('%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME))) : $this->t('never'));
$links['edit'] = array(
'title' => $this->t('Edit'),
'route_name' => 'aggregator.feed_configure',

View File

@ -162,7 +162,7 @@ class Feed extends ContentEntityBase implements FeedInterface {
));
$intervals = array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200);
$period = array_map('format_interval', array_combine($intervals, $intervals));
$period = array_map(array(\Drupal::service('date'), 'formatInterval'), array_combine($intervals, $intervals));
$period[AGGREGATOR_CLEAR_NEVER] = t('Never');
$fields['refresh'] = FieldDefinition::create('list_integer')

View File

@ -68,7 +68,7 @@ class OpmlFeedAdd extends FormBase {
*/
public function buildForm(array $form, array &$form_state) {
$intervals = array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200);
$period = array_map('format_interval', array_combine($intervals, $intervals));
$period = array_map(array(\Drupal::service('date'), 'formatInterval'), array_combine($intervals, $intervals));
$form['upload'] = array(
'#type' => 'file',

View File

@ -13,6 +13,7 @@ use Drupal\aggregator\Plugin\ProcessorInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -51,6 +52,13 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
*/
protected $itemStorage;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a DefaultProcessor object.
*
@ -66,11 +74,14 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
* The entity query object for feed items.
* @param \Drupal\aggregator\ItemStorageInterface $item_storage
* The entity storage for feed items.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, QueryInterface $item_query, ItemStorageInterface $item_storage) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, QueryInterface $item_query, ItemStorageInterface $item_storage, DateFormatter $date_formatter) {
$this->configFactory = $config;
$this->itemStorage = $item_storage;
$this->itemQuery = $item_query;
$this->dateFormatter = $date_formatter;
// @todo Refactor aggregator plugins to ConfigEntity so merging
// the configuration here is not needed.
parent::__construct($configuration + $this->getConfiguration(), $plugin_id, $plugin_definition);
@ -86,7 +97,8 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
$plugin_definition,
$container->get('config.factory'),
$container->get('entity.query')->get('aggregator_item'),
$container->get('entity.manager')->getStorage('aggregator_item')
$container->get('entity.manager')->getStorage('aggregator_item'),
$container->get('date')
);
}
@ -98,10 +110,10 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
$info = $this->getPluginDefinition();
$counts = array(3, 5, 10, 15, 20, 25);
$items = array_map(function ($count) {
return format_plural($count, '1 item', '@count items');
return $this->dateFormatter->formatInterval($count, '1 item', '@count items');
}, array_combine($counts, $counts));
$intervals = array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800);
$period = array_map('format_interval', array_combine($intervals, $intervals));
$period = array_map(array($this->dateFormatter, 'formatInterval'), array_combine($intervals, $intervals));
$period[AGGREGATOR_CLEAR_NEVER] = t('Never');
$form['processors'][$info['id']] = array();

View File

@ -65,7 +65,6 @@ abstract class BlockBase extends ContextAwarePluginBase implements BlockPluginIn
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->setConfiguration($configuration);
}
@ -227,7 +226,7 @@ abstract class BlockBase extends ContextAwarePluginBase implements BlockPluginIn
// Identical options to the ones for page caching.
// @see \Drupal\system\Form\PerformanceForm::buildForm()
$period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400);
$period = array_map('format_interval', array_combine($period, $period));
$period = array_map(array(\Drupal::service('date'), 'formatInterval'), array_combine($period, $period));
$period[0] = '<' . t('no caching') . '>';
$period[\Drupal\Core\Cache\Cache::PERMANENT] = t('Forever');
$form['cache'] = array(

View File

@ -61,7 +61,7 @@ class BlockInterfaceTest extends DrupalUnitTestBase {
$definition = $display_block->getPluginDefinition();
$period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400);
$period = array_map('format_interval', array_combine($period, $period));
$period = array_map(array(\Drupal::service('date'), 'formatInterval'), array_combine($period, $period));
$period[0] = '<' . t('no caching') . '>';
$period[\Drupal\Core\Cache\Cache::PERMANENT] = t('Forever');
$contexts = \Drupal::service("cache_contexts")->getLabels();

View File

@ -10,7 +10,7 @@ namespace Drupal\comment\Form;
use Drupal\comment\CommentInterface;
use Drupal\comment\CommentStorageInterface;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
@ -36,11 +36,11 @@ class CommentAdminOverview extends FormBase {
protected $commentStorage;
/**
* Date service object.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $date;
protected $dateFormatter;
/**
* The module handler.
@ -56,15 +56,15 @@ class CommentAdminOverview extends FormBase {
* The entity manager service.
* @param \Drupal\comment\CommentStorageInterface $comment_storage
* The comment storage.
* @param \Drupal\Core\Datetime\Date $date
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(EntityManagerInterface $entity_manager, CommentStorageInterface $comment_storage, Date $date, ModuleHandlerInterface $module_handler) {
public function __construct(EntityManagerInterface $entity_manager, CommentStorageInterface $comment_storage, DateFormatter $date_formatter, ModuleHandlerInterface $module_handler) {
$this->entityManager = $entity_manager;
$this->commentStorage = $comment_storage;
$this->date = $date;
$this->dateFormatter = $date_formatter;
$this->moduleHandler = $module_handler;
}
@ -209,7 +209,7 @@ class CommentAdminOverview extends FormBase {
'#access' => $commented_entity->access('view'),
) + $commented_entity->urlInfo()->toRenderArray(),
),
'changed' => $this->date->format($comment->getChangedTime(), 'short'),
'changed' => $this->dateFormatter->format($comment->getChangedTime(), 'short'),
);
$comment_uri_options = $comment->urlInfo()->getOptions();
$links = array();

View File

@ -59,8 +59,8 @@ class CommentTokenReplaceTest extends CommentTestBase {
$tests['[comment:body]'] = $comment->comment_body->processed;
$tests['[comment:url]'] = url('comment/' . $comment->id(), $url_options + array('fragment' => 'comment-' . $comment->id()));
$tests['[comment:edit-url]'] = url('comment/' . $comment->id() . '/edit', $url_options);
$tests['[comment:created:since]'] = format_interval(REQUEST_TIME - $comment->getCreatedTime(), 2, $language_interface->id);
$tests['[comment:changed:since]'] = format_interval(REQUEST_TIME - $comment->getChangedTime(), 2, $language_interface->id);
$tests['[comment:created:since]'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $comment->getCreatedTime(), 2, $language_interface->id);
$tests['[comment:changed:since]'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $comment->getChangedTime(), 2, $language_interface->id);
$tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
$tests['[comment:parent:title]'] = String::checkPlain($parent_comment->getSubject());
$tests['[comment:node:nid]'] = $comment->getCommentedEntityId();

View File

@ -8,6 +8,7 @@
namespace Drupal\contact\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Flood\FloodInterface;
use Drupal\contact\CategoryInterface;
use Drupal\user\UserInterface;
@ -28,14 +29,24 @@ class ContactController extends ControllerBase {
*/
protected $flood;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a ContactController object.
*
* @param \Drupal\Core\Flood\FloodInterface $flood
* The flood service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date service.
*/
public function __construct(FloodInterface $flood) {
public function __construct(FloodInterface $flood, DateFormatter $date_formatter) {
$this->flood = $flood;
$this->dateFormatter = $date_formatter;
}
/**
@ -43,7 +54,8 @@ class ContactController extends ControllerBase {
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('flood')
$container->get('flood'),
$container->get('date')
);
}
@ -131,7 +143,7 @@ class ContactController extends ControllerBase {
if (!$this->flood->isAllowed('contact', $limit, $interval)) {
drupal_set_message($this->t('You cannot send more than %limit messages in @interval. Try again later.', array(
'%limit' => $limit,
'@interval' => format_interval($interval),
'@interval' => $this->dateFormatter->formatInterval($interval),
)), 'error');
throw new AccessDeniedHttpException();
}

View File

@ -209,7 +209,7 @@ class ContactPersonalTest extends WebTestBase {
// Submit contact form one over limit.
$this->drupalGet('user/' . $this->contact_user->id(). '/contact');
$this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => $flood_limit, '@interval' => format_interval(\Drupal::config('contact.settings')->get('flood.interval')))), 'Normal user denied access to flooded contact form.');
$this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => $flood_limit, '@interval' => \Drupal::service('date')->formatInterval(\Drupal::config('contact.settings')->get('flood.interval')))), 'Normal user denied access to flooded contact form.');
// Test that the admin user can still access the contact form even though
// the flood limit was reached.

View File

@ -212,7 +212,7 @@ class ContactSitewideTest extends WebTestBase {
// Submit contact form one over limit.
$this->drupalGet('contact');
$this->assertResponse(403);
$this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => \Drupal::config('contact.settings')->get('flood.limit'), '@interval' => format_interval(600))));
$this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => \Drupal::config('contact.settings')->get('flood.limit'), '@interval' => \Drupal::service('date')->formatInterval(600))));
// Test listing controller.
$this->drupalLogin($admin_user);

View File

@ -7,7 +7,7 @@
namespace Drupal\datetime\Plugin\Field\FieldFormatter;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
@ -39,11 +39,11 @@ class DateTimeDefaultFormatter extends FormatterBase implements ContainerFactory
}
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateService;
protected $dateFormatter;
/**
* The date storage.
@ -69,15 +69,15 @@ class DateTimeDefaultFormatter extends FormatterBase implements ContainerFactory
* The view mode.
* @param array $third_party_settings
* Third party settings.
* @param \Drupal\Core\Datetime\Date $date_service
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
* @param \Drupal\Core\Entity\EntityStorageInterface $date_storage
* The date storage.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, Date $date_service, EntityStorageInterface $date_storage) {
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatter $date_formatter, EntityStorageInterface $date_storage) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->dateService = $date_service;
$this->dateFormatter = $date_formatter;
$this->dateStorage = $date_storage;
}
@ -156,7 +156,7 @@ class DateTimeDefaultFormatter extends FormatterBase implements ContainerFactory
*/
function dateFormat($date) {
$format_type = $this->getSetting('format_type');
return $this->dateService->format($date->getTimestamp(), $format_type);
return $this->dateFormatter->format($date->getTimestamp(), $format_type);
}
/**
@ -166,7 +166,7 @@ class DateTimeDefaultFormatter extends FormatterBase implements ContainerFactory
$time = new DrupalDateTime();
$format_types = $this->dateStorage->loadMultiple();
foreach ($format_types as $type => $type_info) {
$format = $this->dateService->format($time->format('U'), $type);
$format = $this->dateFormatter->format($time->format('U'), $type);
$options[$type] = $type_info->label() . ' (' . $format . ')';
}

View File

@ -12,7 +12,7 @@ use Drupal\Component\Utility\String;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -37,11 +37,11 @@ class DbLogController extends ControllerBase {
protected $moduleHandler;
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $date;
protected $dateFormatter;
/**
* The form builder service.
@ -69,15 +69,15 @@ class DbLogController extends ControllerBase {
* A database connection.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* A module handler.
* @param \Drupal\Core\Datetime\Date $date
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder service.
*/
public function __construct(Connection $database, ModuleHandlerInterface $module_handler, Date $date, FormBuilderInterface $form_builder) {
public function __construct(Connection $database, ModuleHandlerInterface $module_handler, DateFormatter $date_formatter, FormBuilderInterface $form_builder) {
$this->database = $database;
$this->moduleHandler = $module_handler;
$this->date = $date;
$this->dateFormatter = $date_formatter;
$this->formBuilder = $form_builder;
}
@ -184,7 +184,7 @@ class DbLogController extends ControllerBase {
// Cells.
array('class' => array('icon')),
$this->t($dblog->type),
$this->date->format($dblog->timestamp, 'short'),
$this->dateFormatter->format($dblog->timestamp, 'short'),
$message,
array('data' => $username),
Xss::filter($dblog->link),
@ -237,7 +237,7 @@ class DbLogController extends ControllerBase {
),
array(
array('data' => $this->t('Date'), 'header' => TRUE),
$this->date->format($dblog->timestamp, 'long'),
$this->dateFormatter->format($dblog->timestamp, 'long'),
),
array(
array('data' => $this->t('User'), 'header' => TRUE),

View File

@ -737,7 +737,7 @@ function template_preprocess_forum_submitted(&$variables) {
$username = array('#theme' => 'username', '#account' => user_load($variables['topic']->uid));
$variables['author'] = drupal_render($username);
}
$variables['time'] = isset($variables['topic']->created) ? format_interval(REQUEST_TIME - $variables['topic']->created) : '';
$variables['time'] = isset($variables['topic']->created) ? \Drupal::service('date')->formatInterval(REQUEST_TIME - $variables['topic']->created) : '';
}
/**

View File

@ -156,6 +156,6 @@ function template_preprocess_locale_translation_update_info(&$variables) {
function template_preprocess_locale_translation_last_check(&$variables) {
$last = $variables['last'];
$variables['last_checked'] = ($last != NULL);
$variables['time'] = format_interval(REQUEST_TIME - $last);
$variables['time'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $last);
$variables['link'] = l(t('Check manually'), 'admin/reports/translations/check', array('query' => drupal_get_destination()));
}

View File

@ -10,7 +10,7 @@ namespace Drupal\node\Controller;
use Drupal\Component\Utility\String;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\node\NodeInterface;
@ -22,20 +22,20 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
class NodeController extends ControllerBase implements ContainerInjectionInterface {
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $date;
protected $dateFormatter;
/**
* Constructs a NodeController object.
*
* @param \Drupal\Core\Datetime\Date $date
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(Date $date) {
$this->date = $date;
public function __construct(DateFormatter $date_formatter) {
$this->dateFormatter = $date_formatter;
}
/**
@ -173,7 +173,7 @@ class NodeController extends ControllerBase implements ContainerInjectionInterfa
'#theme' => 'username',
'#account' => $revision_author,
);
$row[] = array('data' => $this->t('!date by !username', array('!date' => $this->l($this->date->format($revision->revision_timestamp->value, 'short'), 'node.view', array('node' => $node->id())), '!username' => drupal_render($username)))
$row[] = array('data' => $this->t('!date by !username', array('!date' => $this->l($this->dateFormatter->format($revision->revision_timestamp->value, 'short'), 'node.view', array('node' => $node->id())), '!username' => drupal_render($username)))
. (($revision->revision_log->value != '') ? '<p class="revision-log">' . Xss::filter($revision->revision_log->value) . '</p>' : ''),
'class' => array('revision-current'));
$row[] = array('data' => String::placeholder($this->t('current revision')), 'class' => array('revision-current'));
@ -183,7 +183,7 @@ class NodeController extends ControllerBase implements ContainerInjectionInterfa
'#theme' => 'username',
'#account' => $revision_author,
);
$row[] = $this->t('!date by !username', array('!date' => $this->l($this->date->format($revision->revision_timestamp->value, 'short'), 'node.revision_show', array('node' => $node->id(), 'node_revision' => $vid)), '!username' => drupal_render($username)))
$row[] = $this->t('!date by !username', array('!date' => $this->l($this->dateFormatter->format($revision->revision_timestamp->value, 'short'), 'node.revision_show', array('node' => $node->id(), 'node_revision' => $vid)), '!username' => drupal_render($username)))
. (($revision->revision_log->value != '') ? '<p class="revision-log">' . Xss::filter($revision->revision_log->value) . '</p>' : '');
if ($revert_permission) {

View File

@ -8,7 +8,7 @@
namespace Drupal\node;
use Drupal\Component\Utility\String;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
@ -24,11 +24,11 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
class NodeListBuilder extends EntityListBuilder {
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateService;
protected $dateFormatter;
/**
* Constructs a new NodeListBuilder object.
@ -37,13 +37,13 @@ class NodeListBuilder extends EntityListBuilder {
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Drupal\Core\Datetime\Date $date_service
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, Date $date_service) {
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, DateFormatter $date_formatter) {
parent::__construct($entity_type, $storage);
$this->dateService = $date_service;
$this->dateFormatter = $date_formatter;
}
/**
@ -112,7 +112,7 @@ class NodeListBuilder extends EntityListBuilder {
'#account' => $entity->getOwner(),
);
$row['status'] = $entity->isPublished() ? $this->t('published') : $this->t('not published');
$row['changed'] = $this->dateService->format($entity->getChangedTime(), 'short');
$row['changed'] = $this->dateFormatter->format($entity->getChangedTime(), 'short');
$language_manager = \Drupal::languageManager();
if ($language_manager->isMultilingual()) {
$row['language_name'] = $language_manager->getLanguageName($langcode);

View File

@ -8,7 +8,7 @@
namespace Drupal\system;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
@ -22,11 +22,11 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
class DateFormatListBuilder extends ConfigEntityListBuilder {
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateService;
protected $dateFormatter;
/**
* Constructs a new DateFormatListBuilder object.
@ -35,13 +35,13 @@ class DateFormatListBuilder extends ConfigEntityListBuilder {
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Drupal\Core\Datetime\Date $date_service
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, Date $date_service) {
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, DateFormatter $date_formatter) {
parent::__construct($entity_type, $storage);
$this->dateService = $date_service;
$this->dateFormatter = $date_formatter;
}
/**
@ -76,7 +76,7 @@ class DateFormatListBuilder extends ConfigEntityListBuilder {
$row['id'] = $entity->id();
}
$row['label'] = $this->getLabel($entity);
$row['pattern'] = $this->dateService->format(REQUEST_TIME, $entity->id());
$row['pattern'] = $this->dateFormatter->format(REQUEST_TIME, $entity->id());
return $row + parent::buildRow($entity);
}

View File

@ -9,6 +9,7 @@ namespace Drupal\system\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\CronInterface;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -33,6 +34,13 @@ class CronForm extends ConfigFormBase {
*/
protected $cron;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a CronForm object.
*
@ -42,11 +50,14 @@ class CronForm extends ConfigFormBase {
* The state key value store.
* @param \Drupal\Core\CronInterface $cron
* The cron service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, CronInterface $cron) {
public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, CronInterface $cron, DateFormatter $date_formatter) {
parent::__construct($config_factory);
$this->state = $state;
$this->cron = $cron;
$this->dateFormatter = $date_formatter;
}
/**
@ -56,7 +67,8 @@ class CronForm extends ConfigFormBase {
return new static(
$container->get('config.factory'),
$container->get('state'),
$container->get('cron')
$container->get('cron'),
$container->get('date')
);
}
@ -82,7 +94,7 @@ class CronForm extends ConfigFormBase {
'#submit' => array(array($this, 'submitCron')),
);
$status = '<p>' . t('Last run: %cron-last ago.', array('%cron-last' => format_interval(REQUEST_TIME - $this->state->get('system.cron_last')))) . '</p>';
$status = '<p>' . t('Last run: %cron-last ago.', array('%cron-last' => $this->dateFormatter->formatInterval(REQUEST_TIME - $this->state->get('system.cron_last')))) . '</p>';
$form['status'] = array(
'#markup' => $status,
);
@ -102,7 +114,7 @@ class CronForm extends ConfigFormBase {
'#title' => t('Run cron every'),
'#description' => t('More information about setting up scheduled tasks can be found by <a href="@url">reading the cron tutorial on drupal.org</a>.', array('@url' => url('http://drupal.org/cron'))),
'#default_value' => $config->get('threshold.autorun'),
'#options' => array(0 => t('Never')) + array_map('format_interval', array_combine($options, $options)),
'#options' => array(0 => t('Never')) + array_map(array($this->dateFormatter, 'formatInterval'), array_combine($options, $options)),
);
return parent::buildForm($form, $form_state);

View File

@ -7,7 +7,7 @@
namespace Drupal\system\Form;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -18,20 +18,20 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
class DateFormatDeleteForm extends EntityConfirmFormBase {
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateService;
protected $dateFormatter;
/**
* Constructs an DateFormatDeleteForm object.
*
* @param \Drupal\Core\Datetime\Date $date_service
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(Date $date_service) {
$this->dateService = $date_service;
public function __construct(DateFormatter $date_formatter) {
$this->dateFormatter = $date_formatter;
}
/**
@ -49,7 +49,7 @@ class DateFormatDeleteForm extends EntityConfirmFormBase {
public function getQuestion() {
return t('Are you sure you want to remove the format %name : %format?', array(
'%name' => $this->entity->label(),
'%format' => $this->dateService->format(REQUEST_TIME, $this->entity->id()))
'%format' => $this->dateFormatter->format(REQUEST_TIME, $this->entity->id()))
);
}

View File

@ -18,7 +18,7 @@ class DateFormatEditForm extends DateFormatFormBase {
public function form(array $form, array &$form_state) {
$form = parent::form($form, $form_state);
$now = t('Displayed as %date', array('%date' => $this->dateService->format(REQUEST_TIME, $this->entity->id())));
$now = t('Displayed as %date', array('%date' => $this->dateFormatter->format(REQUEST_TIME, $this->entity->id())));
$form['date_format_pattern']['#field_suffix'] = ' <small id="edit-date-format-suffix">' . $now . '</small>';
$form['date_format_pattern']['#default_value'] = $this->entity->getPattern();

View File

@ -10,7 +10,7 @@ namespace Drupal\system\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Config\Entity\ConfigEntityStorageInterface;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Language\LanguageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Datetime\DrupalDateTime;
@ -22,11 +22,11 @@ use Drupal\Core\Entity\EntityForm;
abstract class DateFormatFormBase extends EntityForm {
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateService;
protected $dateFormatter;
/**
* The date format storage.
@ -38,15 +38,15 @@ abstract class DateFormatFormBase extends EntityForm {
/**
* Constructs a new date format form.
*
* @param \Drupal\Core\Datetime\Date $date_service
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date service.
* @param \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $date_format_storage
* The date format storage.
*/
public function __construct(Date $date_service, ConfigEntityStorageInterface $date_format_storage) {
public function __construct(DateFormatter $date_formatter, ConfigEntityStorageInterface $date_format_storage) {
$date = new DrupalDateTime();
$this->dateService = $date_service;
$this->dateFormatter = $date_formatter;
$this->dateFormatStorage = $date_format_storage;
}

View File

@ -8,14 +8,47 @@
namespace Drupal\system\Form;
use Drupal\Component\Utility\String;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configure file system settings for this site.
*/
class FileSystemForm extends ConfigFormBase {
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a FileSystemForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(ConfigFactoryInterface $config_factory, DateFormatter $date_formatter) {
parent::__construct($config_factory);
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static (
$container->get('config.factory'),
$container->get('date')
);
}
/**
* {@inheritdoc}
*/
@ -70,7 +103,7 @@ class FileSystemForm extends ConfigFormBase {
}
$intervals = array(0, 21600, 43200, 86400, 604800, 2419200, 7776000);
$period = array_combine($intervals, array_map('format_interval', $intervals));
$period = array_combine($intervals, array_map(array($this->dateFormatter, 'formatInterval'), $intervals));
$period[0] = t('Never');
$form['temporary_maximum_age'] = array(
'#type' => 'select',

View File

@ -10,6 +10,7 @@ namespace Drupal\system\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Datetime\Date as DateFormatter;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@ -24,17 +25,27 @@ class PerformanceForm extends ConfigFormBase {
*/
protected $renderCache;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a PerformanceForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Cache\CacheBackendInterface $render_cache
* @param \Drupal\Core\Datetime\Date $date_formater
* The date formatter service.
*/
public function __construct(ConfigFactoryInterface $config_factory, CacheBackendInterface $render_cache) {
public function __construct(ConfigFactoryInterface $config_factory, CacheBackendInterface $render_cache, DateFormatter $date_formater) {
parent::__construct($config_factory);
$this->renderCache = $render_cache;
$this->dateFormatter = $date_formater;
}
/**
@ -43,7 +54,8 @@ class PerformanceForm extends ConfigFormBase {
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('cache.render')
$container->get('cache.render'),
$container->get('date')
);
}
@ -82,7 +94,7 @@ class PerformanceForm extends ConfigFormBase {
// Identical options to the ones for block caching.
// @see \Drupal\block\BlockBase::buildConfigurationForm()
$period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400);
$period = array_map('format_interval', array_combine($period, $period));
$period = array_map(array($this->dateFormatter, 'formatInterval'), array_combine($period, $period));
$period[0] = '<' . t('no caching') . '>';
$form['caching']['page_cache_maximum_age'] = array(
'#type' => 'select',

View File

@ -1666,7 +1666,7 @@ function hook_requirements($phase) {
$cron_last = \Drupal::state()->get('system.cron_last');
if (is_numeric($cron_last)) {
$requirements['cron']['value'] = t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
$requirements['cron']['value'] = t('Last run !time ago', array('!time' => \Drupal::service('date')->formatInterval(REQUEST_TIME - $cron_last)));
}
else {
$requirements['cron'] = array(

View File

@ -309,7 +309,7 @@ function system_requirements($phase) {
}
// Set summary and description based on values determined above.
$summary = t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
$summary = t('Last run !time ago', array('!time' => \Drupal::service('date')->formatInterval(REQUEST_TIME - $cron_last)));
$description = '';
if ($severity != REQUIREMENT_INFO) {
$description = t('Cron has not run recently.') . ' ' . $help;

View File

@ -68,7 +68,7 @@ function system_token_info() {
);
$date['since'] = array(
'name' => t("Time-since"),
'description' => t("A date in 'time-since' format. (%date)", array('%date' => format_interval(REQUEST_TIME - 360, 2))),
'description' => t("A date in 'time-since' format. (%date)", array('%date' => \Drupal::service('date')->formatInterval(REQUEST_TIME - 360, 2))),
);
$date['raw'] = array(
'name' => t("Raw timestamp"),
@ -157,7 +157,7 @@ function system_tokens($type, $tokens, array $data = array(), array $options = a
break;
case 'since':
$replacements[$original] = format_interval((REQUEST_TIME - $date), 2, $langcode);
$replacements[$original] = \Drupal::service('date')->formatInterval((REQUEST_TIME - $date), 2, $langcode);
break;
case 'raw':

View File

@ -92,7 +92,7 @@ function tracker_page($account = NULL) {
'title' => array('data' => l($node->getTitle(), 'node/' . $node->id()) . ' ' . drupal_render($mark_build)),
'author' => array('data' => array('#theme' => 'username', '#account' => $node->getOwner())),
'replies' => array('class' => array('replies'), 'data' => $comments),
'last updated' => array('data' => t('!time ago', array('!time' => format_interval(REQUEST_TIME - $node->last_activity)))),
'last updated' => array('data' => t('!time ago', array('!time' => \Drupal::service('date')->formatInterval(REQUEST_TIME - $node->last_activity)))),
);
$rows[] = $row;

View File

@ -13,7 +13,7 @@ use Drupal\user\UserInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\user\UserStorageInterface;
/**
@ -22,11 +22,11 @@ use Drupal\user\UserStorageInterface;
class UserController extends ControllerBase {
/**
* The date formatting service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $date;
protected $dateFormatter;
/**
* The user storage.
@ -38,13 +38,13 @@ class UserController extends ControllerBase {
/**
* Constructs a UserController object.
*
* @param \Drupal\Core\Datetime\Date $date
* The date formatting service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
* @param \Drupal\user\UserStorageInterface $user_storage
* The user storage.
*/
public function __construct(Date $date, UserStorageInterface $user_storage) {
$this->date = $date;
public function __construct(DateFormatter $date_formatter, UserStorageInterface $user_storage) {
$this->dateFormatter = $date_formatter;
$this->userStorage = $user_storage;
}
@ -112,7 +112,7 @@ class UserController extends ControllerBase {
return $this->redirect('user.pass');
}
elseif ($user->isAuthenticated() && ($timestamp >= $user->getLastLoginTime()) && ($timestamp <= $current) && ($hash === user_pass_rehash($user->getPassword(), $timestamp, $user->getLastLoginTime()))) {
$expiration_date = $user->getLastLoginTime() ? $this->date->format($timestamp + $timeout) : NULL;
$expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
return $this->formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm', $user, $expiration_date, $timestamp, $hash);
}
else {

View File

@ -90,7 +90,7 @@ class UserAdminListingTest extends WebTestBase {
$expected_roles = array('custom_role_1', 'custom_role_2');
$this->assertEqual($result_accounts[$role_account_name]['roles'], $expected_roles, 'Ensure roles are listed properly.');
$this->assertEqual($result_accounts[$timestamp_user]['member_for'], format_interval(REQUEST_TIME - $accounts[$timestamp_user]->created->value), 'Ensure the right member time is displayed.');
$this->assertEqual($result_accounts[$timestamp_user]['member_for'], \Drupal::service('date')->formatInterval(REQUEST_TIME - $accounts[$timestamp_user]->created->value), 'Ensure the right member time is displayed.');
}
}

View File

@ -7,6 +7,7 @@
namespace Drupal\user;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
@ -28,6 +29,13 @@ class UserListBuilder extends EntityListBuilder {
*/
protected $queryFactory;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a new UserListBuilder object.
*
@ -37,10 +45,13 @@ class UserListBuilder extends EntityListBuilder {
* The entity storage class.
* @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
* The entity query factory.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, QueryFactory $query_factory) {
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, QueryFactory $query_factory, DateFormatter $date_formatter) {
parent::__construct($entity_type, $storage);
$this->queryFactory = $query_factory;
$this->dateFormatter = $date_formatter;
}
/**
@ -50,7 +61,8 @@ class UserListBuilder extends EntityListBuilder {
return new static(
$entity_type,
$container->get('entity.manager')->getStorage($entity_type->id()),
$container->get('entity.query')
$container->get('entity.query'),
$container->get('date')
);
}
@ -127,9 +139,9 @@ class UserListBuilder extends EntityListBuilder {
'#theme' => 'item_list',
'#items' => $users_roles,
);
$row['member_for'] = format_interval(REQUEST_TIME - $entity->getCreatedTime());
$row['member_for'] = $this->dateFormatter->formatInterval(REQUEST_TIME - $entity->getCreatedTime());
$row['access'] = $entity->access ? $this->t('@time ago', array(
'@time' => format_interval(REQUEST_TIME - $entity->getLastAccessedTime()),
'@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $entity->getLastAccessedTime()),
)) : t('never');
return $row + parent::buildRow($entity);
}

View File

@ -474,7 +474,7 @@ function user_user_view(array &$build, UserInterface $account, EntityViewDisplay
if ($display->getComponent('member_for')) {
$build['member_for'] = array(
'#type' => 'item',
'#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . format_interval(REQUEST_TIME - $account->getCreatedTime()),
'#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date')->formatInterval(REQUEST_TIME - $account->getCreatedTime()),
);
}
}

View File

@ -7,7 +7,10 @@
namespace Drupal\views\Plugin\views\cache;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Plugin\PluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Simple caching of query results for Views displays.
@ -27,6 +30,42 @@ class Time extends CachePluginBase {
*/
protected $usesOptions = TRUE;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a Time cache plugin object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatter $date_formatter) {
$this->dateFormatter = $date_formatter;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('date')
);
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['results_lifespan'] = array('default' => 3600);
@ -40,7 +79,7 @@ class Time extends CachePluginBase {
public function buildOptionsForm(&$form, &$form_state) {
parent::buildOptionsForm($form, $form_state);
$options = array(60, 300, 1800, 3600, 21600, 518400);
$options = array_map('format_interval', array_combine($options, $options));
$options = array_map(array($this->dateFormatter, 'formatInterval'), array_combine($options, $options));
$options = array(-1 => t('Never cache')) + $options + array('custom' => t('Custom'));
$form['results_lifespan'] = array(
@ -97,7 +136,7 @@ class Time extends CachePluginBase {
public function summaryTitle() {
$results_lifespan = $this->getLifespan('results');
$output_lifespan = $this->getLifespan('output');
return format_interval($results_lifespan, 1) . '/' . format_interval($output_lifespan, 1);
return $this->dateFormatter->formatInterval($results_lifespan, 1) . '/' . $this->dateFormatter->formatInterval($output_lifespan, 1);
}
protected function getLifespan($type) {

View File

@ -10,7 +10,7 @@ namespace Drupal\views\Plugin\views\field;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Datetime\Date as DateService;
use Drupal\Core\Datetime\Date as DateFormatter;
/**
* A handler to provide proper displays for dates.
@ -22,11 +22,11 @@ use Drupal\Core\Datetime\Date as DateService;
class Date extends FieldPluginBase {
/**
* The date service.
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateService;
protected $dateFormatter;
/**
* The date format storage.
@ -44,15 +44,15 @@ class Date extends FieldPluginBase {
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Datetime\Date $date_service
* The date service.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
* @param \Drupal\Core\Entity\EntityStorageInterface $date_format_storage
* The date format storage.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, DateService $date_service, EntityStorageInterface $date_format_storage) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatter $date_formatter, EntityStorageInterface $date_format_storage) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->dateService = $date_service;
$this->dateFormatter = $date_formatter;
$this->dateFormatStorage = $date_format_storage;
}
@ -83,7 +83,7 @@ class Date extends FieldPluginBase {
$date_formats = array();
foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) {
$date_formats[$machine_name] = t('@name format: @date', array('@name' => $value->label(), '@date' => $this->dateService->format(REQUEST_TIME, $machine_name)));
$date_formats[$machine_name] = t('@name format: @date', array('@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name)));
}
$form['date_format'] = array(
@ -144,19 +144,19 @@ class Date extends FieldPluginBase {
$time_diff = REQUEST_TIME - $value; // will be positive for a datetime in the past (ago), and negative for a datetime in the future (hence)
switch ($format) {
case 'raw time ago':
return format_interval($time_diff, is_numeric($custom_format) ? $custom_format : 2);
return $this->dateFormatter->formatInterval($time_diff, is_numeric($custom_format) ? $custom_format : 2);
case 'time ago':
return t('%time ago', array('%time' => format_interval($time_diff, is_numeric($custom_format) ? $custom_format : 2)));
return t('%time ago', array('%time' => $this->dateFormatter->formatInterval($time_diff, is_numeric($custom_format) ? $custom_format : 2)));
case 'raw time hence':
return format_interval(-$time_diff, is_numeric($custom_format) ? $custom_format : 2);
return $this->dateFormatter->formatInterval(-$time_diff, is_numeric($custom_format) ? $custom_format : 2);
case 'time hence':
return t('%time hence', array('%time' => format_interval(-$time_diff, is_numeric($custom_format) ? $custom_format : 2)));
return t('%time hence', array('%time' => $this->dateFormatter->formatInterval(-$time_diff, is_numeric($custom_format) ? $custom_format : 2)));
case 'raw time span':
return ($time_diff < 0 ? '-' : '') . format_interval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2);
return ($time_diff < 0 ? '-' : '') . $this->dateFormatter->formatInterval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2);
case 'inverse time span':
return ($time_diff > 0 ? '-' : '') . format_interval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2);
return ($time_diff > 0 ? '-' : '') . $this->dateFormatter->formatInterval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2);
case 'time span':
return t(($time_diff < 0 ? '%time hence' : '%time ago'), array('%time' => format_interval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2)));
return t(($time_diff < 0 ? '%time hence' : '%time ago'), array('%time' => $this->dateFormatter->formatInterval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2)));
case 'custom':
if ($custom_format == 'r') {
return format_date($value, $format, $custom_format, $timezone, 'en');

View File

@ -7,7 +7,9 @@
namespace Drupal\views\Plugin\views\field;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* A handler to provide proper displays for time intervals.
@ -18,6 +20,42 @@ use Drupal\views\ResultRow;
*/
class TimeInterval extends FieldPluginBase {
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a TimeInterval plugin object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date formatter service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatter $date_formatter) {
$this->dateFormatter = $date_formatter;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('date')
);
}
protected function defineOptions() {
$options = parent::defineOptions();
@ -42,7 +80,7 @@ class TimeInterval extends FieldPluginBase {
*/
public function render(ResultRow $values) {
$value = $values->{$this->field_alias};
return format_interval($value, isset($this->options['granularity']) ? $this->options['granularity'] : 2);
return $this->dateFormatter->formatInterval($value, isset($this->options['granularity']) ? $this->options['granularity'] : 2);
}
}

View File

@ -64,11 +64,11 @@ class FieldDateTest extends ViewUnitTestBase {
}
$intervals = array(
'raw time ago' => format_interval(REQUEST_TIME - $time, 2),
'time ago' => t('%time ago', array('%time' => format_interval(REQUEST_TIME - $time, 2))),
'raw time ago' => $this->container->get('date')->formatInterval(REQUEST_TIME - $time, 2),
'time ago' => t('%time ago', array('%time' => $this->container->get('date')->formatInterval(REQUEST_TIME - $time, 2))),
// TODO write tests for them
// 'raw time span' => format_interval(REQUEST_TIME - $time, 2),
// 'time span' => t('%time hence', array('%time' => format_interval(REQUEST_TIME - $time, 2))),
// 'raw time span' => $this->container->get('date')->formatInterval(REQUEST_TIME - $time, 2),
// 'time span' => t('%time hence', array('%time' => $this->container->get('date')->formatInterval(REQUEST_TIME - $time, 2))),
);
$this->assertRenderedDatesEqual($view, $intervals);
}

View File

@ -11,6 +11,7 @@ use Drupal\Component\Utility\Xss;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\String;
use Drupal\Core\Render\Element;
@ -38,6 +39,13 @@ class ViewEditForm extends ViewFormBase {
*/
protected $requestStack;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\Date
*/
protected $dateFormatter;
/**
* Constructs a new ViewEditForm object.
*
@ -45,10 +53,13 @@ class ViewEditForm extends ViewFormBase {
* The factory for the temp store object.
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The request stack object.
* @param \Drupal\Core\Datetime\Date $date_formatter
* The date Formatter service.
*/
public function __construct(TempStoreFactory $temp_store_factory, RequestStack $requestStack) {
public function __construct(TempStoreFactory $temp_store_factory, RequestStack $requestStack, DateFormatter $date_formatter) {
$this->tempStore = $temp_store_factory->get('views');
$this->requestStack = $requestStack;
$this->dateFormatter = $date_formatter;
}
/**
@ -57,7 +68,8 @@ class ViewEditForm extends ViewFormBase {
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.tempstore'),
$container->get('request_stack')
$container->get('request_stack'),
$container->get('date')
);
}
@ -125,7 +137,7 @@ class ViewEditForm extends ViewFormBase {
);
$lock_message_substitutions = array(
'!user' => drupal_render($username),
'!age' => format_interval(REQUEST_TIME - $view->lock->updated),
'!age' => $this->dateFormatter->formatInterval(REQUEST_TIME - $view->lock->updated),
'!break' => $view->url('break-lock'),
);
$form['locked'] = array(

View File

@ -957,7 +957,7 @@ function simpletest_script_reporter_write_xml_results() {
function simpletest_script_reporter_timer_stop() {
echo "\n";
$end = Timer::stop('run-tests');
echo "Test run duration: " . format_interval($end['time'] / 1000);
echo "Test run duration: " . \Drupal::service('date')->formatInterval($end['time'] / 1000);
echo "\n\n";
}

View File

@ -7,7 +7,7 @@
namespace Drupal\Tests\Core\Datetime;
use Drupal\Core\Datetime\Date;
use Drupal\Core\Datetime\Date as DateFormatter;
use Drupal\Tests\UnitTestCase;
/**
@ -42,14 +42,14 @@ class DateTest extends UnitTestCase {
*
* @var \Drupal\Core\Datetime\Date
*/
protected $date;
protected $dateFormatter;
protected function setUp() {
$this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
$this->stringTranslation = $this->getMock('Drupal\Core\StringTranslation\TranslationInterface');
$this->date = new Date($this->entityManager, $this->languageManager, $this->stringTranslation, $this->getConfigFactoryStub());
$this->dateFormatter = new DateFormatter($this->entityManager, $this->languageManager, $this->stringTranslation, $this->getConfigFactoryStub());
}
/**
@ -70,10 +70,10 @@ class DateTest extends UnitTestCase {
// Check if the granularity is specified.
if ($granularity) {
$result = $this->date->formatInterval($interval, $granularity, $langcode);
$result = $this->dateFormatter->formatInterval($interval, $granularity, $langcode);
}
else {
$result = $this->date->formatInterval($interval);
$result = $this->dateFormatter->formatInterval($interval);
}
$this->assertEquals($expected, $result);
@ -123,7 +123,7 @@ class DateTest extends UnitTestCase {
->with('0 sec', array(), array('langcode' => 'xxx-lolspeak'))
->will($this->returnValue('0 sec'));
$result = $this->date->formatInterval(0, 1, 'xxx-lolspeak');
$result = $this->dateFormatter->formatInterval(0, 1, 'xxx-lolspeak');
$this->assertEquals('0 sec', $result);
}