Skip to content
This repository was archived by the owner on Sep 6, 2023. It is now read-only.

Commit 092e58c

Browse files
authored
Merge pull request #3 from ggrachdev/dev
0.06
2 parents c960344 + 0c7f95b commit 092e58c

File tree

11 files changed

+227
-129
lines changed

11 files changed

+227
-129
lines changed

README.md

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,11 @@
1212
<?php
1313
use GGrach\FishGenerator\Generators\FishGenerator;
1414

15-
1615
\Bitrix\Main\Loader::includeModule('ggrachdev.fish_generator');
1716

1817
/**
1918
* В конструктор передаем IBLOCK ID в который нужно сгенерировать тестовый элемент
20-
* При setDebug = true в результирующий массив записываются данные для генерации
19+
* При setDebugMode = true в результирующий массив записываются данные для генерации
2120
* При setStrictMode = true выбрасываются Exception'ы если что-то идет не так
2221
* Вторым параметром в конструктор можно передать локализацию faker, по умолчанию ru_RU
2322
* По умолчанию автоматически генерируются: имя, детальное фото, фото анонса, детальный текст + текст анонса, символьный код
@@ -26,9 +25,9 @@ use GGrach\FishGenerator\Generators\FishGenerator;
2625
* нему нужно обращаться через PROPERTY_... то ничего в качестве префикса ставить не нужно
2726
*/
2827

