Skip to content

Commit

Permalink
Переделана генерация YML - теперь никаких запросов БД, только готовые…
Browse files Browse the repository at this point in the history
… данные на входе
  • Loading branch information
Svitavsky committed Nov 8, 2020
1 parent 78304d9 commit 16c928a
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 124 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
config.php
*.yml
29 changes: 29 additions & 0 deletions Builder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

class Builder
{
/**
* Данные для шаблона
* @var array
*/
private $data;

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

/**
* Создание контента из шаблона для YML
* @return string
*/
public function build(): string
{
extract($this->data);

ob_start();
include 'template.php';
$template = ob_get_clean();
return $template;
}
}
84 changes: 84 additions & 0 deletions YMLGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

class YMLGenerator
{
/**
* Имя файла конфигурации
*/
const CONFIG_FILENAME = 'config.php';

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

/**
* Список товаров
* @var array
*/
public $offers;

/**
* Статус работы
* @var bool
*/
public $success = true;

/**
* Сообщение генератора
* @var string
*/
public $message = '';

public function __construct(array $categories, array $offers)
{
$this->categories = $categories;
$this->offers = $offers;
}

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

$builder = new Builder($config);
$text = $builder->build();
file_put_contents($config['ymlFilename'], $text);

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

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

$config = include self::CONFIG_FILENAME;
$example = include 'config-example.php';

$missingKeys = [];
foreach ($example as $key => $value) {
if (!array_key_exists($key, $config)) {
$missingKeys[] = $key;
}
}

if (count($missingKeys)) {
$keys = implode(' ', $missingKeys);
$this->message = "Отсутствуют параметры в файле конфигурации config.php: {$keys}";
}

$config['date'] = date("Y-m-d H:i", time());

$config['categories'] = $this->categories;
$config['offers'] = $this->offers;
return $config;
}
}
10 changes: 10 additions & 0 deletions config-example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

// Шаблон файла конфигурации, нужно создать аналогичный файл со своими данными с названием config.php
return [
'company_name' => 'Example company', // Название магазина
'company_description' => 'Example company description', // Описание магазина
'company_website' => 'https://example-shop.com', // URL вашего магазина
'yml_filename' => 'example.yml', // Название итогового файла
'currency' => 'RUR' // Валюта для ваших товаров
];
38 changes: 38 additions & 0 deletions template.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<\?xml version="1.0" encoding="UTF-8"?>
<yml_catalog date="<?= $date ?>">
<shop>
<name><?= $companyName ?></name>
<company><?= $companyDescription ?></company>
<url><?= $companyWebsite ?></url>
<currencies>
<?php foreach ($currencies as $code => $rate): ?>
<currency id="<?= $code ?>" rate="<?= $rate ?>"/>
<?php endforeach; ?>
</currencies>
<categories>
<?php foreach ($categories as $category): ?>
<?php if (!is_int($category['id']) || $category['id'] <= 0): ?>
<?php continue; ?>
<?php endif; ?>
<?php if (!is_int($category['parentId']) || $category['parentId'] <= 0): ?>
<?php continue; ?>
<?php endif; ?>
<?php $parentId = isset($category['parentId']) ? "parentId=\"{$category['parentId']}\"" : '' ?>
<category id="<?= $category['id'] ?>" <?= $parentId ?>><?= $category['name'] ?></category>
<?php endforeach; ?>
</categories>
<offers>
<?php foreach ($offers as $offer): ?>
<offer id="<?= $offer['id'] ?>">
<url><?= $offer['url'] ?></url>
<price><?= $offer['price'] ?></price>
<currencyId><?= $offer['currency'] ?></currencyId>
<categoryId><?= $offer['category_id'] ?></categoryId>
<picture><?= $offer['picture'] ?></picture>
<name><?= $offer['name'] ?></name>
<description><?= $offer['description'] ?></description>
</offer>
<?php endforeach; ?>
</offers>
</shop>
</yml_catalog>
124 changes: 0 additions & 124 deletions yandexImport.php

This file was deleted.

0 comments on commit 16c928a

Please sign in to comment.