magento2 icon indicating copy to clipboard operation
magento2 copied to clipboard

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

Open Munktells opened this issue 2 years ago • 21 comments

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

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

Munktells avatar Nov 22 '23 16:11 Munktells

Hi @AlldoGroup. Thank you for your report. To speed up processing of this issue, make sure that the issue is reproducible on the vanilla Magento instance following Steps to reproduce. To deploy vanilla Magento instance on our environment, Add a comment to the issue:


Join Magento Community Engineering Slack and ask your questions in #github channel. :warning: According to the Magento Contribution requirements, all issues must go through the Community Contributions Triage process. Community Contributions Triage is a public meeting. :clock10: You can find the schedule on the Magento Community Calendar page. :telephone_receiver: The triage of issues happens in the queue order. If you want to speed up the delivery of your contribution, join the Community Contributions Triage session to discuss the appropriate ticket.

m2-assistant[bot] avatar Nov 22 '23 16:11 m2-assistant[bot]

Hi @engcom-Dash. Thank you for working on this issue. In order to make sure that issue has enough information and ready for development, please read and check the following instruction: :point_down:

    1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
    1. Verify that issue has a meaningful description and provides enough information to reproduce the issue.
    1. Add Area: XXXXX label to the ticket, indicating the functional areas it may be related to.
    1. Verify that the issue is reproducible on 2.4-develop branch
      Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
      - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
      - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!

m2-assistant[bot] avatar Nov 30 '23 05:11 m2-assistant[bot]

Hi @engcom-November. Thank you for working on this issue. In order to make sure that issue has enough information and ready for development, please read and check the following instruction: :point_down:

  • [ ] 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
  • [ ] 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue.
  • [ ] 3. Add Area: XXXXX label to the ticket, indicating the functional areas it may be related to.
  • [ ] 4. Verify that the issue is reproducible on 2.4-develop branch
    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!
  • [ ] 5. Add label Issue: Confirmed once verification is complete.
  • [ ] 6. Make sure that automatic system confirms that report has been added to the backlog.

m2-assistant[bot] avatar Jan 11 '24 05:01 m2-assistant[bot]

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

