Passed
Push — master ( 45b8af...9db7c4 )
by Aimeos
04:30
created

Standard::location()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
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 18
rs 10
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2017-2024
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Coupon\Import\Csv\Code;
12
13
14
/**
15
 * Job controller for CSV coupon imports.
16
 *
17
 * @package Controller
18
 * @subpackage Jobs
19
 */
20
class Standard
21
	extends \Aimeos\Controller\Jobs\Common\Coupon\Import\Csv\Base
22
	implements \Aimeos\Controller\Jobs\Iface
23
{
24
	/** controller/jobs/coupon/import/csv/code/name
25
	 * Class name of the used coupon code import job 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\Coupon\Import\Csv\Code\Standard
35
	 *
36
	 * and you want to replace it with your own version named
37
	 *
38
	 *  \Aimeos\Controller\Jobs\Coupon\Import\Csv\Code\Mycsv
39
	 *
40
	 * then you have to set the this configuration option:
41
	 *
42
	 *  controller/jobs/coupon/import/csv/code/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 2017.10
55
	 */
56
57
	/** controller/jobs/coupon/import/csv/code/decorators/excludes
58
	 * Excludes decorators added by the "common" option from the coupon code 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/coupon/import/csv/code/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 2017.10
77
	 * @see controller/jobs/common/decorators/default
78
	 * @see controller/jobs/coupon/import/csv/code/decorators/global
79
	 * @see controller/jobs/coupon/import/csv/code/decorators/local
80
	 */
81
82
	/** controller/jobs/coupon/import/csv/code/decorators/global
83
	 * Adds a list of globally available decorators only to the coupon code 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/coupon/import/csv/code/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 2017.10
100
	 * @see controller/jobs/common/decorators/default
101
	 * @see controller/jobs/coupon/import/csv/code/decorators/excludes
102
	 * @see controller/jobs/coupon/import/csv/code/decorators/local
103
	 */
104
105
	/** controller/jobs/coupon/import/csv/code/decorators/local
106
	 * Adds a list of local decorators only to the coupon code 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\Coupon\Import\Csv\Code\Decorator\*") around the job
115
	 * controller.
116
	 *
117
	 *  controller/jobs/coupon/import/csv/code/decorators/local = array( 'decorator2' )
118
	 *
119
	 * This would add the decorator named "decorator2" defined by
120
	 * "\Aimeos\Controller\Jobs\Coupon\Import\Csv\Code\Decorator\Decorator2"
121
	 * only to the job controller.
122
	 *
123
	 * @param array List of decorator names
124
	 * @since 2017.10
125
	 * @see controller/jobs/common/decorators/default
126
	 * @see controller/jobs/coupon/import/csv/code/decorators/excludes
127
	 * @see controller/jobs/coupon/import/csv/code/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', 'Coupon code 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 coupon code 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
		$process = $context->process();
163
164
		try
165
		{
166
			$fs = $context->fs( 'fs-import' );
167
			$site = $context->locale()->getSiteCode();
0 ignored issues
show
Bug introduced by
The method getSiteCode() does not exist on Aimeos\MShop\Locale\Item\Iface. Did you maybe mean getSiteId()? ( Ignorable by Annotation )

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

167
			$site = $context->locale()->/** @scrutinizer ignore-call */ getSiteCode();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
168
			$location = $this->location() . '/' . $site;
169
170
			if( $fs->isDir( $location ) === false ) {
171
				return;
172
			}
173
174
			$logger->info( sprintf( 'Started coupon/code import from "%1$s"', $location ), 'import/csv/coupon/code' );
175
176
			$fcn = function( \Aimeos\MShop\ContextIface $context, $couponId, $fhandle, $path ) {
177
				$this->process( $context, $couponId, $fhandle, $path );
178
			};
179
180
			foreach( map( $fs->scan( $location ) )->sort() as $filename )
181
			{
182
				$path = $location . '/' . $filename;
183
184
				if( $filename[0] === '.' || $fs instanceof \Aimeos\Base\Filesystem\DirIface && $fs->isDir( $path ) ) {
185
					continue;
186
				}
187
188
				list( $couponId,) = explode( '.', $filename );
189
190
				$process->start( $fcn, [$context, $couponId, $fs->reads( $path ), $path] );
191
			}
192
193
			$process->wait();
194
195
			$logger->info( sprintf( 'Finished coupon/code import from "%1$s"', $location ), 'import/csv/coupon/code' );
196
		}
