You are here

public function OrderItemMatcherTest::testCustomField in Commerce Core 8.2

Tests that order items with custom fields are matched properly.

File

modules/cart/tests/src/Kernel/OrderItemMatcherTest.php, line 174

Class

OrderItemMatcherTest
Tests the order item matcher.

Namespace

Drupal\Tests\commerce_cart\Kernel

Code

public function testCustomField() {

  // Show field_custom_text on the add to cart form.
  $form_display = \Drupal::entityTypeManager()
    ->getStorage('entity_form_display')
    ->load('commerce_order_item.default.add_to_cart');
  $this
    ->assertNotEmpty($form_display);
  $form_display
    ->setComponent('field_custom_text', [
    'type' => 'string_textfield',
  ]);
  $form_display
    ->save();
  $order_item1 = OrderItem::create([
    'type' => 'default',
    'quantity' => 2,
    'unit_price' => new Price('12.00', 'USD'),
    'purchased_entity' => $this->variation1,
    'field_custom_text' => 'Blue',
  ]);
  $order_item1
    ->save();
  $order_item2 = OrderItem::create([
    'type' => 'default',
    'quantity' => 6,
    'unit_price' => new Price('12.00', 'USD'),
    'purchased_entity' => $this->variation1,
    'field_custom_text' => 'Red',
  ]);
  $order_item2
    ->save();
  $order_item3 = OrderItem::create([
    'type' => 'default',
    'quantity' => 4,
    'unit_price' => new Price('12.00', 'USD'),
    'purchased_entity' => $this->variation1,
    'field_custom_text' => 'Blue',
  ]);
  $order_item3
    ->save();
  $order_item4 = OrderItem::create([
    'type' => 'default',
    'quantity' => 4,
    'unit_price' => new Price('12.00', 'USD'),
    'purchased_entity' => $this->variation1,
    'field_custom_text' => '',
  ]);
  $order_item4
    ->save();

  // Same purchased entity, different custom text, no match.
  $matches = $this->orderItemMatcher
    ->matchAll($order_item1, [
    $order_item2,
  ]);
  $this
    ->assertEmpty($matches);

  // Same purchased entity, same custom text.
  $match = $this->orderItemMatcher
    ->match($order_item1, [
    $order_item2,
    $order_item3,
  ]);
  $this
    ->assertNotEmpty($match);
  $this
    ->assertEquals($match, $order_item3);

  // Item with missing custom text, no match.
  $order_item5 = OrderItem::create([
    'type' => 'default',
    'quantity' => 5,
    'unit_price' => new Price('12.00', 'USD'),
    'purchased_entity' => $this->variation1,
  ]);
  $matches = $this->orderItemMatcher
    ->matchAll($order_item5, [
    $order_item1,
    $order_item2,
    $order_item3,
  ]);
  $this
    ->assertEmpty($matches);

  // Empty custom text on both sides, match.
  $order_item6 = OrderItem::create([
    'type' => 'default',
    'quantity' => 5,
    'unit_price' => new Price('12.00', 'USD'),
    'purchased_entity' => $this->variation1,
    'field_custom_text' => '',
  ]);
  $match = $this->orderItemMatcher
    ->match($order_item6, [
    $order_item4,
  ]);
  $this
    ->assertNotEmpty($match);
  $this
    ->assertEquals($match, $order_item4);
}