@@ -72,6 +72,31 @@ public function validate($object)
72
72
return true ;
73
73
}
74
74
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
+
75
100
/**
76
101
* Make SKU unique before save
77
102
*
@@ -80,6 +105,37 @@ public function validate($object)
80
105
*/
81
106
public function beforeSave ($ object )
82
107
{
108
+ if ($ object ->getIsDuplicate ()) {
109
+ $ this ->_generateUniqueSku ($ object );
110
+ }
83
111
return parent ::beforeSave ($ object );
84
112
}
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
+ }
85
141
}
0 commit comments