Skip to content

Commit 926d868

Browse files
author
Manish Joy
committed
first commit
0 parents  commit 926d868

File tree

5 files changed

+280
-0
lines changed

5 files changed

+280
-0
lines changed

Console/Command/Run.php

+222
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
<?php
2+
3+
4+
namespace ManishJoy\ProductUrlRewrite\Console\Command;
5+
6+
use Symfony\Component\Console\Command\Command;
7+
use Symfony\Component\Console\Input\InputArgument;
8+
use Symfony\Component\Console\Input\InputOption;
9+
use Symfony\Component\Console\Input\InputInterface;
10+
use Symfony\Component\Console\Output\OutputInterface;
11+
12+
class Run extends Command
13+
{
14+
15+
const PRODUCT_ID_ARGUMENT = "id";
16+
const NAME_OPTION = "option";
17+
18+
protected $_productCollectionFactory;
19+
protected $_productVisibility;
20+
protected $_resources;
21+
protected $_scopeConfig;
22+
protected $_categoryFactory;
23+
protected $_categoryCollection;
24+
protected $_productFactory;
25+
26+
/**
27+
* @param string|null $name The name of the command; passing null means it must be set in configure()
28+
*
29+
* @throws LogicException When the command name is empty
30+
*/
31+
public function __construct(
32+
\Magento\Catalog\Model\ProductFactory $_productFactory,
33+
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
34+
\Magento\Catalog\Model\Product\Visibility $productVisibility,
35+
\Magento\Framework\App\ResourceConnection $resources,
36+
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
37+
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
38+
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollection
39+
)
40+
{
41+
$this->_productFactory = $_productFactory;
42+
$this->_productCollectionFactory = $productCollectionFactory;
43+
$this->_productVisibility = $productVisibility;
44+
$this->_resources = $resources;
45+
$this->_scopeConfig = $scopeConfig;
46+
$this->_categoryFactory = $categoryFactory;
47+
$this->_categoryCollection = $categoryCollection;
48+
return parent::__construct();
49+
}
50+
51+
/**
52+
* {@inheritdoc}
53+
*/
54+
protected function execute(
55+
InputInterface $input,
56+
OutputInterface $output
57+
) {
58+
$paramProductIds = $input->getArgument(self::PRODUCT_ID_ARGUMENT);
59+
60+
$option = $input->getOption(self::NAME_OPTION);
61+
$paramProductIdArray = array_filter(explode(',', $paramProductIds));
62+
63+
$output->writeln("Starting Product Rewrite Process.");
64+
$output->writeln("============================================================================================================");
65+
$resultIdArray = [];
66+
if(!empty($paramProductIdArray)) {
67+
$productCollection = $this->getProductCollection();
68+
$productCollection = $productCollection->addFieldToFilter('entity_id', array('in' => $paramProductIdArray));
69+
foreach ($productCollection as $_product) {
70+
$this->deleteExistingUrlRewrite($_product);
71+
$resultIdArray[] = $this->enterNewUrlRewrite($_product);
72+
$output->write('... ');
73+
}
74+
} else {
75+
$productCollection = $this->getProductCollection();
76+
foreach ($productCollection as $_product) {
77+
$this->deleteExistingUrlRewrite($_product);
78+
$resultIdArray[] = $this->enterNewUrlRewrite($_product);
79+
$output->write('... ');
80+
}
81+
}
82+
83+
$output->writeln('');
84+
$output->writeln("============================================================================================================");
85+
$output->writeln('Congratulations, rewrite process is done for all of the following product Ids');
86+
$output->writeln(implode(', ', $resultIdArray));
87+
$output->writeln('');
88+
$output->writeln("============================================================================================================");
89+
$output->writeln('Run `bin/magento indexer:reindex`');
90+
}
91+
92+
public function deleteExistingUrlRewrite($_product)
93+
{
94+
$connection= $this->_resources->getConnection();
95+
$urlRewriteTable = $this->_resources->getTableName('url_rewrite');
96+
$catalogUrlRewriteProductCategory = $this->_resources->getTableName('catalog_url_rewrite_product_category');
97+
$rows = $connection->fetchAll("SELECT `url_rewrite_id` FROM " . $urlRewriteTable . " WHERE `entity_type` = 'product' AND `entity_id` = "."'".$_product->getId()."'");
98+
if(count($rows) == 0){
99+
return;
100+
}
101+
foreach ($rows as $row) {
102+
$deleteQueryCatalogUrlRewriteProductCategory = "DELETE FROM ". $catalogUrlRewriteProductCategory ." WHERE `url_rewrite_id` = " . $row['url_rewrite_id'];
103+
$connection->query($deleteQueryCatalogUrlRewriteProductCategory);
104+
105+
$deleteUrlRewriteTable = "DELETE FROM ". $urlRewriteTable ." WHERE `url_rewrite_id` = " . $row['url_rewrite_id'];
106+
$connection->query($deleteUrlRewriteTable);
107+
}
108+
109+
}
110+
111+
public function enterNewUrlRewrite($_product)
112+
{
113+
$connection= $this->_resources->getConnection();
114+
$urlRewriteTable = $this->_resources->getTableName('url_rewrite');
115+
$catalogUrlRewriteProductCategory = $this->_resources->getTableName('catalog_url_rewrite_product_category');
116+
117+
$storeIds = $_product->getStoreIds();
118+
$categoryIds = $_product->getCategoryIds();
119+
foreach ($storeIds as $storeId) {
120+
$requestPathWithoutSuffix = $_product->getUrlKey();
121+
122+
// check if request path exists
123+
$mathcingRows = $connection->fetchAll("SELECT `url_rewrite_id` FROM " . $urlRewriteTable . " WHERE `entity_type` = 'product' AND `request_path` = "."'".$requestPathWithoutSuffix.$this->getProductUrlSuffix()."'");
124+
while (count($mathcingRows) > 0) {
125+
$requestPathWithoutSuffix .= '-1';
126+
$mathcingRows = $connection->fetchAll("SELECT `url_rewrite_id` FROM " . $urlRewriteTable . " WHERE `entity_type` = 'product' AND `request_path` = "."'".$requestPathWithoutSuffix.$this->getProductUrlSuffix()."'");
127+
}
128+
$requestPath = $requestPathWithoutSuffix.$this->getProductUrlSuffix();
129+
130+
$targetPath = 'catalog/product/view/id/'.$_product->getId();
131+
$insertUrlRewriteTable = "INSERT INTO ". $urlRewriteTable ." (`entity_type`, `entity_id`, `request_path`, `target_path`, `redirect_type`, `store_id`, `description`, `is_autogenerated`, `metadata`) VALUES ('product', ".$_product->getId().", '".$requestPath."', '".$targetPath."', 0, ".$storeId.", NULL, 1, NULL);";
132+
133+
$connection->query($insertUrlRewriteTable);
134+
$urlRewriteId = $connection->lastInsertId();
135+
136+
foreach ($categoryIds as $categoryId) {
137+
$category = $this->_categoryFactory->create()->load($categoryId);
138+
$categoryPath = $this->getCategoryPath($category, $storeId);
139+
if(empty($categoryPath)) {
140+
continue;
141+
}
142+
$requestPathWithoutSuffix = $categoryPath.$_product->getUrlKey();
143+
144+
// check if request path exists
145+
$mathcingRows = $connection->fetchAll("SELECT `url_rewrite_id` FROM " . $urlRewriteTable . " WHERE `entity_type` = 'product' AND `request_path` = "."'".$requestPathWithoutSuffix.$this->getProductUrlSuffix()."'");
146+
while (count($mathcingRows) > 0) {
147+
$requestPathWithoutSuffix .= '-1';
148+
$mathcingRows = $connection->fetchAll("SELECT `url_rewrite_id` FROM " . $urlRewriteTable . " WHERE `entity_type` = 'product' AND `request_path` = "."'".$requestPathWithoutSuffix.$this->getProductUrlSuffix()."'");
149+
}
150+
$requestPath = $requestPathWithoutSuffix.$this->getProductUrlSuffix();
151+
$requestPath = $categoryPath.$_product->getUrlKey().$this->getProductUrlSuffix();
152+
$targetPath = 'catalog/product/view/id/'.$_product->getId().'/category/'.$categoryId;
153+
$insertUrlRewriteTable = "INSERT INTO ". $urlRewriteTable ." (`entity_type`, `entity_id`, `request_path`, `target_path`, `redirect_type`, `store_id`, `description`, `is_autogenerated`, `metadata`) VALUES ('product', ".$_product->getId().", '".$requestPath."', '".$targetPath."', 0, ".$storeId.", NULL, 1, NULL);";
154+
155+
$connection->query($insertUrlRewriteTable);
156+
$urlRewriteId = $connection->lastInsertId();
157+
158+
$insertCatalogUrlRewriteProductCategory = "INSERT INTO ". $catalogUrlRewriteProductCategory ." (`url_rewrite_id`, `category_id`, `product_id`) VALUES (".$urlRewriteId.", ".$categoryId.", ".$_product->getId().");";
159+
160+
$connection->query($insertCatalogUrlRewriteProductCategory);
161+
}
162+
}
163+
return $_product->getId();
164+
}
165+
166+
public function getCategoryPath($category, $storeId)
167+
{
168+
$pathIds = explode('/', $category->getPath());
169+
$collection = $this->_categoryCollection->create()
170+
->setStoreId($storeId)
171+
->addAttributeToSelect('*')
172+
->addFieldToFilter('entity_id', array('in' => $pathIds));
173+
174+
$urlPath = '';
175+
foreach($collection as $cat){
176+
if (!empty($cat->getUrlKey())) {
177+
$urlPath .= $cat->getUrlKey().'/';
178+
}
179+
}
180+
return $urlPath;
181+
}
182+
183+
/**
184+
* Retrieve product rewrite suffix for store
185+
*
186+
* @param int $storeId
187+
* @return string
188+
* @since 100.0.3
189+
*/
190+
protected function getProductUrlSuffix($storeId = null)
191+
{
192+
return $this->_scopeConfig->getValue(
193+
\Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX,
194+
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
195+
$storeId
196+
);
197+
}
198+
199+
/**
200+
* {@inheritdoc}
201+
*/
202+
protected function configure()
203+
{
204+
$this->setName("mj:producturlrewrite:run");
205+
$this->setDescription("Run Product URL Rewrite");
206+
$this->setDefinition([
207+
new InputArgument(self::PRODUCT_ID_ARGUMENT, InputArgument::OPTIONAL, "Product Ids separated by commas"),
208+
new InputOption(self::NAME_OPTION, "-a", InputOption::VALUE_NONE, "Option functionality")
209+
]);
210+
parent::configure();
211+
}
212+
213+
public function getProductCollection() {
214+
$collection = $this->_productCollectionFactory->create();
215+
$collection->addAttributeToSelect('*');
216+
217+
// // set visibility filter
218+
$collection->setVisibility($this->_productVisibility->getVisibleInSiteIds());
219+
220+
return $collection;
221+
}
222+
}

