You are here

public function OrderTest::testPreSave in Commerce Core 8.2

@covers ::preSave

File

modules/order/tests/src/Kernel/Entity/OrderTest.php, line 310

Class

OrderTest
Tests the Order entity.

Namespace

Drupal\Tests\commerce_order\Kernel\Entity

Code

public function testPreSave() {

  /** @var \Drupal\profile\Entity\ProfileInterface $profile */
  $profile = Profile::create([
    'type' => 'customer',
    'uid' => $this->user
      ->id(),
    'address' => [
      'country_code' => 'US',
      'postal_code' => '53177',
      'locality' => 'Milwaukee',
      'address_line1' => 'Pabst Blue Ribbon Dr',
      'administrative_area' => 'WI',
      'given_name' => 'Frederick',
      'family_name' => 'Pabst',
    ],
  ]);
  $profile
    ->save();
  $profile = $this
    ->reloadEntity($profile);

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = Order::create([
    'type' => 'default',
    'store_id' => $this->store
      ->id(),
    'uid' => '888',
    'billing_profile' => $profile,
    'state' => 'completed',
  ]);
  $order
    ->save();

  // Confirm that saving the order clears an invalid customer ID.
  $this
    ->assertEquals(0, $order
    ->getCustomerId());

  // Confirm that saving the order reassigns the billing profile.
  $order
    ->save();
  $this
    ->assertEquals(0, $order
    ->getBillingProfile()
    ->getOwnerId());
  $this
    ->assertEquals($profile
    ->id(), $order
    ->getBillingProfile()
    ->id());

  /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
  $order_item = OrderItem::create([
    'type' => 'test',
    'quantity' => '1',
    'unit_price' => new Price('2.00', 'USD'),
  ]);
  $order_item
    ->save();
  $order_item = $this
    ->reloadEntity($order_item);

  /** @var \Drupal\commerce_order\Entity\OrderItemInterface $another_order_item */
  $another_order_item = OrderItem::create([
    'type' => 'test',
    'quantity' => '2',
    'unit_price' => new Price('3.00', 'USD'),
  ]);
  $another_order_item
    ->save();
  $another_order_item = $this
    ->reloadEntity($another_order_item);
  $order
    ->setItems([
    $order_item,
    $another_order_item,
  ]);
  $this
    ->assertCount(2, $order
    ->get('order_items'));
  $another_order_item
    ->delete();

  // Assert that saving the order fixes the reference to a deleted order item.
  $order
    ->save();
  $this
    ->reloadEntity($order);
  $this
    ->assertCount(1, $order
    ->get('order_items'));
}