1
0
mirror of synced 2025-02-06 15:29:25 +03:00
moysklad-catalog/MoySkladICMLParser.php

878 lines
33 KiB
PHP
Raw Normal View History

2014-12-17 16:24:51 +03:00
<?php
class MoySkladICMLParser
{
/**
* Базовый адрес для запросов
*/
const BASE_URL = 'https://online.moysklad.ru/api/remap/1.1';
2014-12-17 16:24:51 +03:00
2015-07-20 17:56:21 +03:00
/**
* развернутые ссылки в запросе
*/
const ASSORTIMENT_EXPAND = 'product,productFolder,product.productFolder,supplier,product.supplier,uom,product.uom';
2015-07-20 17:56:21 +03:00
2014-12-17 16:24:51 +03:00
/**
* Таймаут в секундах
*/
const TIMEOUT = 20;
/**
* Шаг для выгрузки элементов в API
2014-12-17 16:24:51 +03:00
*/
const STEP = 100;
2014-12-17 16:24:51 +03:00
/**
* Лимит выгруженных данных
2014-12-17 16:24:51 +03:00
*/
const LIMIT = 100;
2014-12-17 16:24:51 +03:00
/**
* Адрес для запроса ассортимента
2014-12-17 16:24:51 +03:00
*/
const ASSORT_LIST_URL = '/entity/assortment';
2014-12-17 16:24:51 +03:00
/**
* Адрес для запроса ассортимента
2014-12-17 16:24:51 +03:00
*/
const FOLDER_LIST_URL = '/entity/productfolder';
2014-12-17 16:24:51 +03:00
/**
* @var boolean флаг создания корневой дирректории каталога warehouseRoot
2014-12-17 16:24:51 +03:00
*/
protected $noCategory;
2014-12-17 16:24:51 +03:00
/**
* @var string $login - логин МойСклад
*/
protected $login;
/**
* @var string $pass - пароль МойСклад
*/
protected $pass;
2014-12-17 16:24:51 +03:00
/**
* @var string $shop - имя магазина
*/
protected $shop;
/**
* @var array $options - дополнительные опции
*/
protected $options;
/**
* @param $login - логин МойСклад
* @param $pass - пароль МойСклад
* @param $shop - имя магазина
* @param array $options - дополнительные опции
*
*/
public function __construct(
$login,
$pass,
$shop,
array $options = array()
) {
$this->login = $login;
$this->pass = $pass;
$this->shop = $shop;
$this->options = $options;
}
/**
* Генерирует ICML файл
* @return void
*/
public function generateICML()
{
$assortiment = $this->parseAssortiment();
2017-12-20 11:20:47 +03:00
$countAssortiment = count($assortiment);
$categories = $this->parserFolder();
$countCategories = count($categories);
if ($countCategories > 0) {
$assortiment = $this->deleteProduct($categories, $assortiment);
} else {
return;
2015-07-20 17:56:21 +03:00
}
$icml = $this->ICMLCreate($categories, $assortiment);
2017-12-20 11:20:47 +03:00
if ($countCategories > 0 && $countAssortiment > 0) {
2017-09-14 17:00:56 +03:00
$icml->asXML($this->getFilePath());
}
2014-12-17 16:24:51 +03:00
}
2015-07-20 17:56:21 +03:00
/**
2017-09-29 10:40:30 +03:00
* @param string $url
* @return string
2015-07-20 17:56:21 +03:00
*/
2017-09-29 10:40:30 +03:00
protected function requestJson($url)
2015-07-20 17:56:21 +03:00
{
2017-12-20 11:20:47 +03:00
$downloadImage = strripos($url, 'download');
2015-07-20 17:56:21 +03:00
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_USERPWD, $this->login . ':' . $this->pass);
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, self::TIMEOUT);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 60);
2017-12-20 11:20:47 +03:00
if ($downloadImage) {
2017-09-29 10:40:30 +03:00
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
}
2017-12-20 11:20:47 +03:00
curl_setopt($curlHandler, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
$responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$errno = curl_errno($curlHandler);
$error = curl_error($curlHandler);
2015-07-20 17:56:21 +03:00
curl_close($curlHandler);
2017-12-20 11:20:47 +03:00
if ($downloadImage) {
return $responseBody;
}
2017-12-20 11:20:47 +03:00
$result = json_decode($responseBody, true);
if ($statusCode >= 400) {
throw new Exception(
$this->getError($result) .
" [errno = $errno, error = $error]",
$statusCode
);
2017-09-29 10:40:30 +03:00
}
2015-07-20 17:56:21 +03:00
return $result;
2015-07-20 17:56:21 +03:00
}
2014-12-17 16:24:51 +03:00
/**
* Получение категорий товаров
2014-12-17 16:24:51 +03:00
*
* @return array $categories
2014-12-17 16:24:51 +03:00
*/
protected function parserFolder()
2014-12-17 16:24:51 +03:00
{
$categories = [];
$offset = 0;
$end = null;
$ignoreCategories = $this->getIgnoreProductGroupsInfo();
2017-09-29 10:40:30 +03:00
if ($this->noCategory == true) {
$categories[0] = array(
'name' => 'warehouseRoot',
'externalCode' =>'warehouseRoot',
);
2014-12-17 16:24:51 +03:00
}
2017-09-29 10:40:30 +03:00
while (true) {
try {
$response = $this->requestJson(self::BASE_URL . self::FOLDER_LIST_URL . '?expand=productFolder&limit=100&offset=' . $offset);
} catch (Exception $e) {
echo $e->getMessage();
return array();
}
if ($response['rows']) {
foreach ($response['rows'] as $folder) {
if (isset($ignoreCategories['ids']) && is_array($ignoreCategories['ids'])) {
2014-12-17 16:24:51 +03:00
if (in_array($folder['id'], $ignoreCategories['id'])) {
continue;
}
2014-12-17 16:24:51 +03:00
if (isset($folder['productFolder']['id'])) {
if (in_array($folder['productFolder']['id'],$ignoreCategories['ids'])) {
continue;
}
}
}
if (isset($ignoreCategories['externalCode']) && is_array($ignoreCategories['externalCode'])) {
if (in_array($folder['externalCode'],$ignoreCategories['externalCode'])) {
continue;
}
if (isset($folder['productFolder']['externalCode'])) {
if (in_array($folder['productFolder']['externalCode'],$ignoreCategories['externalCode'])) {
continue;
}
}
}
2014-12-17 16:24:51 +03:00
if($folder['archived'] == false) {
$categories[] =
array(
'name' => $folder['name'],
'externalCode' => $folder['externalCode'],
'parentId' => isset($folder['productFolder']) ?
$folder['productFolder']['externalCode'] : '',
);
}
2015-01-15 12:43:36 +03:00
}
}
if (is_null($end)) {
$end = $response['meta']['size'] - self::STEP;
2015-01-15 12:43:36 +03:00
} else {
$end -= self::STEP;
2014-12-17 16:24:51 +03:00
}
2015-01-15 12:43:36 +03:00
if ($end >= 0) {
$offset += self::STEP;
} else {
break;
}
}
2014-12-17 16:24:51 +03:00
return $categories;
2014-12-17 16:24:51 +03:00
}
/**
* Получение ассортимента товаров
2014-12-17 16:24:51 +03:00
*
* @return array $products
2014-12-17 16:24:51 +03:00
*/
protected function parseAssortiment()
{
$products = array();
$offset = 0;
$end = null;
2017-09-29 10:40:30 +03:00
$url = self::BASE_URL . self::ASSORT_LIST_URL . '?expand=' . self::ASSORTIMENT_EXPAND . '&limit=' . self::LIMIT;
2017-09-14 17:00:56 +03:00
$ignoreNoCategoryOffers = isset($this->options['ignoreNoCategoryOffers']) && $this->options['ignoreNoCategoryOffers'];
$ignoreCategories = $this->getIgnoreProductGroupsInfo();
2017-09-14 17:00:56 +03:00
if (isset($this->options['archivedGoods']) && $this->options['archivedGoods'] === true) {
$url .= '&archived=All';
}
while (true) {
try{
$response = $this->requestJson($url.'&offset='.$offset);
} catch (Exception $e) {
echo $e->getMessage();
return array();
}
if ($response && $response['rows']) {
2017-09-29 10:40:30 +03:00
foreach ($response['rows'] as $assortiment) {
2017-09-29 10:40:30 +03:00
if (!empty($assortiment['modificationsCount']) ||
2017-07-26 17:20:31 +03:00
$assortiment['meta']['type'] == 'consignment') {
continue;
2017-09-29 10:40:30 +03:00
}
if ($assortiment['meta']['type'] == 'service' && !isset($this->options['service']))
{
if (!isset($this->options['service']) || !$this->options['service']) {
continue;
}
}
2015-07-20 17:56:21 +03:00
2017-05-12 19:08:32 +04:00
if ($ignoreNoCategoryOffers === true) {
2015-01-15 12:43:36 +03:00
if ( !isset($assortiment['productFolder']['externalCode']) &&
2017-05-12 19:08:32 +04:00
!isset($assortiment['product']['productFolder']['externalCode']) ) {
2015-01-15 12:43:36 +03:00
continue;
}
2014-12-17 16:24:51 +03:00
}
2017-05-12 19:08:32 +04:00
if (isset($ignoreCategories['ids']) && is_array($ignoreCategories['ids'])) {
if (!empty($assortiment['productFolder']['id'])) {
if (in_array($assortiment['productFolder']['id'],$ignoreCategories['ids'])) {
continue;
}
}
2017-09-29 10:40:30 +03:00
2017-05-12 19:08:32 +04:00
if (!empty($assortiment['product']['productFolder']['id'])) {
if (in_array($assortiment['product']['productFolder']['id'],$ignoreCategories['ids'])) {
continue;
}
}
}
2014-12-17 16:24:51 +03:00
if (isset($ignoreCategories['externalCode']) && is_array($ignoreCategories['externalCode'])) {
2014-12-17 16:24:51 +03:00
if (!empty($assortiment['productFolder']['externalCode'])) {
if (in_array($assortiment['productFolder']['externalCode'], $ignoreCategories['externalCode'])) {
continue;
}
}
2014-12-17 16:24:51 +03:00
if (!empty($assortiment['product']['productFolder']['externalCode'])) {
if (in_array($assortiment['product']['productFolder']['externalCode'], $ignoreCategories['externalCode'])) {
continue;
}
}
}
2014-12-17 16:24:51 +03:00
2017-09-29 10:40:30 +03:00
if (isset($assortiment['product']['image']['meta']['href'])) {
$urlImage = $assortiment['product']['image']['meta']['href'];
} elseif (isset($assortiment['image']['meta']['href'])) {
$urlImage = $assortiment['image']['meta']['href'];
} else {
$urlImage = '';
}
2017-09-29 10:40:30 +03:00
$products[$assortiment['id']] = array(
'uuid' => $assortiment['id'],
2017-06-05 15:06:02 +03:00
'id' => !empty($assortiment['product']['externalCode']) ?
($assortiment['product']['externalCode'] . '#' . $assortiment['externalCode']) :
$assortiment['externalCode'],
'exCode' => $assortiment['externalCode'],
'productId' => isset($assortiment['product']['externalCode']) ?
$assortiment['product']['externalCode'] : $assortiment['externalCode'],
'name' => $assortiment['name'],
2017-10-10 10:42:16 +03:00
'productName'=> isset($assortiment['product']['name']) ?
$assortiment['product']['name'] : $assortiment['name'],
'code' => isset($assortiment['code']) ? (string) $assortiment['code'] : '',
'xmlId' => !empty($assortiment['product']['externalCode']) ?
2017-06-05 15:06:02 +03:00
($assortiment['product']['externalCode'] . '#' . $assortiment['externalCode']) :
$assortiment['externalCode'],
2017-06-15 11:31:02 +03:00
'url' => !empty($assortiment['product']['meta']['uuidHref']) ?
$assortiment['product']['meta']['uuidHref'] :
(
!empty($assortiment['meta']['uuidHref']) ?
$assortiment['meta']['uuidHref'] :
''
2017-09-29 10:40:30 +03:00
),
);
if (isset($assortiment['weight'])) {
$products[$assortiment['id']]['weight'] = $assortiment['weight'];
} elseif (isset($assortiment['product']['weight'])) {
$products[$assortiment['id']]['weight'] = $assortiment['product']['weight'];
}
if (isset($this->options['customFields'])) {
if (!empty($assortiment['attributes'])) {
$products[$assortiment['id']]['customFields'] = $this->getCustomFields($assortiment['attributes']);
} elseif (!empty($assortiment['product']['attributes'])){
$products[$assortiment['id']]['customFields'] = $this->getCustomFields($assortiment['product']['attributes']);
}
}
if (!empty($assortiment['barcodes'])){
$products[$assortiment['id']]['barcodes'] = $assortiment['barcodes'];
} elseif (!empty($assortiment['product']['barcodes'])){
$products[$assortiment['id']]['barcodes'] = $assortiment['product']['barcodes'];
}
if (!empty($assortiment['product']['attributes'])) {
$products[$assortiment['id']]['customFields'] = $this->getCustomFields($assortiment['product']['attributes']);
} elseif (!empty($assortiment['attributes'])){
$products[$assortiment['id']]['customFields'] = $this->getCustomFields($assortiment['attributes']);
}
if (isset($this->options['loadPurchasePrice']) && $this->options['loadPurchasePrice'] === true) {
if (isset($assortiment['buyPrice']['value'])) {
$products[$assortiment['id']]['purchasePrice'] = (((float)$assortiment['buyPrice']['value']) / 100);
} elseif (isset($assortiment['product']['buyPrice']['value'])) {
$products[$assortiment['id']]['purchasePrice'] = (((float)$assortiment['product']['buyPrice']['value']) / 100);
} else {
$products[$assortiment['id']]['purchasePrice'] = 0;
}
}
2014-12-17 16:24:51 +03:00
2017-10-10 10:42:16 +03:00
if (isset($assortiment['salePrices'][0]['value']) && $assortiment['salePrices'][0]['value'] != 0) {
$products[$assortiment['id']]['price'] = (((float)$assortiment['salePrices'][0]['value']) / 100);
} elseif (isset($assortiment['product']['salePrices'][0]['value'])) {
$products[$assortiment['id']]['price'] = (((float)$assortiment['product']['salePrices'][0]['value']) / 100);
} else {
$products[$assortiment['id']]['price'] = ((float)0);
}
2017-12-08 16:27:24 +03:00
if (isset($assortiment['uom'])){
if (isset($assortiment['uom']['code'])){
$products[$assortiment['id']]['unit'] = array (
'code' => $assortiment['uom']['code'],
'name' => $assortiment['uom']['name'],
'description' => $assortiment['uom']['description'],
);
} elseif (isset($assortiment['uom']['externalCode'])) {
$products[$assortiment['id']]['unit'] = array (
'code' => $assortiment['uom']['externalCode'],
'name' => str_replace(' ', '',$assortiment['uom']['name']),
'description' => $assortiment['uom']['name'],
);
}
} elseif (isset($assortiment['product']['uom'])) {
2017-12-08 17:53:27 +03:00
if (isset($assortiment['product']['uom']['code'])){
2017-12-08 16:27:24 +03:00
$products[$assortiment['id']]['unit'] = array (
'code' => $assortiment['product']['uom']['code'],
'name' => $assortiment['product']['uom']['name'],
'description' => $assortiment['product']['uom']['description'],
);
} elseif (isset($assortiment['product']['uom']['externalCode'])) {
$products[$assortiment['id']]['unit'] = array (
'code' => $assortiment['product']['uom']['externalCode'],
'name' => str_replace(' ', '',$assortiment['product']['uom']['name']),
'description' => $assortiment['product']['uom']['name'],
);
}
} else {
2017-05-12 19:08:32 +04:00
$products[$assortiment['id']]['unit'] = '';
}
2017-12-08 16:27:24 +03:00
2017-05-12 19:08:32 +04:00
if (isset($assortiment['effectiveVat']) && $assortiment['effectiveVat'] != 0) {
$products[$assortiment['id']]['effectiveVat'] = $assortiment['effectiveVat'];
2017-05-12 19:08:32 +04:00
} elseif (isset($assortiment['product']['effectiveVat']) && $assortiment['product']['effectiveVat'] != 0) {
$products[$assortiment['id']]['effectiveVat'] = $assortiment['product']['effectiveVat'];
} else {
$products[$assortiment['id']]['effectiveVat'] = 'none';
}
2017-09-29 10:40:30 +03:00
2017-05-12 19:08:32 +04:00
if (isset($assortiment['productFolder']['externalCode'])) {
$products[$assortiment['id']]['categoryId'] = $assortiment['productFolder']['externalCode'];
2017-05-12 19:08:32 +04:00
} elseif (isset($assortiment['product']['productFolder']['externalCode'])) {
$products[$assortiment['id']]['categoryId'] = $assortiment['product']['productFolder']['externalCode'];
} else {
$products[$assortiment['id']]['categoryId'] = 'warehouseRoot';
}
if ($products[$assortiment['id']]['categoryId'] == 'warehouseRoot') {
$this->noCategory = true;
}
2014-12-17 16:24:51 +03:00
2017-05-12 19:08:32 +04:00
if (isset($assortiment['article'])) {
$products[$assortiment['id']]['article'] = (string) $assortiment['article'];
2017-05-12 19:08:32 +04:00
} elseif (isset($assortiment['product']['article'])) {
$products[$assortiment['id']]['article'] = (string) $assortiment['product']['article'];
} else {
$products[$assortiment['id']]['article'] = '';
}
2014-12-17 16:24:51 +03:00
2017-05-12 19:08:32 +04:00
if (isset($assortiment['product']['supplier']['name'])) {
$products[$assortiment['id']]['vendor'] = $assortiment['product']['supplier']['name'];
2017-05-12 19:08:32 +04:00
} elseif (isset($assortiment['supplier']['name'])) {
$products[$assortiment['id']]['vendor'] = $assortiment['supplier']['name'];
} else {
$products[$assortiment['id']]['vendor'] = '';
}
2017-09-29 10:40:30 +03:00
if ($urlImage != '') {
$products[$assortiment['id']]['image']['imageUrl'] = $urlImage;
$products[$assortiment['id']]['image']['name'] =
isset($assortiment['image']['filename']) ?
2017-09-29 15:31:47 +03:00
$assortiment['image']['filename'] : $assortiment['product']['image']['filename'];
2017-09-29 10:40:30 +03:00
}
2014-12-17 16:24:51 +03:00
}
}
if (is_null($end)) {
$end = $response['meta']['size'] - self::STEP;
2014-12-17 16:24:51 +03:00
} else {
$end -= self::STEP;
2014-12-17 16:24:51 +03:00
}
if ($end >= 0) {
$offset += self::STEP;
} else {
break;
}
2014-12-17 16:24:51 +03:00
}
unset($response, $assortiment);
2014-12-17 16:24:51 +03:00
return $products;
2014-12-17 16:24:51 +03:00
}
/**
* Формируем итоговый ICML
*
* @param array $categories
* @param array $products
2014-12-17 16:24:51 +03:00
* @return SimpleXMLElement
*/
protected function ICMLCreate($categories, $products)
{
2014-12-17 16:24:51 +03:00
$date = new DateTime();
$xmlstr = '<yml_catalog date="'.$date->format('Y-m-d H:i:s').'"><shop><name>'.$this->shop.'</name></shop></yml_catalog>';
$xml = new SimpleXMLElement($xmlstr);
2017-12-20 11:20:47 +03:00
$countCategories = count($categories);
if ($countCategories > 0) {
2014-12-17 16:24:51 +03:00
$categoriesXml = $this->icmlAdd($xml->shop, 'categories', '');
foreach ($categories as $category) {
$categoryXml = $this->icmlAdd($categoriesXml, 'category', htmlspecialchars($category['name']));
2014-12-17 16:24:51 +03:00
$categoryXml->addAttribute('id', $category['externalCode']);
2017-05-12 19:08:32 +04:00
if (!empty($category['parentId'])) {
$categoryXml->addAttribute('parentId',$category['parentId']);
2014-12-17 16:24:51 +03:00
}
}
}
$offersXml = $this->icmlAdd($xml->shop, 'offers', '');
2017-12-20 11:20:47 +03:00
$countProducts = count($products);
if ($countProducts > 0) {
foreach ($products as $product) {
$offerXml = $offersXml->addChild('offer');
$offerXml->addAttribute('id', $product['id']);
$offerXml->addAttribute('productId', $product['productId']);
2017-09-29 10:40:30 +03:00
$this->icmlAdd($offerXml, 'xmlId', $product['xmlId']);
$this->icmlAdd($offerXml, 'price', number_format($product['price'], 2, '.', ''));
2017-06-15 11:31:02 +03:00
if (isset($product['purchasePrice'])) {
$this->icmlAdd($offerXml, 'purchasePrice', number_format($product['purchasePrice'], 2, '.', ''));
}
if (isset($product['barcodes'])) {
foreach($product['barcodes'] as $barcode){
$this->icmlAdd($offerXml, 'barcode', $barcode);
}
}
$this->icmlAdd($offerXml, 'name', htmlspecialchars($product['name']));
$this->icmlAdd($offerXml, 'productName', htmlspecialchars($product['productName']));
$this->icmlAdd($offerXml, 'vatRate', $product['effectiveVat']);
2014-12-17 16:24:51 +03:00
if (!empty($product['customFields'])) {
if (!empty($product['customFields']['dimensions'])){
$this->icmlAdd($offerXml, 'dimensions', $product['customFields']['dimensions']);
}
if (!empty($product['customFields']['param'])){
foreach($product['customFields']['param'] as $param){
$art = $this->icmlAdd($offerXml, 'param', $param['value']);
$art->addAttribute('code', $param['code']);
$art->addAttribute('name', $param['name']);
}
}
}
if (!empty($product['url'])) {
$this->icmlAdd($offerXml, 'url', htmlspecialchars($product['url']));
2014-12-17 16:24:51 +03:00
}
if ($product['unit'] != '') {
$unitXml = $offerXml->addChild('unit');
$unitXml->addAttribute('code', $product['unit']['code']);
$unitXml->addAttribute('name', $product['unit']['description']);
$unitXml->addAttribute('sym', $product['unit']['name']);
2015-07-21 11:13:59 +03:00
}
if ($product['categoryId']) {
$this->icmlAdd($offerXml, 'categoryId', $product['categoryId']);
}else {
$this->icmlAdd($offerXml, 'categoryId', 'warehouseRoot');
}
2015-07-21 11:13:59 +03:00
if ($product['article']) {
$art = $this->icmlAdd($offerXml, 'param', $product['article']);
$art->addAttribute('code', 'article');
$art->addAttribute('name', 'Артикул');
}
2014-12-17 16:24:51 +03:00
if (isset($product['weight'])) {
if (isset($this->options['tagWeight']) && $this->options['tagWeight'] === true) {
$wei = $this->icmlAdd($offerXml, 'weight', $product['weight']);
} else {
$wei = $this->icmlAdd($offerXml, 'param', $product['weight']);
$wei->addAttribute('code', 'weight');
$wei->addAttribute('name', 'Вес');
}
2014-12-17 16:24:51 +03:00
}
2015-03-05 16:50:55 +03:00
if ($product['code']) {
$cod = $this->icmlAdd($offerXml, 'param', $product['code']);
$cod->addAttribute('code', 'code');
$cod->addAttribute('name', 'Код');
2015-03-05 16:50:55 +03:00
}
if ($product['vendor']) {
$this->icmlAdd($offerXml, 'vendor', $product['vendor']);
}
if (isset($product['image']['imageUrl']) &&
!empty($this->options['imageDownload']['pathToImage']) &&
!empty($this->options['imageDownload']['site']))
{
$imgSrc = $this->saveImage($product['image']);
if (!empty($imgSrc)){
$this->icmlAdd($offerXml, 'picture', $this->saveImage($product['image']));
}
}
}
2014-12-17 16:24:51 +03:00
}
2014-12-17 16:24:51 +03:00
return $xml;
}
/**
* Добавляем элемент в icml
*
* @param SimpleXMLElement $xml
* @param string $name
* @param string $value
* @return SimpleXMLElement
*/
2017-09-29 10:40:30 +03:00
protected function icmlAdd(SimpleXMLElement $xml,$name, $value) {
$elem = $xml->addChild($name, $value);
2014-12-17 16:24:51 +03:00
return $elem;
}
/**
* Возвращает имя ICML-файла
2017-09-29 10:40:30 +03:00
*
2014-12-17 16:24:51 +03:00
* @return string
*/
2017-09-29 10:40:30 +03:00
protected function getFilePath() {
2014-12-17 16:24:51 +03:00
$path = isset($this->options['directory']) && $this->options['directory'] ?
$this->options['directory'] : __DIR__;
2017-12-20 11:20:47 +03:00
$endPath = substr($path, -1);
if ($endPath === '/') {
2014-12-17 16:24:51 +03:00
$path = substr($path, 0, -1);
}
$file = isset($this->options['file']) && $this->options['file'] ?
$this->options['file'] : $this->shop.'.catalog.xml';
return $path.'/'.$file;
}
/**
* Получаем данные для игнорирования товарных групп
*/
2017-09-29 10:40:30 +03:00
protected function getIgnoreProductGroupsInfo() {
2017-05-12 19:08:32 +04:00
if (!isset($this->options['ignoreCategories']) || !is_array($this->options['ignoreCategories'])) {
$info = array();
} else {
$info = $this->options['ignoreCategories'];
}
2017-05-12 19:08:32 +04:00
if (!isset($info['id']) || !is_array($info['id'])) {
$info['id'] = array();
}
2017-05-12 19:08:32 +04:00
if (!isset($info['externalCode']) || !is_array($info['externalCode'])) {
$info['externalCode'] = array();
}
return $info;
}
/**
2017-09-29 10:40:30 +03:00
* Сохранение изображения в дирректорию на сервере
*
* @param array $image
* @return string
*/
2017-09-29 10:40:30 +03:00
protected function saveImage(array $image) {
$root = __DIR__;
$imgDirrectory = $this->options['imageDownload']['pathToImage'];
2017-12-20 11:20:47 +03:00
$startPathDirrectory = substr($imgDirrectory,0, 1);
if ($startPathDirrectory == '/') {
2017-09-29 10:40:30 +03:00
$imgDirrectory = substr($imgDirrectory, 1);
}
2017-12-20 11:20:47 +03:00
$endPathDirrectory = substr($imgDirrectory, -1);
2017-09-29 10:40:30 +03:00
2017-12-20 11:20:47 +03:00
if ($endPathDirrectory == '/') {
2017-09-29 10:40:30 +03:00
$imgDirrectory = substr($imgDirrectory, 0, -1);
}
$imgDirrectoryArray = explode('/', $imgDirrectory);
$root = stristr($root, $imgDirrectoryArray[0], true);
2017-09-29 10:40:30 +03:00
if (file_exists($root . '/' . $imgDirrectory) === false) {
@mkdir($root . '/' . $imgDirrectory);
}
2017-12-20 11:20:47 +03:00
2017-09-29 10:40:30 +03:00
if (file_exists($root . $imgDirrectory . '/' . $image['name']) === false) {
try {
$content = $this->requestJson($image['imageUrl']);
} catch (Exception $e) {
echo $e->getMessage();
return '';
}
2017-09-29 10:40:30 +03:00
if ($content) {
file_put_contents($root . $imgDirrectory . '/' . $image['name'], $content);
}
}
2017-09-29 10:40:30 +03:00
$imageUrl = $this->linkGeneration($image['name']);
2017-09-29 10:40:30 +03:00
return $imageUrl;
}
2017-12-20 11:20:47 +03:00
/**
2017-09-29 10:40:30 +03:00
* Генерация ссылки на изображение
*
* @param string $name
* @return string
*/
2017-09-29 10:40:30 +03:00
protected function linkGeneration($name) {
2017-09-29 10:40:30 +03:00
if (empty($name)) {
return false;
}
2017-09-29 10:40:30 +03:00
$path = $this->options['imageDownload']['pathToImage'];
2017-12-20 11:20:47 +03:00
$startPath = substr($path, 0, 1);
if ($startPath === '/') {
2017-09-29 10:40:30 +03:00
$path = substr($path, 1);
}
2017-12-20 11:20:47 +03:00
$endPath = substr($path, -1);
if ($endPath === '/') {
2017-09-29 10:40:30 +03:00
$path = substr($path, 0, -1);
}
2017-09-29 10:40:30 +03:00
$path = explode('/', $path);
unset($path[0]);
$path = implode('/', $path);
$link = $this->options['imageDownload']['site'] . '/' . $path . '/' . $name;
return $link;
}
/**
* Get error.
*
* @param array
* @return string
* @access private
*/
private function getError($result)
{
$error = "";
if (!empty($result['errors'])) {
foreach ($result['errors'] as $err) {
if (!empty($err['parameter'])) {
$error .= "'" . $err['parameter']."': ".$err['error'];
} else {
$error .= $err['error'];
}
}
unset($err);
return $error;
} else {
if (is_array($result)) {
foreach ($result as $value) {
if (!empty($value['errors'])) {
foreach ($value['errors'] as $err) {
if (!empty($err['parameter'])) {
$error .= "'" . $err['parameter']."': ".$err['error'];
} else {
$error .= $err['error'];
}
}
unset($err);
$error .= " / ";
}
}
unset($value);
2017-12-20 11:20:47 +03:00
$error = trim($error, ' /');
2017-12-19 11:48:45 +03:00
if (!empty($error)) {
return $error;
}
}
}
return "Internal server error (" . json_encode($result) . ")";
}
/**
* Получение массива значений кастомных полей.
*
* @param array
* @return array
* @access private
*/
protected function getCustomFields($attributes) {
$result = array();
if (isset($this->options['customFields']['dimensions'])) {
if (count($this->options['customFields']['dimensions']) == 3) {
$maskArray = $this->options['customFields']['dimensions'];
foreach($attributes as $attribute){
if (in_array($attribute['id'], $this->options['customFields']['dimensions'])){
$attributeValue[$attribute['id']] = $attribute['value'];
}
}
$attributeValue = array_merge(array_flip($maskArray),$attributeValue);
$result['dimensions'] = implode('/', $attributeValue);
} elseif (count($this->options['customFields']['dimensions']) == 1) {
if (isset($this->options['customFields']['separate'])){
foreach($attributes as $attribute){
if (in_array($attribute['id'], $this->options['customFields']['dimensions'])){
$result['dimensions'] = str_replace($this->options['customFields']['separate'], '/', $attribute['value']);
}
}
}
}
}
if (isset($this->options['customFields']['paramTag'])) {
if ($this->options['customFields']['paramTag']) {
foreach ($this->options['customFields']['paramTag'] as $paramTag){
$paramTag = explode('#',$paramTag);
foreach($attributes as $attribute) {
if ($attribute['id'] == $paramTag[1]) {
$result['param'][] = array('code' => $paramTag[0],'name' => $attribute['name'], 'value'=> htmlspecialchars($attribute['value']));
}
}
}
}
}
return $result;
}
protected function deleteProduct($categories, $products) {
foreach ($categories as $category) {
$cat[] = $category['externalCode'];
}
foreach ($products as $product) {
if (!in_array($product['categoryId'],$cat)){
unset($products[$product['uuid']]);
}
}
return $products;
}
2014-12-17 16:24:51 +03:00
}