magento2: Exception: Warning: Trying to access array offset in... -> Calendar.php since upgrade to ICU 74.1 (PHP Intl)

Preconditions and environment

Magento version 2.4.6-P3. PHP v8.1.25. ICU 74.1 (required by PHP Intl) FreeBSD 13.2-RELEASE-p5

Steps to reproduce

Install the above versions and visit either the backend or the frontend.

Expected result

No errors in var/log/exception.log

Actual result

Errors on each store visit in exception.log:

main.CRITICAL: Exception: Warning: Trying to access array offset on value of type null in /vendor/magento/framework/View/Element/Html/Calendar.php on line 114 in /vendor/magento/framework/App/ErrorHandler.php:62

Additional information

Magento is using ‘Swedish’ as locale, and doesn’t use am or pm (24 hrs). Set on Scope -> Default Config Stores -> Configurations -> General -> Locale Options -> Locale Magento is set up with 8 web sites, stores and views.

Line 114 in Calendar.php:

2023-11-22 171407 $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0']));

Triage and priority

  • Severity: S2 - Affects non-critical data or functionality and forces users to employ a workaround.

About this issue

  • Original URL
  • State: open
  • Created 7 months ago
  • Reactions: 6
  • Comments: 25 (15 by maintainers)

Most upvoted comments

We’re also seeing this over here. Error triggers on product detail pages, $localeData['calendar']['gregorian']['AmPmMarkers'] is null in our case.

Using:

  • PHP 8.2.14
  • ICU 74.1 (also tried upgrading to 74.2 but doesn’t resolve the problem)
  • Magento 2.4.6-p3
  • Locale: nl_NL

This quickfix seems to work (no idea if this is the correct way to solve it though):

diff --git a/lib/internal/Magento/Framework/View/Element/Html/Calendar.php b/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
index 884488d77a7..e20c7882cff 100644
--- a/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
+++ b/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
@@ -111,8 +111,8 @@ class Calendar extends \Magento\Framework\View\Element\Template
         $this->assignFieldsValues($localeData);

         // get "am" & "pm" words