197
		catch( \Exception $e )
198
		{
199
			$logger->error( 'Coupon import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'import/csv/couponcode' );
200
			$this->mail( 'Coupon CSV import error', $e->getMessage() . "\n" . $e->getTraceAsString() );
201
			throw $e;
202
		}
203
	}
204
205
206
	/**
207
	 * Returns the position of the "coupon.code" column from the coupon item mapping
208
	 *
209
	 * @param array $mapping Mapping of the "item" columns with position as key and code as value
210
	 * @return int Position of the "coupon.code" column
211
	 * @throws \Aimeos\Controller\Jobs\Exception If no mapping for "coupon.code.code" is found
212
	 */
213
	protected function getCodePosition( array $mapping ) : int
214
	{
215
		foreach( $mapping as $pos => $key )
216
		{
217
			if( $key === 'coupon.code.code' ) {
218
				return $pos;
219
			}
220
		}
221
222
		throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No "coupon.code.code" column in CSV mapping found' ) );
223
	}
224
225
226
	/**
227
	 * Imports the CSV data and creates new coupons or updates existing ones
228
	 *
229
	 * @param \Aimeos\MShop\Coupon\Item\Code\Iface[] $items List of coupons code items
230
	 * @param array $data Associative list of import data as index/value pairs
231
	 * @param string $couponId ID of the coupon item the coupon code should be added to
232
	 * @param \Aimeos\Controller\Jobs\Common\Coupon\Import\Csv\Processor\Iface $processor Processor object
233
	 * @return int Number of coupons that couldn't be imported
234
	 * @throws \Aimeos\Controller\Jobs\Exception
235
	 */
236
	protected function import( array $items, array $data, string $couponId,
237
		\Aimeos\Controller\Jobs\Common\Coupon\Import\Csv\Processor\Iface $processor ) : int
238
	{
239
		$errors = 0;
240
		$context = $this->context();
241
		$manager = \Aimeos\MShop::create( $context, 'coupon/code' );
242
243
		foreach( $data as $code => $list )
244
		{
245
			$manager->begin();
246
247
			try
248
			{
249
				if( isset( $items[$code] ) ) {
250
					$item = $items[$code];
251
				} else {
252
					$item = $manager->create();
253
				}
254
255
				$item->setParentId( $couponId );
256
				$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...
257
258
				$manager->commit();
259
			}
260
			catch( \Exception $e )
261
			{
262
				$manager->rollback();
263
264
				$str = 'Unable to import coupon with code "%1$s": %2$s';
265
				$msg = sprintf( $str, $code, $e->getMessage() . "\n" . $e->getTraceAsString() );
266
				$context->logger()->error( $msg, 'import/csv/coupon/code' );
267
268
				$errors++;
269
			}
270
		}
271
272
		return $errors;
273
	}
274
275
276
	/**
277
	 * Imports content from the given container
278
	 *
279
	 * @param \Aimeos\MShop\ContextIface $context Context object
280
	 * @param string $couponId Unique coupon ID the codes should be imported for
281
	 * @param resource $fhandle File handle of file to import
282
	 * @param string $path Path to the container file
283
	 */
284
	protected function process( \Aimeos\MShop\ContextIface $context, string $couponId, $fhandle, string $path )
285
	{
286
		$total = $errors = 0;
287
		$logger = $context->logger();
288
289
		$maxcnt = $this->size();
290
		$skiplines = $this->skip();
291
		$mappings = $this->mapping();
292
293
294
		$logger->info( sprintf( 'Started coupon code import from "%1$s"', $path ), 'import/csv/couponcode' );
295
296
		$processor = $this->getProcessors( $mappings );
297
		$codePos = $this->getCodePosition( $mappings['code'] );
298
299
		for( $i = 0; $i < $skiplines; $i++ ) {
300
			fgetcsv( $fhandle );
301
		}
302
303
		while( ( $data = $this->getData( $fhandle, $maxcnt, $codePos ) ) !== [] )
304
		{
305
			$items = $this->getCouponCodeItems( array_keys( $data ) );
306
			$errors += $this->import( $items, $data, $couponId, $processor );
307
308
			$total += count( $data );
309
			unset( $items, $data );
310
		}
311
312
		fclose( $fhandle );
313
		$context->fs( 'fs-import' )->rm( $path );
314
315
		$str = 'Finished coupon import: %1$d successful, %2$s errors, %3$s total';
316
		$logger->info( sprintf( $str, $total - $errors, $errors, $total ), 'import/csv/couponcode' );
317
	}
