Passed
Push — master ( 69c572...92beea )
by Aimeos
05:23
created

Standard::__construct()   B

Complexity

Conditions 10
Paths 1

Size

Total Lines 72
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 26
nc 1
nop 1
dl 0
loc 72
rs 7.6666
c 1
b 0
f 0

How to fix   Long Method    Complexity   

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, 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 Price
9
 */
10
11
12
namespace Aimeos\MShop\Price\Manager;
13
14
15
/**
16
 * Default implementation of a price manager.
17
 *
18
 * @package MShop
19
 * @subpackage Price
20
 */
21
class Standard
22
	extends \Aimeos\MShop\Price\Manager\Base
23
	implements \Aimeos\MShop\Price\Manager\Iface, \Aimeos\MShop\Common\Manager\Factory\Iface
24
{
25
	private $searchConfig = array(
26
		'price.id' => array(
27
			'code' => 'price.id',
28
			'internalcode' => 'mpri."id"',
29
			'label' => 'Price ID',
30
			'type' => 'integer',
31
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_INT,
32
		),
33
		'price.siteid' => array(
34
			'code' => 'price.siteid',
35
			'internalcode' => 'mpri."siteid"',
36
			'label' => 'Price site ID',
37
			'type' => 'string',
38
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
39
			'public' => false,
40
		),
41
		'price.type' => array(
42
			'label' => 'Price type ID',
43
			'code' => 'price.type',
44
			'internalcode' => 'mpri."type"',
45
			'type' => 'string',
46
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
47
		),
48
		'price.currencyid' => array(
49
			'code' => 'price.currencyid',
50
			'internalcode' => 'mpri."currencyid"',
51
			'label' => 'Price currency code',
52
			'type' => 'string',
53
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
54
		),
55
		'price.domain' => array(
56
			'code' => 'price.domain',
57
			'internalcode' => 'mpri."domain"',
58
			'label' => 'Price domain',
59
			'type' => 'string',
60
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
61
		),
62
		'price.label' => array(
63
			'code' => 'price.label',
64
			'internalcode' => 'mpri."label"',
65
			'label' => 'Price label',
66
			'type' => 'string',
67
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
68
		),
69
		'price.quantity' => array(
70
			'code' => 'price.quantity',
71
			'internalcode' => 'mpri."quantity"',
72
			'label' => 'Price quantity',
73
			'type' => 'float',
74
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_FLOAT,
75
		),
76
		'price.value' => array(
77
			'code' => 'price.value',
78
			'internalcode' => 'mpri."value"',
79
			'label' => 'Price regular value',
80
			'type' => 'decimal',
81
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
82
		),
83
		'price.costs' => array(
84
			'code' => 'price.costs',
85
			'internalcode' => 'mpri."costs"',
86
			'label' => 'Price shipping costs',
87
			'type' => 'decimal',
88
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
89
		),
90
		'price.rebate' => array(
91
			'code' => 'price.rebate',
92
			'internalcode' => 'mpri."rebate"',
93
			'label' => 'Price rebate amount',
94
			'type' => 'decimal',
95
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
96
		),
97
		'price.taxrate' => array(
98
			'code' => 'price.taxrate',
99
			'internalcode' => 'mpri."taxrate"',
100
			'label' => 'Price tax rates as JSON encoded string',
101
			'type' => 'string',
102
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
103
		),
104
		'price.status' => array(
105
			'code' => 'price.status',
106
			'internalcode' => 'mpri."status"',
107
			'label' => 'Price status',
108
			'type' => 'integer',
109
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_INT,
110
		),
111
		'price.mtime' => array(
112
			'code' => 'price.mtime',
113
			'internalcode' => 'mpri."mtime"',
114
			'label' => 'Price modify date',
115
			'type' => 'datetime',
116
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
117
		),
118
		'price.ctime' => array(
119
			'code' => 'price.ctime',
120
			'internalcode' => 'mpri."ctime"',
121
			'label' => 'Price create date/time',
122
			'type' => 'datetime',
123
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
124
		),
125
		'price.editor' => array(
126
			'code' => 'price.editor',
127
			'internalcode' => 'mpri."editor"',
128
			'label' => 'Price editor',
129
			'type' => 'string',
130
			'internaltype' => \Aimeos\MW\DB\Statement\Base::PARAM_STR,
131
		),
132
		'price:has' => array(
133
			'code' => 'price:has()',
134
			'internalcode' => ':site AND :key AND mprili."id"',
135
			'internaldeps' => ['LEFT JOIN "mshop_price_list" AS mprili ON ( mprili."parentid" = mpri."id" )'],
136
			'label' => 'Price has list item, parameter(<domain>[,<list type>[,<reference ID>)]]',
137
			'type' => 'null',
138
			'internaltype' => 'null',
139
			'public' => false,
140
		),
141
		'price:prop' => array(
142
			'code' => 'price:prop()',
143
			'internalcode' => ':site AND :key AND mpripr."id"',
144
			'internaldeps' => ['LEFT JOIN "mshop_price_property" AS mpripr ON ( mpripr."parentid" = mpri."id" )'],
145
			'label' => 'Price has property item, parameter(<property type>[,<language code>[,<property value>]])',
146
			'type' => 'null',
147
			'internaltype' => 'null',
148
			'public' => false,
149
		),
150
	);
151
152
	private $currencyId;
153
	private $precision;
154
	private $taxflag;
155
156
157
	/**
158
	 * Initializes the object.
159
	 *
160
	 * @param \Aimeos\MShop\Context\Item\Iface $context Context object
161
	 */
162
	public function __construct( \Aimeos\MShop\Context\Item\Iface $context )
163
	{
164
		parent::__construct( $context );
165
166
		$this->setResourceName( 'db-price' );
167
		$this->currencyId = $context->locale()->getCurrencyId();
168
169
		/** mshop/price/taxflag
170
		 * Configuration setting if prices are inclusive or exclusive tax
171
		 *
172
		 * In Aimeos, prices can be entered either completely with or without tax. The
173
		 * default is that prices contains tax. You must specifiy the tax rate for each
174
		 * prices to prevent wrong calculations.
175
		 *
176
		 * @param bool True if gross prices are used, false for net prices
177
		 * @category Developer
178
		 * @category User
179
		 * @since 2016.02
180
		 */
181
		$this->taxflag = $context->config()->get( 'mshop/price/taxflag', true );
182
183
		/** mshop/price/precision
184
		 * Number of decimal digits prices contain
185
		 *
186
		 * Sets the number of decimal digits price values will contain. Internally,
187
		 * prices are calculated as double values with high precision but these
188
		 * values will be rounded after calculation to the configured number of digits.
189
		 *
190
		 * @param int Positive number of digits
191
		 * @category Developer
192
		 * @since 2019.04
193
		 */
194
		$this->precision = $context->config()->get( 'mshop/price/precision', 2 );
195
196
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
197
		$level = $context->config()->get( 'mshop/price/manager/sitemode', $level );
198
199
200
		$this->searchConfig['price:has']['function'] = function( &$source, array $params ) use ( $level ) {
201
202
			$keys = [];
203
204
			foreach( (array) ( $params[1] ?? '' ) as $type ) {
205
				foreach( (array) ( $params[2] ?? '' ) as $id ) {
206
					$keys[] = $params[0] . '|' . ( $type ? $type . '|' : '' ) . $id;
207
				}
208
			}
209
210
			$sitestr = $this->getSiteString( 'mprili."siteid"', $level );
211
			$keystr = $this->toExpression( 'mprili."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
212
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
213
214
			return $params;
215
		};
216
217
218
		$this->searchConfig['price:prop']['function'] = function( &$source, array $params ) use ( $level ) {
219
220
			$keys = [];
221
			$langs = array_key_exists( 1, $params ) ? ( $params[1] ?? 'null' ) : '';
222
223
			foreach( (array) $langs as $lang ) {
224
				foreach( (array) ( $params[2] ?? '' ) as $val ) {
225
					$keys[] = substr( $params[0] . '|' . ( $lang === null ? 'null|' : ( $lang ? $lang . '|' : '' ) ) . $val, 0, 255 );
226
				}
227
			}
228
229
			$sitestr = $this->getSiteString( 'mpripr."siteid"', $level );
230
			$keystr = $this->toExpression( 'mpripr."key"', $keys, '=~' );
231
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
232
233
			return $params;
234
		};
235
	}
236
237
238
	/**
239
	 * Removes old entries from the storage.
240
	 *
241
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
242
	 * @return \Aimeos\MShop\Price\Manager\Iface Manager object for chaining method calls
243
	 */
244
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
245
	{
246
		$path = 'mshop/price/manager/submanagers';
247
		foreach( $this->context()->config()->get( $path, ['type', 'property', 'lists'] ) as $domain ) {
248
			$this->object()->getSubManager( $domain )->clear( $siteids );
249
		}
250
251
		return $this->clearBase( $siteids, 'mshop/price/manager/delete' );
252
	}
253
254
255
	/**
256
	 * Creates a new empty item instance
257
	 *
258
	 * @param array $values Values the item should be initialized with
259
	 * @return \Aimeos\MShop\Price\Item\Iface New price item object
260
	 */
261
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
262
	{
263
		$locale = $this->context()->locale();
264
		$values['price.siteid'] = $locale->getSiteId();
265
266
		if( !isset( $values['price.currencyid'] ) && $locale->getCurrencyId() !== null ) {
267
			$values['price.currencyid'] = $locale->getCurrencyId();
268
		}
269
270
		return $this->createItemBase( $values );
271
	}
272
273
274
275
	/**
276
	 * Returns the available manager types
277
	 *
278
	 * @param bool $withsub Return also the resource type of sub-managers if true
279
	 * @return string[] Type of the manager and submanagers, subtypes are separated by slashes
280
	 */
281
	public function getResourceType( bool $withsub = true ) : array
282
	{
283
		$path = 'mshop/price/manager/submanagers';
284
		return $this->getResourceTypeBase( 'price', $path, ['property', 'lists'], $withsub );
285
	}
286
287
288
	/**
289
	 * Returns the attributes that can be used for searching.
290
	 *
291
	 * @param bool $withsub Return also attributes of sub-managers if true
292
	 * @return \Aimeos\MW\Criteria\Attribute\Iface[] List of search attribute items
293
	 */
294
	public function getSearchAttributes( bool $withsub = true ) : array
295
	{
296
		/** mshop/price/manager/submanagers
297
		 * List of manager names that can be instantiated by the price manager
298
		 *
299
		 * Managers provide a generic interface to the underlying storage.
300
		 * Each manager has or can have sub-managers caring about particular
301
		 * aspects. Each of these sub-managers can be instantiated by its
302
		 * parent manager using the getSubManager() method.
303
		 *
304
		 * The search keys from sub-managers can be normally used in the
305
		 * manager as well. It allows you to search for items of the manager
306
		 * using the search keys of the sub-managers to further limit the
307
		 * retrieved list of items.
308
		 *
309
		 * @param array List of sub-manager names
310
		 * @since 2014.03
311
		 * @category Developer
312
		 */
313
		$path = 'mshop/price/manager/submanagers';
314
315
		return $this->getSearchAttributesBase( $this->searchConfig, $path, [], $withsub );
316
	}
317
318
319
	/**
320
	 * Removes multiple items.
321
	 *
322
	 * @param \Aimeos\MShop\Common\Item\Iface[]|string[] $itemIds List of item objects or IDs of the items
323
	 * @return \Aimeos\MShop\Price\Manager\Iface Manager object for chaining method calls
324
	 */
325
	public function delete( $itemIds ) : \Aimeos\MShop\Common\Manager\Iface
326
	{
327
		/** mshop/price/manager/delete/mysql
328
		 * Deletes the items matched by the given IDs from the database
329
		 *
330
		 * @see mshop/price/manager/delete/ansi
331
		 */
332
333
		/** mshop/price/manager/delete/ansi
334
		 * Deletes the items matched by the given IDs from the database
335
		 *
336
		 * Removes the records specified by the given IDs from the price database.
337
		 * The records must be from the site that is configured via the
338
		 * context item.
339
		 *
340
		 * The ":cond" placeholder is replaced by the name of the ID column and
341
		 * the given ID or list of IDs while the site ID is bound to the question
342
		 * mark.
343
		 *
344
		 * The SQL statement should conform to the ANSI standard to be
345
		 * compatible with most relational database systems. This also
346
		 * includes using double quotes for table and column names.
347
		 *
348
		 * @param string SQL statement for deleting items
349
		 * @since 2014.03
350
		 * @category Developer
351
		 * @see mshop/price/manager/insert/ansi
352
		 * @see mshop/price/manager/update/ansi
353
		 * @see mshop/price/manager/newid/ansi
354
		 * @see mshop/price/manager/search/ansi
355
		 * @see mshop/price/manager/count/ansi
356
		 */
357
		$path = 'mshop/price/manager/delete';
358
359
		return $this->deleteItemsBase( $itemIds, $path )->deleteRefItems( $itemIds );
360
	}
361
362
363
	/**
364
	 * Returns the price item object specificed by its ID.
365
	 *
366
	 * @param string $id Unique price ID referencing an existing price
367
	 * @param string[] $ref List of domains to fetch list items and referenced items for
368
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
369
	 * @return \Aimeos\MShop\Price\Item\Iface $item Returns the price item of the given id
370
	 * @throws \Aimeos\MShop\Exception If item couldn't be found
371
	 */
372
	public function get( string $id, array $ref = [], ?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
373
	{
374
		return $this->getItemBase( 'price.id', $id, $ref, $default );
375
	}
376
377
378
	/**
379
	 * Saves a price item object.
380
	 *
381
	 * @param \Aimeos\MShop\Price\Item\Iface $item Price item object
382
	 * @param bool $fetch True if the new ID should be returned in the item
383
	 * @return \Aimeos\MShop\Price\Item\Iface Updated item including the generated ID
384
	 * @throws \Aimeos\MShop\Price\Exception If price couldn't be saved
385
	 */
386
	public function saveItem( \Aimeos\MShop\Price\Item\Iface $item, bool $fetch = true ) : \Aimeos\MShop\Price\Item\Iface
387
	{
388
		if( !$item->isModified() )
389
		{
390
			$item = $this->savePropertyItems( $item, 'price', $fetch );
391
			return $this->saveListItems( $item, 'price', $fetch );
392
		}
393
394
		$context = $this->context();
395
396
		$dbm = $context->db();
397
		$dbname = $this->getResourceName();
398
		$conn = $dbm->acquire( $dbname );
399
400
		try
401
		{
402
			$id = $item->getId();
403
			$date = date( 'Y-m-d H:i:s' );
404
			$columns = $this->object()->getSaveAttributes();
405
406
			if( $id === null )
407
			{
408
				/** mshop/price/manager/insert/mysql
409
				 * Inserts a new price record into the database table
410
				 *
411
				 * @see mshop/price/manager/insert/ansi
412
				 */
413
414
				/** mshop/price/manager/insert/ansi
415
				 * Inserts a new price record into the database table
416
				 *
417
				 * Items with no ID yet (i.e. the ID is NULL) will be created in
418
				 * the database and the newly created ID retrieved afterwards
419
				 * using the "newid" SQL statement.
420
				 *
421
				 * The SQL statement must be a string suitable for being used as
422
				 * prepared statement. It must include question marks for binding
423
				 * the values from the price item to the statement before they are
424
				 * sent to the database server. The number of question marks must
425
				 * be the same as the number of columns listed in the INSERT
426
				 * statement. The order of the columns must correspond to the
427
				 * order in the save() method, so the correct values are
428
				 * bound to the columns.
429
				 *
430
				 * The SQL statement should conform to the ANSI standard to be
431
				 * compatible with most relational database systems. This also
432
				 * includes using double quotes for table and column names.
433
				 *
434
				 * @param string SQL statement for inserting records
435
				 * @since 2014.03
436
				 * @category Developer
437
				 * @see mshop/price/manager/update/ansi
438
				 * @see mshop/price/manager/newid/ansi
439
				 * @see mshop/price/manager/delete/ansi
440
				 * @see mshop/price/manager/search/ansi
441
				 * @see mshop/price/manager/count/ansi
442
				 */
443
				$path = 'mshop/price/manager/insert';
444
				$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ) );
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

444
				$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
445
			}
446
			else
447
			{
448
				/** mshop/price/manager/update/mysql
449
				 * Updates an existing price record in the database
450
				 *
451
				 * @see mshop/price/manager/update/ansi
452
				 */
453
454
				/** mshop/price/manager/update/ansi
455
				 * Updates an existing price record in the database
456
				 *
457
				 * Items which already have an ID (i.e. the ID is not NULL) will
458
				 * be updated in the database.
459
				 *
460
				 * The SQL statement must be a string suitable for being used as
461
				 * prepared statement. It must include question marks for binding
462
				 * the values from the price item to the statement before they are
463
				 * sent to the database server. The order of the columns must
464
				 * correspond to the order in the save() method, so the
465
				 * correct values are bound to the columns.
466
				 *
467
				 * The SQL statement should conform to the ANSI standard to be
468
				 * compatible with most relational database systems. This also
469
				 * includes using double quotes for table and column names.
470
				 *
471
				 * @param string SQL statement for updating records
472
				 * @since 2014.03
473
				 * @category Developer
474
				 * @see mshop/price/manager/insert/ansi
475
				 * @see mshop/price/manager/newid/ansi
476
				 * @see mshop/price/manager/delete/ansi
477
				 * @see mshop/price/manager/search/ansi
478
				 * @see mshop/price/manager/count/ansi
479
				 */
480
				$path = 'mshop/price/manager/update';
481
				$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
482
			}
483
484
			$idx = 1;
485
			$stmt = $this->getCachedStatement( $conn, $path, $sql );
486
487
			foreach( $columns as $name => $entry ) {
488
				$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\MW\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

488
				$stmt->bind( $idx++, $item->get( $name ), /** @scrutinizer ignore-type */ $entry->getInternalType() );
Loading history...
489
			}
490
491
			$stmt->bind( $idx++, $item->getType() );
492
			$stmt->bind( $idx++, $item->getCurrencyId() );
493
			$stmt->bind( $idx++, $item->getDomain() );
494
			$stmt->bind( $idx++, $item->getLabel() );
495
			$stmt->bind( $idx++, $item->getQuantity(), \Aimeos\MW\DB\Statement\Base::PARAM_INT );
496
			$stmt->bind( $idx++, $item->getValue() );
497
			$stmt->bind( $idx++, $item->getCosts() );
498
			$stmt->bind( $idx++, $item->getRebate() );
499
			$stmt->bind( $idx++, json_encode( $item->getTaxrates(), JSON_FORCE_OBJECT ) );
500
			$stmt->bind( $idx++, $item->getStatus(), \Aimeos\MW\DB\Statement\Base::PARAM_INT );
501
			$stmt->bind( $idx++, $date ); //mtime
502
			$stmt->bind( $idx++, $context->editor() );
503
			$stmt->bind( $idx++, $context->locale()->getSiteId() );
504
505
			if( $id !== null ) {
506
				$stmt->bind( $idx++, $id, \Aimeos\MW\DB\Statement\Base::PARAM_INT );
507
			} else {
508
				$stmt->bind( $idx++, $date ); //ctime
509
			}
510
511
			$stmt->execute()->finish();
512
513
			if( $id === null )
514
			{
515
				/** mshop/price/manager/newid/mysql
516
				 * Retrieves the ID generated by the database when inserting a new record
517
				 *
518
				 * @see mshop/price/manager/newid/ansi
519
				 */
520
521
				/** mshop/price/manager/newid/ansi
522
				 * Retrieves the ID generated by the database when inserting a new record
523
				 *
524
				 * As soon as a new record is inserted into the database table,
525
				 * the database server generates a new and unique identifier for
526
				 * that record. This ID can be used for retrieving, updating and
527
				 * deleting that specific record from the table again.
528
				 *
529
				 * For MySQL:
530
				 *  SELECT LAST_INSERT_ID()
531
				 * For PostgreSQL:
532
				 *  SELECT currval('seq_mpri_id')
533
				 * For SQL Server:
534
				 *  SELECT SCOPE_IDENTITY()
535
				 * For Oracle:
536
				 *  SELECT "seq_mpri_id".CURRVAL FROM DUAL
537
				 *
538
				 * There's no way to retrive the new ID by a SQL statements that
539
				 * fits for most database servers as they implement their own
540
				 * specific way.
541
				 *
542
				 * @param string SQL statement for retrieving the last inserted record ID
543
				 * @since 2014.03
544
				 * @category Developer
545
				 * @see mshop/price/manager/insert/ansi
546
				 * @see mshop/price/manager/update/ansi
547
				 * @see mshop/price/manager/delete/ansi
548
				 * @see mshop/price/manager/search/ansi
549
				 * @see mshop/price/manager/count/ansi
550
				 */
551
				$path = 'mshop/price/manager/newid';
552
				$id = $this->newId( $conn, $path );
553
			}
554
555
			$item->setId( $id );
556
557
			$dbm->release( $conn, $dbname );
558
		}
559
		catch( \Exception $e )
560
		{
561
			$dbm->release( $conn, $dbname );
562
			throw $e;
563
		}
564
565
		$item = $this->savePropertyItems( $item, 'price', $fetch );
566
		return $this->saveListItems( $item, 'price', $fetch );
567
	}
568
569
570
	/**
571
	 * Returns the item objects matched by the given search criteria.
572
	 *
573
	 * @param \Aimeos\MW\Criteria\Iface $search Search criteria object
574
	 * @param string[] $ref List of domains to fetch list items and referenced items for
575
	 * @param int|null &$total Number of items that are available in total
576
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Price\Item\Iface with ids as keys
577
	 */
578
	public function search( \Aimeos\MW\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
579
	{
580
		$map = [];
581
		$context = $this->context();
582
583
		$dbm = $context->db();
584
		$dbname = $this->getResourceName();
585
		$conn = $dbm->acquire( $dbname );
586
587
		try
588
		{
589
			$required = array( 'price' );
590
591
			/** mshop/price/manager/sitemode
592
			 * Mode how items from levels below or above in the site tree are handled
593
			 *
594
			 * By default, only items from the current site are fetched from the
595
			 * storage. If the ai-sites extension is installed, you can create a
596
			 * tree of sites. Then, this setting allows you to define for the
597
			 * whole price domain if items from parent sites are inherited,
598
			 * sites from child sites are aggregated or both.
599
			 *
600
			 * Available constants for the site mode are:
601
			 * * 0 = only items from the current site
602
			 * * 1 = inherit items from parent sites
603
			 * * 2 = aggregate items from child sites
604
			 * * 3 = inherit and aggregate items at the same time
605
			 *
606
			 * You also need to set the mode in the locale manager
607
			 * (mshop/locale/manager/sitelevel) to one of the constants.
608
			 * If you set it to the same value, it will work as described but you
609
			 * can also use different modes. For example, if inheritance and
610
			 * aggregation is configured the locale manager but only inheritance
611
			 * in the domain manager because aggregating items makes no sense in
612
			 * this domain, then items wil be only inherited. Thus, you have full
613
			 * control over inheritance and aggregation in each domain.
614
			 *
615
			 * @param int Constant from Aimeos\MShop\Locale\Manager\Base class
616
			 * @category Developer
617
			 * @since 2018.01
618
			 * @see mshop/locale/manager/sitelevel
619
			 */
620
			$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
621
			$level = $context->config()->get( 'mshop/price/manager/sitemode', $level );
622
623
			/** mshop/price/manager/search/mysql
624
			 * Retrieves the records matched by the given criteria in the database
625
			 *
626
			 * @see mshop/price/manager/search/ansi
627
			 */
628
629
			/** mshop/price/manager/search/ansi
630
			 * Retrieves the records matched by the given criteria in the database
631
			 *
632
			 * Fetches the records matched by the given criteria from the price
633
			 * database. The records must be from one of the sites that are
634
			 * configured via the context item. If the current site is part of
635
			 * a tree of sites, the SELECT statement can retrieve all records
636
			 * from the current site and the complete sub-tree of sites.
637
			 *
638
			 * As the records can normally be limited by criteria from sub-managers,
639
			 * their tables must be joined in the SQL context. This is done by
640
			 * using the "internaldeps" property from the definition of the ID
641
			 * column of the sub-managers. These internal dependencies specify
642
			 * the JOIN between the tables and the used columns for joining. The
643
			 * ":joins" placeholder is then replaced by the JOIN strings from
644
			 * the sub-managers.
645
			 *
646
			 * To limit the records matched, conditions can be added to the given
647
			 * criteria object. It can contain comparisons like column names that
648
			 * must match specific values which can be combined by AND, OR or NOT
649
			 * operators. The resulting string of SQL conditions replaces the
650
			 * ":cond" placeholder before the statement is sent to the database
651
			 * server.
652
			 *
653
			 * If the records that are retrieved should be ordered by one or more
654
			 * columns, the generated string of column / sort direction pairs
655
			 * replaces the ":order" placeholder. In case no ordering is required,
656
			 * the complete ORDER BY part including the "\/*-orderby*\/...\/*orderby-*\/"
657
			 * markers is removed to speed up retrieving the records. Columns of
658
			 * sub-managers can also be used for ordering the result set but then
659
			 * no index can be used.
660
			 *
661
			 * The number of returned records can be limited and can start at any
662
			 * number between the begining and the end of the result set. For that
663
			 * the ":size" and ":start" placeholders are replaced by the
664
			 * corresponding values from the criteria object. The default values
665
			 * are 0 for the start and 100 for the size value.
666
			 *
667
			 * The SQL statement should conform to the ANSI standard to be
668
			 * compatible with most relational database systems. This also
669
			 * includes using double quotes for table and column names.
670
			 *
671
			 * @param string SQL statement for searching items
672
			 * @since 2014.03
673
			 * @category Developer
674
			 * @see mshop/price/manager/insert/ansi
675
			 * @see mshop/price/manager/update/ansi
676
			 * @see mshop/price/manager/newid/ansi
677
			 * @see mshop/price/manager/delete/ansi
678
			 * @see mshop/price/manager/count/ansi
679
			 */
680
			$cfgPathSearch = 'mshop/price/manager/search';
681
682
			/** mshop/price/manager/count/mysql
683
			 * Counts the number of records matched by the given criteria in the database
684
			 *
685
			 * @see mshop/price/manager/count/ansi
686
			 */
687
688
			/** mshop/price/manager/count/ansi
689
			 * Counts the number of records matched by the given criteria in the database
690
			 *
691
			 * Counts all records matched by the given criteria from the price
692
			 * database. The records must be from one of the sites that are
693
			 * configured via the context item. If the current site is part of
694
			 * a tree of sites, the statement can count all records from the
695
			 * current site and the complete sub-tree of sites.
696
			 *
697
			 * As the records can normally be limited by criteria from sub-managers,
698
			 * their tables must be joined in the SQL context. This is done by
699
			 * using the "internaldeps" property from the definition of the ID
700
			 * column of the sub-managers. These internal dependencies specify
701
			 * the JOIN between the tables and the used columns for joining. The
702
			 * ":joins" placeholder is then replaced by the JOIN strings from
703
			 * the sub-managers.
704
			 *
705
			 * To limit the records matched, conditions can be added to the given
706
			 * criteria object. It can contain comparisons like column names that
707
			 * must match specific values which can be combined by AND, OR or NOT
708
			 * operators. The resulting string of SQL conditions replaces the
709
			 * ":cond" placeholder before the statement is sent to the database
710
			 * server.
711
			 *
712
			 * Both, the strings for ":joins" and for ":cond" are the same as for
713
			 * the "search" SQL statement.
714
			 *
715
			 * Contrary to the "search" statement, it doesn't return any records
716
			 * but instead the number of records that have been found. As counting
717
			 * thousands of records can be a long running task, the maximum number
718
			 * of counted records is limited for performance reasons.
719
			 *
720
			 * The SQL statement should conform to the ANSI standard to be
721
			 * compatible with most relational database systems. This also
722
			 * includes using double quotes for table and column names.
723
			 *
724
			 * @param string SQL statement for counting items
725
			 * @since 2014.03
726
			 * @category Developer
727
			 * @see mshop/price/manager/insert/ansi
728
			 * @see mshop/price/manager/update/ansi
729
			 * @see mshop/price/manager/newid/ansi
730
			 * @see mshop/price/manager/delete/ansi
731
			 * @see mshop/price/manager/search/ansi
732
			 */
733
			$cfgPathCount = 'mshop/price/manager/count';
734
735
			$results = $this->searchItemsBase( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $level );
736
737
			while( ( $row = $results->fetch() ) !== null )
738
			{
739
				if( ( $row['price.taxrates'] = json_decode( $config = $row['price.taxrates'], true ) ) === null )
740
				{
741
					$msg = sprintf( 'Invalid JSON as result of search for ID "%2$s" in "%1$s": %3$s', 'mshop_price.taxrates', $row['price.id'], $config );
742
					$this->context()->logger()->warning( $msg, 'core/price' );
743
				}
744
				$map[$row['price.id']] = $row;
745
			}
746
747
			$dbm->release( $conn, $dbname );
748
		}
749
		catch( \Exception $e )
750
		{
751
			$dbm->release( $conn, $dbname );
752
			throw $e;
753
		}
754
755
		$propItems = []; $name = 'price/property';
756
		if( isset( $ref[$name] ) || in_array( $name, $ref, true ) )
757
		{
758
			$propTypes = isset( $ref[$name] ) && is_array( $ref[$name] ) ? $ref[$name] : null;
759
			$propItems = $this->getPropertyItems( array_keys( $map ), 'price', $propTypes );
760
		}
761
762
		return $this->buildItems( $map, $ref, 'price', $propItems );
763
	}
764
765
766
	/**
767
	 * Creates a filter object.
768
	 *
769
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
770
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
771
	 * @return \Aimeos\MW\Criteria\Iface Returns the filter object
772
	 */
773
	public function filter( ?bool $default = false, bool $site = false ) : \Aimeos\MW\Criteria\Iface
774
	{
775
		if( $default !== false )
776
		{
777
			$object = $this->filterBase( 'price', $default );
778
779
			if( $currencyid = $this->context()->locale()->getCurrencyId() ) {
780
				$object->add( ['price.currencyid' => $currencyid] );
781
			}
782
783
			return $object;
784
		}
785
786
		return parent::filter();
787
	}
788
789
790
	/**
791
	 * Returns a new manager for price extensions.
792
	 *
793
	 * @param string $manager Name of the sub manager type in lower case
794
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
795
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager for different extensions, e.g type, etc.
796
	 */
797
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
798
	{
799
		return $this->getSubManagerBase( 'price', $manager, $name );
800
	}
801
802
803
	/**
804
	 * Creates a new price item
805
	 *
806
	 * @param array $values List of attributes for price item
807
	 * @param \Aimeos\MShop\Common\Item\Lists\Iface[] $listItems List of list items
808
	 * @param \Aimeos\MShop\Common\Item\Iface[] $refItems List of referenced items
809
	 * @param \Aimeos\MShop\Common\Item\Property\Iface[] $propItems List of property items
810
	 * @return \Aimeos\MShop\Price\Item\Iface New price item
811
	 */
812
	protected function createItemBase( array $values = [], array $listItems = [], array $refItems = [],
813
		array $propItems = [] ) : \Aimeos\MShop\Common\Item\Iface
814
	{
815
		$values['.currencyid'] = $this->currencyId;
816
		$values['.precision'] = $this->precision;
817
818
		if( !isset( $values['price.taxflag'] ) ) {
819
			$values['price.taxflag'] = $this->taxflag;
820
		}
821
822
		return new \Aimeos\MShop\Price\Item\Standard( $values, $listItems, $refItems, $propItems );
823
	}
824
}
825