Passed
Push — master ( 659531...28cbe9 )
by Aimeos
03:02
created

Standard::importNodes()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
c 1
b 0
f 0
nc 9
nop 2
dl 0
loc 24
rs 9.2222
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2019-2021
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Supplier\Import\Xml;
12
13
14
/**
15
 * Job controller for XML supplier 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
	use \Aimeos\Controller\Common\Common\Import\Xml\Traits;
25
26
27
	/**
28
	 * Returns the localized name of the job.
29
	 *
30
	 * @return string Name of the job
31
	 */
32
	public function getName() : string
33
	{
34
		return $this->context()->translate( 'controller/jobs', 'Supplier import XML' );
35
	}
36
37
38
	/**
39
	 * Returns the localized description of the job.
40
	 *
41
	 * @return string Description of the job
42
	 */
43
	public function getDescription() : string
44
	{
45
		return $this->context()->translate( 'controller/jobs', 'Imports new and updates existing suppliers from XML files' );
46
	}
47
48
49
	/**
50
	 * Executes the job.
51
	 *
52
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
53
	 */
54
	public function run()
55
	{
56
		$context = $this->context();
57
		$config = $context->config();
58
		$logger = $context->logger();
59
60
		/** controller/jobs/supplier/import/xml/location
61
		 * File or directory where the content is stored which should be imported
62
		 *
63
		 * You need to configure the XML file or directory with the XML files that
64
		 * should be imported. It should be an absolute path to be sure but can be
65
		 * relative path if you absolutely know from where the job will be executed
66
		 * from.
67
		 *
68
		 * @param string Absolute file or directory path
69
		 * @since 2019.04
70
		 * @category Developer
71
		 * @category User
72
		 * @see controller/jobs/supplier/import/xml/container/type
73
		 * @see controller/jobs/supplier/import/xml/container/content
74
		 * @see controller/jobs/supplier/import/xml/container/options
75
		 */
76
		$location = $config->get( 'controller/jobs/supplier/import/xml/location' );
77
78
		try
79
		{
80
			$msg = sprintf( 'Started supplier import from "%1$s" (%2$s)', $location, __CLASS__ );
81
			$logger->info( $msg, 'import/xml/supplier' );
82
83
			if( !file_exists( $location ) )
84
			{
85
				$msg = sprintf( 'File or directory "%1$s" doesn\'t exist', $location );
86
				throw new \Aimeos\Controller\Jobs\Exception( $msg );
87
			}
88
89
			$files = [];
90
91
			if( is_dir( $location ) )
92
			{
93
				foreach( new \DirectoryIterator( $location ) as $entry )
94
				{
95
					if( strncmp( $entry->getFilename(), 'supplier', 8 ) === 0 && $entry->getExtension() === 'xml' ) {
96
						$files[] = $entry->getPathname();
97
					}
98
				}
99
			}
100
			else
101
			{
102
				$files[] = $location;
103
			}
104
105
			sort( $files );
106
			$total = 0;
107
108
			foreach( $files as $filepath ) {
109
				$total += $this->import( $filepath );
110
			}
111
112
			$msg = 'Finished supplier import from "%1$s": %2$s total (%3$s MB)';
113
			$mem = number_format( memory_get_peak_usage() / 1024 / 1024, 2 );
114
115
			$logger->info( sprintf( $msg, $location, $total, $mem ), 'import/xml/supplier' );
116
		}
117
		catch( \Exception $e )
118
		{
119
			$logger->error( 'Supplier import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'import/xml/supplier' );
120
			$this->mail( 'Supplier XML import error', $e->getMessage() . "\n" . $e->getTraceAsString() );
121
			throw $e;
122
		}
123
	}
124
125
126
	/**
127
	 * Imports the XML file given by its path
128
	 *
129
	 * @param string $filename Absolute or relative path to the XML file
130
	 * @return int Total number of imported suppliers
131
	 */
132
	protected function import( string $filename ) : int
133
	{
134
		$context = $this->context();
135
		$config = $context->config();
136
137
		/** controller/jobs/supplier/import/xml/domains
138
		 * List of item domain names that should be retrieved along with the supplier items
139
		 *
140
		 * This configuration setting overwrites the shared option
141
		 * "controller/common/supplier/import/xml/domains" if you need a
142
		 * specific setting for the job controller. Otherwise, you should
143
		 * use the shared option for consistency.
144
		 *
145
		 * @param array Associative list of MShop item domain names
146
		 * @since 2019.04
147
		 * @category Developer
148
		 * @see controller/jobs/supplier/import/xml/backup
149
		 * @see controller/jobs/supplier/import/xml/max-query
150
		 */
151
		$domains = $config->get( 'controller/jobs/supplier/import/xml/domains', [] );
152
153
		/** controller/jobs/supplier/import/xml/backup
154
		 * Name of the backup for sucessfully imported files
155
		 *
156
		 * After a XML file was imported successfully, you can move it to another
157
		 * location, so it won't be imported again and isn't overwritten by the
158
		 * next file that is stored at the same location in the file system.
159
		 *
160
		 * You should use an absolute path to be sure but can be relative path
161
		 * if you absolutely know from where the job will be executed from. The
162
		 * name of the new backup location can contain placeholders understood
163
		 * by the PHP DateTime::format() method (with percent signs prefix) to
164
		 * create dynamic paths, e.g. "backup/%Y-%m-%d" which would create
165
		 * "backup/2000-01-01". For more information about the date() placeholders,
166
		 * please have a look  into the PHP documentation of the
167
		 * {@link https://www.php.net/manual/en/datetime.format.php format() method}.
168
		 *
169
		 * **Note:** If no backup name is configured, the file or directory
170
		 * won't be moved away. Please make also sure that the parent directory
171
		 * and the new directory are writable so the file or directory could be
172
		 * moved.
173
		 *
174
		 * @param integer Name of the backup file, optionally with date/time placeholders
175
		 * @since 2019.04
176
		 * @category Developer
177
		 * @see controller/jobs/supplier/import/xml/domains
178
		 * @see controller/jobs/supplier/import/xml/max-query
179
		 */
180
		$backup = $config->get( 'controller/jobs/supplier/import/xml/backup' );
181
182
		/** controller/jobs/supplier/import/xml/max-query
183
		 * Maximum number of XML nodes processed at once
184
		 *
185
		 * Processing and fetching several supplier items at once speeds up importing
186
		 * the XML files. The more items can be processed at once, the faster the
187
		 * import. More items also increases the memory usage of the importer and
188
		 * thus, this parameter should be low enough to avoid reaching the memory
189
		 * limit of the PHP process.
190
		 *
191
		 * @param integer Number of XML nodes
192
		 * @since 2019.04
193
		 * @category Developer
194
		 * @category User
195
		 * @see controller/jobs/supplier/import/xml/domains
196
		 * @see controller/jobs/supplier/import/xml/backup
197
		 */
198
		$maxquery = $config->get( 'controller/jobs/supplier/import/xml/max-query', 100 );
199
200
		$nodes = [];
201
		$total = $slice = 0;
202
		$xml = new \XMLReader();
203
204
		if( $xml->open( $filename, LIBXML_COMPACT | LIBXML_PARSEHUGE ) === false ) {
205
			throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No XML file "%1$s" found', $filename ) );
206
		}
207
208
		while( $xml->read() === true )
209
		{
210
			if( $xml->depth === 1 && $xml->nodeType === \XMLReader::ELEMENT && $xml->name === 'supplieritem' )
211
			{
212
				if( ( $dom = $xml->expand() ) === false )
213
				{
214
					$msg = sprintf( 'Expanding "%1$s" node failed', 'supplieritem' );
215
					throw new \Aimeos\Controller\Jobs\Exception( $msg );
216
				}
217
218
				$nodes[] = $dom;
219
220
				if( $slice++ >= $maxquery )
221
				{
222
					$this->importNodes( $nodes, $domains );
223
					unset( $nodes );
224
					$nodes = [];
225
					$slice = 0;
226
				}
227
228
				$total++;
229
			}
230
		}
231
232
		$this->importNodes( $nodes, $domains );
233
		unset( $nodes );
234
235
		foreach( $this->getProcessors() as $proc ) {
236
			$proc->finish();
237
		}
238
239
		if( !empty( $backup ) && @rename( $filename, $backup = \Aimeos\MW\Str::strtime( $backup ) ) === false )
240
		{
241
			$msg = sprintf( 'Unable to move imported file "%1$s" to "%2$s"', $filename, $backup );
242
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
243
		}
244
245
		return $total;
246
	}
247
248
249
	/**
250
	 * Imports the given DOM nodes
251
	 *
252
	 * @param \DomElement[] $nodes List of nodes to import
253
	 * @param string[] $ref List of domain names whose referenced items will be updated in the supplier items
254
	 */
255
	protected function importNodes( array $nodes, array $ref )
256
	{
257
		$codes = [];
258
259
		foreach( $nodes as $node )
260
		{
261
			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

261
			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...
262
				$codes[$attr->nodeValue] = null;
263
			}
264
		}
265
266
		$manager = \Aimeos\MShop::create( $this->context(), 'supplier' );
267
		$search = $manager->filter()->slice( 0, count( $codes ) )->add( ['supplier.code' => array_keys( $codes )] );
268
		$map = $manager->search( $search, $ref )->col( null, 'supplier.code' );
269
270
		foreach( $nodes as $node )
271
		{
272
			if( ( $attr = $node->attributes->getNamedItem( 'ref' ) ) !== null && isset( $map[$attr->nodeValue] ) ) {
273
				$item = $this->process( $map[$attr->nodeValue], $node );
0 ignored issues
show
Bug introduced by
It seems like $map[$attr->nodeValue] can also be of type null; however, parameter $item of Aimeos\Controller\Jobs\S...Xml\Standard::process() does only seem to accept Aimeos\MShop\Supplier\Item\Iface, maybe add an additional type check? ( Ignorable by Annotation )

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

273
				$item = $this->process( /** @scrutinizer ignore-type */ $map[$attr->nodeValue], $node );
Loading history...
274
			} else {
275
				$item = $this->process( $manager->create(), $node );
276
			}
277
278
			$manager->save( $item );
279
		}
280
	}