-        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0']));
-        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['1']));
+        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0'] ?? null));
+        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['1'] ?? null));

         // get first day of week and weekend days
         $this->assign(

@webcreative24: apply changes from https://github.com/magento/magento2/pull/38364, that works for us.

@engcom-Hotel: it definitely is reproducible.

Are you 100% sure your PHP is using ICU version 74.x? You may need to recompile the php-intl extension. Can you try my dirty test script from this comment: https://github.com/magento/magento2/issues/38214#issuecomment-1898634163 It will output the ICU version used at the top.

Or alternatively, you can run php -i | grep 'ICU version' to view the version used.

Hello @Munktells Thank you for your collaboration

Hello @hostep Thank you to your contribution here I\ll review your PR

I just wrote this (dirty) script to be put in pub/test.php and then openend via https://base-url/test.php, it goes over all locale’s supported by Magento and outputs a table to see which locale supports which amPmMarker key:

<?php

require_once('../vendor/autoload.php');

use Magento\Framework\Locale\Bundle\DataBundle as LocaleDataBundle;
use Magento\Framework\Locale\Config as LocaleConfig;

$locales = (new LocaleConfig())->getAllowedLocales();

$amPmMarkersKeys = ['AmPmMarkers', 'AmPmMarkersAbbr', 'AmPmMarkersNarrow'];

echo sprintf('<h1 style="text-align: center">ICU version: %s</h1>', getIcuVersion());

echo '<table width="100%"><thead><tr><th></th>';
foreach ($amPmMarkersKeys as $key) { echo sprintf('<th>%s</th>', $key); }
echo "</tr></thead><tbody>\n";

$countPerKey = [];

foreach ($locales as $locale) {
    echo sprintf('<tr><th>%s</th>', $locale);

    $localeData = (new LocaleDataBundle())->get($locale);

    foreach ($amPmMarkersKeys as $key) {
        $exists = $localeData['calendar']['gregorian'][$key] ? true : false;
        $values = [];
        if ($exists) {
            $count = $localeData['calendar']['gregorian'][$key]->count();
            for ($i = 0; $i < $count; ++$i) {
                $values[] = $localeData['calendar']['gregorian'][$key][$i];
            }
        }

        $output = $exists ? implode(', ', $values) : 'doesn\'t exists';
        $color = $exists ? '#c3e6cb' : '#f5c6cb';

        echo sprintf('<td bgcolor="%s">%s</td>', $color, $output);

        if ($exists) {
            if (!array_key_exists($key, $countPerKey)) {
                $countPerKey[$key] = 0;
            }
            ++$countPerKey[$key];
        }
    }

    echo "</tr>\n";
}

echo '<tr><th>Total</th>';

foreach ($amPmMarkersKeys as $key) {
    echo sprintf('<td><b>%d</b></td>', $countPerKey[$key]);
}

echo '</tr></tbody></table>';

// borrowed from https://github.com/symfony/intl/blob/5fbee19d24354bbd77b300971eb38469ddbfd7fc/Intl.php#L71-L94
function getIcuVersion(): string
{
    $reflector = new \ReflectionExtension('intl');
    ob_start();
    $reflector->info();
    $output = strip_tags(ob_get_clean());
    preg_match('/^ICU version (?:=>)?(.*)$/m', $output, $matches);

    return $matches[1];
}

Results with ICU 74.1: magento2-github baldwin_test php (1)

Results with ICU 69.1: icu69 php

If somebody wants to test with other versions of ICU, feel free to do so and post the results!

It seems like a lot of data disappeared in the latest version of ICU, no idea why, maybe this is a bug on their end?

Anyway, based on the results from ICU 74.1, it looks like no key is supported by each locale, the key that has the most support is AmPmMarkersAbbr at the moment, so if we decide to keep these 2 lines of code, I vote we use that one. But add a fallback to null in case it doesn’t exist.

So then I would propose we make this change to the core code:

diff --git a/lib/internal/Magento/Framework/View/Element/Html/Calendar.php b/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
index 884488d77a7..28a59b28616 100644
--- a/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
+++ b/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
@@ -111,8 +111,8 @@ class Calendar extends \Magento\Framework\View\Element\Template
         $this->assignFieldsValues($localeData);

         // get "am" & "pm" words
-        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0']));
-        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['1']));
+        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkersAbbr'][0] ?? null));
+        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkersAbbr'][1] ?? null));

         // get first day of week and weekend days
         $this->assign(

Update: I’ve changed my mind again, see my new proposal in #38364

Same issue here with Magento 2.4.7 … 😃

Exception #0 (Exception): Warning: Trying to access array offset on value of type null in /vendor/magento/framework/View/Element/Html/Calendar.php on line 114
php -i | grep 'ICU version'
ICU version => 74.2

Create file patches/composer/github-issue-38364.diff

diff --git a/View/Element/Html/Calendar.php b/View/Element/Html/Calendar.php
index 884488d77a74f..cf8f2e3e789e6 100644
--- a/View/Element/Html/Calendar.php
+++ b/View/Element/Html/Calendar.php
@@ -109,10 +109,7 @@ protected function _toHtml()
         );

         $this->assignFieldsValues($localeData);
-
-        // get "am" & "pm" words
-        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0']));
-        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['1']));
+        $this->assignAmPmWords($localeData);

         // get first day of week and weekend days
         $this->assign(
@@ -209,4 +206,23 @@ private function assignFieldsValues(\ResourceBundle $localeData): void
             $this->assign('week', $this->encoder->encode($localeData['fields']['week']['dn']));
         }
     }
+
+    /**
+     * Assign "am" & "pm" words from the ICU data
+     *
+     * @param \ResourceBundle $localeData
+     */
+    private function assignAmPmWords(\ResourceBundle $localeData): void
+    {
+        // AmPmMarkers and AmPmMarkersAbbr aren't guaranteed to exist, so fallback to null if neither exist
+        $amWord = $localeData['calendar']['gregorian']['AmPmMarkers'][0] ??
+                  $localeData['calendar']['gregorian']['AmPmMarkersAbbr'][0] ??
+                  null;
+        $pmWord = $localeData['calendar']['gregorian']['AmPmMarkers'][1] ??
+                  $localeData['calendar']['gregorian']['AmPmMarkersAbbr'][1] ??
+                  null;
+
+        $this->assign('am', $this->encoder->encode($amWord));
+        $this->assign('pm', $this->encoder->encode($pmWord));
+    }
 }
