From c547fad3082f5fa857700728b0cbaab861e67cc0 Mon Sep 17 00:00:00 2001 From: Svitavsky Date: Sun, 22 Nov 2020 03:26:55 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A4=D0=B0=D0=B9=D0=BB=20config.php=20=D0=B1?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20=D0=BD=D0=B5=20=D0=B8=D1=81?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D1=83=D0=B5=D1=82=D1=81=D1=8F,?= =?UTF-8?q?=20=D0=B2=D1=81=D0=B5=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5=20?= =?UTF-8?q?=D0=B1=D1=83=D0=B4=D1=83=D1=82=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B0=D0=B2=D0=B0=D1=82=D1=8C=D1=81=D1=8F=20=D0=B2=20=D1=81?= =?UTF-8?q?=D0=BA=D1=80=D0=B8=D0=BF=D1=82=20=D0=BF=D1=80=D0=B8=20=D0=B2?= =?UTF-8?q?=D1=8B=D0=B7=D0=BE=D0=B2=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +- Validator.php | 78 +++++++++++++++++++++++++++++++++++----------- YMLGenerator.php | 68 +++++++++------------------------------- config-example.php | 30 ------------------ template.php | 21 +++++++------ 5 files changed, 85 insertions(+), 115 deletions(-) delete mode 100644 config-example.php diff --git a/.gitignore b/.gitignore index aa697dc..690364f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,2 @@ .idea -config.php -*.yml \ No newline at end of file +*.xml \ No newline at end of file diff --git a/Validator.php b/Validator.php index ec79641..18e3dee 100644 --- a/Validator.php +++ b/Validator.php @@ -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', @@ -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]', ]; @@ -86,7 +92,7 @@ class Validator ], 'barcode' => 'string', 'param' => [ - 'name' => 'required|string', + 'name' => 'string', 'unit' => 'string', 'value' => 'required|string' ], @@ -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) { @@ -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; } @@ -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) diff --git a/YMLGenerator.php b/YMLGenerator.php index 3f02c34..96a69a5 100644 --- a/YMLGenerator.php +++ b/YMLGenerator.php @@ -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} успешно сгенерирован!"; } /** diff --git a/config-example.php b/config-example.php deleted file mode 100644 index 9e295c2..0000000 --- a/config-example.php +++ /dev/null @@ -1,30 +0,0 @@ - 'Company name', // Название компании - 'companyDescription' => 'Company description', // Описание компании - 'companyWebsite' => 'https://example.com', // URL вашей компании - - // Название итогового файла с предложениями - 'ymlFilename' => 'example.yml', - - // Переключатель упрощенного типа для предложений - // true - упрощенный тип - // false - произвольный тип - 'simplifiedOffers' => true, - - // Список валют с курсами, формат КОД => КУРС - // Для включения просто раскомментируйте и укажите актуальный курс - 'currencies' => [ - 'RUR' => 1, // Российский рубль (или RUB) -// 'USD' => 30, // Доллар США -// 'EUR' => 40, // Евро -// 'UAH' => 3, // Украинская гривна -// 'BYN' => 30, // Белорусский рубль -// 'KZT' => 0.2, // Казахстанский тенге - ] -]; \ No newline at end of file diff --git a/template.php b/template.php index 537d807..ef792cc 100644 --- a/template.php +++ b/template.php @@ -5,13 +5,13 @@ ?> ' . PHP_EOL ?> - + - - - + + + - $rate): ?> + $rate): ?> @@ -28,9 +28,9 @@ - + > - + @@ -90,7 +90,7 @@ - + @@ -98,13 +98,14 @@ - + - > + + >