Passed
Push — master ( 330c3c...aa616b )
by Aimeos
03:14
created

Standard   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 521
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 91
dl 0
loc 521
rs 10
c 0
b 0
f 0
wmc 29

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 3 1
A getDescription() 0 3 1
A backup() 0 31 1
B run() 0 34 7
A getSuppliers() 0 6 1
A domains() 0 22 1
A skip() 0 21 1
A getCodePosition() 0 10 3
A importSuppliers() 0 42 4
A mapping() 0 35 3
A import() 0 44 4
A max() 0 21 1
A location() 0 26 1
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
		$context = $this->context();
161
162
		try
163
		{
164
			$errors = 0;
165
			$location = $this->location();
166
			$fs = $context->fs( 'fs-import' );
167
168
			if( $fs->isDir( $location ) === false ) {
169
				return;
170
			}
171
172
			foreach( map( $fs->scan( $location ) )->sort() as $filename )
173
			{
174
				$path = $location . '/' . $filename;
175
176
				if( $fs instanceof \Aimeos\Base\Filesystem\DirIface && $fs->isDir( $path ) ) {
177
					continue;
178
				}
179
180
				$errors += $this->import( $path );
181
			}
182
183
			if( $errors > 0 ) {
184
				$this->mail( 'Supplier CSV import', sprintf( 'Invalid supplier lines during import: %1$d', $errors ) );
185
			}
186
		}
187
		catch( \Exception $e )
188
		{
189
			$context->logger()->error( 'Supplier import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'import/csv/supplier' );
190
			$this->mail( 'Supplier CSV import error', $e->getMessage() . "\n" . $e->getTraceAsString() );
191
			throw new \Aimeos\Controller\Jobs\Exception( $e->getMessage() );
192
		}
193
	}
194
195
196
	/**
197
	 * Returns the directory for storing imported files
198
	 *
199
	 * @return string Directory for storing imported files
200
	 */
201
	protected function backup() : string
202
	{
203
		/** controller/jobs/supplier/import/csv/backup
204
		 * Name of the backup for sucessfully imported files
205
		 *
206
		 * After a CSV file was imported successfully, you can move it to another
207
		 * location, so it won't be imported again and isn't overwritten by the
208
		 * next file that is stored at the same location in the file system.
209
		 *
210
		 * You should use an absolute path to be sure but can be relative path
211
		 * if you absolutely know from where the job will be executed from. The
212
		 * name of the new backup location can contain placeholders understood
213
		 * by the PHP DateTime::format() method (with percent signs prefix) to
214
		 * create dynamic paths, e.g. "backup/%Y-%m-%d" which would create
215
		 * "backup/2000-01-01". For more information about the date() placeholders,
216
		 * please have a look  into the PHP documentation of the
217
		 * {@link https://www.php.net/manual/en/datetime.format.php format() method}.
218
		 *
219
		 * **Note:** If no backup name is configured, the file will be removed!
220
		 *
221
		 * @param integer Name of the backup file, optionally with date/time placeholders
222
		 * @since 2020.07
223
		 * @see controller/jobs/supplier/import/csv/domains
224
		 * @see controller/jobs/supplier/import/csv/mapping
225
		 * @see controller/jobs/supplier/import/csv/skip-lines
226
		 * @see controller/jobs/supplier/import/csv/converter
227
		 * @see controller/jobs/supplier/import/csv/strict
228
		 * @see controller/jobs/supplier/import/csv/max-size
229
		 */
230
		$backup = $this->context()->config()->get( 'controller/jobs/supplier/import/csv/backup' );
231
		return \Aimeos\Base\Str::strtime( (string) $backup );
232
	}
233
234
235
	/**
236
	 * Returns the list of domain names that should be retrieved along with the supplier items
237
	 *
238
	 * @return array List of domain names
239
	 */
240
	protected function domains() : array
241
	{
242
		/** controller/jobs/supplier/import/csv/domains
243
		 * List of item domain names that should be retrieved along with the supplier items
244
		 *
245
		 * For efficient processing, the items associated to the suppliers can be
246
		 * fetched to, minimizing the number of database queries required. To be
247
		 * most effective, the list of item domain names should be used in the
248
		 * mapping configuration too, so the retrieved items will be used during
249
		 * the import.
250
		 *
251
		 * @param array Associative list of MShop item domain names
252
		 * @since 2020.07
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/backup
258
		 * @see controller/jobs/supplier/import/csv/max-size
259
		 */
260
		$domains = ['media', 'text', 'supplier/address'];
261
		return $this->context()->config()->get( 'controller/jobs/supplier/import/xml/domains', $domains );
262
	}
263
264
265
	/**
266
	 * Returns the position of the "supplier.code" column from the supplier item mapping
267
	 *
268
	 * @param array $mapping Mapping of the "item" columns with position as key and code as value
269
	 * @return int Position of the "supplier.code" column
270
	 * @throws \Aimeos\Controller\Jobs\Exception If no mapping for "supplier.code" is found
271
	 */
272
	protected function getCodePosition( array $mapping ) : int
