9
9
10
10
use Magento \Catalog \Model \Product ;
11
11
use Magento \CatalogUrlRewrite \Model \ProductUrlPathGenerator ;
12
+ use Magento \UrlRewrite \Model \Exception \UrlAlreadyExistsException ;
12
13
use Magento \UrlRewrite \Model \UrlFinderInterface ;
13
14
use Magento \UrlRewrite \Service \V1 \Data \UrlRewrite ;
14
15
use Magento \CatalogUrlRewrite \Model \ProductUrlRewriteGenerator ;
@@ -50,12 +51,12 @@ public function __construct(
50
51
}
51
52
52
53
/**
53
- * Find Url Key conflicts of a product .
54
+ * Validate Url Key of a Product .
54
55
*
55
56
* @param Product $product
56
- * @return array Array of conflicting Url Keys.
57
+ * @throws UrlAlreadyExistsException
57
58
*/
58
- public function findUrlKeyConflicts (Product $ product ): array
59
+ public function validateUrlKey (Product $ product ): void
59
60
{
60
61
if (!$ product ->getUrlKey ()) {
61
62
$ urlKey = $ this ->productUrlPathGenerator ->getUrlKey ($ product );
@@ -67,7 +68,7 @@ public function findUrlKeyConflicts(Product $product): array
67
68
$ storeIdsToPathForSave = [];
68
69
$ searchData = [
69
70
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE ,
70
- UrlRewrite::REQUEST_PATH => []
71
+ UrlRewrite::REQUEST_PATH => [],
71
72
];
72
73
73
74
foreach ($ stores as $ store ) {
@@ -81,17 +82,25 @@ public function findUrlKeyConflicts(Product $product): array
81
82
}
82
83
83
84
$ urlRewrites = $ this ->urlFinder ->findAllByData ($ searchData );
84
- $ conflicts = [];
85
+ $ exceptionData = [];
85
86
86
87
foreach ($ urlRewrites as $ urlRewrite ) {
87
88
if (in_array ($ urlRewrite ->getRequestPath (), $ storeIdsToPathForSave )
88
89
&& isset ($ storeIdsToPathForSave [$ urlRewrite ->getStoreId ()])
89
- && $ storeIdsToPathForSave [$ urlRewrite ->getStoreId ()] == $ urlRewrite ->getRequestPath ()
90
- && $ product ->getId () != $ urlRewrite ->getEntityId ()) {
91
- $ conflicts [] = $ urlRewrite ;
90
+ && $ storeIdsToPathForSave [$ urlRewrite ->getStoreId ()] === $ urlRewrite ->getRequestPath ()
91
+ && $ product ->getId () !== $ urlRewrite ->getEntityId ()
92
+ ) {
93
+ $ exceptionData [$ urlRewrite ->getUrlRewriteId ()] = $ urlRewrite ->toArray ();
92
94
}
93
95
}
94
96
95
- return $ conflicts ;
97
+ if ($ exceptionData ) {
98
+ throw new UrlAlreadyExistsException (
99
+ __ ('URL key for specified store already exists. ' ),
100
+ null ,
101
+ 0 ,
102
+ $ exceptionData
103
+ );
104
+ }
96
105
}
97
106
}
0 commit comments