Passed
Push — master ( 587f1d...8659e3 )
by Aimeos
05:21
created

Base::iterate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 15
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 2
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2024
6
 * @package MShop
7
 * @subpackage Common
8
 */
9
10
11
namespace Aimeos\MShop\Common\Manager;
12
13
14
/**
15
 * Provides common methods required by most of the manager classes.
16
 *
17
 * @package MShop
18
 * @subpackage Common
19
 */
20
abstract class Base implements \Aimeos\Macro\Iface
21
{
22
	use \Aimeos\Macro\Macroable;
23
	use Sub\Traits;
24
	use Methods;
25
	use Site;
26
	use DB;
27
28
29
	private \Aimeos\MShop\ContextIface $context;
30
31
32
	/**
33
	 * Initialization of class.
34
	 *
35
	 * @param \Aimeos\MShop\ContextIface $context Context object
36
	 */
37
	public function __construct( \Aimeos\MShop\ContextIface $context )
38
	{
39
		$this->context = $context;
40
		$domain = $this->domain();
41
42
		$this->setResourceName( $context->config()->get( 'mshop/' . $domain . '/manager/resource', 'db-' . $domain ) );
43
	}
44
45
46
	/**
47
	 * Removes old entries from the storage.
48
	 *
49
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
50
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager object for chaining method calls
51
	 */
52
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
53
	{
54
		foreach( $this->context()->config()->get( $this->getConfigKey( 'submanagers' ), [] ) as $domain ) {
55
			$this->object()->getSubManager( $domain )->clear( $siteids );
56
		}
57
58
		return $this->clearBase( $siteids, $this->getConfigKey( 'delete', 'mshop/common/manager/delete' ) );
59
	}
60
61
62
	/**
63
	 * Creates a new empty item instance
64
	 *
65
	 * @param array $values Values the item should be initialized with
66
	 * @return \Aimeos\MShop\Common\Item\Iface New attribute item object
67
	 */
68
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
69
	{
70
		$prefix = $this->prefix();
71
		$values[$prefix . 'siteid'] = $values[$prefix . 'siteid'] ?? $this->context()->locale()->getSiteId();
72
73
		return new \Aimeos\MShop\Common\Item\Base( $prefix, $values );
74
	}
75
76
77
	/**
78
	 * Removes multiple items.
79
	 *
80
	 * @param \Aimeos\MShop\Common\Item\Iface[]|string[] $itemIds List of item objects or IDs of the items
81
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager object for chaining method calls
82
	 */
83
	public function delete( $itemIds ) : \Aimeos\MShop\Common\Manager\Iface
84
	{
85
		return $this->deleteItemsBase( $itemIds, $this->getConfigKey( 'delete', 'mshop/common/manager/delete' ) );
86
	}
87
88
89
	/**
90
	 * Creates a search critera object
91
	 *
92
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
93
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
94
	 * @return \Aimeos\Base\Criteria\Iface New search criteria object
95
	 */
96
	public function filter( ?bool $default = false, bool $site = false ) : \Aimeos\Base\Criteria\Iface
97
	{
98
		return $this->filterBase( $this->domain() );
99
	}
100
101
102
	/**
103
	 * Returns the attributes item specified by its ID.
104
	 *
105
	 * @param string $id Unique ID of the attribute item in the storage
106
	 * @param string[] $ref List of domains to fetch list items and referenced items for
107
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
108
	 * @return \Aimeos\MShop\Common\Item\Iface Returns the attribute item of the given id
109
	 * @throws \Aimeos\MShop\Exception If item couldn't be found
110
	 */
111
	public function get( string $id, array $ref = [], ?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
112
	{
113
		return $this->getItemBase( $this->prefix() . 'id', $id, $ref, $default );
114
	}
115
116
117
	/**
118
	 * Returns the available manager types
119
	 *
120
	 * @param bool $withsub Return also the resource type of sub-managers if true
121
	 * @return string[] Type of the manager and submanagers, subtypes are separated by slashes
122
	 * @deprecated 2025.01 Use type() instead
123
	 */
124
	public function getResourceType( bool $withsub = true ) : array
125
	{
126
		return $this->getResourceTypeBase( join( '/', $this->type() ), $this->getConfigKey( 'submanagers' ), [], $withsub );
127
	}
128
129
130
	/**
131
	 * Returns the attributes that can be used for searching.
132
	 *
133
	 * @param bool $withsub Return also attributes of sub-managers if true
134
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of attribute items
135
	 */
136
	public function getSearchAttributes( bool $withsub = true ) : array
137
	{
138
		$prefix = $this->prefix();
139
140
		$attr = array_replace( $this->createAttributes( [
141
			$prefix . 'id' => [
142
				'internalcode' => 'id',
143
				'label' => 'ID',
144
				'type' => 'int',
145
				'public' => false,
146
			],
147
			$prefix . 'siteid' => [
148
				'internalcode' => 'siteid',
149
				'label' => 'Site ID',
150
				'public' => false,
151
			],
152
			$prefix . 'ctime' => [
153
				'internalcode' => 'ctime',
154
				'label' => 'Create date/time',
155
				'type' => 'datetime',
156
				'public' => false,
157
			],
158
			$prefix . 'mtime' => [
159
				'internalcode' => 'mtime',
160
				'label' => 'Modification date/time',
161
				'type' => 'datetime',
162
				'public' => false,
163
			],
164
			$prefix . 'editor' => [
165
				'internalcode' => 'editor',
166
				'label' => 'Editor',
167
				'public' => false,
168
			],
169
		] ), $this->getSaveAttributes() );
170
171
		if( $withsub )
172
		{
173
			$domains = $this->context()->config()->get( $this->getConfigKey( 'submanagers' ), [] );
174
175
			foreach( $domains as $domain ) {
176
				$attr += $this->object()->getSubManager( $domain )->getSearchAttributes( true );
177
			}
178
		}
179
180
		return $attr;
181
	}
182
183
184
	/**
185
	 * Returns a new manager for attribute extensions
186
	 *
187
	 * @param string $manager Name of the sub manager type in lower case
188
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
189
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager for different extensions, e.g Type, List's etc.
190
	 */
191
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
192
	{
193
		$type = $this->type();
194
		$manager = trim( join( '/', array_slice( $type, 1 ) ) . '/' . $manager, '/' );
195
196
		return $this->getSubManagerBase( current( $type ), $manager, $name );
197
	}
198
199
200
	/**
201
	 * Iterates over all matched items and returns the found ones
202
	 *
203
	 * @param \Aimeos\MShop\Common\Cursor\Iface $cursor Cursor object with filter, domains and cursor
204
	 * @param string[] $ref List of domains whose items should be fetched too
205
	 * @return \Aimeos\Map|null List of items implementing \Aimeos\MShop\Common\Item\Iface with ids as keys
206
	 */
207
	public function iterate( \Aimeos\MShop\Common\Cursor\Iface $cursor, array $ref = [] ) : ?\Aimeos\Map
208
	{
209
		if( $cursor->value() === '' ) {
210
			return null;
211
		}
212
213
		if( ( $first = current( $this->getSearchAttributes() ) ) === false ) {
214
			throw new \Aimeos\MShop\Exception( sprintf( 'No search configuration available for "%1$s"', get_class( $this ) ) );
215
		}
216
217
		$filter = $cursor->filter()->add( $first->getCode(), '>', (int) $cursor->value() )->order( $first->getCode() );
218
		$items = $this->search( $filter, $ref );
219
		$cursor->setValue( $items->lastKey() ?: '' );
220
221
		return !$items->isEmpty() ? $items : null;
222
	}
223
224
225
	/**
226
	 * Adds or updates an item object or a list of them.
227
	 *
228
	 * @param \Aimeos\Map|\Aimeos\MShop\Common\Item\Iface[]|\Aimeos\MShop\Common\Item\Iface $items Item or list of items whose data should be saved
229
	 * @param bool $fetch True if the new ID should be returned in the item
230
	 * @return \Aimeos\Map|\Aimeos\MShop\Common\Item\Iface Saved item or items
231
	 */
232
	public function save( $items, bool $fetch = true )
233
	{
234
		foreach( map( $items ) as $item )
235
		{
236
			if( method_exists( $this, 'saveItem' ) ) {
237
				$this->saveItem( $item, $fetch );
0 ignored issues
show
Bug introduced by
The method saveItem() does not exist on Aimeos\MShop\Common\Manager\Base. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

237
				$this->/** @scrutinizer ignore-call */ 
238
           saveItem( $item, $fetch );
Loading history...
238
			} else {
239
				$this->saveBase( $item, $fetch );
240
			}
241
		}
242
243
		return is_array( $items ) ? map( $items ) : $items;
244
	}
245
246
247
	/**
248
	 * Searches for all items matching the given critera.
249
	 *
250
	 * @param \Aimeos\Base\Criteria\Iface $filter Criteria object with conditions, sortations, etc.
251
	 * @param string[] $ref List of domains to fetch list items and referenced items for
252
	 * @param int &$total Number of items that are available in total
253
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Common\Item\Iface with ids as keys
254
	 */
255
	public function search( \Aimeos\Base\Criteria\Iface $filter, array $ref = [], int &$total = null ) : \Aimeos\Map
256
	{
257
		/** mshop/common/manager/search/mysql
258
		 * Retrieves the records matched by the given criteria in the database
259
		 *
260
		 * @see mshop/common/manager/search/ansi
261
		 */
262
263
		/** mshop/common/manager/search/ansi
264
		 * Retrieves the records matched by the given criteria in the database
265
		 *
266
		 * Fetches the records matched by the given criteria from the
267
		 * database. The records must be from one of the sites that are
268
		 * configured via the context item. If the current site is part of
269
		 * a tree of sites, the SELECT statement can retrieve all records
270
		 * from the current site and the complete sub-tree of sites.
271
		 *
272
		 * As the records can normally be limited by criteria from sub-managers,
273
		 * their tables must be joined in the SQL context. This is done by
274
		 * using the "internaldeps" property from the definition of the ID
275
		 * column of the sub-managers. These internal dependencies specify
276
		 * the JOIN between the tables and the used columns for joining. The
277
		 * ":joins" placeholder is then replaced by the JOIN strings from
278
		 * the sub-managers.
279
		 *
280
		 * To limit the records matched, conditions can be added to the given
281
		 * criteria object. It can contain comparisons like column names that
282
		 * must match specific values which can be combined by AND, OR or NOT
283
		 * operators. The resulting string of SQL conditions replaces the
284
		 * ":cond" placeholder before the statement is sent to the database
285
		 * server.
286
		 *
287
		 * If the records that are retrieved should be ordered by one or more
288
		 * columns, the generated string of column / sort direction pairs
289
		 * replaces the ":order" placeholder. Columns of
290
		 * sub-managers can also be used for ordering the result set but then
291
		 * no index can be used.
292
		 *
293
		 * The number of returned records can be limited and can start at any
294
		 * number between the begining and the end of the result set. For that
295
		 * the ":size" and ":start" placeholders are replaced by the
296
		 * corresponding values from the criteria object. The default values
297
		 * are 0 for the start and 100 for the size value.
298
		 *
299
		 * The SQL statement should conform to the ANSI standard to be
300
		 * compatible with most relational database systems. This also
301
		 * includes using double quotes for table and column names.
302
		 *
303
		 * @param string SQL statement for searching items
304
		 * @since 2023.10
305
		 * @see mshop/common/manager/insert/ansi
306
		 * @see mshop/common/manager/update/ansi
307
		 * @see mshop/common/manager/newid/ansi
308
		 * @see mshop/common/manager/delete/ansi
309
		 * @see mshop/common/manager/count/ansi
310
		 */
311
		$cfgPathSearch = $this->getConfigKey( 'search', 'mshop/common/manager/search' );
312
313
		/** mshop/common/manager/count/mysql
314
		 * Counts the number of records matched by the given criteria in the database
315
		 *
316
		 * @see mshop/common/manager/count/ansi
317
		 */
318
319
		/** mshop/common/manager/count/ansi
320
		 * Counts the number of records matched by the given criteria in the database
321
		 *
322
		 * Counts all records matched by the given criteria from the
323
		 * database. The records must be from one of the sites that are
324
		 * configured via the context item. If the current site is part of
325
		 * a tree of sites, the statement can count all records from the
326
		 * current site and the complete sub-tree of sites.
327
		 *
328
		 * As the records can normally be limited by criteria from sub-managers,
329
		 * their tables must be joined in the SQL context. This is done by
330
		 * using the "internaldeps" property from the definition of the ID
331
		 * column of the sub-managers. These internal dependencies specify
332
		 * the JOIN between the tables and the used columns for joining. The
333
		 * ":joins" placeholder is then replaced by the JOIN strings from
334
		 * the sub-managers.
335
		 *
336
		 * To limit the records matched, conditions can be added to the given
337
		 * criteria object. It can contain comparisons like column names that
338
		 * must match specific values which can be combined by AND, OR or NOT
339
		 * operators. The resulting string of SQL conditions replaces the
340
		 * ":cond" placeholder before the statement is sent to the database
341
		 * server.
342
		 *
343
		 * Both, the strings for ":joins" and for ":cond" are the same as for
344
		 * the "search" SQL statement.
345
		 *
346
		 * Contrary to the "search" statement, it doesn't return any records
347
		 * but instead the number of records that have been found. As counting
348
		 * thousands of records can be a long running task, the maximum number
349
		 * of counted records is limited for performance reasons.
350
		 *
351
		 * The SQL statement should conform to the ANSI standard to be
352
		 * compatible with most relational database systems. This also
353
		 * includes using double quotes for table and column names.
354
		 *
355
		 * @param string SQL statement for counting items
356
		 * @since 2023.10
357
		 * @see mshop/common/manager/insert/ansi
358
		 * @see mshop/common/manager/update/ansi
359
		 * @see mshop/common/manager/newid/ansi
360
		 * @see mshop/common/manager/delete/ansi
361
		 * @see mshop/common/manager/search/ansi
362
		 */
363
		$cfgPathCount = $this->getConfigKey( 'count', 'mshop/common/manager/count' );
364
365
		$level = $this->getSiteMode();
366
		$plugins = $this->searchPlugins();
367
		$required = [$this->getSearchKey()];
368
		$conn = $this->context()->db( $this->getResourceName() );
369
370
		$attrs = array_filter( $this->getSearchAttributes( false ), fn( $attr ) => $attr->getType() === 'json' );
371
		$attrs = array_column( $attrs, null, 'code' );
372
373
		$results = $this->searchItemsBase( $conn, $filter, $cfgPathSearch, $cfgPathCount, $required, $total, $level, $plugins );
374
		$prefix = $this->prefix();
375
		$map = $items = [];
376
377
		try
378
		{
379
			while( $row = $results->fetch() )
380
			{
381
				foreach( $attrs as $code => $attr ) {
382
					$row[$code] = json_decode( $row[$code], true );
383
				}
384
385
				$map[$row[$prefix . 'id']] = $row;
386
			}
387
		}
388
		catch( \Exception $e )
389
		{
390
			$results->finish();
391
			throw $e;
392
		}
393
394
		foreach( $this->object()->searchRefs( $map, $ref ) as $id => $row )
395
		{
396
			if( $item = $this->applyFilter( $this->create( $row ) ) ) {
397
				$items[$id] = $item;
398
			}
399
		}
400
401
		return map( $items );
402
	}
403
404
405
	/**
406
	 * Starts a database transaction on the connection identified by the given name
407
	 *
408
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager object for chaining method calls
409
	 */
410
	public function begin() : \Aimeos\MShop\Common\Manager\Iface
411
	{
412
		$this->context->db( $this->getResourceName() )->begin();
413
		return $this;
414
	}
415
416
417
	/**
418
	 * Commits the running database transaction on the connection identified by the given name
419
	 *
420
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager object for chaining method calls
421
	 */
422
	public function commit() : \Aimeos\MShop\Common\Manager\Iface
423
	{
424
		$this->context->db( $this->getResourceName() )->commit();
425
		return $this;
426
	}
427
428
429
	/**
430
	 * Rolls back the running database transaction on the connection identified by the given name
431
	 *
432
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager object for chaining method calls
433
	 */
434
	public function rollback() : \Aimeos\MShop\Common\Manager\Iface
435
	{
436
		$this->context->db( $this->getResourceName() )->rollback();
437
		return $this;
438
	}
439
440
441
	/**
442
	 * Returns the context object.
443
	 *
444
	 * @return \Aimeos\MShop\ContextIface Context object
445
	 */
446
	protected function context() : \Aimeos\MShop\ContextIface
447
	{
448
		return $this->context;
449
	}
450
451
452
	/**
453
	 * Returns the domain of the manager
454
	 *
455
	 * @return string Domain of the manager
456
	 */
457
	protected function domain() : string
458
	{
459
		return current( $this->type() ) ?: '';
460
	}
461
462
463
	/**
464
	 * Returns the site mode constant for inheritance/aggregation
465
	 *
466
	 * @return int Site mode constant (default: SITE_ALL for inheritance and aggregation)
467
	 */
468
	protected function getSiteMode() : int
469
	{
470
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
471
		return $this->context()->config()->get( $this->getConfigKey( 'sitemode', 'mshop/common/manager/sitemode' ), $level );
472
	}
473
474
475
	/**
476
	 * Returns the search plugins for transforming the search criteria
477
	 *
478
	 * @return \Aimeos\MW\Criteria\Plugin\Iface[] List of search plugins
479
	 */
480
	protected function searchPlugins() : array
481
	{
482
		return [];
483
	}
484
}
485