Standard::importTree()   B
last analyzed

Complexity

Conditions 10
Paths 7

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 18
nc 7
nop 4
dl 0
loc 32
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

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), 2019-2025
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Catalog\Import\Xml;
12
13
14
/**
15
 * Job controller for XML catalog imports
16
 *
17
 * @package Controller
18
 * @subpackage Jobs
19
 */
20
class Standard
21
	extends \Aimeos\Controller\Jobs\Base
22
	implements \Aimeos\Controller\Jobs\Iface
23
{
24
	/** controller/jobs/catalog/import/xml/name
25
	 * Class name of the used catalog 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\Catalog\Import\Xml\Standard
35
	 *
36
	 * and you want to replace it with your own version named
37
	 *
38
	 *  \Aimeos\Controller\Jobs\Catalog\Import\Xml\Myxml
39
	 *
40
	 * then you have to set the this configuration option:
41
	 *
42
	 *  controller/jobs/catalog/import/xml/name = Myxml
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 "MyXml"!
52
	 *
53
	 * @param string Last part of the class name
54
	 * @since 2019.04
55
	 */
56
57
	/** controller/jobs/catalog/import/xml/decorators/excludes
58
	 * Excludes decorators added by the "common" option from the catalog 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/catalog/import/xml/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 2019.04
77
	 * @see controller/jobs/common/decorators/default
78
	 * @see controller/jobs/catalog/import/xml/decorators/global
79
	 * @see controller/jobs/catalog/import/xml/decorators/local
80
	 */
81
82
	/** controller/jobs/catalog/import/xml/decorators/global
83
	 * Adds a list of globally available decorators only to the catalog 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/catalog/import/xml/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 2019.04
100
	 * @see controller/jobs/common/decorators/default
101
	 * @see controller/jobs/catalog/import/xml/decorators/excludes
102
	 * @see controller/jobs/catalog/import/xml/decorators/local
103
	 */
104
105
	/** controller/jobs/catalog/import/xml/decorators/local
106
	 * Adds a list of local decorators only to the catalog 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\Catalog\Import\Xml\Decorator\*") around the job
115
	 * controller.
116
	 *
117
	 *  controller/jobs/catalog/import/xml/decorators/local = array( 'decorator2' )
118
	 *
119
	 * This would add the decorator named "decorator2" defined by
120
	 * "\Aimeos\Controller\Jobs\Catalog\Import\Xml\Decorator\Decorator2"
121
	 * only to the job controller.
122
	 *
123
	 * @param array List of decorator names
124
	 * @since 2019.04
125
	 * @see controller/jobs/common/decorators/default
126
	 * @see controller/jobs/catalog/import/xml/decorators/excludes
127
	 * @see controller/jobs/catalog/import/xml/decorators/global
128
	 */
129
130
131
	use \Aimeos\Controller\Jobs\Common\Types;
132
	use \Aimeos\Controller\Jobs\Common\Import\Xml\Traits;
133
134
135
	/**
136
	 * Returns the localized name of the job.
137
	 *
138
	 * @return string Name of the job
139
	 */
140
	public function getName() : string
141
	{
142
		return $this->context()->translate( 'controller/jobs', 'Catalog import XML' );
143
	}
144
145
146
	/**
147
	 * Returns the localized description of the job.
148
	 *
149
	 * @return string Description of the job
150
	 */
151
	public function getDescription() : string
152
	{
153
		return $this->context()->translate( 'controller/jobs', 'Imports new and updates existing categories from XML files' );
154
	}
155
156
157
	/**
158
	 * Executes the job.
159
	 *
160
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
161
	 */
162
	public function run()
163
	{
164
		$context = $this->context();
165
		$logger = $context->logger();
166
167
		try
168
		{
169
			$fs = $context->fs( 'fs-import' );
170
			$site = $context->locale()->getSiteItem()->getCode();
171
			$location = $this->location() . '/' . $site;
172
173
			if( $fs->isDir( $location ) === false ) {
174
				return;
175
			}
176
177
			$logger->info( sprintf( 'Started catalog import from "%1$s"', $location ), 'import/xml/catalog' );
178
179
			foreach( map( $fs->scan( $location ) )->sort() as $filename )
180
			{
181
				$path = $location . '/' . $filename;
182
183
				if( $filename[0] === '.' || $fs instanceof \Aimeos\Base\Filesystem\DirIface && $fs->isDir( $path ) ) {
184
					continue;
185
				}
186
187
				$this->import( $path );
188
			}
189
190
			$logger->info( sprintf( 'Finished catalog import from "%1$s"', $location ), 'import/xml/catalog' );
191
		}
192
		catch( \Exception $e )
193
		{
194
			$logger->error( 'Catalog import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'import/xml/catalog' );
195
			$this->mail( 'Catalog XML import error', $e->getMessage() . "\n" . $e->getTraceAsString() );
196
			throw $e;
197
		}
198
	}
199
200
201
	/**
202
	 * Returns the directory for storing imported files
203
	 *
204
	 * @return string Directory for storing imported files
205
	 */
206
	protected function backup() : string
207
	{
208
		/** controller/jobs/catalog/import/xml/backup
209
		 * Name of the backup for sucessfully imported files
210
		 *
211
		 * After a XML file was imported successfully, you can move it to another
212
		 * location, so it won't be imported again and isn't overwritten by the
213
		 * next file that is stored at the same location in the file system.
214
		 *
215
		 * You should use an absolute path to be sure but can be relative path
216
		 * if you absolutely know from where the job will be executed from. The
217
		 * name of the new backup location can contain placeholders understood
218
		 * by the PHP DateTime::format() method (with percent signs prefix) to
219
		 * create dynamic paths, e.g. "backup/%Y-%m-%d" which would create
220
		 * "backup/2000-01-01". For more information about the date() placeholders,
221
		 * please have a look  into the PHP documentation of the
222
		 * {@link https://www.php.net/manual/en/datetime.format.php format() method}.
223
		 *
224
		 * **Note:** If no backup name is configured, the file will be removed!
225
		 *
226
		 * @param integer Name of the backup file, optionally with date/time placeholders
227
		 * @since 2019.04
228
		 * @see controller/jobs/catalog/import/xml/domains
229
		 * @see controller/jobs/catalog/import/xml/location
230
		 * @see controller/jobs/catalog/import/xml/max-query
231
		 */
232
		$backup = $this->context()->config()->get( 'controller/jobs/catalog/import/xml/backup' );
233
		return \Aimeos\Base\Str::strtime( (string) $backup );
234
	}
235
236
237
	/**
238
	 * Returns the list of domain names that should be retrieved along with the catalog items
239
	 *
240
	 * @return array List of domain names
241
	 */
242
	protected function domains() : array
243
	{
244
		/** controller/jobs/catalog/import/xml/domains
245
		 * List of item domain names that should be retrieved along with the catalog items
246
		 *
247
		 * For efficient processing, the items associated to the products can be
248
		 * fetched to, minimizing the number of database queries required. To be
249
		 * most effective, the list of item domain names should be used in the
250
		 * mapping configuration too, so the retrieved items will be used during
251
		 * the import.
252
		 *
253
		 * @param array Associative list of MShop item domain names
254
		 * @since 2019.04
255
		 * @see controller/jobs/catalog/import/xml/backup
256
		 * @see controller/jobs/catalog/import/xml/location
257
		 * @see controller/jobs/catalog/import/xml/max-query
258
		 */
259
		return $this->context()->config()->get( 'controller/jobs/catalog/import/xml/domains', ['media', 'text'] );
260
	}
261
262
263
	/**
264
	 * Imports the XML file given by its path
265
	 *
266
	 * @param string $path Relative path to the XML file in the file system
267
	 */
268
	protected function import( string $path )
269
	{
270
		$xml = new \XMLReader();
271
		$context = $this->context();
272
		$logger = $context->logger();
273
274
		$fs = $context->fs( 'fs-import' );
275
		$tmpfile = $fs->readf( $path );
276
277
		if( $xml->open( $tmpfile, null, LIBXML_COMPACT | LIBXML_PARSEHUGE ) === false ) {
278
			throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No XML file "%1$s" found', $tmpfile ) );
279
		}
280
281
		$logger->info( sprintf( 'Started catalog import from file "%1$s"', $path ), 'import/xml/catalog' );
282
283
		$this->importTree( $xml, $this->domains() );
284
		$this->saveTypes();
285
286
		foreach( $this->getProcessors() as $proc ) {
287
			$proc->finish();
288
		}
289
290
		unlink( $tmpfile );
291
292
		if( !empty( $backup = $this->backup() ) ) {
293
			$fs->move( $path, $backup );
294
		} else {
295
			$fs->rm( $path );
296
		}
297
298
		$logger->info( sprintf( 'Finished catalog import from file "%1$s"', $path ), 'import/xml/catalog' );
299
	}
300
301
302
	/**
303
	 * Imports a single category node
304
	 *
305
	 * @param \DomElement $node DOM node of "catalogitem" element
306
	 * @param string[] $domains List of domain names whose referenced items will be updated in the catalog items
307
	 * @param string|null $parentid ID of the parent catalog node
308
	 * @param array &$map Will contain the associative list of code/ID pairs of the child categories
309
	 * @return string Catalog ID of the imported category
310
	 */
311
	protected function importNode( \DomElement $node, array $domains, ?string $parentid, array &$map ) : string
312
	{
313
		$manager = \Aimeos\MShop::create( $this->context(), 'catalog' );
314
315
		if( ( $attr = $node->attributes->getNamedItem( 'ref' ) ) !== null )
0 ignored issues
show
Bug introduced by
The method getNamedItem() does not exist on null. ( Ignorable by Annotation )

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

315
		if( ( $attr = $node->attributes->/** @scrutinizer ignore-call */ getNamedItem( 'ref' ) ) !== null )

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...
316
		{
317
			try
318
			{
319
				$item = $manager->find( $attr->nodeValue, $domains );
320
				$manager->move( $item->getId(), $item->getParentId(), $parentid );
321
322
				$item = $this->process( $item, $node );
323
				$currentid = $manager->save( $item )->getId();
324
				unset( $item );
325
326
				$tree = $manager->getTree( $currentid, [], \Aimeos\MW\Tree\Manager\Base::LEVEL_LIST );
327
328
				foreach( $tree->getChildren() as $child ) {
329
					$map[$child->getCode()] = $child->getId();
330
				}
331
332
				return $currentid;
333
			}
334
			catch( \Aimeos\MShop\Exception $e ) {} // not found, create new
335
		}
336
337
		$item = $this->process( $manager->create(), $node );
338
		return $manager->insert( $item, $parentid )->getId();
339
	}
340
341
342
	/**
343
	 * Imports the catalog document
344
	 *
345
	 * @param \XMLReader $xml Catalog document to import
346
	 * @param string[] $domains List of domain names whose referenced items will be updated in the catalog items
347
	 * @param string|null $parentid ID of the parent catalog node
348
	 * @param array $map Associative list of catalog code as keys and category ID as values
349
	 */
350
	protected function importTree( \XMLReader $xml, array $domains, ?string $parentid = null, array $map = [] )
351
	{
352
		$total = 0;
353
		$childMap = [];
354
		$currentid = $parentid;
355
356
		while( $xml->read() === true )
357
		{
358
			if( $xml->nodeType === \XMLReader::ELEMENT && $xml->name === 'catalogitem' )
359
			{
360
				if( ( $node = $xml->expand() ) === false )
361
				{
362
					$msg = sprintf( 'Expanding "%1$s" node failed', 'catalogitem' );
363
					throw new \Aimeos\Controller\Jobs\Exception( $msg );
364
				}
365
366
				if( ( $attr = $node->attributes->getNamedItem( 'ref' ) ) !== null ) {
367
					unset( $map[$attr->nodeValue] );
368
				}
369
370
				$currentid = $this->importNode( $node, $domains, $parentid, $childMap );
371
				$total++;
372
			}
373
			elseif( $xml->nodeType === \XMLReader::ELEMENT && $xml->name === 'catalog' )
374
			{
375
				$this->importTree( $xml, $domains, $currentid, $childMap );
376
				$childMap = [];
377
			}
378
			elseif( $xml->nodeType === \XMLReader::END_ELEMENT && $xml->name === 'catalog' )
379
			{
380
				\Aimeos\MShop::create( $this->context(), 'catalog' )->delete( $map );
381
				break;
382
			}
383
		}
384
	}
385
386
387
	/**
388
	 * Returns the path to the directory with the XML file
389
	 *
390
	 * @return string Path to the directory with the XML file
391
	 */
392
	protected function location() : string
393
	{
394
		/** controller/jobs/catalog/import/xml/location
395
		 * Directory where the CSV files are stored which should be imported
396
		 *
397
		 * It's the relative path inside the "fs-import" virtual file system
398
		 * configuration. The default location of the "fs-import" file system is:
399
		 *
400
		 * * Laravel: ./storage/import/
401
		 * * TYPO3: /uploads/tx_aimeos/.secure/import/
402
		 *
403
		 * @param string Relative path to the XML files
404
		 * @since 2019.04
405
		 * @see controller/jobs/catalog/import/xml/backup
406
		 * @see controller/jobs/catalog/import/xml/domains
407
		 * @see controller/jobs/catalog/import/xml/max-query
408
		 */
409
		return (string) $this->context()->config()->get( 'controller/jobs/catalog/import/xml/location', 'catalog' );
410
	}
411
412
413
	/**
414
	 * Updates the catalog item and its referenced items using the given DOM node
415
	 *
416
	 * @param \Aimeos\MShop\Catalog\Item\Iface $item Catalog item object to update
417
	 * @param \DomElement $node DOM node used for updateding the catalog item
418
	 * @return \Aimeos\MShop\Catalog\Item\Iface $item Updated catalog item object
419
	 */
420
	protected function process( \Aimeos\MShop\Catalog\Item\Iface $item, \DomElement $node ) : \Aimeos\MShop\Catalog\Item\Iface
421
	{
422
		try
423
		{
424
			$list = [];
425
426
			foreach( $node->attributes as $attr ) {
427
				$list[$attr->nodeName] = $attr->nodeValue;
428
			}
429
430
			foreach( $node->childNodes as $tag )
431
			{
432
				if( $tag->nodeName === 'lists' ) {
433
					$item = $this->getProcessor( $tag->nodeName )->process( $item, $tag );
434
				} elseif( $tag->nodeName[0] !== '#' ) {
435
					$list[$tag->nodeName] = $tag->nodeValue;
436
				}
437
			}
438
439
			$list['catalog.config'] = isset( $list['catalog.config'] ) ? json_decode( $list['catalog.config'], true ) : [];
440
			$item->fromArray( $list, true );
441
		}
442
		catch( \Exception $e )
443
		{
444
			$msg = 'Catalog import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString();
445
			$this->context()->logger()->error( $msg, 'import/xml/catalog' );
446
		}
447
448
		return $item;
449
	}
450
}
451