diff --git a/View/Test/Unit/Element/Html/CalendarTest.php b/View/Test/Unit/Element/Html/CalendarTest.php
index 94d3dbb660f6b..51e5834fe8507 100644
--- a/View/Test/Unit/Element/Html/CalendarTest.php
+++ b/View/Test/Unit/Element/Html/CalendarTest.php
@@ -48,6 +48,9 @@ public function localesDataProvider()
             ['en_US'],
             ['ja_JP'],
             ['ko_KR'],
+            ['lv_LV'],
+            ['sv_SE'],
+            ['de_AT'],
         ];
     }

Add to composer.json

    "extra": {
        "magento-force": "override",
        "composer-exit-on-patch-failure": true,
        "patches": {
            "magento/framework": {
                "ICU library where AmPmMarkers": "patches/composer/github-issue-38364.diff"
            }
        }
    }

Many thanks to @hostep! 💯

Yes @hostep,

I compiled the PHP with ICU version 74.1, and after compilation, running the below command was showing ICU version as 74.1:

`php -i | grep 'ICU version``

Hello @Munktells @hostep,

We have tried to reproduce the issue with the mentioned prerequisites and the issue is reproducible for us with the below-mentioned steps:

Manual testing scenarios (*)

  1. Setup clean Magento
  2. In the admin panel, go to Stores > Attributes > Product
  3. Find and edit the special_from_date attribute
  4. Under Storefront Properties, enable both ‘Use in Search’ and ‘Visible in Advanced Search’ and save the attribute
  5. Reindex
  6. Edit the file app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml and add this line at the very bottom: <ul><li>am: <?= $am; ?></li><li>pm: <?= $pm; ?></li></ul>
  7. Configure “lv_LV” locale: bin/magento config:set general/locale/code lv_LV
  8. Flush the caches
  9. In frontend click on the Advanced Search link in the footer
  10. Expected to see “priekšpusdienā” & “pēcpusdienā” (but then escaped for JS)
  11. Expected to see “null” & “null”

Please refer to the below screenshot for reference:

image

Hence confirming the PR.

Thanks

Same issue here on php 8.1 and magento 2.4.6-p3

FYI this also happens on Alpine 3.19 with the following versions of ICU:

icu-data-full-74.1-r0 x86_64 {icu} (ICU) [installed]
icu-libs-74.1-r0 x86_64 {icu} (ICU) [installed]

Locale tested: fr. Page tested: login page of admin area.

After some more looking into and seeing how the ICU data changed between versions 73.2 and 74.1 (this is the commit), it looks like we should use AmPmMarkersAbbr instead of AmPmMarkers.

Also, using the index as a string (['0']) never ever worked, it should have been used as a int ([0])

So I would suggest this change now:

diff --git a/lib/internal/Magento/Framework/View/Element/Html/Calendar.php b/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
index 884488d77a7..28a59b28616 100644
--- a/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
+++ b/lib/internal/Magento/Framework/View/Element/Html/Calendar.php
@@ -111,8 +111,8 @@ class Calendar extends \Magento\Framework\View\Element\Template
         $this->assignFieldsValues($localeData);

         // get "am" & "pm" words
-        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0']));
-        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['1']));
+        $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkersAbbr'][0]));
+        $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkersAbbr'][1]));

         // get first day of week and weekend days
         $this->assign(

However, this code in core Magento has existed for over 9 years (was introduced here), and never worked, also the datetime picker widget only shows dates and not times, so I’m not sure if we even need that am/pm notation at all. So maybe we should just remove those two lines and be done with it?

Hi, Any updates on this error? I am recently getting this error on M2.4.5-p4 and php 8.1