1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Tkotosz\CatalogRouter\Observer; |
4
|
|
|
|
5
|
|
|
use Magento\Catalog\Model\Product; |
6
|
|
|
use Magento\Framework\Event\Observer; |
7
|
|
|
use Magento\Framework\Event\ObserverInterface; |
8
|
|
|
use Magento\Store\Model\StoreManagerInterface; |
9
|
|
|
use Tkotosz\CatalogRouter\Api\ProductResolverInterface; |
10
|
|
|
use Tkotosz\CatalogRouter\Model\Service\UrlPathUsedCheckerContainer; |
11
|
|
|
use Tkotosz\CatalogRouter\Model\UrlPath; |
12
|
|
|
use Tkotosz\CatalogRouter\Model\EntityData; |
13
|
|
|
|
14
|
|
|
class ProductUrlPathValidatorObserver implements ObserverInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var UrlPathUsedCheckerContainer |
18
|
|
|
*/ |
19
|
|
|
private $urlPathUsedChecker; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var StoreManagerInterface |
23
|
|
|
*/ |
24
|
|
|
private $storeManager; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var ProductResolverInterface |
28
|
|
|
*/ |
29
|
|
|
private $productResolver; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param UrlPathUsedCheckerContainer $urlPathUsedChecker |
33
|
|
|
* @param StoreManagerInterface $storeManager |
34
|
|
|
* @param ProductResolverInterface $productResolver |
35
|
|
|
*/ |
36
|
|
|
public function __construct(UrlPathUsedCheckerContainer $urlPathUsedChecker, StoreManagerInterface $storeManager, ProductResolverInterface $productResolver) |
37
|
|
|
{ |
38
|
|
|
$this->urlPathUsedChecker = $urlPathUsedChecker; |
39
|
|
|
$this->storeManager = $storeManager; |
40
|
|
|
$this->productResolver = $productResolver; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param Observer $observer |
45
|
|
|
* @return void |
46
|
|
|
*/ |
47
|
|
|
public function execute(Observer $observer) |
48
|
|
|
{ |
49
|
|
|
/** @var Product $product */ |
50
|
|
|
$product = $observer->getEvent()->getProduct(); |
51
|
|
|
|
52
|
|
|
foreach ($product->getStoreIds() as $storeId) { |
53
|
|
|
$urlKeyInStore = $this->productResolver->resolveById($product->getId(), $storeId)->getUrlKey(); |
54
|
|
|
$urlPath = new UrlPath($urlKeyInStore); |
55
|
|
|
$resolvedEntities = $this->urlPathUsedChecker->check($urlPath, $storeId); |
56
|
|
|
|
57
|
|
|
if (count($resolvedEntities) > 1) { |
58
|
|
|
$store = $this->storeManager->getStore($storeId); |
59
|
|
|
$messages = []; |
60
|
|
|
foreach ($resolvedEntities as $entity) { |
61
|
|
|
if ($entity->getType() == 'product' && $entity->getId() == $product->getId()) { |
62
|
|
|
continue; |
63
|
|
|
} |
64
|
|
|
$messages[] = __( |
65
|
|
|
'The "%1" url path already used by a %2 with id %3 in the %4 (storeid: %5) store', |
66
|
|
|
$urlPath->getIdentifier(), |
67
|
|
|
$entity->getType(), |
68
|
|
|
$entity->getId(), |
69
|
|
|
$store->getName(), |
70
|
|
|
$store->getId() |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
throw new \Exception(join("<br>", $messages)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|