Skip to content

Commit

Permalink
Merge pull request #2 from Svitavsky/remove-config
Browse files Browse the repository at this point in the history
Удаление файла конфигурации
  • Loading branch information
Svitavsky committed Nov 22, 2020
2 parents ceb119f + c547fad commit a9ed1ae
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 115 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
.idea
config.php
*.yml
*.xml
78 changes: 59 additions & 19 deletions Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ class Validator
// Формат записи для поля dimensions
const DIMENSIONS_REGEX = '/[0-9]*\.?[0-9]*\/[0-9]*\.?[0-9]*\/[0-9]*\.?[0-9]*/';

// Замена кода валюты, чтобы во всей выгрузке был 1 код
const CURRENCY_REPLACEMENTS = [
'RUR' => 'RUB',
'RUB' => 'RUR'
];

// Поля для упрощенного типа
const SIMPLIFIED_TYPE_FIELDS = [
'name' => 'required|string',
Expand Down Expand Up @@ -67,7 +73,7 @@ class Validator
'expiry' => 'string',
'weight' => 'float',
'dimensions' => 'dimensions',
'downloadable' => 'float',
'downloadable' => 'boolean',
'age_month' => 'range[0-12]',
'age_year' => 'select[0,6,12,16,18]',
];
Expand All @@ -86,7 +92,7 @@ class Validator
],
'barcode' => 'string',
'param' => [
'name' => 'required|string',
'name' => 'string',
'unit' => 'string',
'value' => 'required|string'
],
Expand All @@ -97,37 +103,61 @@ class Validator
];

/**
* Поля, зависимые от типа вывода
* Основные данные о магазине
* @var array
*/
private $shop;

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

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

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

public function __construct(array $config)
/**
* Список доступных стран
* @var array
*/
private $availableCountries;

public function __construct(array $data)
{
$this->config = $config;
$this->typeFields = $config['simplifiedOffers'] ? self::SIMPLIFIED_TYPE_FIELDS : self::CUSTOM_TYPE_FIELDS;
$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)
{
$allRules = self::FIELDS_RULES + $this->typeFields;

$validated = [];
foreach ($offers as $offer) {
$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 @@ -218,8 +248,8 @@ private function string($value)

private function boolean($value)
{
$isTrue = in_array($value, self::BOOLEAN_TRUE);
$isFalse = in_array($value, self::BOOLEAN_FALSE);
$isTrue = $value === true || in_array($value, self::BOOLEAN_TRUE);
$isFalse = $value === false || in_array($value, self::BOOLEAN_FALSE);

return $isTrue || $isFalse;
}
Expand Down Expand Up @@ -321,14 +351,24 @@ 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') {
$value = 'RUR';
}

if (in_array('RUB', $currencies) && $value === 'RUR') {
$value = 'RUB';
}

return in_array($value, $currencies);
}

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

This file was deleted.

21 changes: 11 additions & 10 deletions template.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,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><?= $config['companyWebsite'] ?></url>
<name><?= $shop['name'] ?></name>
<company><?= $shop['description'] ?></company>
<url><?= $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 All @@ -28,9 +28,9 @@
<?php foreach ($offers as $offer): ?>
<offer id="<?= $offer['id'] ?>"
<?= isset($offer['bid']) ? "bid=\"{$offer['bid']}\"" : '' ?>
<?= $config['simplifiedOffers'] ? 'type="vendor.model"' : '' ?>
<?= isset($offer['type']) ? "type=\"{$offer['type']}\"" : '' ?>
<?= isset($offer['available']) ? "available=\"{$offer['available']}\"" : '' ?> >
<?php if ($config['simplifiedOffers']): ?>
<?php if (!isset($offer['type'])): ?>
<name><?= $offer['name'] ?></name>
<?php if (isset($offer['vendor'])): ?>
<vendor><?= $offer['vendor'] ?></vendor>
Expand Down Expand Up @@ -90,21 +90,22 @@
<?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'])): ?>
<adult><?= $offer['adult'] ?></adult>
<?php endif; ?>
<?php if (isset($offer['barcode']) && is_array($offer['barcode'])): ?>
<?php foreach ($offer['barcode'] as $barcode): ?>
<barcode><?= $offer['barcode'] ?></barcode>
<barcode><?= $barcode ?></barcode>
<?php endforeach; ?>
<?php endif; ?>
<?php if (isset($offer['param']) && is_array($offer['param'])): ?>
<?php foreach ($offer['param'] as $param): ?>
<?php $unit = isset($param['unit']) ? "unit=\"{$param['unit']}\"" : ''; ?>
<param name="<?= $param['name'] ?>" <?= $unit ?>><?= $param['value'] ?></param>
<?php $name = isset($param['name']) ? "name=\"{$param['name']}\"" : ''; ?>
<param <?= $name ?> <?= $unit ?>><?= $param['value'] ?></param>
<?php endforeach; ?>
<?php endif; ?>
<?php if (isset($offer['condition'], $offer['condition_description']) &&
Expand Down

0 comments on commit a9ed1ae

Please sign in to comment.