You are here

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

Expanded class hierarchy of CartAddResource

1 file declares its use of CartAddResource
CartAddResourceSelectStoreExceptionTest.php in tests/src/Kernel/CartAddResourceSelectStoreExceptionTest.php

File

src/Plugin/rest/resource/CartAddResource.php, line 33

Namespace

Drupal\commerce_cart_api\Plugin\rest\resource
View 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

Namesort descending Modifiers Type Description Overrides
CartAddResource::$chainOrderTypeResolver protected property The chain order type resolver.
CartAddResource::$chainPriceResolver protected property The chain base price resolver.
CartAddResource::$currentStore protected property The current store.
CartAddResource::$currentUser protected property The current user.
CartAddResource::$entityRepository protected property The entity repository.
CartAddResource::$entityTypeManager protected property The entity type manager.
CartAddResource::$orderItemStorage protected property The order item store.
CartAddResource::create public static function Creates an instance of the plugin. Overrides CartResourceBase::create
CartAddResource::post public function Add order items to the session's carts.
CartAddResource::selectStore protected function Selects the store for the given purchasable entity.
CartAddResource::__construct public function Constructs a new CartAddResource object. Overrides CartResourceBase::__construct
CartResourceBase::$cartManager protected property The cart manager.
CartResourceBase::$cartProvider protected property The cart provider.
CartResourceBase::getBaseRouteRequirements protected function Gets the base route requirements for a particular method. Overrides ResourceBase::getBaseRouteRequirements
CartResourceBase::permissions public function We do not return specific resource permissions, as we respect the existing cart management and ownership logic. Overrides ResourceBase::permissions
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
ResourceBase::$logger protected property A logger instance.
ResourceBase::$serializerFormats protected property The available serialization formats.
ResourceBase::availableMethods public function Returns the available HTTP request methods on this plugin. Overrides ResourceInterface::availableMethods 1
ResourceBase::getBaseRoute protected function Gets the base route for a particular method. 2
ResourceBase::requestMethods protected function Provides predefined HTTP request methods.
ResourceBase::routes public function Returns a collection of routes with URL path information for the resource. Overrides ResourceInterface::routes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.