Passed
Push — master ( ce780a...b27fbc )
by Aimeos
03:18
created

Standard::getContainer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 58
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 58
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A Standard::import() 0 37 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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