composer.json

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"name": "manishjoy/module-producturlrewrite",
3+
"description": "free magento 2 extension to resolve product url rewrite issue",
4+
"type": "magento2-module",
5+
"version": "1.0.0",
6+
"license": [
7+
"OSL-3.0",
8+
"AFL-3.0"
9+
],
10+
"require": {
11+
"php": "~7.0.13|~7.1.0",
12+
"magento/module-store": "*",
13+
"magento/module-catalog": "*",
14+
"magento/module-indexer": "*",
15+
"magento/module-customer": "*",
16+
"magento/module-directory": "*",
17+
"magento/module-catalog-inventory": "*",
18+
"magento/module-url-rewrite": "*",
19+
"magento/module-configurable-product": "*",
20+
"magento/framework": "*"
21+
},
22+
"authors": [
23+
{
24+
"name": "Manish Joy",
25+
"email": "[email protected]",
26+
"homepage": "https://in.linkedin.com/in/manishjoy",
27+
"role": "Developer"
28+
}
29+
],
30+
"autoload": {
31+
"files": [
32+
"registration.php"
33+
],
34+
"psr-4": {
35+
"ManishJoy\\ProductUrlRewrite\\": ""
36+
}
37+
}
38+
}

etc/di.xml

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?xml version="1.0" ?>
2+
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
3+
<type name="Magento\Framework\Console\CommandList">
4+
<arguments>
5+
<argument name="commands" xsi:type="array">
6+
<item name="Run" xsi:type="object">ManishJoy\ProductUrlRewrite\Console\Command\Run</item>
7+
</argument>
8+
</arguments>
9+
</type>
10+
</config>

etc/module.xml

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" ?>
2+
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
3+
<module name="ManishJoy_ProductUrlRewrite" setup_version="1.0.0"/>
4+
</config>

registration.php

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php
2+
\Magento\Framework\Component\ComponentRegistrar::register(
3+
\Magento\Framework\Component\ComponentRegistrar::MODULE,
4+
'ManishJoy_ProductUrlRewrite',
5+
__DIR__
6+
);

0 commit comments

Comments
 (0)