forked from corpsepk/yii2-yandex-market-yml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYandexMarketYml.php
108 lines (87 loc) · 2.75 KB
/
YandexMarketYml.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
/**
* @link https://github.com/corpsepk/yii2-yandex-market-yml
* @copyright Copyright (c) 2016 Corpsepk
* @license http://opensource.org/licenses/MIT
*/
namespace corpsepk\yml;
use Yii;
use yii\base\Module;
use yii\base\InvalidConfigException;
use yii\caching\Cache;
use corpsepk\yml\models\Shop;
use corpsepk\yml\behaviors\YmlCategoryBehavior;
use corpsepk\yml\behaviors\YmlOfferBehavior;
use yii\base\BootstrapInterface;
/**
* Yii2 module for automatically generating Yandex.Market YML.
*
* @author Corpsepk
* @package corpsepk\yml
*/
class YandexMarketYml extends Module implements BootstrapInterface
{
public $controllerNamespace = 'corpsepk\yml\controllers';
/** @var int */
public $cacheExpire = 86400;
/** @var Cache|string */
public $cacheProvider = 'cache';
/** @var string */
public $cacheKey = 'YandexMarketYml';
/** @var boolean Use php's gzip compressing. */
public $enableGzip = false;
/** @var YmlCategoryBehavior */
public $categoryModel;
/** @var array */
public $offerModels;
/** @var array */
public $shopOptions = [];
/** @var string for console*/
public $outputFilePath;
public function init()
{
parent::init();
if (is_string($this->cacheProvider)) {
$this->cacheProvider = Yii::$app->{$this->cacheProvider};
}
if (!$this->cacheProvider instanceof Cache) {
throw new InvalidConfigException('Invalid `cacheKey` parameter was specified.');
}
}
public function bootstrap($app)
{
if ($app instanceof \yii\console\Application) {
$this->controllerNamespace = 'corpsepk\yml\commands';
}
}
/**
* Build and cache a yandex.market yml
* @return string
*/
public function buildYml()
{
$shop = new Shop();
$shop->attributes = $this->shopOptions;
$categoryModel = new $this->categoryModel;
$shop->categories = $categoryModel->generateCategories();
foreach ($this->offerModels as $modelName) {
/** @var YmlOfferBehavior $model */
if (is_array($modelName)) {
$model = new $modelName['class'];
} else {
$model = new $modelName;
}
$shop->offers = array_merge($shop->offers, $model->generateOffers());
}
if (!$shop->validate()) {
return $this->createControllerByID('default')->renderPartial('errors', [
'shop' => $shop,
]);
}
$ymlData = $this->createControllerByID('default')->renderPartial('index', [
'shop' => $shop,
]);
$this->cacheProvider->set($this->cacheKey, $ymlData, $this->cacheExpire);
return $ymlData;
}
}