Skip to content

Commit

Permalink
Merge
Browse files Browse the repository at this point in the history
  • Loading branch information
Svitavsky committed Nov 22, 2020
2 parents 7c607e6 + a9ed1ae commit 25d1c04
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 102 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
.idea
config.php
*.xml
54 changes: 43 additions & 11 deletions Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,29 +103,61 @@ class Validator
];

/**
* Конфигурация модуля
* Основные данные о магазине
* @var array
*/
private $config;
private $shop;

public function __construct(array $config)
/**
* Список валют, принимаемых магазином и их курс
* @var array
*/
private $currencies;

/**
* Список категорий магазина
* @var array
*/
private $categories;

/**
* Список предложений магазина
* @var array
*/
private $offers;

/**
* Список доступных стран
* @var array
*/
private $availableCountries;

public function __construct(array $data)
{
$this->config = $config;
$this->shop = $data['shop'] ?? [];
$this->currencies = $data['currencies'] ?? [];
$this->categories = $data['categories'] ?? [];
$this->offers = $data['offers'] ?? [];
$this->availableCountries = $data['availableCountries'] ?? [];
}

public function validateAll(array $data)
public function validateAll()
{
return [
'offers' => $this->offers($data['offers']),
'categories' => $this->categories($data['categories'])
'shop' => $this->shop,
'offers' => $this->offers($this->offers),
'categories' => $this->categories($this->categories),
'currencies' => $this->currencies,
'availableCountries' => $this->availableCountries
];
}

private function offers(array $offers)
{
$validated = [];
foreach ($offers as $offer) {
$allRules = self::FIELDS_RULES + (isset($offer['type']) ? self::CUSTOM_TYPE_FIELDS : self::SIMPLIFIED_TYPE_FIELDS);
$typeFields = isset($offer['type']) ? self::CUSTOM_TYPE_FIELDS : self::SIMPLIFIED_TYPE_FIELDS;
$allRules = self::FIELDS_RULES + $typeFields;
foreach ($allRules as $field => $rulesList) {
$rules = explode('|', $rulesList);
foreach ($rules as $rule) {
Expand Down Expand Up @@ -319,7 +351,7 @@ private function length($value, $length)

private function currency($value)
{
$currencies = array_keys($this->config['currencies']);
$currencies = array_keys($this->currencies);

// В выгрузке можно применять оба кода рубля, используем тот, который указан в конфиге
if (in_array('RUR', $currencies) && $value === 'RUB') {
Expand All @@ -335,8 +367,8 @@ private function currency($value)

private function country($value)
{
$countries = $this->config['availableCountries'];
return in_array($value, $countries);
$availableCountries = $this->availableCountries;
return in_array($value, $availableCountries);
}

private function getRuleOptions(string $rule)
Expand Down
68 changes: 14 additions & 54 deletions YMLGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,72 +5,32 @@
class YMLGenerator
{
/**
* Список данных
* @var array
*/
public $data;

/**
* Сообщение генератора
* Название итогового файла
* @var string
*/
public $message = '';
public $filename;

public function __construct(array $data)
public function __construct(string $filename)
{
$this->data = $data;
$this->filename = $filename;
}

/**
* Запуск генератора
* @param array $data
*/
public function run()
public function run(array $data)
{
$config = $this->getConfig();
$data = $this->getData($config);
$data['config'] = $config;
if ($this->message) {
return;
}

$builder = new Builder($data);
$text = $builder->build();
$outputFile = strlen($config['ymlFilename']) ? $config['ymlFilename'] : 'shop.yml';
file_put_contents($outputFile, $text);

$this->message = "Файл {$config['ymlFilename']} успешно сгенерирован!";
}

private function getData(array $config)
{
$validator = new Validator($config);
return $validator->validateAll($this->data);
}

private function getConfig()
{
if (!file_exists('config.php')) {
$this->message = 'Файл конфигурации config.php не найден! Создайте его, затем перезапустите генератор.';
}

$config = include 'config.php';
$example = include 'config.example.php';

$missingKeys = [];
foreach ($example as $key => $value) {
if (!array_key_exists($key, $config)) {
$missingKeys[] = $key;
}
}
$data['availableCountries'] = $this->getAvailableCountries();
$validator = new Validator($data);
$result = $validator->validateAll();
$result['date'] = date("Y-m-d H:i", time());

if (count($missingKeys)) {
$keys = implode(' ', $missingKeys);
$this->message = "Отсутствуют обязательные параметры в файле конфигурации config.php: {$keys}";
}
$builder = new Builder($result);
$content = $builder->build();
file_put_contents($this->filename, $content);

$config['availableCountries'] = $this->getAvailableCountries();
$config['date'] = date("Y-m-d H:i", time());
return $config;
echo "Файл {$this->filename} успешно сгенерирован!";
}

/**
Expand Down
30 changes: 0 additions & 30 deletions config.example.php
Original file line number Diff line number Diff line change
@@ -1,30 +0,0 @@
<?php

// Шаблон файла конфигурации
// Для работоспособности модуля, скопируйте данный с названием config.php и измените данные на свои

return [
// Основные данные о компании
'companyName' => 'Company name', // Название компании
'companyDescription' => 'Company description', // Описание компании
'companyWebsite' => 'https://example.com', // URL вашей компании

// Название итогового файла с предложениями
'ymlFilename' => 'example.xml',

// Переключатель упрощенного типа для предложений
// true - упрощенный тип
// false - произвольный тип
'simplifiedOffers' => true,

// Список валют с курсами, формат КОД => КУРС
// Для включения просто раскомментируйте и укажите актуальный курс
'currencies' => [
'RUR' => 1, // Российский рубль (или RUB)
// 'USD' => 30, // Доллар США
// 'EUR' => 40, // Евро
// 'UAH' => 3, // Украинская гривна
// 'BYN' => 30, // Белорусский рубль
// 'KZT' => 0.2, // Казахстанский тенге
]
];
12 changes: 6 additions & 6 deletions template.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

?>
<?= '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL ?>
<yml_catalog date="<?= $config['date'] ?>">
<yml_catalog date="<?= $date ?>">
<shop>
<name><?= $config['companyName'] ?></name>
<company><?= $config['companyDescription'] ?></company>
<url><?= rawurlencode(utf8_encode($config['companyWebsite'])) ?></url>
<name><?= $shop['name'] ?></name>
<company><?= $shop['description'] ?></company>
<url><?= rawurlencode(utf8_encode($shop['website'])) ?></url>
<currencies>
<?php foreach ($config['currencies'] as $code => $rate): ?>
<?php foreach ($currencies as $code => $rate): ?>
<currency id="<?= $code ?>" rate="<?= $rate ?>"/>
<?php endforeach; ?>
</currencies>
Expand Down Expand Up @@ -98,7 +98,7 @@
<?php if (isset($offer['manufacturer_warranty'])): ?>
<manufacturer_warranty><?= $offer['manufacturer_warranty'] ?></manufacturer_warranty>
<?php endif; ?>
<?php if (isset($offer['country_of_origin']) && in_array($offer['country_of_origin'], $config['availableCountries'])): ?>
<?php if (isset($offer['country_of_origin']) && in_array($offer['country_of_origin'], $availableCountries)): ?>
<country_of_origin><?= $offer['country_of_origin'] ?></country_of_origin>
<?php endif; ?>
<?php if (isset($offer['adult'])): ?>
Expand Down

0 comments on commit 25d1c04

Please sign in to comment.