Created
January 28, 2022 15:58
-
-
Save dmaksimov/10757eccbc6a92934e594074f99b9842 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use App\Models\Product; | |
use App\Models\ProductVariant; | |
use Illuminate\Console\Command; | |
class FindProductDuplicates extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'find-product-duplicates'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Command description'; | |
/** | |
* Create a new command instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
/** | |
* Execute the console command. | |
* | |
* @return int | |
*/ | |
public function handle() | |
{ | |
// Find duplicates | |
$products = Product::orderBy('id')->get(); | |
foreach ($products as $product) { | |
if ($duplicateProduct = $this->findDuplicate($product)) { | |
if ($duplicateProduct->title != $product->title) { | |
$this->info($product->title . '(#'.$product->id.')' . ' :: ' . $duplicateProduct->title . '(#'.$duplicateProduct->id.')'); | |
} | |
} | |
} | |
return 0; | |
} | |
protected function findDuplicate($product) | |
{ | |
if ($product->uses_variants) { | |
foreach ($product->variants as $variant) { | |
if (empty($variant->sku)) { | |
continue; | |
} | |
$duplicateVariant = ProductVariant::where('product_id', '!=', $product->id) | |
->where('sku', $variant->sku) | |
->first(); | |
if ($duplicateVariant) { | |
return $duplicateVariant->product; | |
} | |
} | |
} else { | |
if (! empty($product->sku)) { | |
$duplicateProduct = Product::where('id', '!=', $product->id) | |
->where('sku', $product->sku) | |
->first(); | |
if ($duplicateProduct) { | |
return $duplicateProduct; | |
} | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment