improvements-2.x-dev/tests/src/Traits/ImprovementsCommerceTestTrait.php
tests/src/Traits/ImprovementsCommerceTestTrait.php
<?php
namespace Drupal\Tests\improvements\Traits;
use Drupal\commerce_cart\CartProviderInterface;
use Drupal\commerce_order\Entity\Order;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\Entity\OrderItemInterface;
use Drupal\commerce_order\OrderItemStorageInterface;
use Drupal\commerce_price\Price;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_product\Entity\ProductInterface;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Tests\RandomGeneratorTrait;
trait ImprovementsCommerceTestTrait {
use RandomGeneratorTrait;
/**
* Create product variation.
*/
public function createProductVariation(string $sku = NULL, $price = NULL, string $type = 'default'): ProductVariationInterface {
$variation = ProductVariation::create([
'type' => $type,
'sku' => $sku ?: $this->randomMachineName(),
'price' => $price ?: new Price(random_int(1, 1000), 'USD'),
]);
$variation->save();
return $variation;
}
/**
* Create product.
*/
public function createProduct(string $title = NULL, array $variations = [], string $type = 'default', $store = 1): ProductInterface {
$product = Product::create([
'type' => $type,
'title' => $title ?: $this->randomMachineName(),
'stores' => [$store],
'variations' => $variations,
]);
$product->save();
return $product;
}
/**
* Create order item by product.
*/
public function createOrderItemByVariation(ProductVariationInterface $variation, array $values = []): OrderItemInterface {
$entity_type_manager = $this->container->get('entity_type.manager'); /** @var EntityTypeManagerInterface $entity_type_manager */
$order_item_storage = $entity_type_manager->getStorage('commerce_order_item'); /** @var OrderItemStorageInterface $order_item_storage */
$order_item = $order_item_storage->createFromPurchasableEntity($variation, $values);
$order_item->save();
return $order_item;
}
/**
* Create order.
*/
public function createOrder(array $order_items = [], array $values = []): OrderInterface {
$order = Order::create([
'type' => 'default',
'state' => 'completed',
'mail' => 'test@example.com',
'ip_address' => '127.0.0.1',
'uid' => \Drupal::currentUser()->id(),
'store_id' => 1,
'order_items' => $order_items,
] + $values);
$order->save();
return $order;
}
/**
* Clear cart caches.
*/
public function clearCartCaches(): void {
$cart_provider = $this->container->get('commerce_cart.cart_provider'); /** @var CartProviderInterface $cart_provider */
$cart_provider->clearCaches();
$entity_type_manager = $this->container->get('entity_type.manager'); /** @var EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager->getStorage('commerce_order')->resetCache();
$entity_type_manager->getStorage('commerce_order_item')->resetCache();
}
}
