-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCore.php
469 lines (408 loc) · 13.1 KB
/
Core.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
<?php namespace Wc1c\Main\Schemas\Productscleanercml;
defined('ABSPATH') || exit;
use XMLReader;
use Wc1c\Cml\Contracts\ClassifierDataContract;
use Wc1c\Cml\Contracts\ProductDataContract;
use Wc1c\Cml\Decoder;
use Wc1c\Cml\Entities\Catalog;
use Wc1c\Cml\Reader;
use Wc1c\Main\Exceptions\Exception;
use Wc1c\Main\Schemas\Abstracts\SchemaAbstract;
use Wc1c\Wc\Products\Factory;
/**
* Core
*
* @package Wc1c\Main\Schemas\Productscleanercml
*/
class Core extends SchemaAbstract
{
/**
* @var string Текущий каталог в файловой системе
*/
protected $upload_directory;
/**
* @var Admin
*/
public $admin;
/**
* @var Receiver
*/
public $receiver;
/**
* Core constructor.
*/
public function __construct()
{
$this->setId('productscleanercml');
$this->setVersion('0.4.0');
$this->setName(__('Cleaning of products via CommerceML', 'wc1c-main'));
$this->setDescription(__('Cleaning of existing products in WooCommerce according to the nomenclature from 1C via the CommerceML protocol.', 'wc1c-main'));
}
/**
* @param $admin
*
* @return void
*/
protected function setAdmin($admin)
{
$this->admin = $admin;
}
/**
* @param $receiver
*
* @return void
*/
protected function setReceiver($receiver)
{
$this->receiver = $receiver;
}
/**
* Initialize
*
* @return boolean
*/
public function init(): bool
{
$this->setOptions($this->configuration()->getOptions());
$this->setUploadDirectory($this->configuration()->getUploadDirectory() . DIRECTORY_SEPARATOR . 'catalog');
if(true === wc1c()->context()->isAdmin('plugin'))
{
$admin = Admin::instance();
$admin->setCore($this);
$admin->initConfigurationsFields();
$this->setAdmin($admin);
}
if(true === wc1c()->context()->isReceiver())
{
$receiver = Receiver::instance();
$receiver->setCore($this);
$receiver->initHandler();
$this->setReceiver($receiver);
add_action('wc1c_schema_productscleanercml_file_processing_read', [$this, 'processingTimer'], 5, 1);
add_action('wc1c_schema_productscleanercml_file_processing_read', [$this, 'processingClassifier'], 10, 1);
add_action('wc1c_schema_productscleanercml_file_processing_read', [$this, 'processingCatalog'], 20, 1);
add_action('wc1c_schema_productscleanercml_processing_products_item', [$this, 'processingProductsItem'], 10, 2);
}
return true;
}
/**
* Receiver
*
* @return void
*/
public function receiver()
{
if($this->configuration()->isEnabled() === false)
{
$message = __('Configuration is offline.', 'wc1c-main');
wc1c()->log('receiver')->warning($message);
$this->receiver->sendResponseByType('failure', $message);
}
try
{
$this->configuration()->setDateActivity(time());
$this->configuration()->save();
}
catch(\Throwable $e)
{
$message = __('Error saving configuration.', 'wc1c-main');
wc1c()->log('receiver')->error($message, ['exception' => $e]);
$this->receiver->sendResponseByType('failure', $message);
}
$action = false;
$wc1c_receiver_action = 'wc1c_receiver_' . $this->getId();
if(has_action($wc1c_receiver_action))
{
$action = true;
ob_start();
nocache_headers();
do_action($wc1c_receiver_action);
ob_end_clean();
}
if(false === $action)
{
$message = __('Receiver request is very bad! Action not found.', 'wc1c-main');
wc1c()->log('receiver')->warning($message, ['action' => $wc1c_receiver_action]);
$this->receiver->sendResponseByType('failure', $message);
}
}
/**
* @return string
*/
public function getUploadDirectory(): string
{
return $this->upload_directory;
}
/**
* @param mixed $upload_directory
*/
public function setUploadDirectory($upload_directory)
{
$this->upload_directory = $upload_directory;
}
/**
* CommerceML file processing
*
* @param string $file_path
*
* @return boolean true - success, false - error
*/
public function fileProcessing(string $file_path): bool
{
try
{
$decoder = new Decoder();
}
catch(\Throwable $exception)
{
$this->log()->error(__('The file cannot be processed. DecoderCML threw an exception.', 'wc1c-main'), ['exception' => $exception]);
return false;
}
if(has_filter('wc1c_schema_productscleanercml_file_processing_decoder'))
{
$decoder = apply_filters('wc1c_schema_productscleanercml_file_processing_decoder', $decoder, $this);
}
try
{
$reader = new Reader($file_path, $decoder);
}
catch(\Throwable $exception)
{
$this->log()->error(__('The file cannot be processed. ReaderCML threw an exception.', 'wc1c-main'), ['exception' => $exception]);
return false;
}
$this->log()->debug(__('Filetype:', 'wc1c-main') . ' ' . $reader->getFiletype(), ['filetype' => $reader->getFiletype()]);
if(has_filter('wc1c_schema_productscleanercml_file_processing_reader'))
{
$reader = apply_filters('wc1c_schema_productscleanercml_file_processing_reader', $reader, $this);
}
while($reader->read())
{
try
{
do_action('wc1c_schema_productscleanercml_file_processing_read', $reader, $this);
}
catch(\Throwable $e)
{
$this->log()->error(__('Import file processing not completed. ReaderCML threw an exception.', 'wc1c-main'), ['exception' => $e]);
break;
}
}
return $reader->ready;
}
/**
* Принудительное прерывание обработки при израсходовании доступного времени
*
* @param Reader $reader
*
* @return void
* @throws Exception
*/
public function processingTimer(Reader $reader)
{
if(wc1c()->timer()->getMaximum() !== 0 && !wc1c()->timer()->isRemainingBiggerThan(5))
{
throw new Exception(__('There was not enough time to load all the data.', 'wc1c-main'));
}
}
/**
* Обработка данных классификатора
*
* @param Reader $reader
*
* @return void
* @throws \Exception
*/
public function processingClassifier(Reader $reader)
{
if($reader->filetype !== 'import' && $reader->filetype !== 'offers')
{
return;
}
if($reader->nodeName === 'Классификатор' && $reader->xml_reader->nodeType === XMLReader::ELEMENT)
{
/**
* Декодируем данные классификатора из XML в объект
*/
$classifier = $reader->decoder()->process('classifier', $reader->xml_reader->readOuterXml());
/**
* Внешняя обработка классификатора
*
* @param ClassifierDataContract $classifier
* @param SchemaAbstract $this
*/
if(has_filter('wc1c_schema_productscleanercml_processing_classifier'))
{
$classifier = apply_filters('wc1c_schema_productscleanercml_processing_classifier', $classifier, $this);
}
if(!$classifier instanceof ClassifierDataContract)
{
$this->log()->debug(__('Classifier !instanceof ClassifierDataContract. Skip processing.', 'wc1c-main'), ['data' => $classifier]);
return;
}
$reader->classifier = $classifier;
try
{
do_action('wc1c_schema_productscleanercml_processing_classifier_item', $classifier, $reader, $this);
}
catch(\Throwable $e)
{
$this->log()->warning(__('An exception was thrown while saving the classifier.', 'wc1c-main'), ['exception' => $e]);
}
$reader->next();
}
}
/**
* Обработка каталога товаров
*
* @param Reader $reader
*
* @return void
* @throws \Exception
*/
public function processingCatalog(Reader $reader)
{
if($reader->getFiletype() !== 'import')
{
return;
}
if(is_null($reader->catalog))
{
$reader->catalog = new Catalog();
}
if($reader->nodeName === 'Каталог' && $reader->xml_reader->nodeType === XMLReader::ELEMENT)
{
$only_changes = $reader->xml_reader->getAttribute('СодержитТолькоИзменения') ?: true;
if($only_changes === 'false')
{
$only_changes = false;
}
$reader->catalog->setOnlyChanges($only_changes);
}
if($reader->parentNodeName === 'Каталог' && $reader->xml_reader->nodeType === XMLReader::ELEMENT)
{
switch($reader->nodeName)
{
case 'Ид':
$reader->catalog->setId($reader->xml_reader->readString());
break;
case 'ИдКлассификатора':
$reader->catalog->setClassifierId($reader->xml_reader->readString());
break;
case 'Наименование':
$reader->catalog->setName($reader->xml_reader->readString());
break;
case 'Владелец':
$owner = $reader->decoder()->process('counterparty', $reader->xml_reader->readOuterXml());
$reader->catalog->setOwner($owner);
break;
case 'Описание':
$reader->catalog->setDescription($reader->xml_reader->readString());
break;
}
}
if($reader->parentNodeName === 'Товары' && $reader->nodeName === 'Товар' && $reader->xml_reader->nodeType === XMLReader::ELEMENT)
{
/**
* Декодирование данных продукта из XML в объект реализующий ProductDataContract
*/
$product = $reader->decoder->process('product', $reader->xml_reader->readOuterXml());
/**
* Внешняя фильтрация перед непосредственной обработкой
*
* @param ProductDataContract $product
* @param Reader $reader
* @param SchemaAbstract $this
*/
if(has_filter('wc1c_schema_productscleanercml_processing_products'))
{
$product = apply_filters('wc1c_schema_productscleanercml_processing_products', $product, $reader, $this);
}
if(!$product instanceof ProductDataContract)
{
$this->log()->debug(__('Product !instanceof ProductDataContract. Skip processing.', 'wc1c-main'), ['data' => $product]);
return;
}
try
{
do_action('wc1c_schema_productscleanercml_processing_products_item', $product, $reader, $this);
}
catch(\Throwable $e)
{
$this->log()->warning(__('An exception was thrown while saving the product.', 'wc1c-main'), ['exception' => $e]);
}
$reader->next();
}
}
/**
* Обработка данных продукта (товара) из каталога товаров, данные могут быть как продуктом, так и характеристикой.
*
* @param $external_product ProductDataContract
* @param $reader Reader
*
* @return void
* @throws Exception
*/
public function processingProductsItem(ProductDataContract $external_product, Reader $reader)
{
$this->log()->info(__('Processing a product from a catalog of products.', 'wc1c-main'), ['product_id' => $external_product->getId(), 'product_characteristic_id' => $external_product->getCharacteristicId()]);
if('yes' !== $this->getOptions('clean', 'no'))
{
$this->log()->info(__('Cleaning of products is disabled. Processing skipped.', 'wc1c-main'), ['product_id' => $external_product->getId(), 'product_characteristic_id' => $external_product->getCharacteristicId()]);
return;
}
$product_id = 0;
$product_factory = new Factory();
/*
* Поиск продукта по идентификатору 1С
*/
if('yes' === $this->getOptions('sync_by_id', 'yes'))
{
$product_id = $product_factory->findIdsByExternalIdAndCharacteristicId($external_product->getId(), $external_product->getCharacteristicId());
$this->log()->debug(__('Product search result by external code from 1C.', 'wc1c-main'), ['product_ids' => $product_id]);
if(is_array($product_id)) // todo: обработка нескольких?
{
$this->log()->notice(__('Several identical products were found. The first one is selected.', 'wc1c-main'), ['product_ids' => $product_id]);
$product_id = reset($product_id);
}
}
/**
* Поиск идентификатора существующего продукта по внешним алгоритмам
*
* @param int $product_id Идентификатор найденного продукта
* @param ProductDataContract $external_product Данные продукта в CML
* @param SchemaAbstract $this
* @param Reader $reader Текущий итератор
*
* @return int|false
*/
if(empty($product_id) && has_filter('wc1c_schema_productscleanercml_processing_products_search'))
{
$product_id = apply_filters('wc1c_schema_productscleanercml_processing_products_search', $product_id, $external_product, $this, $reader);
$this->log()->debug(__('Product search result by external algorithms.', 'wc1c-main'), ['product_ids' => $product_id]);
}
/**
* Ни один продукт не найден
*/
if(empty($product_id))
{
$this->log()->info(__('Product is not found.', 'wc1c-main'));
return;
}
/*
* Экземпляр продукта по найденному идентификатору продукта
*/
$cleaning_product = $product_factory->getProduct($product_id);
/**
* Окончательное удаление
*/
if('yes' === $this->getOptions('clean_final', 'no'))
{
$cleaning_product->delete(true);
}
else
{
$cleaning_product->delete(false);
}
}
}