57 lines
1.9 KiB
PHP
57 lines
1.9 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace Modules\Core\Catalog\Services;
|
||
|
|
|
||
|
|
use Lunar\Models\ProductVariant;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Generates a SKU for every ProductVariant missing one — extracted out of
|
||
|
|
* Command\BackfillMissingSkusCommand (which becomes a thin CLI wrapper
|
||
|
|
* around this, keeping --dry-run/progress-bar concerns out of the
|
||
|
|
* reusable logic) so MigrateImport\RunMigrateImportJob can also call it
|
||
|
|
* directly, right after a Shopify import, with no CLI concerns at all.
|
||
|
|
*
|
||
|
|
* Format is "SKU-P{product_id}-V{variant_id}": deterministic and
|
||
|
|
* guaranteed unique without a uniqueness check, since product_id/
|
||
|
|
* variant_id already are. Only variants with a null `sku` are touched —
|
||
|
|
* not an importer bug when one shows up after a Shopify import, the
|
||
|
|
* source CSV rows genuinely had no `Variant SKU` value (see
|
||
|
|
* MigrateImport\Shopify\ShopifyExportImporter).
|
||
|
|
*/
|
||
|
|
class SkuBackfillService
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* @param ?callable(ProductVariant, string): void $onEach invoked
|
||
|
|
* once per variant with the sku about to be written (or, when
|
||
|
|
* $dryRun is true, that WOULD be written) — the command's own
|
||
|
|
* --dry-run listing and progress bar hook in here without this
|
||
|
|
* service knowing anything about console output.
|
||
|
|
* @return int the number of variants processed
|
||
|
|
*/
|
||
|
|
public function backfill(bool $dryRun = false, ?callable $onEach = null): int
|
||
|
|
{
|
||
|
|
$query = ProductVariant::query()->whereNull('sku');
|
||
|
|
$total = $query->count();
|
||
|
|
|
||
|
|
if ($total === 0) {
|
||
|
|
return 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
$query->chunkById(500, function ($variants) use ($dryRun, $onEach) {
|
||
|
|
foreach ($variants as $variant) {
|
||
|
|
$sku = "SKU-P{$variant->product_id}-V{$variant->id}";
|
||
|
|
|
||
|
|
if (! $dryRun) {
|
||
|
|
$variant->update(['sku' => $sku]);
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($onEach !== null) {
|
||
|
|
$onEach($variant, $sku);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
return $total;
|
||
|
|
}
|
||
|
|
}
|