Skip to content

Commit f27826e

Browse files
committed
magento-engcom#101: Re-add SKU generation in case product is duplicated. Duplicate needs a SKU to be saved.
1 parent fe30575 commit f27826e

File tree

1 file changed

+56
-0
lines changed
  • app/code/Magento/Catalog/Model/Product/Attribute/Backend

1 file changed

+56
-0
lines changed

app/code/Magento/Catalog/Model/Product/Attribute/Backend/Sku.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,31 @@ public function validate($object)
7272
return true;
7373
}
7474

75+
/**
76+
* Generate and set unique SKU to product
77+
*
78+
* @param Product $object
79+
* @return void
80+
*/
81+
protected function _generateUniqueSku($object)
82+
{
83+
$attribute = $this->getAttribute();
84+
$entity = $attribute->getEntity();
85+
$attributeValue = $object->getData($attribute->getAttributeCode());
86+
$increment = null;
87+
while (!$entity->checkAttributeUniqueValue($attribute, $object)) {
88+
if ($increment === null) {
89+
$increment = $this->_getLastSimilarAttributeValueIncrement($attribute, $object);
90+
}
91+
$sku = trim($attributeValue);
92+
if (strlen($sku . '-' . ++$increment) > self::SKU_MAX_LENGTH) {
93+
$sku = substr($sku, 0, -strlen($increment) - 1);
94+
}
95+
$sku = $sku . '-' . $increment;
96+
$object->setData($attribute->getAttributeCode(), $sku);
97+
}
98+
}
99+
75100
/**
76101
* Make SKU unique before save
77102
*
@@ -80,6 +105,37 @@ public function validate($object)
80105
*/
81106
public function beforeSave($object)
82107
{
108+
if ($object->getIsDuplicate()) {
109+
$this->_generateUniqueSku($object);
110+
}
83111
return parent::beforeSave($object);
84112
}
113+
114+
/**
115+
* Return increment needed for SKU uniqueness
116+
*
117+
* @param \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute
118+
* @param Product $object
119+
* @return int
120+
*/
121+
protected function _getLastSimilarAttributeValueIncrement($attribute, $object)
122+
{
123+
$connection = $this->getAttribute()->getEntity()->getConnection();
124+
$select = $connection->select();
125+
$value = $object->getData($attribute->getAttributeCode());
126+
$bind = ['attribute_code' => trim($value) . '-%'];
127+
128+
$select->from(
129+
$this->getTable(),
130+
$attribute->getAttributeCode()
131+
)->where(
132+
$attribute->getAttributeCode() . ' LIKE :attribute_code'
133+
)->order(
134+
['entity_id DESC', $attribute->getAttributeCode() . ' ASC']
135+
)->limit(
136+
1
137+
);
138+
$data = $connection->fetchOne($select, $bind);
139+
return abs((int)str_replace($value, '', $data));
140+
}
85141
}

0 commit comments

Comments
 (0)