Passed
Push — master ( b7d939...326a3e )
by Aimeos
02:59
created

Standard::domains()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 22
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2018-2022
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Supplier\Import\Csv;
12
13
14
/**
15
 * Job controller for CSV supplier imports.
16
 *
17
 * @package Controller
18
 * @subpackage Jobs
19
 */
20
class Standard
21
	extends \Aimeos\Controller\Common\Supplier\Import\Csv\Base
22
	implements \Aimeos\Controller\Jobs\Iface
23
{
24
	/** controller/jobs/supplier/import/csv/name
25
	 * Class name of the used supplier suggestions scheduler controller implementation
26
	 *
27
	 * Each default job controller can be replace by an alternative imlementation.
28
	 * To use this implementation, you have to set the last part of the class
29
	 * name as configuration value so the controller factory knows which class it
30
	 * has to instantiate.
31
	 *
32
	 * For example, if the name of the default class is
33
	 *
34
	 *  \Aimeos\Controller\Jobs\Supplier\Import\Csv\Standard
35
	 *
36
	 * and you want to replace it with your own version named
37
	 *
38
	 *  \Aimeos\Controller\Jobs\Supplier\Import\Csv\Mycsv
39
	 *
40
	 * then you have to set the this configuration option:
41
	 *
42
	 *  controller/jobs/supplier/import/csv/name = Mycsv
43
	 *
44
	 * The value is the last part of your own class name and it's case sensitive,
45
	 * so take care that the configuration value is exactly named like the last
46
	 * part of the class name.
47
	 *
48
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
49
	 * characters are possible! You should always start the last part of the class
50
	 * name with an upper case character and continue only with lower case characters
51
	 * or numbers. Avoid chamel case names like "MyCsv"!
52
	 *
53
	 * @param string Last part of the class name
54
	 * @since 2020.07
55
	 */
56
57
	/** controller/jobs/supplier/import/csv/decorators/excludes
58
	 * Excludes decorators added by the "common" option from the supplier import CSV job controller
59
	 *
60
	 * Decorators extend the functionality of a class by adding new aspects
61
	 * (e.g. log what is currently done), executing the methods of the underlying
62
	 * class only in certain conditions (e.g. only for logged in users) or
63
	 * modify what is returned to the caller.
64
	 *
65
	 * This option allows you to remove a decorator added via
66
	 * "controller/jobs/common/decorators/default" before they are wrapped
67
	 * around the job controller.
68
	 *
69
	 *  controller/jobs/supplier/import/csv/decorators/excludes = array( 'decorator1' )
70
	 *
71
	 * This would remove the decorator named "decorator1" from the list of
72
	 * common decorators ("\Aimeos\Controller\Jobs\Common\Decorator\*") added via
73
	 * "controller/jobs/common/decorators/default" to the job controller.
74
	 *
75
	 * @param array List of decorator names
76
	 * @since 2020.07
77
	 * @see controller/jobs/common/decorators/default
78
	 * @see controller/jobs/supplier/import/csv/decorators/global
79
	 * @see controller/jobs/supplier/import/csv/decorators/local
80
	 */
81
82
	/** controller/jobs/supplier/import/csv/decorators/global
83
	 * Adds a list of globally available decorators only to the supplier import CSV job controller
84
	 *
85
	 * Decorators extend the functionality of a class by adding new aspects
86
	 * (e.g. log what is currently done), executing the methods of the underlying
87
	 * class only in certain conditions (e.g. only for logged in users) or
88
	 * modify what is returned to the caller.
89
	 *
90
	 * This option allows you to wrap global decorators
91
	 * ("\Aimeos\Controller\Jobs\Common\Decorator\*") around the job controller.
92
	 *
93
	 *  controller/jobs/supplier/import/csv/decorators/global = array( 'decorator1' )
94
	 *
95
	 * This would add the decorator named "decorator1" defined by
96
	 * "\Aimeos\Controller\Jobs\Common\Decorator\Decorator1" only to the job controller.
97
	 *
98
	 * @param array List of decorator names
99
	 * @since 2020.07
100
	 * @see controller/jobs/common/decorators/default
101
	 * @see controller/jobs/supplier/import/csv/decorators/excludes
102
	 * @see controller/jobs/supplier/import/csv/decorators/local
103
	 */
104
105
	/** controller/jobs/supplier/import/csv/decorators/local
106
	 * Adds a list of local decorators only to the supplier import CSV job controller
107
	 *
108
	 * Decorators extend the functionality of a class by adding new aspects
109
	 * (e.g. log what is currently done), executing the methods of the underlying
110
	 * class only in certain conditions (e.g. only for logged in users) or
111
	 * modify what is returned to the caller.
112
	 *
113
	 * This option allows you to wrap local decorators
114
	 * ("\Aimeos\Controller\Jobs\Supplier\Import\Csv\Decorator\*") around the job
115
	 * controller.
116
	 *
117
	 *  controller/jobs/supplier/import/csv/decorators/local = array( 'decorator2' )
118
	 *
119
	 * This would add the decorator named "decorator2" defined by
120
	 * "\Aimeos\Controller\Jobs\Supplier\Import\Csv\Decorator\Decorator2"
121
	 * only to the job controller.
122
	 *
123
	 * @param array List of decorator names
124
	 * @since 2020.07
125
	 * @see controller/jobs/common/decorators/default
126
	 * @see controller/jobs/supplier/import/csv/decorators/excludes
127
	 * @see controller/jobs/supplier/import/csv/decorators/global
128
	 */
129
130
131
	/**
132
	 * Returns the localized name of the job.
133
	 *
134
	 * @return string Name of the job
135
	 */
136
	public function getName() : string
137
	{
138
		return $this->context()->translate( 'controller/jobs', 'Supplier import CSV' );
139
	}
140
141
142
	/**
143
	 * Returns the localized description of the job.
144
	 *
145
	 * @return string Description of the job
146
	 */
147
	public function getDescription() : string
148
	{
149
		return $this->context()->translate( 'controller/jobs', 'Imports new and updates existing suppliers from CSV files' );
150
	}
151
152
153
	/**
154
	 * Executes the job.
155
	 *
156
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
157
	 */
158
	public function run()
159
	{
160
		$total = $errors = 0;
161
		$context = $this->context();
162
		$logger = $context->logger();
163
		$mappings = $this->mapping();
164
		$maxcnt = $this->max();
165
		$skiplines = $this->skip();
166
167
168
		try
169
		{
170
			$codePos = $this->getCodePosition( $mappings['item'] );
171
			$processor = $this->getProcessors( $mappings );
172
			$supplierMap = $this->getSupplierMap( $this->domains() );
173
			$container = $this->getContainer();
174
			$path = $container->getName();
175
176
177
			$msg = sprintf( 'Started supplier import from "%1$s" (%2$s)', $path, __CLASS__ );
178
			$logger->notice( $msg, 'import/csv/supplier' );
179
180
			foreach( $container as $content )
181
			{
182
				$name = $content->getName();
0 ignored issues
show
Unused Code introduced by
The assignment to $name is dead and can be removed.
Loading history...
183
184
				for( $i = 0; $i < $skiplines; $i++ )
185
				{
186
					$content->next();
187
				}
188
189
				while( ( $data = $this->getData( $content, $maxcnt, $codePos ) ) !== [] )
190
				{
191
					$errors += $this->import( $supplierMap, $data, $mappings['item'], $processor );
192
					$total += count( $data );
193
					unset( $data );
194
				}
195
			}
196
197
			$container->close();
198
		}
199
		catch( \Exception $e )
200
		{
201
			$logger->error( 'Supplier import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'import/csv/supplier' );
202
			$this->mail( 'Supplier CSV import error', $e->getMessage() . "\n" . $e->getTraceAsString() );
203
			throw new \Aimeos\Controller\Jobs\Exception( $e->getMessage() );
204
		}
205
206
		$str = 'Finished supplier import from "%1$s": %2$d successful, %3$s errors, %4$s total (%5$s)';
207
		$msg = sprintf( $str, $path, $total - $errors, $errors, $total, __CLASS__ );
208
		$logger->notice( $msg, 'import/csv/supplier' );
209
210
		if( $errors > 0 )
211
		{
212
			$msg = sprintf( 'Invalid supplier lines in "%1$s": %2$d/%3$d', $path, $errors, $total );
213
			$this->mail( 'Supplier CSV import error', $msg );
214
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
215
		}
216
217
		if( !empty( $backup = $this->backup() ) && @rename( $path, $backup ) === false )
218
		{
219
			$msg = sprintf( 'Unable to move imported file "%1$s" to "%2$s"', $path, $backup );
220
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
221
		}
222
	}
223
224
225
	/**
226
	 * Returns the directory for storing imported files
227
	 *
228
	 * @return string Directory for storing imported files
229
	 */
230
	protected function backup() : string
231
	{
232
		/** controller/jobs/supplier/import/csv/backup
233
		 * Name of the backup for sucessfully imported files
234
		 *
235
		 * After a CSV file was imported successfully, you can move it to another
236
		 * location, so it won't be imported again and isn't overwritten by the
237
		 * next file that is stored at the same location in the file system.
238
		 *
239
		 * You should use an absolute path to be sure but can be relative path
240
		 * if you absolutely know from where the job will be executed from. The
241
		 * name of the new backup location can contain placeholders understood
242
		 * by the PHP DateTime::format() method (with percent signs prefix) to
243
		 * create dynamic paths, e.g. "backup/%Y-%m-%d" which would create
244
		 * "backup/2000-01-01". For more information about the date() placeholders,
245
		 * please have a look  into the PHP documentation of the
246
		 * {@link https://www.php.net/manual/en/datetime.format.php format() method}.
247
		 *
248
		 * **Note:** If no backup name is configured, the file will be removed!
249
		 *
250
		 * @param integer Name of the backup file, optionally with date/time placeholders
251
		 * @since 2020.07
252
		 * @see controller/jobs/supplier/import/csv/domains
253
		 * @see controller/jobs/supplier/import/csv/mapping
254
		 * @see controller/jobs/supplier/import/csv/skip-lines
255
		 * @see controller/jobs/supplier/import/csv/converter
256
		 * @see controller/jobs/supplier/import/csv/strict
257
		 * @see controller/jobs/supplier/import/csv/max-size
258
		 */
259
		$backup = $this->context()->config()->get( 'controller/jobs/supplier/import/csv/backup' );
260
		return \Aimeos\Base\Str::strtime( (string) $backup );
261
	}
262
263
264
	/**
265
	 * Returns the list of domain names that should be retrieved along with the supplier items
266
	 *
267
	 * @return array List of domain names
268
	 */
269
	protected function domains() : array
270
	{
271
		/** controller/jobs/supplier/import/csv/domains
272
		 * List of item domain names that should be retrieved along with the supplier items
273
		 *
274
		 * For efficient processing, the items associated to the products can be
275
		 * fetched to, minimizing the number of database queries required. To be
276
		 * most effective, the list of item domain names should be used in the
277
		 * mapping configuration too, so the retrieved items will be used during
278
		 * the import.
279
		 *
280
		 * @param array Associative list of MShop item domain names
281
		 * @since 2020.07
282
		 * @see controller/jobs/supplier/import/csv/mapping
283
		 * @see controller/jobs/supplier/import/csv/skip-lines
284
		 * @see controller/jobs/supplier/import/csv/converter
285
		 * @see controller/jobs/supplier/import/csv/strict
286
		 * @see controller/jobs/supplier/import/csv/backup
287
		 * @see controller/jobs/supplier/import/csv/max-size
288
		 */
289
		$domains = ['media', 'text', 'supplier/address'];
290
		return $this->context()->config()->get( 'controller/jobs/supplier/import/xml/domains', $domains );
291
	}
292
293
294
	/**
295
	 * Returns the position of the "supplier.code" column from the supplier item mapping
296
	 *
297
	 * @param array $mapping Mapping of the "item" columns with position as key and code as value
298
	 * @return int Position of the "supplier.code" column
299
	 * @throws \Aimeos\Controller\Jobs\Exception If no mapping for "supplier.code" is found
300
	 */
301
	protected function getCodePosition( array $mapping ) : int
302
	{
303
		foreach( $mapping as $pos => $key )
304
		{
305
			if( $key === 'supplier.code' ) {
306
				return $pos;
307
			}
308
		}
309
310
		throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No "supplier.code" column in CSV mapping found' ) );
311
	}
312
313
314
	/**
315
	 * Opens and returns the container which includes the supplier data
316
	 *
317
	 * @return \Aimeos\MW\Container\Iface Container object
318
	 */
319
	protected function getContainer() : \Aimeos\MW\Container\Iface
320
	{
321
		$config = $this->context()->config();
322
323
		/** controller/jobs/supplier/import/csv/container/type
324
		 * Nave of the container type to read the data from
325
		 *
326
		 * The container type tells the importer how it should retrieve the data.
327
		 * There are currently three container types that support the necessary
328
		 * CSV content:
329
		 *
330
		 * * Directory
331
		 * * Zip
332
		 *
333
		 * @param string Container type name
334
		 * @since 2020.07
335
		 * @category User
336
		 * @see controller/jobs/supplier/import/csv/location
337
		 * @see controller/jobs/supplier/import/csv/container/content
338
		 * @see controller/jobs/supplier/import/csv/container/options
339
		 */
340
		$container = $config->get( 'controller/jobs/supplier/import/csv/container/type', 'Directory' );
341
342
		/** controller/jobs/supplier/import/csv/container/content
343
		 * Name of the content type inside the container to read the data from
344
		 *
345
		 * The content type must always be a CSV-like format and there are
346
		 * currently two format types that are supported:
347
		 *
348
		 * * CSV
349
		 *
350
		 * @param array Content type name
351
		 * @since 2020.07
352
		 * @category User
353
		 * @see controller/jobs/supplier/import/csv/location
354
		 * @see controller/jobs/supplier/import/csv/container/type
355
		 * @see controller/jobs/supplier/import/csv/container/options
356
		 */
357
		$content = $config->get( 'controller/jobs/supplier/import/csv/container/content', 'CSV' );
358
359
		/** controller/jobs/supplier/import/csv/container/options
360
		 * List of file container options for the supplier import files
361
		 *
362
		 * Some container/content type allow you to hand over additional settings
363
		 * for configuration. Please have a look at the article about
364
		 * {@link http://aimeos.org/docs/Developers/Utility/Create_and_read_files container/content files}
365
		 * for more information.
366
		 *
367
		 * @param array Associative list of option name/value pairs
368
		 * @since 2020.07
369
		 * @category User
370
		 * @see controller/jobs/supplier/import/csv/location
371
		 * @see controller/jobs/supplier/import/csv/container/content
372
		 * @see controller/jobs/supplier/import/csv/container/type
373
		 */
374
		$options = $config->get( 'controller/jobs/supplier/import/csv/container/options', [] );
375
376
		if( empty( $location = $this->location() ) )
377
		{
378
			$msg = sprintf( 'Required configuration for "%1$s" is missing', 'controller/jobs/supplier/import/csv/location' );
379
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
380
		}
381
382
		return \Aimeos\MW\Container\Factory::getContainer( $location, $container, $content, $options );
383
	}
384
385
386
	/**
387
	 * Returns the supplier items building the tree as list
388
	 *
389
	 * @param array $domains List of domain names whose items should be fetched too
390
	 * @return array Associative list of supplier codes as keys and items implementing \Aimeos\MShop\Supplier\Item\Iface as values
391
	 */
392
	protected function getSupplierMap( array $domains ) : array
393
	{
394
		$map = [];
395
		$manager = \Aimeos\MShop::create( $this->context(), 'supplier' );
396
		$search = $manager->filter()->slice( 0, 0x7fffffff );
397
398
		foreach( $manager->search( $search, $domains ) as $item )
399
		{
400
			$map[$item->getCode()] = $item;
401
		}
402
403
		return $map;
404
	}
405
406
407
	/**
408
	 * Imports the CSV data and creates new suppliers or updates existing ones
409
	 *
410
	 * @param array &$supplierMap Associative list of supplier items with codes as keys and items implementing \Aimeos\MShop\Supplier\Item\Iface as values
411
	 * @param array $data Associative list of import data as index/value pairs
412
	 * @param array $mapping Associative list of positions and domain item keys
413
	 * @param \Aimeos\Controller\Common\Supplier\Import\Csv\Processor\Iface $processor Processor object
414
	 * @return int Number of suppliers that couldn't be imported
415
	 * @throws \Aimeos\Controller\Jobs\Exception
416
	 */
417
	protected function import( array &$supplierMap, array $data, array $mapping,
418
		\Aimeos\Controller\Common\Supplier\Import\Csv\Processor\Iface $processor ) : int
419
	{
420
		$errors = 0;
421
		$context = $this->context();
422
		$manager = \Aimeos\MShop::create( $context, 'supplier' );
423
424
		foreach( $data as $code => $list )
425
		{
426
			$manager->begin();
427
428
			try
429
			{
430
				$code = trim( $code );
431
432
				if( isset( $supplierMap[$code] ) )
433
				{
434
					$item = $supplierMap[$code];
435
				} else
436
				{
437
					$item = $manager->create();
438
				}
439
440
				$map = $this->getMappedChunk( $list, $mapping );
441
442
				if( isset( $map[0] ) )
443
				{
444
					$map = $map[0]; // there can only be one chunk for the base supplier data
445
					$item->fromArray( $map, true );
446
447
					$list = $processor->process( $item, $list );
0 ignored issues
show
Unused Code introduced by
The assignment to $list is dead and can be removed.
Loading history...
448
					$supplierMap[$code] = $item;
449
450
					$manager->save( $item );
451
				}
452
453
				$manager->commit();
454
			}
455
			catch( \Exception $e )
456
			{
457
				$manager->rollback();
458
459
				$msg = sprintf( 'Unable to import supplier with code "%1$s": %2$s', $code, $e->getMessage() );
460
				$context->logger()->error( $msg, 'import/csv/supplier' );
461
462
				$errors++;
463
			}
464
		}
465
466
		return $errors;
467
	}
468
469
470
	/**
471
	 * Returns the path to the directory with the CSV file
472
	 *
473
	 * @return string Path to the directory with the CSV file
474
	 */
475
	protected function location() : string
476
	{
477
		/** controller/jobs/supplier/import/csv/location
478
		 * File or directory where the content is stored which should be imported
479
		 *
480
		 * You need to configure the file or directory that acts as container
481
		 * for the CSV files that should be imported. It should be an absolute
482
		 * path to be sure but can be relative path if you absolutely know from
483
		 * where the job will be executed from.
484
		 *
485
		 * The path can point to any supported container format as long as the
486
		 * content is in CSV format, e.g.
487
		 *
488
		 * * Directory container / CSV file
489
		 * * Zip container / compressed CSV file
490
		 *
491
		 * @param string Relative path to the CSV files
492
		 * @since 2020.07
493
		 * @see controller/jobs/supplier/import/csv/backup
494
		 * @see controller/jobs/supplier/import/csv/domains
495
		 * @see controller/jobs/supplier/import/csv/location
496
		 * @see controller/jobs/supplier/import/csv/mapping
497
		 * @see controller/jobs/supplier/import/csv/max-size
498
		 * @see controller/jobs/supplier/import/csv/skip-lines
499
		 */
500
		return (string) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/location', 'supplier' );
501
	}
502
503
504
	/**
505
	 * Returns the CSV column mapping
506
	 *
507
	 * @return array CSV column mapping
508
	 */
509
	protected function mapping() : array
510
	{
511
		/** controller/jobs/supplier/import/csv/mapping
512
		 * List of mappings between the position in the CSV file and item keys
513
		 *
514
		 * The importer have to know which data is at which position in the CSV
515
		 * file. Therefore, you need to specify a mapping between each position
516
		 * and the MShop domain item key (e.g. "supplier.code") it represents.
517
		 *
518
		 * You can use all domain item keys which are used in the fromArray()
519
		 * methods of the item classes.
520
		 *
521
		 * These mappings are grouped together by their processor names, which
522
		 * are responsible for importing the data, e.g. all mappings in "item"
523
		 * will be processed by the base supplier importer while the mappings in
524
		 * "text" will be imported by the text processor.
525
		 *
526
		 * @param array Associative list of processor names and lists of key/position pairs
527
		 * @since 2020.07
528
		 * @see controller/jobs/supplier/import/csv/domains
529
		 * @see controller/jobs/supplier/import/csv/skip-lines
530
		 * @see controller/jobs/supplier/import/csv/converter
531
		 * @see controller/jobs/supplier/import/csv/strict
532
		 * @see controller/jobs/supplier/import/csv/backup
533
		 * @see controller/jobs/supplier/import/csv/max-size
534
		 */
535
		$map = (array) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/mapping', $this->getDefaultMapping() );
536
537
		if( !isset( $map['item'] ) || !is_array( $map['item'] ) )
538
		{
539
			$msg = sprintf( 'Required mapping key "%1$s" is missing or contains no array', 'item' );
540
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
541
		}
542
543
		return $map;
544
	}
545
546
547
	/**
548
	 * Returns the maximum number of CSV rows to import at once
549
	 *
550
	 * @return int Maximum number of CSV rows to import at once
551
	 */
552
	protected function max() : int
553
	{
554
		/** controller/common/supplier/import/csv/max-size
555
		 * Maximum number of CSV rows to import at once
556
		 *
557
		 * It's more efficient to read and import more than one row at a time
558
		 * to speed up the import. Usually, the bigger the chunk that is imported
559
		 * at once, the less time the importer will need. The downside is that
560
		 * the amount of memory required by the import process will increase as
561
		 * well. Therefore, it's a trade-off between memory consumption and
562
		 * import speed.
563
		 *
564
		 * @param integer Number of rows
565
		 * @since 2020.07
566
		 * @see controller/jobs/supplier/import/csv/backup
567
		 * @see controller/jobs/supplier/import/csv/domains
568
		 * @see controller/jobs/supplier/import/csv/location
569
		 * @see controller/jobs/supplier/import/csv/mapping
570
		 * @see controller/jobs/supplier/import/csv/skip-lines
571
		 */
572
		return (int) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/max-size', 1000 );
573
	}
574
575
576
	/**
577
	 * Returns the number of rows skipped in front of each CSV files
578
	 *
579
	 * @return int Number of rows skipped in front of each CSV files
580
	 */
581
	protected function skip() : int
582
	{
583
		/** controller/jobs/supplier/import/csv/skip-lines
584
		 * Number of rows skipped in front of each CSV files
585
		 *
586
		 * Some CSV files contain header information describing the content of
587
		 * the column values. These data is for informational purpose only and
588
		 * can't be imported into the database. Using this option, you can
589
		 * define the number of lines that should be left out before the import
590
		 * begins.
591
		 *
592
		 * @param integer Number of rows
593
		 * @since 2020.07
594
		 * @see controller/jobs/supplier/import/csv/domains
595
		 * @see controller/jobs/supplier/import/csv/mapping
596
		 * @see controller/jobs/supplier/import/csv/converter
597
		 * @see controller/jobs/supplier/import/csv/strict
598
		 * @see controller/jobs/supplier/import/csv/backup
599
		 * @see controller/jobs/supplier/import/csv/max-size
600
		 */
601
		return (int) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/skip-lines', 0 );
602
	}
603
}
604