Passed
Push — master ( 2bb224...2eebaa )
by Aimeos
06:13
created

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