318
319
320
	/**
321
	 * Returns the path to the directory with the CSV file
322
	 *
323
	 * @return string Path to the directory with the CSV file
324
	 */
325
	protected function location() : string
326
	{
327
		/** controller/jobs/coupon/import/csv/code/location
328
		 * Directory where the CSV files are stored which should be imported
329
		 *
330
		 * It's the relative path inside the "fs-import" virtual file system
331
		 * configuration. The default location of the "fs-import" file system is:
332
		 *
333
		 * * Laravel: ./storage/import/
334
		 * * TYPO3: /uploads/tx_aimeos/.secure/import/
335
		 *
336
		 * @param string Relative path to the CSV files
337
		 * @since 2024.04
338
		 * @see controller/jobs/coupon/import/csv/code/mapping
339
		 * @see controller/jobs/coupon/import/csv/code/max-size
340
		 * @see controller/jobs/coupon/import/csv/code/skip-lines
341
		 */
342
		return (string) $this->context()->config()->get( 'controller/jobs/coupon/import/csv/code/location', 'couponcode' );
343
	}
344
345
346
	/**
347
	 * Returns the column mapping
348
	 *
349
	 * @return array Mapping of the columns
350
	 */
351
	protected function mapping() : array
352
	{
353
		/** controller/jobs/coupon/import/csv/code/mapping
354
		 * List of mappings between the position in the CSV file and item keys
355
		 *
356
		 * This configuration setting overwrites the shared option
357
		 * "controller/jobs/coupon/import/csv/mapping" if you need a
358
		 * specific setting for the job controller. Otherwise, you should
359
		 * use the shared option for consistency.
360
		 *
361
		 * @param array Associative list of processor names and lists of key/position pairs
362
		 * @since 2017.10
363
		 * @see controller/jobs/coupon/import/csv/code/location
364
		 * @see controller/jobs/coupon/import/csv/code/max-size
365
		 * @see controller/jobs/coupon/import/csv/code/skip-lines
366
		 */
367
		return $this->context()->config()->get( 'controller/jobs/coupon/import/csv/code/mapping', $this->getDefaultMapping() );
368
	}
369
370
371
	/**
372
	 * Returns the maximum number of items processed at once
373
	 *
374
	 * @return int Maximum number of items
375
	 */
376
	protected function size() : int
377
	{
378
		/** controller/jobs/coupon/import/csv/code/max-size
379
		 * Maximum number of CSV rows to import at once
380
		 *
381
		 * It's more efficient to read and import more than one row at a time
382
		 * to speed up the import. Usually, the bigger the chunk that is imported
383
		 * at once, the less time the importer will need. The downside is that
384
		 * the amount of memory required by the import process will increase as
385
		 * well. Therefore, it's a trade-off between memory consumption and
386
		 * import speed.
387
		 *
388
		 * @param integer Number of rows
389
		 * @since 2017.10
390
		 * @see controller/jobs/coupon/import/csv/code/location
391
		 * @see controller/jobs/coupon/import/csv/code/mapping
392
		 * @see controller/jobs/coupon/import/csv/code/skip-lines
393
		 */
394
		return (int) $this->context()->config()->get( 'controller/jobs/coupon/import/csv/code/max-size', 1000 );
395
	}
396
397
398
	/**
399
	 * Returns the number of lines to skip at the beginning of the file
400
	 *
401
	 * @return int Number of linees to skip
402
	 */
403
	protected function skip() : int
404
	{
405
		/** controller/jobs/coupon/import/csv/code/skip-lines
406
		 * Number of rows skipped in front of each CSV files
407
		 *
408
		 * Some CSV files contain header information describing the content of
409
		 * the column values. These data is for informational purpose only and
410
		 * can't be imported into the database. Using this option, you can
411
		 * define the number of lines that should be left out before the import
412
		 * begins.
413
		 *
414
		 * @param integer Number of rows
415
		 * @since 2015.08
416
		 * @see controller/jobs/coupon/import/csv/code/location
417
		 * @see controller/jobs/coupon/import/csv/code/mapping
418
		 * @see controller/jobs/coupon/import/csv/code/max-size
419
		 */
420
		return (int) $this->context()->config()->get( 'controller/jobs/coupon/import/csv/code/skip-lines', 0 );
421
	}
422
}
423