Standard   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 521
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 94
c 2
b 0
f 0
dl 0
loc 521
rs 10
wmc 30

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 3 1
A getDescription() 0 3 1
A skip() 0 21 1
A mapping() 0 35 3
A max() 0 21 1
A backup() 0 31 1
B run() 0 40 8
A getSuppliers() 0 6 1
A domains() 0 22 1
A getCodePosition() 0 10 3
A importSuppliers() 0 41 4
A import() 0 44 4
A location() 0 21 1
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2018-2025
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\Jobs\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
		$logger = $context->logger();
162
163
		try
164
		{
165
			$errors = 0;
166
			$fs = $context->fs( 'fs-import' );
167
			$site = $context->locale()->getSiteItem()->getCode();
168
			$location = $this->location() . '/' . $site;
169
170
			if( $fs->isDir( $location ) === false ) {
171
				return;
172
			}
173
174
			$logger->info( sprintf( 'Started supplier import from "%1$s"', $location ), 'import/csv/supplier' );
175
176
			foreach( map( $fs->scan( $location ) )->sort() as $filename )
177
			{
178
				$path = $location . '/' . $filename;
179
180
				if( $filename[0] === '.' || $fs instanceof \Aimeos\Base\Filesystem\DirIface && $fs->isDir( $path ) ) {
181
					continue;
182
				}
183
184
				$errors += $this->import( $path );
185
			}
186
187
			if( $errors > 0 ) {
188
				$this->mail( 'Supplier CSV import', sprintf( 'Invalid supplier lines during import: %1$d', $errors ) );
189
			}
190
191
			$logger->info( sprintf( 'Finished supplier import from "%1$s"', $location ), 'import/csv/supplier' );
192
		}
193
		catch( \Exception $e )
194
		{
195
			$logger->error( 'Supplier import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'import/csv/supplier' );
196
			$this->mail( 'Supplier CSV import error', $e->getMessage() . "\n" . $e->getTraceAsString() );
197
			throw new \Aimeos\Controller\Jobs\Exception( $e->getMessage() );
198
		}
199
	}
200
201
202
	/**
203
	 * Returns the directory for storing imported files
204
	 *
205
	 * @return string Directory for storing imported files
206
	 */
207
	protected function backup() : string
208
	{
209
		/** controller/jobs/supplier/import/csv/backup
210
		 * Name of the backup for sucessfully imported files
211
		 *
212
		 * After a CSV file was imported successfully, you can move it to another
213
		 * location, so it won't be imported again and isn't overwritten by the
214
		 * next file that is stored at the same location in the file system.
215
		 *
216
		 * You should use an absolute path to be sure but can be relative path
217
		 * if you absolutely know from where the job will be executed from. The
218
		 * name of the new backup location can contain placeholders understood
219
		 * by the PHP DateTime::format() method (with percent signs prefix) to
220
		 * create dynamic paths, e.g. "backup/%Y-%m-%d" which would create
221
		 * "backup/2000-01-01". For more information about the date() placeholders,
222
		 * please have a look  into the PHP documentation of the
223
		 * {@link https://www.php.net/manual/en/datetime.format.php format() method}.
224
		 *
225
		 * **Note:** If no backup name is configured, the file will be removed!
226
		 *
227
		 * @param integer Name of the backup file, optionally with date/time placeholders
228
		 * @since 2020.07
229
		 * @see controller/jobs/supplier/import/csv/domains
230
		 * @see controller/jobs/supplier/import/csv/mapping
231
		 * @see controller/jobs/supplier/import/csv/skip-lines
232
		 * @see controller/jobs/supplier/import/csv/converter
233
		 * @see controller/jobs/supplier/import/csv/strict
234
		 * @see controller/jobs/supplier/import/csv/max-size
235
		 */
236
		$backup = $this->context()->config()->get( 'controller/jobs/supplier/import/csv/backup' );
237
		return \Aimeos\Base\Str::strtime( (string) $backup );
238
	}
239
240
241
	/**
242
	 * Returns the list of domain names that should be retrieved along with the supplier items
243
	 *
244
	 * @return array List of domain names
245
	 */
246
	protected function domains() : array
247
	{
248
		/** controller/jobs/supplier/import/csv/domains
249
		 * List of item domain names that should be retrieved along with the supplier items
250
		 *
251
		 * For efficient processing, the items associated to the suppliers can be
252
		 * fetched to, minimizing the number of database queries required. To be
253
		 * most effective, the list of item domain names should be used in the
254
		 * mapping configuration too, so the retrieved items will be used during
255
		 * the import.
256
		 *
257
		 * @param array Associative list of MShop item domain names
258
		 * @since 2020.07
259
		 * @see controller/jobs/supplier/import/csv/mapping
260
		 * @see controller/jobs/supplier/import/csv/skip-lines
261
		 * @see controller/jobs/supplier/import/csv/converter
262
		 * @see controller/jobs/supplier/import/csv/strict
263
		 * @see controller/jobs/supplier/import/csv/backup
264
		 * @see controller/jobs/supplier/import/csv/max-size
265
		 */
266
		$domains = ['media', 'text', 'supplier/address'];
267
		return $this->context()->config()->get( 'controller/jobs/supplier/import/xml/domains', $domains );
268
	}
269
270
271
	/**
272
	 * Returns the position of the "supplier.code" column from the supplier item mapping
273
	 *
274
	 * @param array $mapping Mapping of the "item" columns with position as key and code as value
275
	 * @return int Position of the "supplier.code" column
276
	 * @throws \Aimeos\Controller\Jobs\Exception If no mapping for "supplier.code" is found
277
	 */
