Base::create()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2025
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 attributes that can be used for searching.
119
	 *
120
	 * @param bool $withsub Return also attributes of sub-managers if true
121
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of attribute items
122
	 */
123
	public function getSearchAttributes( bool $withsub = true ) : array
124
	{
125
		$prefix = $this->prefix();
126
127
		$attr = array_replace( $this->createAttributes( [
128
			$prefix . 'id' => [
129
				'internalcode' => 'id',
130
				'label' => 'ID',
131
				'type' => 'int',
132
				'public' => false,
133
			],
134
			$prefix . 'siteid' => [
135
				'internalcode' => 'siteid',
136
				'label' => 'Site ID',
137
				'public' => false,
138
			],
139
			$prefix . 'ctime' => [
140
				'internalcode' => 'ctime',
141
				'label' => 'Create date/time',
142
				'type' => 'datetime',
143
				'public' => false,
144
			],
145
			$prefix . 'mtime' => [
146
				'internalcode' => 'mtime',
147
				'label' => 'Modification date/time',
148
				'type' => 'datetime',
149
				'public' => false,
150
			],
151
			$prefix . 'editor' => [
152
				'internalcode' => 'editor',
153
				'label' => 'Editor',
154
				'public' => false,
155
			],
156
		] ), $this->object()->getSaveAttributes() );
157
158
		if( $withsub )
159
		{
160
			$domains = $this->context()->config()->get( $this->getConfigKey( 'submanagers' ), [] );
161
162
			foreach( $domains as $domain ) {
163
				$attr += $this->object()->getSubManager( $domain )->getSearchAttributes( true );
164
			}
165
		}
166
167
		return $attr;
168
	}
169
170
171
	/**
172
	 * Returns a new manager for attribute extensions
173
	 *
174
	 * @param string $manager Name of the sub manager type in lower case
175
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
176
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager for different extensions, e.g Type, List's etc.
177
	 */
178
	public function getSubManager( string $manager, ?string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
179
	{
180
		$type = $this->type();
181
		$manager = trim( join( '/', array_slice( $type, 1 ) ) . '/' . $manager, '/' );
182
183
		return $this->getSubManagerBase( current( $type ), $manager, $name );
184
	}
185
186
187
	/**
188
	 * Iterates over all matched items and returns the found ones
189
	 *
190
	 * @param \Aimeos\MShop\Common\Cursor\Iface $cursor Cursor object with filter, domains and cursor
191
	 * @param string[] $ref List of domains whose items should be fetched too
192
	 * @return \Aimeos\Map|null List of items implementing \Aimeos\MShop\Common\Item\Iface with ids as keys
193
	 */
194
	public function iterate( \Aimeos\MShop\Common\Cursor\Iface $cursor, array $ref = [] ) : ?\Aimeos\Map
195
	{
196
		if( $cursor->value() === '' ) {
197
			return null;
198
		}
199
200
		if( ( $first = current( $this->object()->getSearchAttributes() ) ) === false ) {
201
			throw new \Aimeos\MShop\Exception( sprintf( 'No search configuration available for "%1$s"', get_class( $this ) ) );
202
		}
203
204
		$filter = $cursor->filter()->add( $first->getCode(), '>', (int) $cursor->value() )->order( $first->getCode() );
205
		$items = $this->search( $filter, $ref );
206
		$cursor->setValue( $items->lastKey() ?: '' );
207
208
		return !$items->isEmpty() ? $items : null;
209
	}
210
211
212
	/**
213
	 * Adds or updates an item object or a list of them.
214
	 *
215
	 * @param \Aimeos\Map|\Aimeos\MShop\Common\Item\Iface[]|\Aimeos\MShop\Common\Item\Iface $items Item or list of items whose data should be saved
216
	 * @param bool $fetch True if the new ID should be returned in the item
217
	 * @return \Aimeos\Map|\Aimeos\MShop\Common\Item\Iface Saved item or items
218
	 */
219
	public function save( $items, bool $fetch = true )
220
	{
221
		foreach( map( $items ) as $item )
222
		{
223
			if( method_exists( $this, 'saveItem' ) ) {
224
				$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

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