Passed
Push — master ( 7c4495...5a52ba )
by Aimeos
04:17
created

Standard   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 1035
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 60
eloc 326
c 2
b 0
f 0
dl 0
loc 1035
rs 3.6

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 26 5
A delete() 0 28 6
A move() 0 24 2
A get() 0 3 1
A search() 0 184 6
A saveItem() 0 16 2
A filter() 0 3 1
A insert() 0 25 2
A find() 0 4 1
A clear() 0 56 2
A getSearchAttributes() 0 22 1
A getResourceType() 0 4 1
A create() 0 4 1
A saveChildren() 0 26 5
A updateUsage() 0 131 4
A getSubManager() 0 3 1
A lock() 0 28 2
A getPath() 0 33 6
B getTree() 0 58 9
A unlock() 0 29 2

How to fix   Complexity   

Complex Class

Complex classes like Standard often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Standard, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Metaways Infosystems GmbH, 2011
6
 * @copyright Aimeos (aimeos.org), 2015-2022
7
 * @package MShop
8
 * @subpackage Catalog
9
 */
10
11
12
namespace Aimeos\MShop\Catalog\Manager;
13
14
15
/**
16
 * Catalog manager with methods for managing categories products, text, media.
17
 *
18
 * @package MShop
19
 * @subpackage Catalog
20
 */
21
class Standard extends Base
22
	implements \Aimeos\MShop\Catalog\Manager\Iface, \Aimeos\MShop\Common\Manager\Factory\Iface