278
	protected function getCodePosition( array $mapping ) : int
279
	{
280
		foreach( $mapping as $pos => $key )
281
		{
282
			if( $key === 'supplier.code' ) {
283
				return $pos;
284
			}
285
		}
286
287
		throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No "supplier.code" column in CSV mapping found' ) );
288
	}
289
290
291
	/**
292
	 * Returns the supplier items for the given codes
293
	 *
294
	 * @param array $codes List of supplier codes
295
	 * @param array $domains List of domains whose items should be fetched too
296
	 * @return \Aimeos\Map Associative list of supplier codes as key and supplier items as value
297
	 */
298
	protected function getSuppliers( array $codes, array $domains ) : \Aimeos\Map
299
	{
300
		$manager = \Aimeos\MShop::create( $this->context(), 'supplier' );
301
		$search = $manager->filter()->add( ['supplier.code' => $codes] )->slice( 0, count( $codes ) );
302
303
		return $manager->search( $search, $domains )->col( null, 'supplier.code' );
304
	}
305
306
307
	/**
308
	 * Imports the CSV file from the given path
309
	 *
310
	 * @param string $path Relative path to the CSV file
311
	 * @return int Number of lines which couldn't be imported
312
	 */
313
	protected function import( string $path ) : int
314
	{
315
		$context = $this->context();
316
		$logger = $context->logger();
317
318
		$logger->info( sprintf( 'Started supplier import from "%1$s"', $path ), 'import/csv/supplier' );
319
320
		$maxcnt = $this->max();
321
		$skiplines = $this->skip();
322
		$domains = $this->domains();
323
324
		$mappings = $this->mapping();
325
		$processor = $this->getProcessors( $mappings );
326
		$codePos = $this->getCodePosition( $mappings['item'] );
327
328
		$fs = $context->fs( 'fs-import' );
329
		$fh = $fs->reads( $path );
330
		$total = $errors = 0;
331
332
		for( $i = 0; $i < $skiplines; $i++ ) {
333
			fgetcsv( $fh, null, ',', '"', '' );
334
		}
335
336
		while( ( $data = $this->getData( $fh, $maxcnt, $codePos ) ) !== [] )
337
		{
338
			$suppliers = $this->getSuppliers( array_keys( $data ), $domains );
339
			$errors += $this->importSuppliers( $suppliers, $data, $mappings['item'], $processor );
340
341
			$total += count( $data );
342
			unset( $suppliers, $data );
343
		}
344
345
		fclose( $fh );
346
347
		if( !empty( $backup = $this->backup() ) ) {
348
			$fs->move( $path, $backup );
349
		} else {
350
			$fs->rm( $path );
351
		}
352
353
		$str = sprintf( 'Finished supplier import from "%1$s" (%2$d/%3$d)', $path, $errors, $total );
354
		$logger->info( $str, 'import/csv/supplier' );
355
356
		return $errors;
357
	}
358
359
360
	/**
361
	 * Imports the CSV data and creates new suppliers or updates existing ones
362
	 *
363
	 * @param \Aimeos\Map $suppliers Associative list of supplier items with codes as keys and items implementing \Aimeos\MShop\Supplier\Item\Iface as values
364
	 * @param array $data Associative list of import data as index/value pairs
365
	 * @param array $mapping Associative list of positions and domain item keys
366
	 * @param \Aimeos\Controller\Jobs\Common\Supplier\Import\Csv\Processor\Iface $processor Processor object
367
	 * @return int Number of suppliers that couldn't be imported
368
	 * @throws \Aimeos\Controller\Jobs\Exception
369
	 */
370
	protected function importSuppliers( \Aimeos\Map $suppliers, array $data, array $mapping,
371
		\Aimeos\Controller\Jobs\Common\Supplier\Import\Csv\Processor\Iface $processor ) : int
372
	{
373
		$errors = 0;
374
		$context = $this->context();
375
		$manager = \Aimeos\MShop::create( $context, 'supplier' );
376
377
		foreach( $data as $code => $list )
378
		{
379
			$manager->begin();
380
381
			try
382
			{
383
				$code = trim( $code );
384
				$item = $suppliers[$code] ?? $manager->create();
385
				$map = current( $this->getMappedChunk( $list, $mapping ) ); // there can only be one chunk for the base supplier data
386
387
				if( $map )
388
				{
389
					$item->fromArray( $map, true );
390
391
					$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...
392
					$suppliers[$code] = $item;
393
394
					$manager->save( $item );
395
				}
396
397
				$manager->commit();
398
			}
399
			catch( \Exception $e )
400
			{
401
				$manager->rollback();
402
403
				$msg = sprintf( 'Unable to import supplier with code "%1$s": %2$s', $code, $e->getMessage() );
404
				$context->logger()->error( $msg, 'import/csv/supplier' );
405
406
				$errors++;
407
			}
408
		}
409
410
		return $errors;
411
	}
412
413
414
	/**
415
	 * Returns the path to the directory with the CSV file
416
	 *
417
	 * @return string Path to the directory with the CSV file
418
	 */
419
	protected function location() : string
420
	{
421
		/** controller/jobs/supplier/import/csv/location
422
		 * Directory where the CSV files are stored which should be imported
423
		 *
424
		 * It's the relative path inside the "fs-import" virtual file system
425
		 * configuration. The default location of the "fs-import" file system is:
426
		 *
427
		 * * Laravel: ./storage/import/
428
		 * * TYPO3: /uploads/tx_aimeos/.secure/import/
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/jobs/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