Passed
Push — master ( a2156e...434824 )
by Aimeos
03:54
created

Standard::backup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 34
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 34
rs 10
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\Catalog\Import\Csv;
12
13
use \Aimeos\Base\Logger\Base as Log;
0 ignored issues
show
Bug introduced by
The type \Aimeos\Base\Logger\Base was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

603
				$context->logger()->error( 'Not imported: ' . /** @scrutinizer ignore-type */ print_r( $list, true ), 'import/csv/catalog' );
Loading history...
604
			}
605
		}
606
607
		return $errors;
608
	}
609
610
611
	/**
612
	 * Returns the path to the directory with the CSV file
613
	 *
614
	 * @return string Path to the directory with the CSV file
615
	 */
616
	protected function location() : string
617
	{
618
		/** controller/jobs/catalog/import/csv/location
619
		 * File or directory where the content is stored which should be imported
620
		 *
621
		 * You need to configure the CSV file or directory with the CSV files that
622
		 * should be imported. It should be an absolute path to be sure but can be
623
		 * relative path if you absolutely know from where the job will be executed
624
		 * from.
625
		 *
626
		 * @param string Relative path to the CSV files
627
		 * @since 2015.08
628
		 * @see controller/jobs/catalog/import/csv/backup
629
		 * @see controller/jobs/catalog/import/csv/converter
630
		 * @see controller/jobs/catalog/import/csv/domains
631
		 * @see controller/jobs/catalog/import/csv/location
632
		 * @see controller/jobs/catalog/import/csv/mapping
633
		 * @see controller/jobs/catalog/import/csv/max-size
634
		 * @see controller/jobs/catalog/import/csv/skip-lines
635
		 */
636
		return (string) $this->context()->config()->get( 'controller/jobs/catalog/import/csv/location', 'catalog' );
637
	}
638
639
640
	/**
641
	 * Returns the CSV column mapping
642
	 *
643
	 * @return array CSV column mapping
644
	 */
645
	protected function mapping() : array
646
	{
647
		/** controller/jobs/catalog/import/csv/mapping
648
		 * List of mappings between the position in the CSV file and item keys
649
		 *
650
		 * The importer have to know which data is at which position in the CSV
651
		 * file. Therefore, you need to specify a mapping between each position
652
		 * and the MShop domain item key (e.g. "catalog.code") it represents.
653
		 *
654
		 * You can use all domain item keys which are used in the fromArray()
655
		 * methods of the item classes.
656
		 *
657
		 * These mappings are grouped together by their processor names, which
658
		 * are responsible for importing the data, e.g. all mappings in "item"
659
		 * will be processed by the base catalog importer while the mappings in
660
		 * "text" will be imported by the text processor.
661
		 *
662
		 * @param array Associative list of processor names and lists of key/position pairs
663
		 * @since 2018.04
664
		 * @see controller/jobs/catalog/import/csv/backup
665
		 * @see controller/jobs/catalog/import/csv/converter
666
		 * @see controller/jobs/catalog/import/csv/domains
667
		 * @see controller/jobs/catalog/import/csv/location
668
		 * @see controller/jobs/catalog/import/csv/max-size
669
		 * @see controller/jobs/catalog/import/csv/skip-lines
670
		 * @see controller/jobs/catalog/import/csv/strict
671
		 */
672
		return (array) $this->context()->config()->get( 'controller/jobs/catalog/import/csv/mapping', $this->getDefaultMapping() );
673
	}
674
675
676
	/**
677
	 * Returns the maximum number of CSV rows to import at once
678
	 *
679
	 * @return int Maximum number of CSV rows to import at once
680
	 */
681
	protected function max() : int
682
	{
683
		/** controller/jobs/catalog/import/csv/max-size
684
		 * Maximum number of CSV rows to import at once
685
		 *
686
		 * It's more efficient to read and import more than one row at a time
687
		 * to speed up the import. Usually, the bigger the chunk that is imported
688
		 * at once, the less time the importer will need. The downside is that
689
		 * the amount of memory required by the import process will increase as
690
		 * well. Therefore, it's a trade-off between memory consumption and
691
		 * import speed.
692
		 *
693
		 * @param integer Number of rows
694
		 * @since 2018.04
695
		 * @see controller/jobs/catalog/import/csv/backup
696
		 * @see controller/jobs/catalog/import/csv/converter
697
		 * @see controller/jobs/catalog/import/csv/domains
698
		 * @see controller/jobs/catalog/import/csv/location
699
		 * @see controller/jobs/catalog/import/csv/mapping
700
		 * @see controller/jobs/catalog/import/csv/skip-lines
701
		 * @see controller/jobs/catalog/import/csv/strict
702
		 */
703
		return (int) $this->context()->config()->get( 'controller/jobs/catalog/import/csv/max-size', 1000 );
704
	}
705
706
707
	/**
708
	 * Returns the number of rows skipped in front of each CSV files
709
	 *
710
	 * @return int Number of rows skipped in front of each CSV files
711
	 */
712
	protected function skip() : int
713
	{
714
		/** controller/jobs/catalog/import/csv/skip-lines
715
		 * Number of rows skipped in front of each CSV files
716
		 *
717
		 * Some CSV files contain header information describing the content of
718
		 * the column values. These data is for informational purpose only and
719
		 * can't be imported into the database. Using this option, you can
720
		 * define the number of lines that should be left out before the import
721
		 * begins.
722
		 *
723
		 * @param integer Number of rows
724
		 * @since 2015.08
725
		 * @see controller/jobs/catalog/import/csv/backup
726
		 * @see controller/jobs/catalog/import/csv/converter
727
		 * @see controller/jobs/catalog/import/csv/domains
728
		 * @see controller/jobs/catalog/import/csv/location
729
		 * @see controller/jobs/catalog/import/csv/mapping
730
		 * @see controller/jobs/catalog/import/csv/max-size
731
		 * @see controller/jobs/catalog/import/csv/strict
732
		 */
733
		return (int) $this->context()->config()->get( 'controller/jobs/catalog/import/csv/skip-lines', 0 );
734
	}
735
736
737
	/**
738
	 * Returns if all columns from the file should be logged that are not mapped and therefore not imported
739
	 */
740
	protected function strict() : bool
741
	{
742
		/** controller/jobs/catalog/import/csv/strict
743
		 * Log all columns from the file that are not mapped and therefore not imported
744
		 *
745
		 * Depending on the mapping, there can be more columns in the CSV file
746
		 * than those which will be imported. This can be by purpose if you want
747
		 * to import only selected columns or if you've missed to configure one
748
		 * or more columns. This configuration option will log all columns that
749
		 * have not been imported if set to true. Otherwise, the left over fields
750
		 * in the imported line will be silently ignored.
751
		 *
752
		 * @param boolen True if not imported columns should be logged, false if not
753
		 * @since 2015.08
754
		 * @see controller/jobs/catalog/import/csv/backup
755
		 * @see controller/jobs/catalog/import/csv/converter
756
		 * @see controller/jobs/catalog/import/csv/domains
757
		 * @see controller/jobs/catalog/import/csv/location
758
		 * @see controller/jobs/catalog/import/csv/mapping
759
		 * @see controller/jobs/catalog/import/csv/max-size
760
		 * @see controller/jobs/catalog/import/csv/skip-lines
761
		 */
762
		return (bool) $this->context()->config()->get( 'controller/jobs/catalog/import/csv/strict', true );
763
	}
764
}
765