productUrlRewriteGenerator = $productUrlRewriteGenerator; $this->urlPersist = $urlPersist; $this->productUrlPathGenerator = $productUrlPathGenerator ?: ObjectManager::getInstance() ->get(ProductUrlPathGenerator::class); } /** * Generate urls for UrlRewrite and save it in storage * * @param \Magento\Framework\Event\Observer $observer * @return void * @throws \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException */ public function execute(\Magento\Framework\Event\Observer $observer) { /** @var Product $product */ $product = $observer->getEvent()->getProduct(); if ($product->dataHasChangedFor('url_key') || $product->getIsChangedCategories() || $product->getIsChangedWebsites() || $product->dataHasChangedFor('visibility') ) { if ($product->isVisibleInSiteVisibility()) { $product->unsUrlPath(); $product->setUrlPath($this->productUrlPathGenerator->getUrlPath($product)); $this->urlPersist->replace($this->productUrlRewriteGenerator->generate($product)); } } } }