Problem/Motivation

This was found in #2904423: Translated field denormalization creates duplicate values
Because isEmpty() calls ensureLoaded() which creates an empty item count() will return 1 on an empty field after isEmpty() is called but 0 before.

Since isEmpty() is just check it seems like count should be the same before and after.

Proposed resolution

Maybe override count() and call ensureLoaded(). Not sure 😉

Remaining tasks

Determine if current behavior is a problem and find a solution if it is.

User interface changes

None

API changes

Data model changes

Comments

tedbow created an issue. See original summary.

tedbow’s picture

StatusFileSize
new1.68 KB

Here is test that fails and shows the problem.

tedbow’s picture

Status: Active » Needs review
tedbow’s picture

StatusFileSize
new1.58 KB
new2.29 KB

Overrided count() to call ensureLoaded(). This changes count() to return 1 on an empty field before and after isEmpty() call.

The last submitted patch, 2: 2905524-2-test-only-FAIL.patch, failed testing. View results

berdir’s picture

fix makes sense I think, we should IMHO definitely also extend \Drupal\Tests\path\Kernel\PathItemTest which has a ton of test coverage around loading/changing computed values in the path field. Not sure if we still need a unit test then, feels a bit like we're testing an implementation detail there.

I could imagine that e.g. #2392845: Add a trait to standardize handling of computed item lists will change how the implementation looks like exactly, and then we'd need to update the unit test.

wim leers’s picture

@Berdir++ — thanks for the feedback!

tedbow’s picture

StatusFileSize
new4.32 KB
new4.93 KB
new2.64 KB

Ok I added to PathItemTest.

The only that doesn't feel real intuitive to me is:

$node = Node::create([
      'title' => 'Testing no path',
      'type' => 'foo',
    ]);
    // Test using count() first.
    $this->assertEquals(1, count($node->get('path')));
    $this->assertTrue($node->get('path')->isEmpty());

    $node->save();
    $this->assertEquals(1, count($node->get('path')));
    $this->assertFalse($node->get('path')->isEmpty());

So the field is not empty after a save even though the count has not changed.

$node->get('path')->getValue() will equal

array(1) {
  [0]=>
  array(1) {
    ["langcode"]=>
    string(2) "en"
  }
}

so it is not empty because the field has language code.

The last submitted patch, 9: 2905524-9-TEST_ONLY.patch, failed testing. View results

amateescu’s picture

