DefaultVariantBehavior.php
2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace common\behaviors;
use yii\base\Behavior;
use common\modules\product\models\Product;
use common\modules\product\models\ProductVariant;
use common\modules\product\models\ProductUnit;
use common\modules\product\models\ProductStock;
use common\modules\product\models\Stock;
/**
* Class DefaultVariantBehavior
* @package common/behaviors
* @property Product $owner
* @see ProductVariant
*/
class DefaultVariantBehavior extends Behavior
{
/**
* Catches product's insert event
*
* @return array
*/
public function events()
{
return [
Product::EVENT_AFTER_INSERT => 'addDefaultVariant',
];
}
/**
* Creates new default product's variant and sets it's to stock
* marked as default and sets to it unit also marked as default
*/
public function addDefaultVariant()
{
/**
* @var Stock $stock
* @var ProductUnit $defaultUnit
*/
$defaultVariant = new ProductVariant();
$defaultVariant->product_id = $this->owner->product_id;
/**
* Gets default unit for variant
*/
$defaultUnit = ProductUnit::find()
->where([
'is_default' => true,
])->one();
$defaultVariant->product_unit_id = $defaultUnit->product_unit_id;
$defaultVariant->stock = 1;
$defaultVariant->name = 'default';
$defaultVariant->sku = 'default';
$defaultVariant->save();
/**
* Gets default stock
*/
$stock = Stock::find()
->where([
'is_default' => true,
])->one();
/**
* Add a new stock record
*/
$defaultStock = new ProductStock();
$defaultStock->product_id = $this->owner->product_id;
$defaultStock->stock_id = $stock->stock_id;
$defaultStock->quantity = $defaultVariant->stock;
$defaultStock->product_variant_id = $defaultVariant->product_variant_id;
$defaultStock->save();
}
}