29-
$result = (new FishGenerator(6))->setDebug(true)->setStrictMode(true)
28+
$result = (new FishGenerator(6))->setDebugMode(true)->setStrictMode(true)
3029
->setCategoryPhoto(['technics', 'business', 'city'])
31-
->setPropertyRules([
30+
->setGenerationRules([
3231
/*
3332
* Если свойство является системым, то ставим в начале *, если свойство является дополнительным у инфоблока (Т.е PROPERTY_NAME), то не ставим
3433
* Если нужно задать строгое значение свойства при добавлении элементов, то ставим =, можно группировать: *=, =, *, при этом в $
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
namespace GGrach\FishGenerator\Cache;
4+
5+
6+
class RuntimeCache {
7+
8+
private static $cacheRegister;
9+
10+
public static function get($key) {
11+
if (self::has($key))
12+
{
13+
return self::getRegister()[$key];
14+
}
15+
16+
return null;
17+
}
18+
19+
public static function has($key) {
20+
return \array_key_exists($key, self::getRegister());
21+
}
22+
23+
public static function set($key, $value) {
24+
self::$cacheRegister[$key] = $value;
25+
}
26+
27+
public static function getRegister() {
28+
return self::$cacheRegister;
29+
}
30+
31+
32+
public static function remove($key) {
33+
if(self::has($key))
34+
{
35+
unset(self::$cacheRegister[$key]);
36+
}
37+
}
38+
39+
public static function removeAll()
40+
{
41+
self::$cacheRegister = [];
42+
}
43+
}

ggrachdev.fish_generator/classes/general/FishGenerator/Debug.php renamed to ggrachdev.fish_generator/classes/general/FishGenerator/Debug/Debug.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?
22

3-
namespace GGrach\FishGenerator;
3+
namespace GGrach\FishGenerator\Debug;
44

55
/**
66
* @todo Add https://dummyimage.com/
@@ -71,7 +71,7 @@ public function getResultData(): array {
7171
}
7272
}
7373

74-
public function setDebug(bool $valueDebug) {
74+
public function setDebugMode(bool $valueDebug) {
7575
$this->isDebug = $valueDebug;
7676
return $this;
7777
}

ggrachdev.fish_generator/classes/general/FishGenerator/Generators/ElementGenerator.php

Lines changed: 15 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,15 @@
33
namespace GGrach\FishGenerator\Generators;
44

55
use GGrach\FishGenerator\Exceptions\GenerateElementException;
6-
use GGrach\FishGenerator\Exceptions\SearchIblockException;
76
use GGrach\FishGenerator\Exceptions\GeneratorTypeException;
87
use GGrach\FishGenerator\PropertyRulesElementFilter;
8+
use GGrach\FishGenerator\Parser\RuleGenerationParser;
99

1010
/**
1111
* Логика генерации элемента
1212
*/
1313
class ElementGenerator extends PropertyRulesElementFilter {
1414

15-
/**
16-
* Свойства которые считаются за стандартные свойства битрикса
17-
*/
18-
const STANDART_PROPERTIES = [
19-
'NAME', 'ACTIVE', 'CODE', 'IBLOCK_SECTION_ID', 'DETAIL_TEXT', 'PREVIEW_TEXT', 'SORT'
20-
];
21-
2215
/**
2316
* @var Object Адаптированный генератор
2417
* @todo Добавить интерфейс, возможность сменить генератор
@@ -46,10 +39,10 @@ public function generate(int $countElements) {
4639

4740
$categoryPhoto = $this->getRandomCategoryPhoto();
4841

49-
$arPropertyGenerated = $this->getGeneratedPropertyArray();
42+
$arValidPropertiesForGeneration = RuleGenerationParser::parse($this->arPropertyGenerateRules);
5043

51-
$linkPreviewImage = $this->dataGenerator->imageUrl(1000, 1000, $categoryPhoto);
52-
$linkDetailImage = $this->dataGenerator->imageUrl(1000, 1000, $categoryPhoto);
44+
$linkPreviewImage = 'https://loremflickr.com/1000/1000/'.$categoryPhoto.'?salt='. \uniqid();
45+
$linkDetailImage = 'https://loremflickr.com/1000/1000/'.$categoryPhoto.'?salt='. \uniqid();
5346

5447
$previewPicture = $this->generatePhotoFromLink($linkPreviewImage);
5548
$detailPicture = $this->generatePhotoFromLink($linkDetailImage);
@@ -65,15 +58,15 @@ public function generate(int $countElements) {
6558
];
6659

6760
// Вставляем стандартные свойства
68-
if (!empty($arPropertyGenerated['STANDART_PROPERTIES'])) {
69-
foreach ($arPropertyGenerated['STANDART_PROPERTIES'] as $propCode => $propValue) {
61+
if (!empty($arValidPropertiesForGeneration['STANDART_PROPERTIES'])) {
62+
foreach ($arValidPropertiesForGeneration['STANDART_PROPERTIES'] as $propCode => $propValue) {
7063
$arField[$propCode] = $propValue;
7164
}
7265
}
7366

7467
// Вставляем свойства
75-
if (!empty($arPropertyGenerated['PROPERTIES'])) {
76-
$arField['PROPERTY_VALUES'] = $arPropertyGenerated['PROPERTIES'];
68+
if (!empty($arValidPropertiesForGeneration['PROPERTIES'])) {
69+
$arField['PROPERTY_VALUES'] = $arValidPropertiesForGeneration['PROPERTIES'];
7770
}
7871

7972
$arField['NAME'] = str_replace('$', ($i + 1), $arField['NAME']);
@@ -85,8 +78,9 @@ public function generate(int $countElements) {
8578
$arField['CODE'] = \CUtil::translit($arField['NAME'], "ru");
8679

8780
$el = new \CIBlockElement();
81+
$productId = $el->Add($arField, false, true, false);
8882

89-
if ($productId = $el->Add($arField, false, true, false)) {
83+
if ($productId) {
9084
$this->addSuccess($arField);
9185
} else {
9286
$this->addError($el->LAST_ERROR . ' ON LINE ' . __LINE__);
@@ -108,76 +102,6 @@ public function generate(int $countElements) {
108102
return $this->getResultData();
109103
}
110104

111-
/**
112-
* Получить обработанный массив сгенерированных данных для элемента
113-
*
114-
* @return array
115-
*/
116-
protected function getGeneratedPropertyArray(): array {
117-
118-
$arPropertyGenerated = [
119-
'PROPERTIES' => [],
120-
'STANDART_PROPERTIES' => []
121-
];
122-
123-
if (!empty($this->arPropertyGenerateRules)) {
124-
125-
foreach ($this->arPropertyGenerateRules as $propertyName => $typeGenerator) {
126-
127-
$isStandartProperties = in_array(str_replace(['*', '='], ['', ''], $propertyName), static::STANDART_PROPERTIES) && ($propertyName[0] == '*' || $propertyName[1] == '*');
128-
129-
$isDefaultValue = false;
130-
131-
if ($isStandartProperties) {
132-
if ($propertyName[0] === '=' || $propertyName[1] === '=') {
133-
$isDefaultValue = true;
134-
}
135-
} else {
136-
if ($propertyName[0] === '=') {
137-
$isDefaultValue = true;
138-
}
139-
}
140-
141-
if (!is_array($typeGenerator)) {
142-
$arParams = explode('(', str_replace(')', '', $typeGenerator));
143-
$typeGenerator = array_shift($arParams);
144-
145-
$valuePropety = null;
146-
147-
if (!$isDefaultValue) {
148-
$valuePropety = $this->generateItem($typeGenerator, $arParams);
149-
} else {
150-
$valuePropety = $typeGenerator;
151-
}
152-
} else {
153-
154-
if (sizeof($typeGenerator) == 2) {
155-
156-
if (is_numeric($typeGenerator[1]) && is_string($typeGenerator[0])) {
157-
158-
$count = $typeGenerator[1];
159-
160-
$arParams = explode('(', str_replace(')', '', $typeGenerator[0]));
161-
$typeGenerator = array_shift($arParams);
162-
163-
$valuePropety = $this->generateItem($typeGenerator, $arParams, $count);
164-
}
165-
}
166-
}
167-
168-
if ($valuePropety !== null) {
169-
if ($isStandartProperties) {
170-
$arPropertyGenerated['STANDART_PROPERTIES'][str_replace(['*', '='], ['', ''], $propertyName)] = $valuePropety;
171-
} else {
172-
$arPropertyGenerated['PROPERTIES'][str_replace(['*', '='], ['', ''], $propertyName)] = $valuePropety;
173-
}
174-
}
175-
}
176-
}
177-
178-
return $arPropertyGenerated;
179-
}
180-
181105
/**
182106
* Сгенерировать данные
183107
*
@@ -304,7 +228,9 @@ protected function generateItem(string $typeGenerator, array $arParams = [], int
304228
$categoryPhoto = $this->getRandomCategoryPhoto();
305229

306230
$fileArray = [
307-
'VALUE' => $this->generatePhotoFromLink($this->dataGenerator->imageUrl($width, $height, $categoryPhoto))
231+
'VALUE' => $this->generatePhotoFromLink(
232+
'https://loremflickr.com/'.$width.'/'.$height.'/'.$categoryPhoto.'?salt='. \uniqid()
233+
)
308234
];
309235

310236
if (!empty($fileArray['VALUE']['tmp_name'])) {
@@ -313,7 +239,7 @@ protected function generateItem(string $typeGenerator, array $arParams = [], int
313239
}
314240
}
315241
} else {
316-
$linkImg = $this->dataGenerator->imageUrl($width, $height, $categoryPhoto);
242+
$linkImg = 'https://loremflickr.com/'.$width.'/'.$height.'/'.$categoryPhoto.'?salt='. \uniqid();
317243
$valuePropety = $this->generatePhotoFromLink($linkImg);
318244
}
319245
break;
@@ -330,7 +256,7 @@ protected function generateItem(string $typeGenerator, array $arParams = [], int
330256
if (!empty($arParams[0])) {
331257
$arRand = explode(',', $arParams[0]);
332258

333-
$arRand = array_map(function($el) {
259+
$arRand = array_map(function ($el) {
334260
return trim($el);
335261
}, $arRand);
336262

ggrachdev.fish_generator/classes/general/FishGenerator/Generators/FishGenerator.php

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,42 +4,37 @@
44

55
use GGrach\FishGenerator\Exceptions\SearchIblockException;
66

7-
/**
8-
* @todo Добавить исключения
9-
*/
107
final class FishGenerator extends ElementGenerator {
11-
12-
/**
13-
* @var array Кеш
14-
*/
15-
public $arCache = [];
16-
8+
179
/*
1810
* @var int ID Инфоблока в который будет осуществлена генерация
1911
*/
2012
protected $iblockId = null;
2113

2214
/**
23-
*
2415
* @param int $iblockId
2516
* @param string $localization Локализация
2617
* @throws BitrixRedactionException
2718
*/
2819
public function __construct(int $iblockId, string $localization = 'ru_RU') {
2920

21+
if ($iblockId <= 0) {
22+
throw new SearchIblockException('Iblock id ' . $iblockId . ' can be above zero ');
23+
}
24+
3025
if (\Bitrix\Main\Loader::includeModule("iblock")) {
3126
$dbRes = \CIBlock::GetList(
3227
[],
3328
["ID" => $iblockId]
3429
);
3530

3631
if (!$dbRes->GetNext()) {
37-
throw new SearchIblockException('Указаный инфоблок не найден');
32+
throw new SearchIblockException('Not found iblock with id ' . $iblockId);
3833
}
3934
$this->dataGenerator = \Faker\Factory::create($localization);
4035
$this->iblockId = $iblockId;
4136
} else {
42-
throw new BitrixRedactionException('Не найдены необходимые для работы библиотеки модули');
37+
throw new BitrixRedactionException('Modules required for the library to work were not found');
4338
}
4439
}
4540

ggrachdev.fish_generator/classes/general/FishGenerator/Generators/PhotoGenerator.php

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
namespace GGrach\FishGenerator\Generators;
44

55
use GGrach\FishGenerator\Exceptions\GeneratePhotoException;
6-
use GGrach\FishGenerator\Debug;
6+
use GGrach\FishGenerator\Debug\Debug;
77

88
/**
99
* @todo Add https://dummyimage.com/
@@ -35,7 +35,7 @@ class PhotoGenerator extends Debug {
3535
* @param string|array $categoryPhoto
3636
* @return \GGrach\Generators\ElementFishGenerator
3737
*/
38-
public function setCategoryPhoto($categoryPhoto): ElementFishGenerator {
38+
public function setCategoryPhoto($categoryPhoto): self {
3939

4040
$isValidPhotoCategory = false;
4141

@@ -55,7 +55,7 @@ public function setCategoryPhoto($categoryPhoto): ElementFishGenerator {
5555
}
5656

5757
if ($isValidPhotoCategory === false) {
58-
if ($this->$isStrictMode) {
58+
if ($this->isStrictMode) {
5959
if (is_array($categoryPhoto)) {
6060
throw new GeneratePhotoException('Not found photos with categories ' . implode(',', $categoryPhoto));
6161
} else {
@@ -73,17 +73,30 @@ public function setCategoryPhoto($categoryPhoto): ElementFishGenerator {
7373
}
7474

7575
public function generatePhotoFromLink(string $photoLink): array {
76-
$pictureArray = \CFile::MakeFileArray($photoLink);
76+
77+
// Получаем итоговую ссылку даже если есть редирект
78+
$ch = \curl_init();
79+
\curl_setopt($ch, CURLOPT_URL, $photoLink);
80+
\curl_setopt($ch, CURLOPT_HEADER, true);
81+
\curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
82+
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
83+
84+
\curl_exec($ch);
85+
86+
$url = \curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
87+
\curl_close($ch);
88+
89+
$pictureArray = \CFile::MakeFileArray($url);
7790
if (empty($pictureArray['tmp_name'])) {
78-
79-
$error = 'Ошибка сохранения изображения по ссылке '.$photoLink.', возможно, у Вас не хватает ресурсов сервера или недоступен сайт lorempixel.com откуда берутся фотографии';
80-
91+
92+
$error = 'Error save image from link ' . $photoLink . ', maybe, can not available site generator';
93+
8194
$this->addError($error);
82-
95+
8396
if ($this->isStrictMode) {
8497
throw new GeneratePhotoException($error);
8598
}
86-
99+
87100
$pictureArray = [];
88101
} else {
89102
$pictureArray['name'] = $pictureArray['name'] . '.jpg';

0 commit comments

Comments
 (0)