Passed
Push — master ( f72d01...db0b8d )
by Aimeos
04:47
created

Base::call()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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