273
	{
274
		foreach( $mapping as $pos => $key )
275
		{
276
			if( $key === 'supplier.code' ) {
277
				return $pos;
278
			}
279
		}
280
281
		throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No "supplier.code" column in CSV mapping found' ) );
282
	}
283
284
285
	/**
286
	 * Returns the supplier items for the given codes
287
	 *
288
	 * @param array $codes List of supplier codes
289
	 * @param array $domains List of domains whose items should be fetched too
290
	 * @return \Aimeos\Map Associative list of supplier codes as key and supplier items as value
291
	 */
292
	protected function getSuppliers( array $codes, array $domains ) : \Aimeos\Map
293
	{
294
		$manager = \Aimeos\MShop::create( $this->context(), 'supplier' );
295
		$search = $manager->filter()->add( ['supplier.code' => $codes] )->slice( 0, count( $codes ) );
296
297
		return $manager->search( $search, $domains )->col( null, 'supplier.code' );
298
	}
299
300
301
	/**
302
	 * Imports the CSV file from the given path
303
	 *
304
	 * @param string $path Relative path to the CSV file
305
	 * @return int Number of lines which couldn't be imported
306
	 */
307
	protected function import( string $path ) : int
308
	{
309
		$context = $this->context();
310
		$logger = $context->logger();
311
		$fs = $context->fs( 'fs-import' );
312
313
		$logger->info( sprintf( 'Started supplier import from "%1$s"', $path ), 'import/csv/supplier' );
314
315
		$maxcnt = $this->max();
316
		$skiplines = $this->skip();
317
		$domains = $this->domains();
318
319
		$mappings = $this->mapping();
320
		$processor = $this->getProcessors( $mappings );
321
		$codePos = $this->getCodePosition( $mappings['item'] );
322
323
		$total = $errors = 0;
324
		$fh = $fs->reads( $path );
325
326
		for( $i = 0; $i < $skiplines; $i++ ) {
327
			fgetcsv( $fh );
328
		}
329
330
		while( ( $data = $this->getData( $fh, $maxcnt, $codePos ) ) !== [] )
331
		{
332
			$suppliers = $this->getSuppliers( array_keys( $data ), $domains );
333
			$errors += $this->importSuppliers( $suppliers, $data, $mappings['item'], $processor );
334
335
			$total += count( $data );
336
			unset( $suppliers, $data );
337
		}
338
339
		fclose( $fh );
340
341
		if( !empty( $backup = $this->backup() ) ) {
342
			$fs->move( $path, $backup );
343
		} else {
344
			$fs->rm( $path );
345
		}
346
347
		$str = sprintf( 'Finished supplier import from "%1$s" (%2$d/%3$d)', $path, $errors, $total );
348
		$logger->info( $str, 'import/csv/supplier' );
349
350
		return $errors;
351
	}
352
353
354
	/**
355
	 * Imports the CSV data and creates new suppliers or updates existing ones
356
	 *
357
	 * @param \Aimeos\Map $suppliers Associative list of supplier items with codes as keys and items implementing \Aimeos\MShop\Supplier\Item\Iface as values
358
	 * @param array $data Associative list of import data as index/value pairs
359
	 * @param array $mapping Associative list of positions and domain item keys
360
	 * @param \Aimeos\Controller\Common\Supplier\Import\Csv\Processor\Iface $processor Processor object
361
	 * @return int Number of suppliers that couldn't be imported
362
	 * @throws \Aimeos\Controller\Jobs\Exception
363
	 */
364
	protected function importSuppliers( \Aimeos\Map $suppliers, array $data, array $mapping,
365
		\Aimeos\Controller\Common\Supplier\Import\Csv\Processor\Iface $processor ) : int
366
	{
367
		$items = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $items is dead and can be removed.
Loading history...
368
		$errors = 0;
369
		$context = $this->context();
370
		$manager = \Aimeos\MShop::create( $context, 'supplier' );
371
372
		foreach( $data as $code => $list )
373
		{
374
			$manager->begin();
375
376
			try
377
			{
378
				$code = trim( $code );
379
				$item = $suppliers[$code] ?? $manager->create();
380
				$map = current( $this->getMappedChunk( $list, $mapping ) ); // there can only be one chunk for the base supplier data
381
382
				if( $map )
383
				{
384
					$item->fromArray( $map, true );
385
386
					$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...
387
					$suppliers[$code] = $item;
388
389
					$manager->save( $item );
390
				}
391
392
				$manager->commit();
393
			}
394
			catch( \Exception $e )
395
			{
396
				$manager->rollback();
397
398
				$msg = sprintf( 'Unable to import supplier with code "%1$s": %2$s', $code, $e->getMessage() );
399
				$context->logger()->error( $msg, 'import/csv/supplier' );
400
401
				$errors++;
402
			}
403
		}
404
405
		return $errors;
406
	}
407
408
409
	/**
410
	 * Returns the path to the directory with the CSV file
411
	 *
412
	 * @return string Path to the directory with the CSV file
413
	 */
414
	protected function location() : string