Keivanph avatar Jan 15 '24 13:01 Keivanph

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(

hostep avatar Jan 16 '24 14:01 hostep

Simplest way to reproduce (just tried this on latest commit from 2.4-develop branch):

Preconditions:

  • PHP 8.2.x
  • ICU library version 74.1 or 74.2 (dependency of the php-intl extension)

Steps to reproduce:

  1. Setup clean Magento
  2. Configure nl_NL locale: bin/magento config:set general/locale/code nl_NL
  3. In backoffice, go to Stores > Attributes > Product
  4. Find and edit the special_from_date attribute
  5. Under Storefront Properties, enable both 'Use in Search' and 'Visible in Advanced Search' and save the attribute
  6. Reindex & flush caches
  7. In frontend click on the Advanced Search link in the footer
  8. You'll see this error:
1 exception(s):
Exception #0 (Exception): Warning: Trying to access array offset on value of type null in lib/internal/Magento/Framework/View/Element/Html/Calendar.php on line 114

Exception #0 (Exception): Warning: Trying to access array offset on value of type null in lib/internal/Magento/Framework/View/Element/Html/Calendar.php on line 114
<pre>#1 Magento\Framework\View\Element\Html\Calendar->_toHtml() called at [lib/internal/Magento/Framework/View/Element/AbstractBlock.php:1117]
#2 Magento\Framework\View\Element\AbstractBlock->Magento\Framework\View\Element\{closure}() called at [lib/internal/Magento/Framework/View/Element/AbstractBlock.php:1121]
#3 Magento\Framework\View\Element\AbstractBlock->_loadCache() called at [lib/internal/Magento/Framework/View/Element/AbstractBlock.php:670]
#4 Magento\Framework\View\Element\AbstractBlock->toHtml() called at [lib/internal/Magento/Framework/View/Layout.php:578]
#5 Magento\Framework\View\Layout->_renderBlock() called at [lib/internal/Magento/Framework/View/Layout.php:555]
#6 Magento\Framework\View\Layout->renderNonCachedElement() called at [generated/code/Magento/Framework/View/Layout/Interceptor.php:149]
#7 Magento\Framework\View\Layout\Interceptor->renderNonCachedElement() called at [lib/internal/Magento/Framework/View/Layout.php:510]
#8 Magento\Framework\View\Layout->renderElement() called at [generated/code/Magento/Framework/View/Layout/Interceptor.php:140]
#9 Magento\Framework\View\Layout\Interceptor->renderElement() called at [lib/internal/Magento/Framework/View/Layout.php:606]
#10 Magento\Framework\View\Layout->_renderContainer() called at [lib/internal/Magento/Framework/View/Layout.php:557]
...

hostep avatar Jan 16 '24 19:01 hostep

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?

hostep avatar Jan 16 '24 19:01 hostep

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

hostep avatar Jan 18 '24 14:01 hostep

Hello @Munktells Thank you for your collaboration

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

andrewbess avatar Jan 19 '24 06:01 andrewbess

Hi @engcom-Hotel. Thank you for working on this issue. In order to make sure that issue has enough information and ready for development, please read and check the following instruction: :point_down:

  • [ ] 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
  • [ ] 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue.
  • [ ] 3. Add Area: XXXXX label to the ticket, indicating the functional areas it may be related to.
  • [ ] 4. Verify that the issue is reproducible on 2.4-develop branch
    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!
  • [ ] 5. Add label Issue: Confirmed once verification is complete.
  • [ ] 6. Make sure that automatic system confirms that report has been added to the backlog.

m2-assistant[bot] avatar Jan 24 '24 14:01 m2-assistant[bot]

Hello @Munktells,

Thanks for the report and collaboration!

Thanks @hostep for the updated steps to reproduce.

We have tried to reproduce the issue in the 2.4-develop branch but it seems the issue is not reproducible for us. Please refer to the below screenshots and let us know if we missed anything:

  • ICU Version: image

  • PHP Version: 8.1.2

  • Locale: nl_NL image

Marking this issue as Needs Update for now.

Thanks

engcom-Hotel avatar Jan 25 '24 07:01 engcom-Hotel

@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.

hostep avatar Jan 25 '24 09:01 hostep

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.

guvra avatar Jan 29 '24 09:01 guvra

Same issue here with nl_NL as locale. Reproducible with ICU 74.1

$ php -i | grep 'ICU version'
ICU version => 74.1

LeanderFS avatar Jan 29 '24 14:01 LeanderFS

Same issue here on php 8.1 and magento 2.4.6-p3

kayintveen avatar Feb 08 '24 12:02 kayintveen

@engcom-Hotel: can you please retry to reproduce? More and more people are running into the problem ... It would be appreciated if https://github.com/magento/magento2/pull/38364 would get some more attention and gets included in Magento 2.4.7 if possible...

hostep avatar Feb 21 '24 19:02 hostep

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

engcom-Hotel avatar Feb 26 '24 13:02 engcom-Hotel

:white_check_mark: Jira issue https://jira.corp.adobe.com/browse/AC-11423 is successfully created for this GitHub issue.

github-jira-sync-bot avatar Feb 26 '24 13:02 github-jira-sync-bot

:white_check_mark: Confirmed by @engcom-Hotel. Thank you for verifying the issue.
Issue Available: @engcom-Hotel, You will be automatically unassigned. Contributors/Maintainers can claim this issue to continue. To reclaim and continue work, reassign the ticket to yourself.

m2-assistant[bot] avatar Feb 26 '24 13:02 m2-assistant[bot]

@engcom-Hotel: those are incorrect steps, the correct steps are mentioned earlier in this comment: https://github.com/magento/magento2/issues/38214#issuecomment-1894345126

Have you already figured out how to run php with ICU library version 74.x?

hostep avatar Feb 26 '24 14:02 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``

engcom-Hotel avatar Feb 27 '24 10:02 engcom-Hotel

how to fix it?

webcreative24 avatar Mar 21 '24 01:03 webcreative24

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

hostep avatar Mar 21 '24 07:03 hostep

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! 💯

PieterCappelle avatar Apr 23 '24 07:04 PieterCappelle

  • +1 issue on ICU version => 74.2 & Magento 2.4.3-p3 ro_RO

tuyennn avatar Apr 25 '24 08:04 tuyennn

Same issue here

  • Magento 2.4.0
  • PHP 7.4.33
  • ICU 74.2
  • de_DE

elburro1887 avatar May 15 '24 20:05 elburro1887