Passed
Push — master ( 159f60...4cb637 )
by Aimeos
06:08
created

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