415
	{
416
		/** controller/jobs/supplier/import/csv/location
417
		 * File or directory where the content is stored which should be imported
418
		 *
419
		 * You need to configure the file or directory that acts as container
420
		 * for the CSV files that should be imported. It should be an absolute
421
		 * path to be sure but can be relative path if you absolutely know from
422
		 * where the job will be executed from.
423
		 *
424
		 * The path can point to any supported container format as long as the
425
		 * content is in CSV format, e.g.
426
		 *
427
		 * * Directory container / CSV file
428
		 * * Zip container / compressed CSV file
429
		 *
430
		 * @param string Relative path to the CSV files
431
		 * @since 2020.07
432
		 * @see controller/jobs/supplier/import/csv/backup
433
		 * @see controller/jobs/supplier/import/csv/domains
434
		 * @see controller/jobs/supplier/import/csv/location
435
		 * @see controller/jobs/supplier/import/csv/mapping
436
		 * @see controller/jobs/supplier/import/csv/max-size
437
		 * @see controller/jobs/supplier/import/csv/skip-lines
438
		 */
439
		return (string) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/location', 'supplier' );
440
	}
441
442
443
	/**
444
	 * Returns the CSV column mapping
445
	 *
446
	 * @return array CSV column mapping
447
	 */
448
	protected function mapping() : array
449
	{
450
		/** controller/jobs/supplier/import/csv/mapping
451
		 * List of mappings between the position in the CSV file and item keys
452
		 *
453
		 * The importer have to know which data is at which position in the CSV
454
		 * file. Therefore, you need to specify a mapping between each position
455
		 * and the MShop domain item key (e.g. "supplier.code") it represents.
456
		 *
457
		 * You can use all domain item keys which are used in the fromArray()
458
		 * methods of the item classes.
459
		 *
460
		 * These mappings are grouped together by their processor names, which
461
		 * are responsible for importing the data, e.g. all mappings in "item"
462
		 * will be processed by the base supplier importer while the mappings in
463
		 * "text" will be imported by the text processor.
464
		 *
465
		 * @param array Associative list of processor names and lists of key/position pairs
466
		 * @since 2020.07
467
		 * @see controller/jobs/supplier/import/csv/domains
468
		 * @see controller/jobs/supplier/import/csv/skip-lines
469
		 * @see controller/jobs/supplier/import/csv/converter
470
		 * @see controller/jobs/supplier/import/csv/strict
471
		 * @see controller/jobs/supplier/import/csv/backup
472
		 * @see controller/jobs/supplier/import/csv/max-size
473
		 */
474
		$map = (array) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/mapping', $this->getDefaultMapping() );
475
476
		if( !isset( $map['item'] ) || !is_array( $map['item'] ) )
477
		{
478
			$msg = sprintf( 'Required mapping key "%1$s" is missing or contains no array', 'item' );
479
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
480
		}
481
482
		return $map;
483
	}
484
485
486
	/**
487
	 * Returns the maximum number of CSV rows to import at once
488
	 *
489
	 * @return int Maximum number of CSV rows to import at once
490
	 */
491
	protected function max() : int
492
	{
493
		/** controller/common/supplier/import/csv/max-size
494
		 * Maximum number of CSV rows to import at once
495
		 *
496
		 * It's more efficient to read and import more than one row at a time
497
		 * to speed up the import. Usually, the bigger the chunk that is imported
498
		 * at once, the less time the importer will need. The downside is that
499
		 * the amount of memory required by the import process will increase as
500
		 * well. Therefore, it's a trade-off between memory consumption and
501
		 * import speed.
502
		 *
503
		 * @param integer Number of rows
504
		 * @since 2020.07
505
		 * @see controller/jobs/supplier/import/csv/backup
506
		 * @see controller/jobs/supplier/import/csv/domains
507
		 * @see controller/jobs/supplier/import/csv/location
508
		 * @see controller/jobs/supplier/import/csv/mapping
509
		 * @see controller/jobs/supplier/import/csv/skip-lines
510
		 */
511
		return (int) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/max-size', 1000 );
512
	}
513
514
515
	/**
516
	 * Returns the number of rows skipped in front of each CSV files
517
	 *
518
	 * @return int Number of rows skipped in front of each CSV files
519
	 */
520
	protected function skip() : int
521
	{
522
		/** controller/jobs/supplier/import/csv/skip-lines
523
		 * Number of rows skipped in front of each CSV files
524
		 *
525
		 * Some CSV files contain header information describing the content of
526
		 * the column values. These data is for informational purpose only and
527
		 * can't be imported into the database. Using this option, you can
528
		 * define the number of lines that should be left out before the import
529
		 * begins.
530
		 *
531
		 * @param integer Number of rows
532
		 * @since 2020.07
533
		 * @see controller/jobs/supplier/import/csv/domains
534
		 * @see controller/jobs/supplier/import/csv/mapping
535
		 * @see controller/jobs/supplier/import/csv/converter
536
		 * @see controller/jobs/supplier/import/csv/strict
537
		 * @see controller/jobs/supplier/import/csv/backup
538
		 * @see controller/jobs/supplier/import/csv/max-size
539
		 */
540
		return (int) $this->context()->config()->get( 'controller/jobs/supplier/import/csv/skip-lines', 0 );
541
	}
542
}
543