WishlistAssignment.php in Commerce Wishlist 8.3
File
src/WishlistAssignment.php
View source
<?php
namespace Drupal\commerce_wishlist;
use Drupal\commerce_wishlist\Event\WishlistAssignEvent;
use Drupal\commerce_wishlist\Event\WishlistEvents;
use Drupal\commerce_wishlist\Entity\WishlistInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class WishlistAssignment implements WishlistAssignmentInterface {
protected $entityTypeManager;
protected $eventDispatcher;
protected $configFactory;
protected $wishlistManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, EventDispatcherInterface $event_dispatcher, ConfigFactoryInterface $config_factory, WishlistManagerInterface $wishlist_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->eventDispatcher = $event_dispatcher;
$this->configFactory = $config_factory;
$this->wishlistManager = $wishlist_manager;
}
public function assign(WishlistInterface $wishlist, UserInterface $account) {
if (!empty($wishlist
->getOwnerId())) {
return;
}
$wishlist
->setOwner($account);
$shipping_profile = $wishlist
->getShippingProfile();
if ($shipping_profile && empty($shipping_profile
->getOwnerId())) {
$shipping_profile
->setOwner($account);
$shipping_profile
->save();
}
$event = new WishlistAssignEvent($wishlist, $account);
$this->eventDispatcher
->dispatch(WishlistEvents::WISHLIST_ASSIGN, $event);
$wishlist
->save();
}
public function assignMultiple(array $wishlists, UserInterface $account) {
$allow_multiple = (bool) $this->configFactory
->get('commerce_wishlist.settings')
->get('allow_multiple');
$wishlist_storage = $this->entityTypeManager
->getStorage('commerce_wishlist');
foreach ($wishlists as $wishlist) {
$default_wishlist = $wishlist_storage
->loadDefaultByUser($account, $wishlist
->bundle());
if ($allow_multiple || !$default_wishlist) {
$this
->assign($wishlist, $account);
continue;
}
$this->wishlistManager
->merge($wishlist, $default_wishlist);
}
}
}