+++ b/core/modules/path/tests/src/Kernel/PathItemTest.php
@@ -49,16 +49,63 @@ public function testPathItem() {
+    $node = Node::create([
+      'title' => 'Testing no path',
+      'type' => 'foo',
+    ]);
+    // Test using count() first.
+    $this->assertEquals(1, count($node->get('path')));

This a big problem: for non-computed fields, the count() of an empty field is 0, so it should be the same for computed ones as well.

The problem here, as you mentioned in #9, is that \Drupal\path\Plugin\Field\FieldType\PathItem::ensureLoaded() always sets the langcode property, even if there's no alias for that entity.

So that's what we need to fix, IMO :)

tedbow’s picture

StatusFileSize
new3.14 KB
new6.32 KB

This a big problem: for non-computed fields, the count() of an empty field is 0, so it should be the same for computed ones as well.

Agreed!
The reason an empty PathItemList was returning 1 for count was because in PathFieldItemList::ensureLoaded
we actually created an empty field item.

protected function ensureLoaded() {
    if (!isset($this->list[0]) && $this->definition->isComputed()) {
      $this->list[0] = $this->createItem(0);
    }
  }

I tried to remove that all together but then PathItemTest would fail here:

$node_storage->resetCache();
$loaded_node = $node_storage->load($node->id());
$this->assertFalse($loaded_node->get('path')->isEmpty());

Basically when you reset cache and load the entity with a path item:

  1. the $this->list initially has no items.
  2. create the first item in ensureLoaded() which initially be empty.
  3. PathFieldItemList::isEmpty will call ensureLoaded() then call parent::isEmpty()
  4. This is a call to ItemList::isEmpty which will call PathItem::isEmpty on every item.
  5. In this case it is we only have 1 empty item but PathItem::isEmpty will call PathItem::ensureLoaded which loads the alias value if it exists.

This works great for entities that will have an alias value. But entities that do not have a alias item this leaves an empty PathItem in PathFieldItemList::$list.

This causes count($node_with_no_path->get('path') == 1 because there is an empty PathItem. But $node_with_no_path->get('path')->isEmpty() == TRUE because isEmtpty:

Determines whether the list contains any non-empty items.

So the solutions is in PathFieldItemList::ensureLoaded to immediately call isEmpty() on newly created PathItem which load the alias if it exists and remove the item if it is empty.

protected function ensureLoaded() {
    if (!isset($this->list[0]) && $this->definition->isComputed()) {
      // Create the first item in the list which will load the computed alias
      // value if it exists.
      $this->list[0] = $this->createItem(0);
      // If no alias actually exists remove the empty item. This ensures that
      // count() will not return 1 for an empty list.
      if ($this->list[0]->isEmpty()) {
        unset($this->list[0]);
      }
    }
  }

This ensures that an empty PathItem will not remain in $this->list[0] but it will contain the correct value if it does exist.

berdir’s picture

I expect/hope that this will break some tests because the path widget relies on having the correct langcode set. I'll look at this ASAP.

amateescu’s picture

  1. +++ b/core/modules/path/src/Plugin/Field/FieldType/PathFieldItemList.php
    @@ -76,7 +76,14 @@ public function count() {
    +      // If no alias actually exists remove the empty item. This ensures that
    +      // count() will not return 1 for an empty list.
    +      if ($this->list[0]->isEmpty()) {
    +        unset($this->list[0]);
    +      }
    

    Instead of doing this manually, we should simply call $this->filterEmptyItems() at the bottom of the method.

  2. +++ b/core/modules/path/src/Plugin/Field/FieldType/PathItem.php
    @@ -174,12 +174,12 @@ protected function ensureLoaded() {
    -          $this->langcode = $this->getLangcode();
    +            $this->langcode = $this->getLangcode();
    

    Unneeded spaces :)

  3. +++ b/core/modules/path/tests/src/Kernel/PathItemTest.php
    @@ -57,12 +57,12 @@ public function testPathItem() {
         // Test using count() first.
    -    $this->assertEquals(1, count($node->get('path')));
    +    $this->assertEquals(0, count($node->get('path')));
    
    @@ -70,12 +70,12 @@ public function testPathItem() {
         // Test using isEmpty() first.
    

    Since the actual bug was that count() was returning the wrong thing, I don't we need to test with various methods being called before other methods, a simple check that count() returns the expected value in every scenario (new node without any alias, new node with an alias, saved node without any alias, saved node with an alias) is enough.

Status: Needs review » Needs work

The last submitted patch, 12: 2905524-12.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

tedbow’s picture

Status: Needs work » Needs review
StatusFileSize
new1.95 KB
new6.69 KB

@Berdir yep forgot about that. I think we can rely on having an empty field item except for langcode though. This patch checks if langcode exists and uses the entity langcode if it does not.
This fixes the failing test for me locally.

#14.1 fixed.
2. fixed
3. actually the bug as reported in the title is that count behaves differently if isEmpty() has been called. So the bug did only happen if isEmpty was called before.
This code will show 2 different counts in HEAD

$node = Node::create([
      'type' => 'article',
      'title' => 'helloooo',
    ]);

    $node->save();

    \Drupal::entityTypeManager()->getStorage('node')->resetCache([$node->id()]);
    $node = Node::load($node->id());
    drupal_set_message("isempty 1st " . $node->get('path')->isEmpty());
    drupal_set_message("count 2nd " . count($node->get('path')));

    \Drupal::entityTypeManager()->getStorage('node')->resetCache([$node->id()]);
    $node = Node::load($node->id());
    drupal_set_message("count 1st " . count($node->get('path')));
    drupal_set_message("is empty 2nd " . $node->get('path')->isEmpty());

So it seems like it is good to have test make sure we don't accidently cause this to happen again.

amateescu’s picture

actually the bug as reported in the title is that count behaves differently if isEmpty() has been called. So the bug did only happen if isEmpty was called before.
This code will show 2 different counts in HEAD

As far as I see, it's not only about isEmpty() being called before, it's about any method that would call ensureLoaded() internally :) So the test could also try to get() the field item list instead of calling isEmpty(), maybe that would be a more reliable way to test the bug.. not sure.

Status: Needs review » Needs work

The last submitted patch, 16: 2905524-16.patch, failed testing. View results

tedbow’s picture

Status: Needs work » Needs review
StatusFileSize
new1.68 KB
new5.01 KB

Ok the only remaining failure is from the unit test this patch add PathFieldItemListTest but that is probably not needed anymore because we are adding this coverage to PathItemTest as suggested in by @Berdir in #7. The test failing because it was still expecting count() to return 1 for an empty PathFieldItemList which we determined is not correct. So I am removing the test.

#17 I am not sure what we should do here. ensureLoaded() is called by 4 public functions on PathFieldItemList now so calling count() before and after any of those functions would have resulted in a different value before this patch I think. The bug just happened to be caught on isEmpty. I don't think any of the methods is better or worse to test on. If we need the test at all.

wim leers’s picture

StatusFileSize
new2.43 KB
new1.45 KB
new4.18 KB

#9: that is indeed very confusing 🤔
#11++
#12: 😵

#17:

As far as I see, it's not only about isEmpty() being called before, it's about any method that would call ensureLoaded() internally :)

+1

#19:

If we need the test at all.

Hm, I was thinking this too: what if we could remove all the tested permutations, and just test it once? So, basically what @amateescu is saying. I did that, it looks like the attached patch.

wim leers’s picture

Issue tags: +API-First Initiative, +Entity Field API, +blocker
StatusFileSize
new776 bytes
new4.18 KB
+++ b/core/modules/path/src/Plugin/Field/FieldWidget/PathWidget.php
@@ -47,7 +47,7 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen
+      '#value' => $items[$delta]->langcode?: $entity->language()->getId(),

Nit: Needs space before the ternary operator. Fixed.


As far as I'm concerned, this is ready, but I think only @amateescu or @Berdir can RTBC this.

The last submitted patch, 20: 2905524-20-test-only-FAIL.patch, failed testing. View results

The last submitted patch, 20: 2905524-20.patch, failed testing. View results

amateescu’s picture

Note that I'm getting into the same problems with the path widget as #12 in #2916300-4: Use ComputedFieldItemListTrait for the path field type because that patch also fixes this issue :)

Also, I'm not qualified at all to RTBC the changes to the path widget, so we'll have to wait for @Berdir :)

wim leers’s picture

wim leers’s picture

Should this be postponed on #2916300: Use ComputedFieldItemListTrait for the path field type (which is itself blocked on #2392845: Add a trait to standardize handling of computed item lists)? AFAICT it should.

@amateescu, what do you think?

amateescu’s picture

Title: The count() method used on PathFieldItemList behaves differently if isEmpty() has been called. » [PP-2] The count() method used on PathFieldItemList behaves differently if isEmpty() has been called.
Status: Needs review » Postponed

@Wim Leers, yup, it would be good to wait a bit because those two issues will most likely fix this one as well.

wim leers’s picture

👍

wim leers’s picture

Title: [PP-2] The count() method used on PathFieldItemList behaves differently if isEmpty() has been called. » The count() method used on PathFieldItemList behaves differently if isEmpty() has been called.
Status: Postponed » Needs review
StatusFileSize
new2.26 KB

Both #2916300: Use ComputedFieldItemListTrait for the path field type and #2392845: Add a trait to standardize handling of computed item lists are in. #21 no longer applied. Rebased.

But in rebasing, the conflicts were near 100% of the non-test changes. Only a single line change remains — all other changes have already been made in those two blockers. Which confirms @amateescu's prediction in #27 :)

However … then the test this issue was adding no longer works:

    $node = Node::create([
      'title' => 'Testing no path',
      'type' => 'foo',
    ]);
    $this->assertTrue($node->get('path')->isEmpty());

does not pass because var_dump($node->get('path')->getValue()); results in:

array(1) {
  [0]=>
  array(1) {
    ["langcode"]=>
    string(2) "en"
  }
}

This test should fail due to that reason.

The only possible explanation is that this patch's PathFieldItemList::ensureLoaded() and/or PathItem::ensureLoaded() implementations were different from those implementations added in the blockers.

wim leers’s picture

StatusFileSize
new1.51 KB
new3.7 KB

The root cause for #29:

      // If no alias actually exists remove the empty item. This ensures that
      // count() will not return 1 for an empty list.
      $this->filterEmptyItems();

This was being added in this issue, but not in the two blockers. Plus, #2916300: Use ComputedFieldItemListTrait for the path field type seems to have introduced incorrect logic for PathItem::isEmpty(): the mere presence of the langcode property while the other two properties are absent is enough to make the field item "not empty". @amateescu in #2916300-8: Use ComputedFieldItemListTrait for the path field type specifically said it was up to this issue to fix this behavior.

So, here's the intended fix AFAICT. Hopefully @amateescu can confirm :)

wim leers’s picture

+++ b/core/modules/path/src/Plugin/Field/FieldWidget/PathWidget.php
@@ -47,7 +47,7 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen
-      '#value' => $items[$delta]->langcode,
+      '#value' => $items[$delta]->langcode ?: $entity->language()->getId(),

I doubt this change is necessary. Tests don't fail if I revert this change in any case.

The last submitted patch, 29: 2905524-29.patch, failed testing. View results

amateescu’s picture

Re #31: Yes, that's not needed anymore, the change from #2916300-8: Use ComputedFieldItemListTrait for the path field type is the one that made it obsolete.

+++ b/core/modules/path/src/Plugin/Field/FieldType/PathFieldItemList.php
@@ -39,6 +39,9 @@ protected function computeValue() {
+    $this->filterEmptyItems();

I don't think this is the correct fix. While I was working on the other issue I had a thought that we should move the default 'langcode' assignment to the item list class thus allowing the item class to behave normally (i.e. actually return 0 on count() when the field is empty).

Status: Needs review » Needs work

The last submitted patch, 30: 2905524-30.patch, failed testing. View results

wim leers’s picture

I'm happy to let you decide how this should be fixed! You know far more about Entity/Field/Typed Data API than I do :)

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

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

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

smustgrave’s picture

Status: Needs work » Postponed (maintainer needs more info)
Issue tags: +stale-issue-cleanup

Thank you for reporting this problem. We rely on issue reports like this one to resolve bugs and improve Drupal core.

Since there has been no activity here for over 8 years we are asking if this problem persists on a currently supported version of Drupal. To help, add a comment explaining if the problem still occurs or not. Any extra detail you can provide can help others who experienced this.

Since we need more information to move forward with this issue, the status is now Postponed (maintainer needs more info). If we don't receive additional information to help with the issue, it may be closed after three months.
Thanks!

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.