Passed
Push — master ( 93e002...0990f3 )
by Aimeos
02:39
created

Standard::run()   B

Complexity

Conditions 8
Paths 52

Size

Total Lines 67
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 27
nc 52
nop 0
dl 0
loc 67
rs 8.4444
c 0
b 0
f 0

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), 2019
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
	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()
33
	{
34
		return $this->getContext()->getI18n()->dt( 'controller/jobs', 'Catalog 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()
44
	{
45
		return $this->getContext()->getI18n()->dt( 'controller/jobs', 'Imports new and updates existing categories 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->getContext();
57
		$config = $context->getConfig();
58
		$logger = $context->getLogger();
59
60
		/** controller/jobs/catalog/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/catalog/import/xml/container/type
73
		 * @see controller/jobs/catalog/import/xml/container/content
74
		 * @see controller/jobs/catalog/import/xml/container/options
75
		 */
76
		$location = $config->get( 'controller/jobs/catalog/import/xml/location' );
77
78
		try
79
		{
80
			$msg = sprintf( 'Started catalog import from "%1$s" (%2$s)', $location, __CLASS__ );
81
			$logger->log( $msg, \Aimeos\MW\Logger\Base::INFO );
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(), 'catalog', 7 ) === 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 catalog import from "%1$s": %2$s total (%3$s MB)';
113
			$mem = number_format( memory_get_peak_usage() / 1024 / 1024, 2 );
114
115
			$logger->log( sprintf( $msg, $location, $total, $mem ), \Aimeos\MW\Logger\Base::INFO );
116
		}
117
		catch( \Exception $e )
118
		{
119
			$logger->log( 'Catalog import error: ' . $e->getMessage() . "\n" . $e->getTraceAsString() );
120
			throw $e;
121
		}
122
	}
123
124
125
	/**
126
	 * Imports the XML file given by its path
127
	 *
128
	 * @param string $filename Absolute or relative path to the XML file
129
	 * @return integer Total number of imported catalogs
130
	 */
131
	protected function import( $filename )
132
	{
133
		$context = $this->getContext();
134
		$config = $context->getConfig();
135
		$domains = ['media', 'product', 'text'];
136
137
		/** controller/jobs/catalog/import/xml/domains
138
		 * List of item domain names that should be retrieved along with the catalog items
139
		 *
140
		 * This configuration setting overwrites the shared option
141
		 * "controller/common/catalog/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/catalog/import/xml/backup
149
		 * @see controller/jobs/catalog/import/xml/max-query
150
		 */
151
		$domains = $config->get( 'controller/jobs/catalog/import/xml/domains', $domains );
152
153
		/** controller/jobs/catalog/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 strftime() function to create dynamic paths, e.g. "backup/%Y-%m-%d"
164
		 * which would create "backup/2000-01-01". For more information about the
165
		 * strftime() placeholders, please have a look into the PHP documentation of
166
		 * the {@link http://php.net/manual/en/function.strftime.php strftime() function}.
167
		 *
168
		 * '''Note:''' If no backup name is configured, the file or directory
169
		 * won't be moved away. Please make also sure that the parent directory
170
		 * and the new directory are writable so the file or directory could be
171
		 * moved.
172
		 *
173
		 * @param integer Name of the backup file, optionally with date/time placeholders
174
		 * @since 2019.04
175
		 * @category Developer
176
		 * @see controller/jobs/catalog/import/xml/domains
177
		 * @see controller/jobs/catalog/import/xml/max-query
178
		 */
179
		$backup = $config->get( 'controller/jobs/catalog/import/xml/backup' );
180
181
182
		$xml = new \XMLReader();
183
184
		if( $xml->open( $filename, LIBXML_COMPACT | LIBXML_PARSEHUGE ) === false ) {
185
			throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No XML file "%1$s" found', $filename ) );
186
		}
187
188
		$total = $this->importTree( $xml, $domains );
189
190
		if( !empty( $backup ) && @rename( $filename, strftime( $backup ) ) === false )
191
		{
192
			$msg = sprintf( 'Unable to move imported file "%1$s" to "%2$s"', $filename, $backup );
193
			throw new \Aimeos\Controller\Jobs\Exception( $msg );
194
		}
195
196
		return $total;
197
	}
198
199
200
	/**
201
	 * Imports a single category node
202
	 *
203
	 * @param \DomElement $node DOM node of "catalogitem" element
204
	 * @param string[] $ref List of domain names whose referenced items will be updated in the catalog items
205
	 * @param string|null $parentid ID of the parent catalog node
206
	 * @return array Associative list of catalog codes as keys and category IDs as values
207
	 */
208
	protected function importNode( \DomElement $node, $ref, &$parentid )
209
	{
210
		$manager = \Aimeos\MShop::create( $this->getContext(), 'catalog' );
211
212
		if( ( $attr = $node->attributes->getNamedItem( 'ref' ) ) !== null )
213
		{
214
			try
215
			{
216
				$item = $manager->findItem( $attr->nodeValue, $ref );
217
				$manager->moveItem( $item->getId(), $item->getParentId(), $parentid );
218
219
				$item = $this->process( $item, $node );
220
				$parentid = $manager->saveItem( $item )->getId();
221
				unset( $item );
222
223
				$map = [];
224
				$tree = $manager->getTree( $parentid, [], \Aimeos\MW\Tree\Manager\Base::LEVEL_LIST );
225
226
				foreach( $tree->getChildren() as $child ) {
227
					$map[$child->getCode()] = $child->getId();
228
				}
229
230
				return $map;
231
			}
232
			catch( \Aimeos\MShop\Exception $e ) {} // not found, create new
233
		}
234
235
		$item = $this->process( $manager->createItem(), $node );
0 ignored issues
show
Bug introduced by
$manager->createItem() of type Aimeos\MShop\Attribute\Item\Iface is incompatible with the type Aimeos\MShop\Catalog\Item\Iface expected by parameter $item of Aimeos\Controller\Jobs\C...Xml\Standard::process(). ( Ignorable by Annotation )

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

235
		$item = $this->process( /** @scrutinizer ignore-type */ $manager->createItem(), $node );
Loading history...
236
		$parentid = $manager->insertItem( $item, $parentid )->getId();
237
238
		return [];
239
	}
240
241
242
	/**
243
	 * Imports the catalog document
244
	 *
245
	 * @param \XMLReader $xml Catalog document to import
246
	 * @param string[] $ref List of domain names whose referenced items will be updated in the catalog items
247
	 * @param string|null $parentid ID of the parent catalog node
248
	 * @param array $map Associative list of catalog code as keys and category ID as values
249
	 * @return integer Number of imported categories
250
	 */
251
	protected function importTree( \XMLReader $xml, array $ref, $parentid = null, array $map = [] )
252
	{
253
		$total = 0;
254
		$childMap = [];
255
256
		while( $xml->read() === true )
257
		{
258
			if( $xml->nodeType === \XMLReader::ELEMENT && $xml->name === 'catalogitem' )
259
			{
260
				if( ( $node = $xml->expand() ) === false )
261
				{
262
					$msg = sprintf( 'Expanding "%1$s" node failed', 'catalogitem' );
263
					throw new \Aimeos\Controller\Jobs\Exception( $msg );
264
				}
265
266
				if( ( $attr = $node->attributes->getNamedItem( 'ref' ) ) !== null ) {
267
					unset( $map[$attr->nodeValue] );
268
				}
269
270
				$childMap = $this->importNode( $node, $ref, $parentid );
271
				$total++;
272
			}
273
			elseif( $xml->nodeType === \XMLReader::ELEMENT && $xml->name === 'catalog' )
274
			{
275
				$this->importTree( $xml, $ref, $parentid, $childMap );
276
			}
277
			elseif( $xml->nodeType === \XMLReader::END_ELEMENT && $xml->name === 'catalog' && $map !== [] )
278
			{
279
				\Aimeos\MShop::create( $this->getContext(), 'catalog' )->deleteItems( $map );
280
				break;
281
			}
282
		}
283
284
		return $total;
285
	}
286
287
288
	/**
289
	 * Updates the catalog item and its referenced items using the given DOM node
290
	 *
291
	 * @param \Aimeos\MShop\Catalog\Item\Iface $item Catalog item object to update
292
	 * @param \DomElement $node DOM node used for updateding the catalog item
293
	 * @return \Aimeos\MShop\Catalog\Item\Iface $item Updated catalog item object
294
	 */
295
	protected function process( \Aimeos\MShop\Catalog\Item\Iface $item, \DomElement $node )
296
	{
297
		$list = [];
298
299
		foreach( $node->attributes as $attr ) {
300
			$list[$attr->nodeName] = $attr->nodeValue;
301
		}
302
303
		foreach( $node->childNodes as $tag )
304
		{
305
			if( $tag->nodeName === 'lists' ) {
306
				$item = $this->getProcessor( $tag->nodeName )->process( $item, $tag );
307
			} else {
308
				$list[$tag->nodeName] = $tag->nodeValue;
309
			}
310
		}
311
312
		return $item->fromArray( $list, true );
313
	}
314
}
315