Passed
Push — master ( 9f10fb...4013e0 )
by Aimeos
05:50
created

Base::log()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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