You are here

class FormatDateFilter in Typed Data API enhancements 8

A data filter for formatting dates.

Plugin annotation


@DataFilter(
  id = "format_date",
  label = @Translation("Formats a date, using a configured date type or a custom date format string."),
)

Hierarchy

Expanded class hierarchy of FormatDateFilter

File

src/Plugin/TypedDataFilter/FormatDateFilter.php, line 24

Namespace

Drupal\typed_data\Plugin\TypedDataFilter
View source
class FormatDateFilter extends DataFilterBase implements ContainerFactoryPluginInterface {

  /**
   * The date formatter.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

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

  /**
   * {@inheritdoc}
   *
   * @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\DateFormatterInterface $date_formatter
   *   The date formatter to use.
   * @param \Drupal\Core\Entity\EntityStorageInterface $date_format_storage
   *   The date format storage.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatterInterface $date_formatter, EntityStorageInterface $date_format_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->dateFormatter = $date_formatter;
    $this->dateFormatStorage = $date_format_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('date.formatter'), $container
      ->get('entity_type.manager')
      ->getStorage('date_format'));
  }

  /**
   * {@inheritdoc}
   */
  public function filter(DataDefinitionInterface $definition, $value, array $arguments, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($definition
      ->getDataType() != 'timestamp') {

      // Convert the date to an timestamp.
      $value = $this
        ->getTypedDataManager()
        ->create($definition, $value)
        ->getDateTime()
        ->getTimestamp();
    }
    $arguments += [
      0 => 'medium',
      1 => '',
      2 => NULL,
      3 => NULL,
    ];
    if ($arguments[0] != 'custom' && $bubbleable_metadata) {
      $config = $this->dateFormatStorage
        ->load($arguments[0]);
      if (!$config) {
        throw new InvalidArgumentException("Unknown date format {$arguments[0]} given.");
      }
      $bubbleable_metadata
        ->addCacheableDependency($config);
    }
    return $this->dateFormatter
      ->format($value, $arguments[0], $arguments[1], $arguments[2], $arguments[3]);
  }

  /**
   * {@inheritdoc}
   */
  public function canFilter(DataDefinitionInterface $definition) {
    return is_subclass_of($definition
      ->getClass(), DateTimeInterface::class);
  }

  /**
   * {@inheritdoc}
   */
  public function filtersTo(DataDefinitionInterface $definition, array $arguments) {
    return DataDefinition::create('string');
  }

  /**
   * {@inheritdoc}
   */
  public function validateArguments(DataDefinitionInterface $definition, array $arguments) {
    $fails = parent::validateArguments($definition, $arguments);
    $arguments += [
      0 => 'medium',
      1 => '',
      2 => NULL,
      3 => NULL,
    ];
    if ($arguments[0] != 'custom' && $this->dateFormatStorage
      ->load($arguments[0]) === NULL) {
      $fails[] = $this
        ->t('Unkown date format %format given.', [
        '%format' => $arguments[0],
      ]);
    }
    if ($arguments[0] != 'custom' && $arguments[1]) {
      $fails[] = $this
        ->t("If a custom date format is supplied, 'custom' must be passed as date format.");
    }
    elseif ($arguments[0] == 'custom' && !$arguments[1]) {
      $fails[] = $this
        ->t("If 'custom' is given as date type, a custom date formatting string must be provided; e.g., 'Y-m-d H:i:s'.");
    }
    return $fails;

    // @todo Should we validate timezones and langcodes also?
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DataFilterBase::$filterId protected property The filter id.
DataFilterBase::$pluginDefinition protected property The plugin definition. Overrides PluginBase::$pluginDefinition
DataFilterBase::allowsNullValues public function Defines whether the filter is able to process NULL values. Overrides DataFilterInterface::allowsNullValues 1
DataFilterBase::getNumberOfRequiredArguments public function Gets the number of required arguments. Overrides DataFilterInterface::getNumberOfRequiredArguments 2
DataFilterBase::suggestArgument public function Suggests some possible argument values based on user input. Overrides DataFilterInterface::suggestArgument
FormatDateFilter::$dateFormatStorage protected property The date format storage.
FormatDateFilter::$dateFormatter protected property The date formatter.
FormatDateFilter::canFilter public function Determines whether data based upon the given definition can be filtered. Overrides DataFilterInterface::canFilter
FormatDateFilter::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
FormatDateFilter::filter public function Filters the given data value. Overrides DataFilterInterface::filter
FormatDateFilter::filtersTo public function Describes the data after applying the filter. Overrides DataFilterInterface::filtersTo
FormatDateFilter::validateArguments public function Validates the inputted arguments. Overrides DataFilterBase::validateArguments
FormatDateFilter::__construct public function Overrides DataFilterBase::__construct
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2