281
282
283
	/**
284
	 * Updates the supplier item and its referenced items using the given DOM node
285
	 *
286
	 * @param \Aimeos\MShop\Supplier\Item\Iface $item Supplier item object to update
287
	 * @param \DomElement $node DOM node used for updateding the supplier item
288
	 * @return \Aimeos\MShop\Supplier\Item\Iface $item Updated supplier item object
289
	 */
290
	protected function process( \Aimeos\MShop\Supplier\Item\Iface $item, \DomElement $node ) : \Aimeos\MShop\Supplier\Item\Iface
291
	{
292
		try
293
		{
294
			$list = [];
295
296
			foreach( $node->attributes as $attr ) {
297
				$list[$attr->nodeName] = $attr->nodeValue;
298
			}
299
300
			foreach( $node->childNodes as $tag )
301
			{
302
				if( in_array( $tag->nodeName, ['address', 'lists', 'property'] ) ) {
303
					$item = $this->getProcessor( $tag->nodeName )->process( $item, $tag );
304
				} elseif( $tag->nodeName[0] !== '#' ) {
305
					$list[$tag->nodeName] = $tag->nodeValue;
306
				}
307
			}
308
309
			$item->fromArray( $list, true );
310
		}
311
		catch( \Exception $e )
312
		{
313
			$msg = 'Supplier import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString();
314
			$this->context()->logger()->error( $msg, 'import/xml/supplier' );
315
		}
316
317
		return $item;
318
	}
319
}
320