commerce_product_bundles-8.x-1.0/src/EventSubscriber/BundleDuplicateSubscriber.php
src/EventSubscriber/BundleDuplicateSubscriber.php
<?php
namespace Drupal\commerce_product_bundles\EventSubscriber;
use Drupal\entity\BundleEntityDuplicatorInterface;
use Drupal\entity\Event\EntityDuplicateEvent;
use Drupal\entity\Event\EntityEvents;
use Drupal\commerce_product_bundles\Entity\ProductBundleInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BundleDuplicateSubscriber implements EventSubscriberInterface {
/**
* The bundle entity duplicator.
*
* @var \Drupal\entity\BundleEntityDuplicatorInterface
*/
protected $bundleEntityDuplicator;
/**
* BundleDuplicateSubscriber constructor.
*
* @param \Drupal\entity\BundleEntityDuplicatorInterface $bundle_entity_duplicator
*/
public function __construct(BundleEntityDuplicatorInterface $bundle_entity_duplicator) {
$this->bundleEntityDuplicator = $bundle_entity_duplicator;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
EntityEvents::ENTITY_DUPLICATE => ['onEntityDuplicate'],
];
return $events;
}
/**
* Duplicates product bundle bundle variations.
*
* @param \Drupal\entity\Event\EntityDuplicateEvent $event
* The entity duplicate event.
*/
public function onEntityDuplicate(EntityDuplicateEvent $event) {
$entity = $event->getEntity();
if ($entity instanceof ProductBundleInterface) {
$source_eck = $event->getSourceEntity();
// Clone each bundle variation.
if ($source_eck->hasVariations()) {
$duplicatedVariations = [];
foreach ($source_eck->getVariations() as $bundleVariation) {
$duplicateVariationEntity = $bundleVariation->createDuplicate();
$duplicateVariationEntity->setTitle($duplicateVariationEntity->getTitle() . ' - copy');
$duplicateVariationEntity->product_bundle_id = $entity->id();
$duplicateVariationEntity->save();
$duplicatedVariations[] = $duplicateVariationEntity;
}
// Set bundle variations.
$entity->setVariations($duplicatedVariations);
}
}
}
}
