DefaultVariantBehavior.php 1.89 KB
<?php
    namespace artbox\catalog\behaviors;
    
    use artbox\catalog\models\Product;
    use artbox\catalog\models\Variant;
    use artbox\catalog\models\VariantLang;
    use artbox\core\models\Language;
    use yii\base\Behavior;
    
    /**
     * Class DefaultVariantBehavior
     *
     * @property Product $owner
     * @see     ProductVariant
     */
    class DefaultVariantBehavior extends Behavior
    {
        /**
         * @inheritdoc
         */
        public function events()
        {
            return [
                Product::EVENT_AFTER_INSERT => 'addDefaultVariant',
            ];
        }
        
        /**
         * Creates new default product's variant
         */
        public function addDefaultVariant()
        {
            $defaultVariant = new Variant();
            $defaultVariant->product_id = $this->owner->id;
            $defaultVariant->stock = 1;
            $defaultVariant->sku = 'default';
            $defaultVariant->save(false);
            
            /**
             * Saving languages
             */
            $activeLanguageIds = Language::find()
                                         ->select('id')
                                         ->where(
                                             [
                                                 'status' => true,
                                             ]
                                         )
                                         ->asArray()
                                         ->column();
            foreach ($activeLanguageIds as $languageId) {
                $variantLanguage = new VariantLang();
                $variantLanguage->language_id = $languageId;
                $variantLanguage->variant_id = $defaultVariant->id;
                $variantLanguage->title = 'default_' . $languageId;
                $variantLanguage->save(false);
            }
        }
        
    }