lireincore / ymlparser Goto Github PK
View Code? Open in Web Editor NEWYML (Yandex Market Language) parser
License: MIT License
YML (Yandex Market Language) parser
License: MIT License
<?xml version="1.0" encoding="windows-1251"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog date="2016-12-02 08:11">
<shop>
<name>Shop.com.ua</name>
<company>Интернет магазин Shop.com.ua</company>
<url>www.shop.com.ua/</url>
<cpa>0</cpa>
<currencies>
<currency id="UAH" rate="1"/>
</currencies>
<categories>
<category id="1"><![CDATA[Test category]]></category>
</categories>
<offers>
<offer id="1294928" type="vendor.model" available="true">
<name><![CDATA[Test name]]></name>
<url>http://www.shop.com.ua/1294928.html</url>
<price>5430</price>
<currencyId>UAH</currencyId>
<categoryId>1</categoryId>
<picture>http://www.shop.com.ua/1294928.png</picture>
<delivery>true</delivery>
<vendor><![CDATA[Test vendor]]></vendor>
<model><![CDATA[Test model]]></model>
<description><![CDATA[Test description]]></description>
</offer>
</offers>
</shop>
</yml_catalog>
Этот xml выдает ошибку:
XMLReader::read(): Element 'cpa': This element is not expected. Expected is one of ( platform, version, agency, email, currencies )
В документации можно указывать cpa как и в элементе offers так и в элементе shop.
https://github.com/lireincore/ymlparser/blob/master/src/Currency.php#L42
if ($this->plus !== null && (!is_numeric($this->rate) || (int)$this->plus < 0))
Тут точно должен быть rate?
Присутствует проблема с самозакрывающимися тегами, то есть парсер не может определить, что тег завершается и уходит в бесконечную рекурсию.
Пример, ломающего тега
<accessory offer="502"/>
Код (ломается в генераторе):
$yml = new YML();
$yml->parse($someUrl, __DIR__ . '/yml/yml.xsd');
foreach ($yml->getOffers() as $offer) {
...
}
Текст ошибки:
...
PHP 256. LireinCore\YMLParser\YML->parseAttributes() /app/vendor/lireincore/ymlparser/src/YML.php:182
PHP Fatal error: Maximum function nesting level of '256' reached, aborting! in /app/vendor/yiisoft/yii2/base/ErrorHandler.php on line 234
Пример, файла для воспроизведения - https://gist.github.com/tisOO/85d8a27b0998a130ab92315748542308
Проблема решается просто, если добавить проверку на пустоту тега до парсинга атрибутов в код YML функции parseNode:
protected function parseNode($basePath)
{
$xml = $this->XMLReader;
$name = $xml->name;
$path = $basePath . '/' . $name;
$value = '';
$nodes = [];
$isEmpty = $xml->isEmptyElement;
$attributes = $this->parseAttributes();
if (!$isEmpty) {
while ($this->read()) {
if ($xml->nodeType == \XMLReader::ELEMENT) {
$nodes[] = $this->parseNode($path);
} elseif (($xml->nodeType == \XMLReader::TEXT || $xml->nodeType == \XMLReader::CDATA) && $xml->hasValue) {
$value .= $xml->value;
} elseif ($this->path == $basePath) {
break;
}
}
}
$value = (trim($value)) ? $value : null;
return ['name' => $name, 'attributes' => $attributes, 'value' => $value, 'nodes' => $nodes];
}
Но далее возникнет еще одна проблема: нам необходимо импортировать различные yml-файлы, от opencart-магазинов, использующих плагин, который добавляет тег accessory. Этот тег мы игнорируем, но есть проблема в функции AOffer::setAttribute:
/**
* @param array $attrNode
* @return $this
*/
public function setAttribute(array $attrNode)
{
if ($attrNode['name'] == 'outlets') {
foreach ($attrNode['nodes'] as $subNode) {
$this->addOutlet((new Outlet())->setAttributes($subNode['attributes']));
}
} elseif ($attrNode['name'] == 'picture') {
$this->addPicture($attrNode['value']);
} elseif ($attrNode['name'] == 'barcode') {
$this->addBarcode($attrNode['value']);
} elseif ($attrNode['name'] == 'param') {
$this->addParam((new Param())->setAttributes($attrNode['attributes'] + ['value' => $attrNode['value']]));
} else {
if (!is_null($attrNode['value'])) $this->setField($attrNode['name'], $attrNode['value']);
if (!empty($attrNode['attributes'])) {
foreach ($attrNode['attributes'] as $name => $value) {
$this->setField($name, $value);
}
}
}
return $this;
}
А именно в последней проверке, попытке установить значение атрибута в объект предложения:
if (!empty($attrNode['attributes'])) {
foreach ($attrNode['attributes'] as $name => $value) {
$this->setField($name, $value);
}
}
В нашем случае, см. приложенный gist с yml, тег имеет вид <accessory offer="502"/>
, то есть атрибут имеет имя offer и значение 502. Далее вызывается функция setField, которая проверяет, если у объекта функция setOffer, а она разумеется существует, что и приводит к ошибке.
Можно ли каким-то образом изменить это поведение? То есть не пытаться устанавливать атрибуты неизвестных тегов в объект предложения?
Оften the logical value of the attribute is written with a capital letter, for example, Truе. However, the validator in "ymlparser" does not pass such values. I suggest the following improvement to be written in /src/Offer/AOffer.php
:
if ($this->pickup !== null && !$this->isValidBoolean($this->pickup)) {
$this->addError("Offer: incorrect value in attribute 'pickup'");
}
private function isValidBoolean($attribute)
{
$lc_attr = lcfirst($attribute);
return $lc_attr === 'true' || $lc_attr === 'false';
}
Can I make the pull request for this?
"XMLReader::read(): Element 'phone': This element is not expected. Expected is one of ( platform, version, agency, email, currencies )."
Exception!
URL: https://3234444.com/export/yandex_yml4_.xml
Problem cause is XMLSchema in yml.xsd file provided with ymlparser. There is no phone node. While Shop class have it.
Solution is to use corrected schema file.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="yml_catalog">
<xs:complexType>
<xs:sequence>
<xs:element name="shop">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="url" type="xs:string" />
<xs:element name="platform" type="xs:string" minOccurs="0" />
<xs:element name="version" type="xs:string" minOccurs="0" />
<xs:element name="agency" type="xs:string" minOccurs="0" />
<xs:element name="email" type="xs:string" minOccurs="0" />
<xs:element name="currencies">
<xs:complexType>
Пример xml
<?xml version="1.0" encoding="windows-1251"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog date="2016-12-02 08:11">
<shop>
<name>Shop.com.ua</name>
<company>Интернет магазин Shop.com.ua</company>
<url>www.shop.com.ua/</url>
<currencies>
<currency id="UAH" rate="1"/>
</currencies>
<categories>
<category id="1"><![CDATA[Test category]]></category>
</categories>
<offers>
<offer id="1294928" type="vendor.model" available="true">
<name><![CDATA[Test name]]></name>
<url>http://www.shop.com.ua/1294928.html</url>
<price>5430</price>
<currencyId>UAH</currencyId>
<categoryId>1</categoryId>
<picture>http://www.shop.com.ua/1294928.png</picture>
<delivery>true</delivery>
<vendor><![CDATA[Test vendor]]></vendor>
<model><![CDATA[Test model]]></model>
<description><![CDATA[Test description]]></description>
</offer>
</offers>
</shop>
</yml_catalog>
Результат работы:
"Category: incorrect value"
"Offer: missing required attribute 'model'"
"Offer: missing required attribute 'vendor'"
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.