Passed
Push — master ( e4c773...e22f62 )
by Aimeos
05:40
created

Base::require()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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