Passed
Push — master ( 0cda2e...f3fa1e )
by Aimeos
17:16 queued 07:34
created

Base::saveOrder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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-2021
7
 * @package MShop
8
 * @subpackage Service
9
 */
10
11
12
namespace Aimeos\MShop\Service\Provider;
13
14
15
/**
16
 * Abstract class for all service provider implementations with some default methods.
17
 *
18
 * @package MShop
19
 * @subpackage Service
20
 */
21
abstract class Base
22
	implements Iface, \Aimeos\MW\Macro\Iface
23
{
24
	use \Aimeos\MW\Macro\Traits;
25
26
	private $object;
27
	private $context;
28
	private $serviceItem;
29
	private $beGlobalConfig;
30
31
32
	/**
33
	 * Initializes the service provider object.
34
	 *
35
	 * @param \Aimeos\MShop\Context\Item\Iface $context Context object with required objects
36
	 * @param \Aimeos\MShop\Service\Item\Iface $serviceItem Service item with configuration for the provider
37
	 */
38
	public function __construct( \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\MShop\Service\Item\Iface $serviceItem )
39
	{
40
		$this->context = $context;
41
		$this->serviceItem = $serviceItem;
42
	}
43
44
45
	/**
46
	 * Returns the price when using the provider.
47
	 * Usually, this is the lowest price that is available in the service item but can also be a calculated based on
48
	 * the basket content, e.g. 2% of the value as transaction cost.
49
	 *
50
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
51
	 * @return \Aimeos\MShop\Price\Item\Iface Price item containing the price, shipping, rebate
52
	 */
53
	public function calcPrice( \Aimeos\MShop\Order\Item\Base\Iface $basket ) : \Aimeos\MShop\Price\Item\Iface
54
	{
55
		$manager = \Aimeos\MShop::create( $this->context, 'price' );
56
		$prices = $this->serviceItem->getRefItems( 'price', 'default', 'default' );
57
58
		return $prices->isEmpty() ? $manager->create() : $manager->getLowestPrice( $prices, 1 );
59
	}
60
61
62
	/**
63
	 * Checks the backend configuration attributes for validity.
64
	 *
65
	 * @param array $attributes Attributes added by the shop owner in the administraton interface
66
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
67
	 * 	known by the provider but aren't valid resp. null for attributes whose values are OK
68
	 */
69
	public function checkConfigBE( array $attributes ) : array
70
	{
71
		return [];
72
	}
73
74
75
	/**
76
	 * Checks the frontend configuration attributes for validity.
77
	 *
78
	 * @param array $attributes Attributes entered by the customer during the checkout process
79
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
80
	 * 	known by the provider but aren't valid resp. null for attributes whose values are OK
81
	 */
82
	public function checkConfigFE( array $attributes ) : array
83
	{
84
		return [];
85
	}
86
87
88
	/**
89
	 * Returns the configuration attribute definitions of the provider to generate a list of available fields and
90
	 * rules for the value of each field in the administration interface.
91
	 *
92
	 * @return array List of attribute definitions implementing \Aimeos\MW\Common\Critera\Attribute\Iface
93
	 */
94
	public function getConfigBE() : array
95
	{
96
		return [];
97
	}
98
99
100
	/**
101
	 * Returns the configuration attribute definitions of the provider to generate a list of available fields and
102
	 * rules for the value of each field in the frontend.
103
	 *
104
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
105
	 * @return array List of attribute definitions implementing \Aimeos\MW\Common\Critera\Attribute\Iface
106
	 */
107
	public function getConfigFE( \Aimeos\MShop\Order\Item\Base\Iface $basket ) : array
108
	{
109
		return [];
110
	}
111
112
113
	/**
114
	 * Returns the service item which also includes the configuration for the service provider.
115
	 *
116
	 * @return \Aimeos\MShop\Service\Item\Iface Service item
117
	 */
118
	public function getServiceItem() : \Aimeos\MShop\Service\Item\Iface
119
	{
120
		return $this->serviceItem;
121
	}
122
123
124
	/**
125
	 * Injects additional global configuration for the backend.
126
	 *
127
	 * It's used for adding additional backend configuration from the application
128
	 * like the URLs to redirect to.
129
	 *
130
	 * Supported redirect URLs are:
131
	 * - payment.url-success
132
	 * - payment.url-failure
133
	 * - payment.url-cancel
134
	 * - payment.url-update
135
	 *
136
	 * @param array $config Associative list of config keys and their value
137
	 * @return \Aimeos\MShop\Service\Provider\Iface Provider object for chaining method calls
138
	 */
139
	public function injectGlobalConfigBE( array $config ) : \Aimeos\MShop\Service\Provider\Iface
140
	{
141
		$this->beGlobalConfig = $config;
142
		return $this;
143
	}
144
145
146
	/**
147
	 * Checks if payment provider can be used based on the basket content.
148
	 * Checks for country, currency, address, RMS, etc. -> in separate decorators
149
	 *
150
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
151
	 * @return bool True if payment provider can be used, false if not
152
	 */
153
	public function isAvailable( \Aimeos\MShop\Order\Item\Base\Iface $basket ) : bool
154
	{
155
		return true;
156
	}
157
158
159
	/**
160
	 * Checks what features the payment provider implements.
161
	 *
162
	 * @param int $what Constant from abstract class
163
	 * @return bool True if feature is available in the payment provider, false if not
164
	 */
165
	public function isImplemented( int $what ) : bool
166
	{
167
		return false;
168
	}
169
170
171
	/**
172
	 * Queries for status updates for the given order if supported.
173
	 *
174
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
175
	 * @return \Aimeos\MShop\Order\Item\Iface Updated order item object
176
	 */
177
	public function query( \Aimeos\MShop\Order\Item\Iface $order ) : \Aimeos\MShop\Order\Item\Iface
178
	{
179
		$msg = $this->context->translate( 'mshop', 'Method "%1$s" for provider not available' );
180
		throw new \Aimeos\MShop\Service\Exception( sprintf( $msg, 'query' ) );
181
	}
182
183
184
	/**
185
	 * Injects the outer object into the decorator stack
186
	 *
187
	 * @param \Aimeos\MShop\Service\Provider\Iface $object First object of the decorator stack
188
	 * @return \Aimeos\MShop\Service\Provider\Iface Service object for chaining method calls
189
	 */
190
	public function setObject( \Aimeos\MShop\Service\Provider\Iface $object ) : \Aimeos\MShop\Service\Provider\Iface
191
	{
192
		$this->object = $object;
193
		return $this;
194
	}
195
196
197
	/**
198
	 * Looks for new update files and updates the orders for which status updates were received.
199
	 * If batch processing of files isn't supported, this method can be empty.
200
	 *
201
	 * @return bool True if the update was successful, false if async updates are not supported
202
	 * @throws \Aimeos\MShop\Service\Exception If updating one of the orders failed
203
	 */
204
	public function updateAsync() : bool
205
	{
206
		return false;
207
	}
208
209
210
	/**
211
	 * Updates the order status sent by payment gateway notifications
212
	 *
213
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
214
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
215
	 * @return \Psr\Http\Message\ResponseInterface Response object
216
	 */
217
	public function updatePush( \Psr\Http\Message\ServerRequestInterface $request,
218
		\Psr\Http\Message\ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
219
	{
220
		return $response->withStatus( 501, 'Not implemented' );
221
	}
222
223
224
	/**
225
	 * Updates the orders for whose status updates have been received by the confirmation page
226
	 *
227
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object with parameters and request body
228
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order item that should be updated
229
	 * @return \Aimeos\MShop\Order\Item\Iface Updated order item
230
	 * @throws \Aimeos\MShop\Service\Exception If updating the orders failed
231
	 */
232
	public function updateSync( \Psr\Http\Message\ServerRequestInterface $request,
233
		\Aimeos\MShop\Order\Item\Iface $order ) : \Aimeos\MShop\Order\Item\Iface
234
	{
235
		return $order;
236
	}
237
238
239
	/**
240
	 * Checks required fields and the types of the given data map
241
	 *
242
	 * @param array $criteria Multi-dimensional associative list of criteria configuration
243
	 * @param array $map Values to check agains the criteria
244
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
245
	 * 	known by the provider but aren't valid resp. null for attributes whose values are OK
246
	 */
247
	protected function checkConfig( array $criteria, array $map ) : array
248
	{
249
		$helper = new \Aimeos\MShop\Common\Helper\Config\Standard( $this->getConfigItems( $criteria ) );
250
		return $helper->check( $map );
251
	}
252
253
254
	/**
255
	 * Returns the criteria attribute items for the backend configuration
256
	 *
257
	 * @return \Aimeos\MW\Criteria\Attribute\Iface[] List of criteria attribute items
258
	 */
259
	protected function getConfigItems( array $configList ) : array
260
	{
261
		$list = [];
262
263
		foreach( $configList as $key => $config ) {
264
			$list[$key] = new \Aimeos\MW\Criteria\Attribute\Standard( $config );
265
		}
266
267
		return $list;
268
	}
269
270
271
	/**
272
	 * Returns the configuration value that matches one of the given keys.
273
	 *
274
	 * The config of the service item and (optionally) the global config
275
	 * is tested in the order of the keys. The first one that matches will
276
	 * be returned.
277
	 *
278
	 * @param array|string $keys Key name or list of key names that should be tested for in the order to test
279
	 * @param mixed $default Returned value if the key wasn't was found
280
	 * @return mixed Value of the first key that matches or null if none was found
281
	 */
282
	protected function getConfigValue( $keys, $default = null )
283
	{
284
		foreach( (array) $keys as $key )
285
		{
286
			if( ( $value = $this->getServiceItem()->getConfigValue( $key ) ) !== null ) {
287
				return $value;
288
			}
289
290
			if( isset( $this->beGlobalConfig[$key] ) ) {
291
				return $this->beGlobalConfig[$key];
292
			}
293
		}
294
295
		return $default;
296
	}
297
298
299
	/**
300
	 * Returns the context item.
301
	 *
302
	 * @return \Aimeos\MShop\Context\Item\Iface Context item
303
	 */
304
	protected function getContext() : \Aimeos\MShop\Context\Item\Iface
305
	{
306
		return $this->context;
307
	}
308
309
310
	/**
311
	 * Returns the calculated amount of the price item
312
	 *
313
	 * @param \Aimeos\MShop\Price\Item\Iface $price Price item
314
	 * @param bool $costs Include costs per item
315
	 * @param bool $tax Include tax
316
	 * @param int $precision Number for decimal digits
317
	 * @return string Formatted money amount
318
	 */
319
	protected function getAmount( \Aimeos\MShop\Price\Item\Iface $price, bool $costs = true, bool $tax = true,
320
		int $precision = null ) : string
321
	{
322
		$amount = $price->getValue();
323
324
		if( $costs === true ) {
325
			$amount += $price->getCosts();
326
		}
327
328
		if( $tax === true && $price->getTaxFlag() === false )
329
		{
330
			$tmp = clone $price;
331
332
			if( $costs === false )
333
			{
334
				$tmp->clear();
335
				$tmp->setValue( $price->getValue() );
336
				$tmp->setTaxRate( $price->getTaxRate() );
337
				$tmp->setQuantity( $price->getQuantity() );
338
			}
339
340
			$amount += $tmp->getTaxValue();
341
		}
342
343
		return number_format( $amount, $precision !== null ? $precision : $price->getPrecision(), '.', '' );
344
	}
345
346
347
	/**
348
	 * Returns the order service matching the given code from the basket
349
	 *
350
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
351
	 * @param string $type Service type constant from \Aimeos\MShop\Order\Item\Service\Base
352
	 * @param string $code Code of the service item that should be returned
353
	 * @return \Aimeos\MShop\Order\Item\Base\Service\Iface Order service item
354
	 * @throws \Aimeos\MShop\Order\Exception If no service for the given type and code is found
355
	 */
356
	protected function getBasketService( \Aimeos\MShop\Order\Item\Base\Iface $basket, string $type,
357
		string $code ) : \Aimeos\MShop\Order\Item\Base\Service\Iface
358
	{
359
		$msg = $this->context->translate( 'mshop', 'Service not available' );
360
361
		return map( $basket->getService( $type ) )->find( function( $service ) use ( $code ) {
362
				return $service->getCode() === $code;
363
		}, new \Aimeos\MShop\Service\Exception( $msg ) );
364
	}
365
366
367
	/**
368
	 * Returns the first object of the decorator stack
369
	 *
370
	 * @return \Aimeos\MShop\Service\Provider\Iface First object of the decorator stack
371
	 */
372
	protected function object() : \Aimeos\MShop\Service\Provider\Iface
373
	{
374
		return $this->object ?? $this;
375
	}
376
377
378
	/**
379
	 * Returns the order item for the given ID.
380
	 *
381
	 * @param string $id Unique order ID
382
	 * @return \Aimeos\MShop\Order\Item\Iface $item Order object
383
	 */
384
	protected function getOrder( string $id ) : \Aimeos\MShop\Order\Item\Iface
385
	{
386
		$manager = \Aimeos\MShop::create( $this->context, 'order' );
387
388
		$search = $manager->filter();
389
		$expr = [
390
			$search->compare( '==', 'order.id', $id ),
391
			$search->compare( '==', 'order.base.service.code', $this->serviceItem->getCode() ),
392
		];
393
		$search->setConditions( $search->and( $expr ) );
394
395
		if( ( $item = $manager->search( $search )->first() ) === null )
396
		{
397
			$msg = $this->context->translate( 'mshop', 'No order for ID "%1$s" found' );
398
			throw new \Aimeos\MShop\Service\Exception( sprintf( $msg, $id ) );
399
		}
400
401
		return $item;
402
	}
403
404
405
	/**
406
	 * Returns the base order which is equivalent to the basket.
407
	 *
408
	 * @param string $baseId Order base ID stored in the order item
409
	 * @param int $parts Bitmap of the basket parts that should be loaded
410
	 * @return \Aimeos\MShop\Order\Item\Base\Iface Basket, optional with addresses, products, services and coupons
411
	 */
412
	protected function getOrderBase( string $baseId,
413
		int $parts = \Aimeos\MShop\Order\Item\Base\Base::PARTS_SERVICE ) : \Aimeos\MShop\Order\Item\Base\Iface
414
	{
415
		return \Aimeos\MShop::create( $this->context, 'order/base' )->load( $baseId, $parts );
416
	}
417
418
419
	/**
420
	 * Logs the given message with the passed log level
421
	 *
422
	 * @param mixed $msg Message or object
423
	 * @param int $level Log level (default: ERR)
424
	 * @return self Same object for fluid method calls
425
	 */
426
	protected function log( $msg, int $level = \Aimeos\MW\Logger\Base::ERR ) : self
427
	{
428
		$facility = basename( str_replace( '\\', '/', get_class( $this ) ) );
429
		$trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
430
		$trace = array_pop( $trace ) ?: [];
431
		$name = ( $trace['class'] ?? '' ) . '::' . ( $trace['function'] ?? '' );
432
433
		if( !is_scalar( $msg ) ) {
434
			$msg = print_r( $msg, true );
435
		}
436
437
		$this->context->logger()->log( $name . ': ' . $msg, $level, 'core/service/' . $facility );
438
		return $this;
439
	}
440
441
442
	/**
443
	 * Saves the order item.
444
	 *
445
	 * @param \Aimeos\MShop\Order\Item\Iface $item Order object
446
	 * @return \Aimeos\MShop\Order\Item\Iface Order object including the generated ID
447
	 */
448
	protected function saveOrder( \Aimeos\MShop\Order\Item\Iface $item ) : \Aimeos\MShop\Order\Item\Iface
449
	{
450
		return \Aimeos\MShop::create( $this->context, 'order' )->save( $item );
451
	}
452
453
454
	/**
455
	 * Returns the service related data from the customer account if available
456
	 *
457
	 * @param string $customerId Unique customer ID the service token belongs to
458
	 * @param string $type Type of the value that should be returned
459
	 * @return array|string|null Service data or null if none is available
460
	 */
461
	protected function getCustomerData( string $customerId, string $type )
462
	{
463
		if( $customerId != null )
464
		{
465
			$manager = \Aimeos\MShop::create( $this->context, 'customer' );
466
			$item = $manager->get( $customerId, ['service'] );
467
			$serviceId = $this->getServiceItem()->getId();
468
469
			if( ( $listItem = $item->getListItem( 'service', 'default', $serviceId ) ) !== null ) {
470
				return $listItem->getConfigValue( $type );
471
			}
472
		}
473
474
		return null;
475
	}
476
477
478
	/**
479
	 * Saves the base order which is equivalent to the basket and its dependent objects.
480
	 *
481
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $base Order base object with associated items
482
	 * @param int $parts Bitmap of the basket parts that should be stored
483
	 * @return \Aimeos\MShop\Order\Item\Base\Iface Stored order base item
484
	 */
485
	protected function saveOrderBase( \Aimeos\MShop\Order\Item\Base\Iface $base,
486
		int $parts = \Aimeos\MShop\Order\Item\Base\Base::PARTS_SERVICE ) : \Aimeos\MShop\Order\Item\Base\Iface
487
	{
488
		return \Aimeos\MShop::create( $this->context, 'order/base' )->store( $base, $parts );
489
	}
490
491
492
	/**
493
	 * Sets the attributes in the given service item.
494
	 *
495
	 * @param \Aimeos\MShop\Order\Item\Base\Service\Iface $orderServiceItem Order service item that will be added to the basket
496
	 * @param array $attributes Attribute key/value pairs entered by the customer during the checkout process
497
	 * @param string $type Type of the configuration values (delivery or payment)
498
	 * @return \Aimeos\MShop\Order\Item\Base\Service\Iface Modified order service item
499
	 */
500
	protected function setAttributes( \Aimeos\MShop\Order\Item\Base\Service\Iface $orderServiceItem, array $attributes,
501
		string $type ) : \Aimeos\MShop\Order\Item\Base\Service\Iface
502
	{
503
		$manager = \Aimeos\MShop::create( $this->context, 'order/base/service/attribute' );
504
505
		foreach( $attributes as $key => $value )
506
		{
507
			$item = $manager->create();
508
			$item->setCode( $key );
509
			$item->setValue( $value );
510
			$item->setType( $type );
511
512
			$orderServiceItem->setAttributeItem( $item );
513
		}
514
515
		return $orderServiceItem;
516
	}
517
518
519
	/**
520
	 * Adds the service data to the customer account if available
521
	 *
522
	 * @param string $customerId Unique customer ID the service token belongs to
523
	 * @param string $type Type of the value that should be added
524
	 * @param string|array $data Service data to store
525
	 * @param \Aimeos\MShop\Service\Provider\Iface Provider object for chaining method calls
0 ignored issues
show
Bug introduced by
The type Aimeos\MShop\Service\Provider\Provider was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
526
	 */
527
	protected function setCustomerData( string $customerId, string $type, $data ) : \Aimeos\MShop\Service\Provider\Iface
528
	{
529
		if( $customerId != null )
530
		{
531
			$manager = \Aimeos\MShop::create( $this->context, 'customer' );
532
			$item = $manager->get( $customerId, ['service'] );
533
			$serviceId = $this->getServiceItem()->getId();
534
535
			if( ( $listItem = $item->getListItem( 'service', 'default', $serviceId, false ) ) === null )
536
			{
537
				$listManager = \Aimeos\MShop::create( $this->context, 'customer/lists' );
538
				$listItem = $listManager->create()->setType( 'default' )->setRefId( $serviceId );
539
			}
540
541
			$listItem->setConfig( array_merge( $listItem->getConfig(), [$type => $data] ) );
542
			$manager->save( $item->addListItem( 'service', $listItem ) );
543
		}
544
545
		return $this;
546
	}
547
548
549
	/**
550
	 * Throws an exception with the given message
551
	 *
552
	 * @param string $msg Message
553
	 * @param string|null $domain Translation domain
554
	 * @param int $code Custom error code
555
	 */
556
	protected function throw( string $msg, string $domain = null, int $code = 0 )
557
	{
558
		if( $domain ) {
559
			$msg = $this->context->translate( $domain, $msg );
560
		}
561
562
		throw new \Aimeos\MShop\Service\Exception( $msg, $code );
563
	}
564
}
565