There is an issue with Magento 2.2.2 (and possibly previous versions) where products that have a url_path set on them cannot be duplicated - "The value specified in the URL Key field would generate a URL that already exists." For us these came from migrated products, but this is just background for my current problem.
To get around the issue, I added an afterCopy plugin to clear url_path from the duplicated product. However, it would not fire, and after debugging I decided to just add a beforeCopy to clear it from the product prior to copying. This resulted in both before and after methods running. Some more experimentation and without the $product->setUrlPath(null);
call it will not run the afterCopy method.
<?php
namespace My\Namespace\Model\Plugin;
class CopierPlugin
{
public function afterCopy(\Magento\Catalog\Model\Product\Copier $subject, $duplicate)
{
$duplicate->setUrlPath(null);
return $duplicate;
}
public function beforeCopy(\Magento\Catalog\Model\Product\Copier $subject, \Magento\Catalog\Model\Product $product)
{
$product->setUrlPath(null); // without this line, the afterCopy will not fire
return [$product];
}
}
Has anyone else seem similar behavior with plugins? I don't have time to delve further into the depths of how Magento determines to run specific plugin methods at the moment, but if I get some more time I may dig in further.