23
{
24
	private $searchConfig = array(
25
		'id' => array(
26
			'code' => 'catalog.id',
27
			'internalcode' => 'mcat."id"',
28
			'label' => 'ID',
29
			'type' => 'integer',
30
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
31
			'public' => false,
32
		),
33
		'catalog.siteid' => array(
34
			'code' => 'catalog.siteid',
35
			'internalcode' => 'mcat."siteid"',
36
			'label' => 'Site ID',
37
			'type' => 'string',
38
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
39
			'public' => false,
40
		),
41
		'parentid' => array(
42
			'code' => 'catalog.parentid',
43
			'internalcode' => 'mcat."parentid"',
44
			'label' => 'Parent ID',
45
			'type' => 'integer',
46
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
47
			'public' => false,
48
		),
49
		'level' => array(
50
			'code' => 'catalog.level',
51
			'internalcode' => 'mcat."level"',
52
			'label' => 'Tree level',
53
			'type' => 'integer',
54
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
55
			'public' => false,
56
		),
57
		'left' => array(
58
			'code' => 'catalog.left',
59
			'internalcode' => 'mcat."nleft"',
60
			'label' => 'Left value',
61
			'type' => 'integer',
62
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
63
			'public' => false,
64
		),
65
		'right' => array(
66
			'code' => 'catalog.right',
67
			'internalcode' => 'mcat."nright"',
68
			'label' => 'Right value',
69
			'type' => 'integer',
70
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
71
			'public' => false,
72
		),
73
		'label' => array(
74
			'code' => 'catalog.label',
75
			'internalcode' => 'mcat."label"',
76
			'label' => 'Label',
77
			'type' => 'string',
78
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
79
		),
80
		'code' => array(
81
			'code' => 'catalog.code',
82
			'internalcode' => 'mcat."code"',
83
			'label' => 'Code',
84
			'type' => 'string',
85
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
86
		),
87
		'status' => array(
88
			'code' => 'catalog.status',
89
			'internalcode' => 'mcat."status"',
90
			'label' => 'Status',
91
			'type' => 'integer',
92
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
93
		),
94
		'catalog.url' => array(
95
			'code' => 'catalog.url',
96
			'internalcode' => 'mcat."url"',
97
			'label' => 'URL segment',
98
			'type' => 'string',
99
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
100
		),
101
		'catalog.target' => array(
102
			'code' => 'catalog.target',
103
			'internalcode' => 'mcat."target"',
104
			'label' => 'URL target',
105
			'type' => 'string',
106
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
107
		),
108
		'catalog.config' => array(
109
			'code' => 'catalog.config',
110
			'internalcode' => 'mcat."config"',
111
			'label' => 'Config',
112
			'type' => 'string',
113
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
114
			'public' => false,
115
		),
116
		'catalog.ctime' => array(
117
			'label' => 'Create date/time',
118
			'code' => 'catalog.ctime',
119
			'internalcode' => 'mcat."ctime"',
120
			'type' => 'datetime',
121
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
122
			'public' => false,
123
		),
124
		'catalog.mtime' => array(
125
			'label' => 'Modify date/time',
126
			'code' => 'catalog.mtime',
127
			'internalcode' => 'mcat."mtime"',
128
			'type' => 'datetime',
129
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
130
			'public' => false,
131
		),
132
		'catalog.editor' => array(
133
			'code' => 'catalog.editor',
134
			'internalcode' => 'mcat."editor"',
135
			'label' => 'Editor',
136
			'type' => 'string',
137
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
138
			'public' => false,
139
		),
140
		'catalog:has' => array(
141
			'code' => 'catalog:has()',
142
			'internalcode' => ':site AND :key AND mcatli."id"',
143
			'internaldeps' => ['LEFT JOIN "mshop_catalog_list" AS mcatli ON ( mcatli."parentid" = mcat."id" )'],
144
			'label' => 'Catalog has list item, parameter(<domain>[,<list type>[,<reference ID>)]]',
145
			'type' => 'null',
146
			'internaltype' => 'null',
147
			'public' => false,
148
		),
149
	);
150
151
152
	/**
153
	 * Initializes the object.
154
	 *
155
	 * @param \Aimeos\MShop\ContextIface $context Context object
156
	 */
157
	public function __construct( \Aimeos\MShop\ContextIface $context )
158
	{
159
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
160
		$level = $context->config()->get( 'mshop/catalog/manager/sitemode', $level );
161
162
163
		$this->searchConfig['catalog:has']['function'] = function( &$source, array $params ) use ( $level ) {
164
165
			$keys = [];
166
167
			foreach( (array) ( $params[1] ?? '' ) as $type ) {
168
				foreach( (array) ( $params[2] ?? '' ) as $id ) {
169
					$keys[] = $params[0] . '|' . ( $type ? $type . '|' : '' ) . $id;
170
				}
171
			}
172
173
			$sitestr = $this->siteString( 'mcatli."siteid"', $level );
174
			$keystr = $this->toExpression( 'mcatli."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
175
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
176
177
			return $params;
178
		};
179
180
181
		parent::__construct( $context, $this->searchConfig );
182
		$this->setResourceName( 'db-catalog' );
183
	}
184
185
186
	/**
187
	 * Removes old entries from the storage.
188
	 *
189
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
190
	 * @return \Aimeos\MShop\Catalog\Manager\Iface Manager object for chaining method calls
191
	 */
192
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
193
	{
194
		$context = $this->context();
195
		$config = $context->config();
196
		$search = $this->object()->filter();
197
198
		foreach( $config->get( 'mshop/catalog/manager/submanagers', ['lists'] ) as $domain ) {
199
			$this->object()->getSubManager( $domain )->clear( $siteids );
200
		}
201
202
		$conn = $context->db( $this->getResourceName() );
203
204
			/** mshop/catalog/manager/cleanup/mysql
205
			 * Deletes the categories for the given site from the database
206
			 *
207
			 * @see mshop/catalog/manager/cleanup/ansi
208
			 */
209
210
			/** mshop/catalog/manager/cleanup/ansi
211
			 * Deletes the categories for the given site from the database
212
			 *
213
			 * Removes the records matched by the given site ID from the catalog
214
			 * database.
215
			 *
216
			 * The ":siteid" placeholder is replaced by the name and value of the
217
			 * site ID column and the given ID or list of IDs.
218
			 *
219
			 * The SQL statement should conform to the ANSI standard to be
220
			 * compatible with most relational database systems. This also
221
			 * includes using double quotes for table and column names.
222
			 *
223
			 * @param string SQL statement for removing the records
224
			 * @since 2014.03
225
			 * @category Developer
226
			 * @see mshop/catalog/manager/delete/ansi
227
			 * @see mshop/catalog/manager/insert/ansi
228
			 * @see mshop/catalog/manager/update/ansi
229
			 * @see mshop/catalog/manager/newid/ansi
230
			 * @see mshop/catalog/manager/search/ansi
231
			 * @see mshop/catalog/manager/count/ansi
232
			 */
233
			$path = 'mshop/catalog/manager/cleanup';
234
			$sql = $this->getSqlConfig( $path );
235
236
			$types = array( 'siteid' => \Aimeos\Base\DB\Statement\Base::PARAM_STR );
237
			$translations = array( 'siteid' => '"siteid"' );
238
239
			$search->setConditions( $search->compare( '==', 'siteid', $siteids ) );
240
			$sql = str_replace( ':siteid', $search->getConditionSource( $types, $translations ), $sql );
241
242
			$stmt = $conn->create( $sql );
243
			$stmt->bind( 1, 0, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
244
			$stmt->bind( 2, 0x7FFFFFFF, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
245
			$stmt->execute()->finish();
246
247
		return $this;
248
	}
249
250
251
	/**
252
	 * Creates a new empty item instance
253
	 *
254
	 * @param array $values Values the item should be initialized with
255
	 * @return \Aimeos\MShop\Catalog\Item\Iface New catalog item object
256
	 */
257
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
258
	{
259
		$values['siteid'] = $this->context()->locale()->getSiteId();
260
		return $this->createItemBase( $values );
261
	}
262
263
264
	/**
265
	 * Creates a filter object.
266
	 *
267
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
268
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
269
	 * @return \Aimeos\Base\Criteria\Iface Returns the filter object
270
	 */
271
	public function filter( ?bool $default = false, bool $site = false ) : \Aimeos\Base\Criteria\Iface
272
	{
273
		return $this->filterBase( 'catalog', $default );
274
	}
275
276
277
	/**
278
	 * Removes multiple items.
279
	 *
280
	 * @param \Aimeos\MShop\Common\Item\Iface|array|string $items List of item objects or IDs of the items
281
	 * @return \Aimeos\MShop\Catalog\Manager\Iface Manager object for chaining method calls
282
	 */
283
	public function delete( $items ) : \Aimeos\MShop\Common\Manager\Iface
284
	{
285
		if( is_map( $items ) ) { $items = $items->toArray(); }
286
		if( !is_array( $items ) ) { $items = [$items]; }
287
		if( empty( $items ) ) { return $this; }
288
289
		$this->begin();
290
		$this->lock();
291
292
		try
293
		{
294
			$siteid = $this->context()->locale()->getSiteId();
295
296
			foreach( $items as $item ) {
297
				$this->createTreeManager( $siteid )->deleteNode( (string) $item );
298
			}
299
300
			$this->unlock();
301
			$this->commit();
302
		}
303
		catch( \Exception $e )
304
		{
305
			$this->unlock();
306
			$this->rollback();
307
			throw $e;
308
		}
309
310
		return $this->deleteRefItems( $items );
311
	}
312
313
314
	/**
315
	 * Returns the item specified by its code and domain/type if necessary
316
	 *
317
	 * @param string $code Code of the item
318
	 * @param string[] $ref List of domains to fetch list items and referenced items for
319
	 * @param string|null $domain Domain of the item if necessary to identify the item uniquely
320
	 * @param string|null $type Type code of the item if necessary to identify the item uniquely
321
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
322
	 * @return \Aimeos\MShop\Catalog\Item\Iface Catalog item object
323
	 */
324
	public function find( string $code, array $ref = [], string $domain = null, string $type = null,
325
		?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
326
	{
327
		return $this->findBase( array( 'catalog.code' => $code ), $ref, $default );
328
	}
329
330
331
	/**
332
	 * Returns the item specified by its ID.
333
	 *
334
	 * @param string $id Unique ID of the catalog item
335
	 * @param string[] $ref List of domains to fetch list items and referenced items for
336
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
337
	 * @return \Aimeos\MShop\Catalog\Item\Iface Catalog item of the given ID
338
	 * @throws \Aimeos\MShop\Exception If item couldn't be found
339
	 */
340
	public function get( string $id, array $ref = [], ?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
341
	{
342
		return $this->getItemBase( 'catalog.id', $id, $ref, $default );
343
	}
344
345
346
	/**
347
	 * Returns the available manager types
348
	 *
349
	 * @param bool $withsub Return also the resource type of sub-managers if true
350
	 * @return string[] Type of the manager and submanagers, subtypes are separated by slashes
351
	 */
352
	public function getResourceType( bool $withsub = true ) : array
353
	{
354
		$path = 'mshop/catalog/manager/submanagers';
355
		return $this->getResourceTypeBase( 'catalog', $path, array( 'lists' ), $withsub );
356
	}
357
358
359
	/**
360
	 * Returns the attributes that can be used for searching.
361
	 *
362
	 * @param bool $withsub Return also attributes of sub-managers if true
363
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of search attribute items
364
	 */
365
	public function getSearchAttributes( bool $withsub = true ) : array
366
	{
367
		/** mshop/catalog/manager/submanagers
368
		 * List of manager names that can be instantiated by the catalog manager
369
		 *
370
		 * Managers provide a generic interface to the underlying storage.
371
		 * Each manager has or can have sub-managers caring about particular
372
		 * aspects. Each of these sub-managers can be instantiated by its
373
		 * parent manager using the getSubManager() method.
374
		 *
375
		 * The search keys from sub-managers can be normally used in the
376
		 * manager as well. It allows you to search for items of the manager
377
		 * using the search keys of the sub-managers to further limit the
378
		 * retrieved list of items.
379
		 *
380
		 * @param array List of sub-manager names
381
		 * @since 2014.03
382
		 * @category Developer
383
		 */
384
		$path = 'mshop/catalog/manager/submanagers';
385
386
		return $this->getSearchAttributesBase( $this->searchConfig, $path, [], $withsub );
387
	}
388
389
390
	/**
391
	 * Adds a new item object.
392
	 *
393
	 * @param \Aimeos\MShop\Catalog\Item\Iface $item Item which should be inserted
394
	 * @param string|null $parentId ID of the parent item where the item should be inserted into
395
	 * @param string|null $refId ID of the item where the item should be inserted before (null to append)
396
	 * @return \Aimeos\MShop\Catalog\Item\Iface $item Updated item including the generated ID
397
	 */
398
	public function insert( \Aimeos\MShop\Catalog\Item\Iface $item, string $parentId = null,
399
		string $refId = null ) : \Aimeos\MShop\Catalog\Item\Iface
400
	{
401
		$this->begin();
402
		$this->lock();
403
404
		try
405
		{
406
			$node = $item->getNode();
0 ignored issues
show
Bug introduced by
The method getNode() does not exist on Aimeos\MShop\Catalog\Item\Iface. Did you maybe mean getCode()? ( Ignorable by Annotation )

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

406
			/** @scrutinizer ignore-call */ 
407
   $node = $item->getNode();

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...
407
			$siteid = $this->context()->locale()->getSiteId();
408
409
			$this->createTreeManager( $siteid )->insertNode( $node, $parentId, $refId );
410
			$this->updateUsage( $node->getId(), $item, true );
411
			$this->unlock();
412
			$this->commit();
413
		}
414
		catch( \Exception $e )
415
		{
416
			$this->unlock();
417
			$this->rollback();
418
			throw $e;
419
		}
420
421
		$item = $this->saveListItems( $item, 'catalog' );
422
		return $this->saveChildren( $item );
423
	}
424
425
426
	/**
427
	 * Moves an existing item to the new parent in the storage.
428
	 *
429
	 * @param string $id ID of the item that should be moved
430
	 * @param string|null $oldParentId ID of the old parent item which currently contains the item that should be removed
431
	 * @param string|null $newParentId ID of the new parent item where the item should be moved to
432
	 * @param string|null $refId ID of the item where the item should be inserted before (null to append)
433
	 * @return \Aimeos\MShop\Catalog\Manager\Iface Manager object for chaining method calls
434
	 */
435
	public function move( string $id, string $oldParentId = null, string $newParentId = null,
436
		string $refId = null ) : \Aimeos\MShop\Catalog\Manager\Iface
437
	{
438
		$this->begin();
439
		$this->lock();
440
441
		try
442
		{
443
			$item = $this->object()->get( $id );
444
			$siteid = $this->context()->locale()->getSiteId();
445
446
			$this->createTreeManager( $siteid )->moveNode( $id, $oldParentId, $newParentId, $refId );
447
			$this->updateUsage( $id, $item );
448
			$this->unlock();
449
			$this->commit();
450
		}
451
		catch( \Exception $e )
452
		{
453
			$this->unlock();
454
			$this->rollback();
455
			throw $e;
456
		}
457
458
		return $this;
459
	}
460
461
462
	/**
463
	 * Updates an item object.
464
	 *
465
	 * @param \Aimeos\MShop\Catalog\Item\Iface $item Item object whose data should be saved
466
	 * @param bool $fetch True if the new ID should be returned in the item
467
	 * @return \Aimeos\MShop\Catalog\Item\Iface $item Updated item including the generated ID
468
	 */
469
	public function saveItem( \Aimeos\MShop\Catalog\Item\Iface $item, bool $fetch = true ) : \Aimeos\MShop\Catalog\Item\Iface
470
	{
471
		if( !$item->isModified() )
472
		{
473
			$item = $this->saveListItems( $item, 'catalog', $fetch );
474
			return $this->saveChildren( $item );
475
		}
476
477
		$node = $item->getNode();
478
		$siteid = $this->context()->locale()->getSiteId();
479
480
		$this->createTreeManager( $siteid )->saveNode( $node );
481
		$this->updateUsage( $node->getId(), $item );
482
483
		$item = $this->saveListItems( $item, 'catalog', $fetch );
484
		return $this->saveChildren( $item );
485
	}
486
487
488
	/**
489
	 * Searches for all items matching the given critera.
490
	 *
491
	 * @param \Aimeos\Base\Criteria\Iface $search Search criteria object
492
	 * @param string[] $ref List of domains to fetch list items and referenced items for
493
	 * @param int|null &$total Number of items that are available in total
494
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Catalog\Item\Iface with ids as keys
495
	 */
496
	public function search( \Aimeos\Base\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
497
	{
498
		$nodeMap = $siteMap = [];
499
		$context = $this->context();
500
		$conn = $context->db( $this->getResourceName() );
501
502
			$required = array( 'catalog' );
503
504
			/** mshop/catalog/manager/sitemode
505
			 * Mode how items from levels below or above in the site tree are handled
506
			 *
507
			 * By default, only items from the current site are fetched from the
508
			 * storage. If the ai-sites extension is installed, you can create a
509
			 * tree of sites. Then, this setting allows you to define for the
510
			 * whole catalog domain if items from parent sites are inherited,
511
			 * sites from child sites are aggregated or both.
512
			 *
513
			 * Available constants for the site mode are:
514
			 * * 0 = only items from the current site
515
			 * * 1 = inherit items from parent sites
516
			 * * 2 = aggregate items from child sites
517
			 * * 3 = inherit and aggregate items at the same time
518
			 *
519
			 * You also need to set the mode in the locale manager
520
			 * (mshop/locale/manager/sitelevel) to one of the constants.
521
			 * If you set it to the same value, it will work as described but you
522
			 * can also use different modes. For example, if inheritance and
523
			 * aggregation is configured the locale manager but only inheritance
524
			 * in the domain manager because aggregating items makes no sense in
525
			 * this domain, then items wil be only inherited. Thus, you have full
526
			 * control over inheritance and aggregation in each domain.
527
			 *
528
			 * @param int Constant from Aimeos\MShop\Locale\Manager\Base class
529
			 * @category Developer
530
			 * @since 2018.01
531
			 * @see mshop/locale/manager/sitelevel
532
			 */
533
			$level = \Aimeos\MShop\Locale\Manager\Base::SITE_PATH;
534
			$level = $context->config()->get( 'mshop/catalog/manager/sitemode', $level );
535
536
			/** mshop/catalog/manager/search-item/mysql
537
			 * Retrieves the records matched by the given criteria in the database
538
			 *
539
			 * @see mshop/catalog/manager/search-item/ansi
540
			 */
541
542
			/** mshop/catalog/manager/search-item/ansi
543
			 * Retrieves the records matched by the given criteria in the database
544
			 *
545
			 * Fetches the records matched by the given criteria from the catalog
546
			 * database. The records must be from one of the sites that are
547
			 * configured via the context item. If the current site is part of
548
			 * a tree of sites, the SELECT statement can retrieve all records
549
			 * from the current site and the complete sub-tree of sites.
550
			 *
551
			 * As the records can normally be limited by criteria from sub-managers,
552
			 * their tables must be joined in the SQL context. This is done by
553
			 * using the "internaldeps" property from the definition of the ID
554
			 * column of the sub-managers. These internal dependencies specify
555
			 * the JOIN between the tables and the used columns for joining. The
556
			 * ":joins" placeholder is then replaced by the JOIN strings from
557
			 * the sub-managers.
558
			 *
559
			 * To limit the records matched, conditions can be added to the given
560
			 * criteria object. It can contain comparisons like column names that
561
			 * must match specific values which can be combined by AND, OR or NOT
562
			 * operators. The resulting string of SQL conditions replaces the
563
			 * ":cond" placeholder before the statement is sent to the database
564
			 * server.
565
			 *
566
			 * If the records that are retrieved should be ordered by one or more
567
			 * columns, the generated string of column / sort direction pairs
568
			 * replaces the ":order" placeholder. In case no ordering is required,
569
			 * the complete ORDER BY part including the "\/*-orderby*\/...\/*orderby-*\/"
570
			 * markers is removed to speed up retrieving the records. Columns of
571
			 * sub-managers can also be used for ordering the result set but then
572
			 * no index can be used.
573
			 *
574
			 * The number of returned records can be limited and can start at any
575
			 * number between the begining and the end of the result set. For that
576
			 * the ":size" and ":start" placeholders are replaced by the
577
			 * corresponding values from the criteria object. The default values
578
			 * are 0 for the start and 100 for the size value.
579
			 *
580
			 * The SQL statement should conform to the ANSI standard to be
581
			 * compatible with most relational database systems. This also
582
			 * includes using double quotes for table and column names.
583
			 *
584
			 * @param string SQL statement for searching items
585
			 * @since 2014.03
586
			 * @category Developer
587
			 * @see mshop/catalog/manager/delete/ansi
588
			 * @see mshop/catalog/manager/get/ansi
589
			 * @see mshop/catalog/manager/insert/ansi
590
			 * @see mshop/catalog/manager/update/ansi
591
			 * @see mshop/catalog/manager/newid/ansi
592
			 * @see mshop/catalog/manager/search/ansi
593
			 * @see mshop/catalog/manager/count/ansi
594
			 * @see mshop/catalog/manager/move-left/ansi
595
			 * @see mshop/catalog/manager/move-right/ansi
596
			 * @see mshop/catalog/manager/update-parentid/ansi
597
			 */
598
			$cfgPathSearch = 'mshop/catalog/manager/search-item';
599
600
			/** mshop/catalog/manager/count/mysql
601
			 * Counts the number of records matched by the given criteria in the database
602
			 *
603
			 * @see mshop/catalog/manager/count/ansi
604
			 */
605
606
			/** mshop/catalog/manager/count/ansi
607
			 * Counts the number of records matched by the given criteria in the database
608
			 *
609
			 * Counts all records matched by the given criteria from the catalog
610
			 * database. The records must be from one of the sites that are
611
			 * configured via the context item. If the current site is part of
612
			 * a tree of sites, the statement can count all records from the
613
			 * current site and the complete sub-tree of sites.
614
			 *
615
			 * As the records can normally be limited by criteria from sub-managers,
616
			 * their tables must be joined in the SQL context. This is done by
617
			 * using the "internaldeps" property from the definition of the ID
618
			 * column of the sub-managers. These internal dependencies specify
619
			 * the JOIN between the tables and the used columns for joining. The
620
			 * ":joins" placeholder is then replaced by the JOIN strings from
621
			 * the sub-managers.
622
			 *
623
			 * To limit the records matched, conditions can be added to the given
624
			 * criteria object. It can contain comparisons like column names that
625
			 * must match specific values which can be combined by AND, OR or NOT
626
			 * operators. The resulting string of SQL conditions replaces the
627
			 * ":cond" placeholder before the statement is sent to the database
628
			 * server.
629
			 *
630
			 * Both, the strings for ":joins" and for ":cond" are the same as for
631
			 * the "search" SQL statement.
632
			 *
633
			 * Contrary to the "search" statement, it doesn't return any records
634
			 * but instead the number of records that have been found. As counting
635
			 * thousands of records can be a long running task, the maximum number
636
			 * of counted records is limited for performance reasons.
637
			 *
638
			 * The SQL statement should conform to the ANSI standard to be
639
			 * compatible with most relational database systems. This also
640
			 * includes using double quotes for table and column names.
641
			 *
642
			 * @param string SQL statement for counting items
643
			 * @since 2014.03
644
			 * @category Developer
645
			 * @see mshop/catalog/manager/delete/ansi
646
			 * @see mshop/catalog/manager/get/ansi
647
			 * @see mshop/catalog/manager/insert/ansi
648
			 * @see mshop/catalog/manager/update/ansi
649
			 * @see mshop/catalog/manager/newid/ansi
650
			 * @see mshop/catalog/manager/search/ansi
651
			 * @see mshop/catalog/manager/search-item/ansi
652
			 * @see mshop/catalog/manager/move-left/ansi
653
			 * @see mshop/catalog/manager/move-right/ansi
654
			 * @see mshop/catalog/manager/update-parentid/ansi
655
			 */
656
			$cfgPathCount = 'mshop/catalog/manager/count';
657
658
			if( $search->getSortations() === [] ) {
659
				$search->setSortations( [$search->sort( '+', 'catalog.left' )] );
660
			}
661
662
			$results = $this->searchItemsBase( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $level );
663
664
			while( ( $row = $results->fetch() ) !== null ) {
665
				$siteMap[(string) $row['siteid']][(string) $row['id']] = new \Aimeos\MW\Tree\Node\Standard( $row );
666
			}
667
668
			$sitePath = array_reverse( (array) $this->context()->locale()->getSitePath() );
669
670
			foreach( $sitePath as $siteId )
671
			{
672
				if( isset( $siteMap[$siteId] ) && !empty( $siteMap[$siteId] ) )
673
				{
674
					$nodeMap = $siteMap[$siteId];
675
					break;
676
				}
677
			}
678
679
		return $this->buildItems( $nodeMap, $ref, 'catalog' );
680
	}
681
682
683
	/**
684
	 * Returns a list of items starting with the given category that are in the path to the root node
685
	 *
686
	 * @param string $id ID of item to get the path for
687
	 * @param string[] $ref List of domains to fetch list items and referenced items for
688
	 * @return \Aimeos\Map Associative list of catalog items implementing \Aimeos\MShop\Catalog\Item\Iface with IDs as keys
689
	 */
690
	public function getPath( string $id, array $ref = [] ) : \Aimeos\Map
691
	{
692
		$mode = \Aimeos\MShop\Locale\Manager\Base::SITE_PATH;
693
		$mode = $this->context()->config()->get( 'mshop/catalog/manager/sitemode', $mode );
694
695
		if( $mode !== \Aimeos\MShop\Locale\Manager\Base::SITE_ONE ) {
696
			$sitePath = array_reverse( (array) $this->context()->locale()->getSitePath() );
697
		} else {
698
			$sitePath = [$this->context()->locale()->getSiteId()];
699
		}
700
701
		foreach( $sitePath as $siteId )
702
		{
703
			try {
704
				$path = $this->createTreeManager( $siteId )->getPath( $id );
705
			} catch( \Exception $e ) {
706
				continue;
707
			}
708
709
			if( !empty( $path ) )
710
			{
711
				$itemMap = [];
712
713
				foreach( $path as $node ) {
714
					$itemMap[$node->getId()] = $node;
715
				}
716
717
				return $this->buildItems( $itemMap, $ref, 'catalog' );
718
			}
719
		}
720
721
		$msg = $this->context()->translate( 'mshop', 'Catalog path for ID "%1$s" not found' );
722
		throw new \Aimeos\MShop\Catalog\Exception( sprintf( $msg, $id ) );
723
	}
724
725
726
	/**
727
	 * Returns a node and its descendants depending on the given resource.
728
	 *
729
	 * @param string|null $id Retrieve nodes starting from the given ID
730
	 * @param string[] List of domains (e.g. text, media, etc.) whose referenced items should be attached to the objects
731
	 * @param int $level One of the level constants from \Aimeos\MW\Tree\Manager\Base
732
	 * @param \Aimeos\Base\Criteria\Iface|null $criteria Optional criteria object with conditions
733
	 * @return \Aimeos\MShop\Catalog\Item\Iface Catalog item, maybe with subnodes
734
	 */
735
	public function getTree( string $id = null, array $ref = [], int $level = \Aimeos\MW\Tree\Manager\Base::LEVEL_TREE,
736
		\Aimeos\Base\Criteria\Iface $criteria = null ) : \Aimeos\MShop\Catalog\Item\Iface
737
	{
738
		$mode = \Aimeos\MShop\Locale\Manager\Base::SITE_PATH;
739
		$mode = $this->context()->config()->get( 'mshop/catalog/manager/sitemode', $mode );
740
741
		if( $mode !== \Aimeos\MShop\Locale\Manager\Base::SITE_ONE ) {
742
			$sitePath = array_reverse( (array) $this->context()->locale()->getSitePath() );
743
		} else {
744
			$sitePath = [$this->context()->locale()->getSiteId()];
745
		}
746
747
		foreach( $sitePath as $siteId )
748
		{
749
			try {
750
				$node = $this->createTreeManager( $siteId )->getNode( $id, $level, $criteria );
751
			} catch( \Aimeos\MW\Tree\Exception $e ) {
752
				continue;
753
			}
754
755
			$listItems = $listItemMap = $refIdMap = [];
756
			$nodeMap = $this->getNodeMap( $node );
757
758
			if( count( $ref ) > 0 ) {
759
				$listItems = $this->getListItems( array_keys( $nodeMap ), $ref, 'catalog' );
760
			}
761
762
			foreach( $listItems as $listItem )
763
			{
764
				$domain = $listItem->getDomain();
765
				$parentid = $listItem->getParentId();
766
767
				$listItemMap[$parentid][$domain][$listItem->getId()] = $listItem;
768
				$refIdMap[$domain][$listItem->getRefId()][] = $parentid;
769
			}
770
771
			$refItemMap = $this->getRefItems( $refIdMap, $ref );
772
			$nodeid = $node->getId();
773
774
			$listItems = [];
775
			if( array_key_exists( $nodeid, $listItemMap ) ) {
776
				$listItems = $listItemMap[$nodeid];
777
			}
778
779
			$refItems = [];
780
			if( array_key_exists( $nodeid, $refItemMap ) ) {
781
				$refItems = $refItemMap[$nodeid];
782
			}
783
784
			if( $item = $this->applyFilter( $this->createItemBase( [], $listItems, $refItems, [], $node ) ) )
785
			{
786
				$this->createTree( $node, $item, $listItemMap, $refItemMap );
0 ignored issues
show
Bug introduced by
$node of type void is incompatible with the type Aimeos\MW\Tree\Node\Iface expected by parameter $node of Aimeos\MShop\Catalog\Manager\Base::createTree(). ( Ignorable by Annotation )

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

786
				$this->createTree( /** @scrutinizer ignore-type */ $node, $item, $listItemMap, $refItemMap );
Loading history...
787
				return $item;
788
			}
789
		}
790
791
		$msg = $this->context()->translate( 'mshop', 'No catalog node for ID "%1$s"' );
792
		throw new \Aimeos\MShop\Catalog\Exception( sprintf( $msg, $id ) );
793
	}
794
795
796
	/**
797
	 * Creates a new extension manager in the domain.
798
	 *
799
	 * @param string $manager Name of the sub manager type
800
	 * @param string|null $name Name of the implementation, will be from configuration (or Default)
801
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager extending the domain functionality
802
	 */
803
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
804
	{
805
		return $this->getSubManagerBase( 'catalog', $manager, $name );
806
	}
807
808
809
	/**
810
	 * Saves the children of the given node
811
	 *
812
	 * @param \Aimeos\MShop\Catalog\Item\Iface $item Catalog item object incl. child items
813
	 * @return \Aimeos\MShop\Catalog\Item\Iface Catalog item with saved child items
814
	 */
815
	protected function saveChildren( \Aimeos\MShop\Catalog\Item\Iface $item ) : \Aimeos\MShop\Catalog\Item\Iface
816
	{
817
		$rmIds = [];
818
		foreach( $item->getChildrenDeleted() as $child ) {
819
			$rmIds[] = $child->getId();
820
		}
821
822
		$this->delete( $rmIds );
823
824
		foreach( $item->getChildren() as $child )
825
		{
826
			if( $child->getId() !== null )
827
			{
828
				$this->save( $child );
829
830
				if( $child->getParentId() !== $item->getParentId() ) {
831
					$this->move( $child->getId(), $item->getParentId(), $child->getParentId() );
832
				}
833
			}
834
			else
835
			{
836
				$this->insert( $child, $item->getId() );
837
			}
838
		}
839
840
		return $item;
841
	}
842
843
844
	/**
845
	 * Locks the catalog table against modifications from other connections
846
	 *
847
	 * @return \Aimeos\MShop\Catalog\Manager\Iface Manager object for chaining method calls
848
	 */
849
	protected function lock() : \Aimeos\MShop\Catalog\Manager\Iface
850
	{
851
		/** mshop/catalog/manager/lock/mysql
852
		 * SQL statement for locking the catalog table
853
		 *
854
		 * @see mshop/catalog/manager/lock/ansi
855
		 */
856
857
		/** mshop/catalog/manager/lock/ansi
858
		 * SQL statement for locking the catalog table
859
		 *
860
		 * Updating the nested set of categories in the catalog table requires locking
861
		 * the whole table to avoid data corruption. This statement will be followed by
862
		 * insert or update statements and closed by an unlock statement.
863
		 *
864
		 * @param string Lock SQL statement
865
		 * @since 2019.04
866
		 * @category Developer
867
		 */
868
		$path = 'mshop/catalog/manager/lock';
869
870
		if( ( $sql = $this->getSqlConfig( $path ) ) !== $path )
871
		{
872
			$conn = $this->context()->db( $this->getResourceName() );
873
			$conn->create( $sql )->execute()->finish();
0 ignored issues
show
Bug introduced by
It seems like $sql can also be of type array; however, parameter $sql of Aimeos\Base\DB\Connection\Iface::create() does only seem to accept string, 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

873
			$conn->create( /** @scrutinizer ignore-type */ $sql )->execute()->finish();
Loading history...
874
		}
875
876
		return $this;
877
	}
878
879
880
	/**
881
	 * Unlocks the catalog table for modifications from other connections
882
	 *
883
	 * @return \Aimeos\MShop\Catalog\Manager\Iface Manager object for chaining method calls
884
	 */
885
	protected function unlock() : \Aimeos\MShop\Catalog\Manager\Iface
886
	{
887
		/** mshop/catalog/manager/unlock/mysql
888
		 * SQL statement for unlocking the catalog table
889
		 *
890
		 * @see mshop/catalog/manager/unlock/ansi
891
		 */
892
893
		/** mshop/catalog/manager/unlock/ansi
894
		 * SQL statement for unlocking the catalog table
895
		 *
896
		 * Updating the nested set of categories in the catalog table requires locking
897
		 * the whole table to avoid data corruption. This statement will be executed
898
		 * after the table is locked and insert or update statements have been sent to
899
		 * the database.
900
		 *
901
		 * @param string Lock SQL statement
902
		 * @since 2019.04
903
		 * @category Developer
904
		 */
905
		 $path = 'mshop/catalog/manager/unlock';
906
907
		if( ( $sql = $this->getSqlConfig( $path ) ) !== $path )
908
		{
909
			$conn = $this->context()->db( $this->getResourceName() );
910
			$conn->create( $sql )->execute()->finish();
0 ignored issues
show
Bug introduced by
It seems like $sql can also be of type array; however, parameter $sql of Aimeos\Base\DB\Connection\Iface::create() does only seem to accept string, 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

910
			$conn->create( /** @scrutinizer ignore-type */ $sql )->execute()->finish();
Loading history...
911
		}
912
913
		return $this;
914
	}
915
916
917
	/**
918
	 * Updates the usage information of a node.
919
	 *
920
	 * @param string $id Id of the record
921
	 * @param \Aimeos\MShop\Catalog\Item\Iface $item Catalog item
922
	 * @param bool $case True if the record shoud be added or false for an update
923
	 * @return \Aimeos\MShop\Catalog\Manager\Iface Manager object for chaining method calls
924
	 */
925
	private function updateUsage( string $id, \Aimeos\MShop\Catalog\Item\Iface $item,
926
		bool $case = false ) : \Aimeos\MShop\Catalog\Manager\Iface
927
	{
928
		$date = date( 'Y-m-d H:i:s' );
929
		$context = $this->context();
930
		$conn = $context->db( $this->getResourceName() );
931
932
			$siteid = $context->locale()->getSiteId();
933
			$columns = $this->object()->getSaveAttributes();
934
935
			if( $case !== true )
936
			{
937
				/** mshop/catalog/manager/update-usage/mysql
938
				 * Updates the config, editor and mtime value of an updated record
939
				 *
940
				 * @see mshop/catalog/manager/update-usage/ansi
941
				 */
942
943
				/** mshop/catalog/manager/update-usage/ansi
944
				 * Updates the config, editor and mtime value of an updated record
945
				 *
946
				 * Each record contains some usage information like when it was
947
				 * created, last modified and by whom. These information are part
948
				 * of the catalog items and the generic tree manager doesn't care
949
				 * about this information. Thus, they are updated after the tree
950
				 * manager saved the basic record information.
951
				 *
952
				 * The SQL statement must be a string suitable for being used as
953
				 * prepared statement. It must include question marks for binding
954
				 * the values from the catalog item to the statement before they are
955
				 * sent to the database server. The order of the columns must
956
				 * correspond to the order in the method using this statement,
957
				 * so the correct values are bound to the columns.
958
				 *
959
				 * The SQL statement should conform to the ANSI standard to be
960
				 * compatible with most relational database systems. This also
961
				 * includes using double quotes for table and column names.
962
				 *
963
				 * @param string SQL statement for updating records
964
				 * @since 2014.03
965
				 * @category Developer
966
				 * @see mshop/catalog/manager/delete/ansi
967
				 * @see mshop/catalog/manager/get/ansi
968
				 * @see mshop/catalog/manager/insert/ansi
969
				 * @see mshop/catalog/manager/newid/ansi
970
				 * @see mshop/catalog/manager/search/ansi
971
				 * @see mshop/catalog/manager/search-item/ansi
972
				 * @see mshop/catalog/manager/count/ansi
973
				 * @see mshop/catalog/manager/move-left/ansi
974
				 * @see mshop/catalog/manager/move-right/ansi
975
				 * @see mshop/catalog/manager/update-parentid/ansi
976
				 * @see mshop/catalog/manager/insert-usage/ansi
977
				 */
978
				$path = 'mshop/catalog/manager/update-usage';
979
				$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
0 ignored issues
show
Bug introduced by
It seems like $this->getSqlConfig($path) can also be of type array; however, parameter $sql of Aimeos\MShop\Common\Manager\Base::addSqlColumns() does only seem to accept string, 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

979
				$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ), false );
Loading history...
980
			}
981
			else
982
			{
983
				/** mshop/catalog/manager/insert-usage/mysql
984
				 * Updates the config, editor, ctime and mtime value of an inserted record
985
				 *
986
				 * @see mshop/catalog/manager/insert-usage/ansi
987
				 */
988
989
				/** mshop/catalog/manager/insert-usage/ansi
990
				 * Updates the config, editor, ctime and mtime value of an inserted record
991
				 *
992
				 * Each record contains some usage information like when it was
993
				 * created, last modified and by whom. These information are part
994
				 * of the catalog items and the generic tree manager doesn't care
995
				 * about this information. Thus, they are updated after the tree
996
				 * manager inserted the basic record information.
997
				 *
998
				 * The SQL statement must be a string suitable for being used as
999
				 * prepared statement. It must include question marks for binding
1000
				 * the values from the catalog item to the statement before they are
1001
				 * sent to the database server. The order of the columns must
1002
				 * correspond to the order in the method using this statement,
1003
				 * so the correct values are bound to the columns.
1004
				 *
1005
				 * The SQL statement should conform to the ANSI standard to be
1006
				 * compatible with most relational database systems. This also
1007
				 * includes using double quotes for table and column names.
1008
				 *
1009
				 * @param string SQL statement for updating records
1010
				 * @since 2014.03
1011
				 * @category Developer
1012
				 * @see mshop/catalog/manager/delete/ansi
1013
				 * @see mshop/catalog/manager/get/ansi
1014
				 * @see mshop/catalog/manager/insert/ansi
1015
				 * @see mshop/catalog/manager/newid/ansi
1016
				 * @see mshop/catalog/manager/search/ansi
1017
				 * @see mshop/catalog/manager/search-item/ansi
1018
				 * @see mshop/catalog/manager/count/ansi
1019
				 * @see mshop/catalog/manager/move-left/ansi
1020
				 * @see mshop/catalog/manager/move-right/ansi
1021
				 * @see mshop/catalog/manager/update-parentid/ansi
1022
				 * @see mshop/catalog/manager/update-usage/ansi
1023
				 */
1024
				$path = 'mshop/catalog/manager/insert-usage';
1025
				$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
1026
			}
1027
1028
			$idx = 1;
1029
			$stmt = $this->getCachedStatement( $conn, $path, $sql );
1030
1031
			foreach( $columns as $name => $entry ) {
1032
				$stmt->bind( $idx++, $item->get( $name ), $entry->getInternalType() );
0 ignored issues
show
Bug introduced by
It seems like $entry->getInternalType() can also be of type string; however, parameter $type of Aimeos\Base\DB\Statement\Iface::bind() does only seem to accept integer, 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

1032
				$stmt->bind( $idx++, $item->get( $name ), /** @scrutinizer ignore-type */ $entry->getInternalType() );
Loading history...
1033
			}
1034
1035
			$stmt->bind( $idx++, $item->getUrl() );
1036
			$stmt->bind( $idx++, json_encode( $item->getConfig() ) );
1037
			$stmt->bind( $idx++, $date ); // mtime
1038
			$stmt->bind( $idx++, $context->editor() );
1039
			$stmt->bind( $idx++, $item->getTarget() );
1040
1041
			if( $case !== true )
1042
			{
1043
				$stmt->bind( $idx++, $siteid );
1044
				$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
1045
			}
1046
			else
1047
			{
1048
				$stmt->bind( $idx++, $date ); // ctime
1049
				$stmt->bind( $idx++, $siteid );
1050
				$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
1051
			}
1052
1053
			$stmt->execute()->finish();
1054
1055
		return $this;
1056
	}
1057
}
1058