Product::copy PHP Method

copy() public method

public copy ( ) : null | Product
return null | Product
    public function copy()
    {
        $transaction = Yii::app()->getDb()->beginTransaction();
        $model = new Product();
        try {
            $model->setAttributes($this->getAttributes());
            $model->slug = null;
            $similarNamesCount = Yii::app()->getDb()->createCommand()->select('count(*)')->from($this->tableName())->where("name like :name", [':name' => $this->name . ' [%]'])->queryScalar();
            $model->name = $this->name . ' [' . ($similarNamesCount + 1) . ']';
            $model->slug = \yupe\helpers\YText::translit($model->name);
            $model->image = $this->image;
            $attributes = $model->attributes;
            $typeAttributes = $this->getTypesAttributesValues();
            $variantAttributes = $categoriesIds = [];
            if ($variants = $this->variants) {
                foreach ($variants as $variant) {
                    $variantAttributes[] = $variant->getAttributes(['attribute_id', 'attribute_value', 'amount', 'type', 'sku']);
                }
            }
            if ($categories = $this->categories) {
                foreach ($categories as $category) {
                    $categoriesIds[] = $category->id;
                }
            }
            if (!$model->saveData($attributes, $typeAttributes, $variantAttributes, $categoriesIds)) {
                throw new CDbException('Error copy product!');
            }
            $transaction->commit();
            return $model;
        } catch (Exception $e) {
            $transaction->rollback();
        }
        return null;
    }