Problem/Motivation

I have a page that displays a series of calendar events, where each event has a start and end date. I found that having just a dozen or so events would result in the same DB query being repeated over a thousand times:

SELECT "cid", "data", "created", "expire", "serialized", "tags", "checksum" FROM "cache_config" WHERE "cid" IN ( 'core.date_format.' ) ORDER BY "cid"

Steps to reproduce

This code results in two database queries instead of one:

\Drupal::service('date.formatter')->format(time(), 'bad type', '', NULL, 'en');
\Drupal::service('date.formatter')->format(time(), 'bad type', '', NULL, 'en');

Proposed resolution

The reason for this lies in Drupal\Core\Datetime::dateFormat():

protected function dateFormat($type, $langcode) {
    if (!isset($this->dateFormats[$type][$langcode])) {
      $original_language = $this->languageManager->getConfigOverrideLanguage();
      $this->languageManager->setConfigOverrideLanguage(new Language(['id' => $langcode]));
      $this->dateFormats[$type][$langcode] = $this->dateFormatStorage->load($type);
      $this->languageManager->setConfigOverrideLanguage($original_language);
    }
    return $this->dateFormats[$type][$langcode];
  }

The problem is that the result of isset($array['key']) is FALSE if the value stored in the array at that position is NULL. So when the result of $this->dateFormatStorage->load($type) is NULL the same (non-existant) date format is re-fetched every time this function gets called with the same values.

The solution is to use array_key_exists() instead of isset():

    if (!array_key_exists($type, $this->dateFormats) || !array_key_exists($langcode, $this->dateFormats[$type])) {
CommentFileSizeAuthor
date-format.patch939 bytesgribnif

Issue fork drupal-3484404

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

gribnif created an issue. See original summary.

tolstoydotcom’s picture

I was able to duplicate the issue. The patch applied and looks OK.

One question is whether using a non-existent format should thrown an exception or not. Given the use of a fallback format, it seems like the idea is that a formatted date should be returned even if a bad format is used. So, this seems OK to me unless someone suggests logging a warning the first time a non-existent format is used.

kumudb made their first commit to this issue’s fork.

kumudb’s picture

MR has been raised for this issue. Please review and merge.

quietone’s picture

Version: 11.0.x-dev » 11.x-dev

Changes are made on on 11.x (our main development branch) first, and are then back ported as needed according to our policies.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.