class CartAddResource in Commerce Cart API 8
Creates order items for the session's carts.
Plugin annotation
@RestResource(
id = "commerce_cart_add",
label = @Translation("Cart add"),
uri_paths = {
"create" = "/cart/add"
}
)
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\rest\Plugin\ResourceBase implements ContainerFactoryPluginInterface, ResourceInterface
- class \Drupal\commerce_cart_api\Plugin\rest\resource\CartResourceBase
- class \Drupal\commerce_cart_api\Plugin\rest\resource\CartAddResource
- class \Drupal\commerce_cart_api\Plugin\rest\resource\CartResourceBase
- class \Drupal\rest\Plugin\ResourceBase implements ContainerFactoryPluginInterface, ResourceInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
Expanded class hierarchy of CartAddResource
1 file declares its use of CartAddResource
File
- src/
Plugin/ rest/ resource/ CartAddResource.php, line 33
Namespace
Drupal\commerce_cart_api\Plugin\rest\resourceView source
class CartAddResource extends CartResourceBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The order item store.
*
* @var \Drupal\commerce_order\OrderItemStorageInterface
*/
protected $orderItemStorage;
/**
* The chain order type resolver.
*
* @var \Drupal\commerce_order\Resolver\ChainOrderTypeResolverInterface
*/
protected $chainOrderTypeResolver;
/**
* The current store.
*
* @var \Drupal\commerce_store\CurrentStoreInterface
*/
protected $currentStore;
/**
* The chain base price resolver.
*
* @var \Drupal\commerce_price\Resolver\ChainPriceResolverInterface
*/
protected $chainPriceResolver;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* Constructs a new CartAddResource object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param array $serializer_formats
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\commerce_cart\CartProviderInterface $cart_provider
* The cart provider.
* @param \Drupal\commerce_cart\CartManagerInterface $cart_manager
* The cart manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\commerce_order\Resolver\ChainOrderTypeResolverInterface $chain_order_type_resolver
* The chain order type resolver.
* @param \Drupal\commerce_store\CurrentStoreInterface $current_store
* The current store.
* @param \Drupal\commerce_price\Resolver\ChainPriceResolverInterface $chain_price_resolver
* The chain base price resolver.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, CartProviderInterface $cart_provider, CartManagerInterface $cart_manager, EntityTypeManagerInterface $entity_type_manager, ChainOrderTypeResolverInterface $chain_order_type_resolver, CurrentStoreInterface $current_store, ChainPriceResolverInterface $chain_price_resolver, AccountInterface $current_user, EntityRepositoryInterface $entity_repository) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger, $cart_provider, $cart_manager);
$this->entityTypeManager = $entity_type_manager;
$this->orderItemStorage = $entity_type_manager
->getStorage('commerce_order_item');
$this->chainOrderTypeResolver = $chain_order_type_resolver;
$this->currentStore = $current_store;
$this->chainPriceResolver = $chain_price_resolver;
$this->currentUser = $current_user;
$this->entityRepository = $entity_repository;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->getParameter('serializer.formats'), $container
->get('logger.factory')
->get('rest'), $container
->get('commerce_cart.cart_provider'), $container
->get('commerce_cart.cart_manager'), $container
->get('entity_type.manager'), $container
->get('commerce_order.chain_order_type_resolver'), $container
->get('commerce_store.current_store'), $container
->get('commerce_price.chain_price_resolver'), $container
->get('current_user'), $container
->get('entity.repository'));
}
/**
* Add order items to the session's carts.
*
* @param array $data
* The unserialized request body.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request.
*
* @return \Drupal\rest\ModifiedResourceResponse
* The resource response.
*
* @throws \Exception
*/
public function post(array $data, Request $request) {
$order_items = [];
// Do an initial validation of the payload before any processing.
foreach ($data as $key => $order_item_data) {
if (!isset($order_item_data['purchased_entity_type'])) {
throw new UnprocessableEntityHttpException(sprintf('You must specify a purchasable entity type for row: %s', $key));
}
if (!isset($order_item_data['purchased_entity_id'])) {
throw new UnprocessableEntityHttpException(sprintf('You must specify a purchasable entity ID for row: %s', $key));
}
if (!$this->entityTypeManager
->hasDefinition($order_item_data['purchased_entity_type'])) {
throw new UnprocessableEntityHttpException(sprintf('You must specify a valid purchasable entity type for row: %s', $key));
}
}
foreach ($data as $order_item_data) {
$storage = $this->entityTypeManager
->getStorage($order_item_data['purchased_entity_type']);
$purchased_entity = $storage
->load($order_item_data['purchased_entity_id']);
if (!$purchased_entity || !$purchased_entity instanceof PurchasableEntityInterface) {
continue;
}
$purchased_entity = $this->entityRepository
->getTranslationFromContext($purchased_entity);
$store = $this
->selectStore($purchased_entity);
$order_item = $this->orderItemStorage
->createFromPurchasableEntity($purchased_entity, [
'quantity' => !empty($order_item_data['quantity']) ? $order_item_data['quantity'] : 1,
]);
$context = new Context($this->currentUser, $store);
$order_item
->setUnitPrice($this->chainPriceResolver
->resolve($purchased_entity, $order_item
->getQuantity(), $context));
$order_type_id = $this->chainOrderTypeResolver
->resolve($order_item);
$cart = $this->cartProvider
->getCart($order_type_id, $store);
if (!$cart) {
$cart = $this->cartProvider
->createCart($order_type_id, $store);
}
if (!isset($order_item_data['combine'])) {
$order_item_data['combine'] = TRUE;
}
$order_items[] = $this->cartManager
->addOrderItem($cart, $order_item, $order_item_data['combine']);
}
$response = new ModifiedResourceResponse(array_values($order_items), 200);
return $response;
}
/**
* Selects the store for the given purchasable entity.
*
* If the entity is sold from one store, then that store is selected.
* If the entity is sold from multiple stores, and the current store is
* one of them, then that store is selected.
*
* @param \Drupal\commerce\PurchasableEntityInterface $entity
* The entity being added to cart.
*
* @throws \Exception
* When the entity can't be purchased from the current store.
*
* @return \Drupal\commerce_store\Entity\StoreInterface
* The selected store.
*/
protected function selectStore(PurchasableEntityInterface $entity) {
$stores = $entity
->getStores();
if (count($stores) === 1) {
$store = reset($stores);
}
elseif (count($stores) === 0) {
// Malformed entity.
throw new UnprocessableEntityHttpException('The given entity is not assigned to any store.');
}
else {
$store = $this->currentStore
->getStore();
if (!in_array($store, $stores)) {
// Indicates that the site listings are not filtered properly.
throw new UnprocessableEntityHttpException("The given entity can't be purchased from the current store.");
}
}
return $store;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
CartAddResource:: |
protected | property | The chain order type resolver. | |
CartAddResource:: |
protected | property | The chain base price resolver. | |
CartAddResource:: |
protected | property | The current store. | |
CartAddResource:: |
protected | property | The current user. | |
CartAddResource:: |
protected | property | The entity repository. | |
CartAddResource:: |
protected | property | The entity type manager. | |
CartAddResource:: |
protected | property | The order item store. | |
CartAddResource:: |
public static | function |
Creates an instance of the plugin. Overrides CartResourceBase:: |
|
CartAddResource:: |
public | function | Add order items to the session's carts. | |
CartAddResource:: |
protected | function | Selects the store for the given purchasable entity. | |
CartAddResource:: |
public | function |
Constructs a new CartAddResource object. Overrides CartResourceBase:: |
|
CartResourceBase:: |
protected | property | The cart manager. | |
CartResourceBase:: |
protected | property | The cart provider. | |
CartResourceBase:: |
protected | function |
Gets the base route requirements for a particular method. Overrides ResourceBase:: |
|
CartResourceBase:: |
public | function |
We do not return specific resource permissions, as we respect the existing
cart management and ownership logic. Overrides ResourceBase:: |
|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
3 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
ResourceBase:: |
protected | property | A logger instance. | |
ResourceBase:: |
protected | property | The available serialization formats. | |
ResourceBase:: |
public | function |
Returns the available HTTP request methods on this plugin. Overrides ResourceInterface:: |
1 |
ResourceBase:: |
protected | function | Gets the base route for a particular method. | 2 |
ResourceBase:: |
protected | function | Provides predefined HTTP request methods. | |
ResourceBase:: |
public | function |
Returns a collection of routes with URL path information for the resource. Overrides ResourceInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. |