/
ProductFixture.php
82 lines (73 loc) · 2.05 KB
/
ProductFixture.php
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
79
80
81
82
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\commerce\test\fixtures\elements;
use craft\base\ElementInterface;
use craft\commerce\db\Table;
use craft\commerce\elements\Product;
use craft\commerce\Plugin;
use craft\db\Query;
use craft\test\fixtures\elements\BaseElementFixture;
use yii\base\InvalidArgumentException;
/**
* Class ProductFixture.
*
* Credit to: https://github.com/robuust/craft-fixtures
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @author Robuust digital | Bob Olde Hampsink <bob@robuust.digital>
* @author Global Network Group | Giel Tettelaar <giel@yellowflash.net>
* @since 2.1
*/
class ProductFixture extends BaseElementFixture
{
/**
* @var array
*/
protected array $productTypeIds = [];
/**
* {@inheritdoc}
*/
public function init(): void
{
parent::init();
// Ensure loaded
$commerce = Plugin::getInstance();
if (!$commerce) {
throw new InvalidArgumentException('Commerce plugin needs to be loaded before using the ProductFixture');
}
// Get all product type id's
$this->productTypeIds = $this->_getProductTypeIds();
}
/**
* @inheritdoc
*/
public function afterLoad(): void
{
$this->productTypeIds = $this->_getProductTypeIds();
}
protected function createElement(): ElementInterface
{
return new Product();
}
/**
* Get array of product type IDs indexed by handle.
* This uses a raw query to avoid service level caching/memoization.
*
* @TODO review the necessity of this at the next breakpoint version. #COM-54
*/
private function _getProductTypeIds(): array
{
return (new Query())
->select([
'productTypes.id',
'productTypes.handle',
])
->from([Table::PRODUCTTYPES . ' productTypes'])
->indexBy('handle')
->column();
}
}