Standard::isSubscription()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 10
c 0
b 0
f 0
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2017-2025
6
 * @package Client
7
 * @subpackage JsonApi
8
 */
9
10
11
namespace Aimeos\Client\JsonApi\Order;
12
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
16
17
/**
18
 * JSON API standard client
19
 *
20
 * @package Client
21
 * @subpackage JsonApi
22
 */
23
class Standard
24
	extends \Aimeos\Client\JsonApi\Base
25
	implements \Aimeos\Client\JsonApi\Iface
26
{
27
	/** client/jsonapi/order/name
28
	 * Class name of the used order client implementation
29
	 *
30
	 * Each default JSON API client can be replace by an alternative imlementation.
31
	 * To use this implementation, you have to set the last part of the class
32
	 * name as configuration value so the client factory knows which class it
33
	 * has to instantiate.
34
	 *
35
	 * For example, if the name of the default class is
36
	 *
37
	 *  \Aimeos\Client\JsonApi\Order\Standard
38
	 *
39
	 * and you want to replace it with your own version named
40
	 *
41
	 *  \Aimeos\Client\JsonApi\Order\Myorder
42
	 *
43
	 * then you have to set the this configuration option:
44
	 *
45
	 *  client/jsonapi/order/name = Myorder
46
	 *
47
	 * The value is the last part of your own class name and it's case sensitive,
48
	 * so take care that the configuration value is exactly named like the last
49
	 * part of the class name.
50
	 *
51
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
52
	 * characters are possible! You should always start the last part of the class
53
	 * name with an upper case character and continue only with lower case characters
54
	 * or numbers. Avoid chamel case names like "MyOrder"!
55
	 *
56
	 * @param string Last part of the class name
57
	 * @since 2017.03
58
	 * @category Developer
59
	 */
60
61
	/** client/jsonapi/order/decorators/excludes
62
	 * Excludes decorators added by the "common" option from the JSON API clients
63
	 *
64
	 * Decorators extend the functionality of a class by adding new aspects
65
	 * (e.g. log what is currently done), executing the methods of the underlying
66
	 * class only in certain conditions (e.g. only for logged in users) or
67
	 * modify what is returned to the caller.
68
	 *
69
	 * This option allows you to remove a decorator added via
70
	 * "client/jsonapi/common/decorators/default" before they are wrapped
71
	 * around the JsonApi client.
72
	 *
73
	 *  client/jsonapi/decorators/excludes = array( 'decorator1' )
74
	 *
75
	 * This would remove the decorator named "decorator1" from the list of
76
	 * common decorators ("\Aimeos\Client\JsonApi\Common\Decorator\*") added via
77
	 * "client/jsonapi/common/decorators/default" for the JSON API client.
78
	 *
79
	 * @param array List of decorator names
80
	 * @since 2017.07
81
	 * @category Developer
82
	 * @see client/jsonapi/common/decorators/default
83
	 * @see client/jsonapi/order/decorators/global
84
	 * @see client/jsonapi/order/decorators/local
85
	 */
86
87
	/** client/jsonapi/order/decorators/global
88
	 * Adds a list of globally available decorators only to the JsonApi client
89
	 *
90
	 * Decorators extend the functionality of a class by adding new aspects
91
	 * (e.g. log what is currently done), executing the methods of the underlying
92
	 * class only in certain conditions (e.g. only for logged in users) or
93
	 * modify what is returned to the caller.
94
	 *
95
	 * This option allows you to wrap global decorators
96
	 * ("\Aimeos\Client\JsonApi\Common\Decorator\*") around the JsonApi
97
	 * client.
98
	 *
99
	 *  client/jsonapi/order/decorators/global = array( 'decorator1' )
100
	 *
101
	 * This would add the decorator named "decorator1" defined by
102
	 * "\Aimeos\Client\JsonApi\Common\Decorator\Decorator1" only to the
103
	 * "order" JsonApi client.
104
	 *
105
	 * @param array List of decorator names
106
	 * @since 2017.07
107
	 * @category Developer
108
	 * @see client/jsonapi/common/decorators/default
109
	 * @see client/jsonapi/order/decorators/excludes
110
	 * @see client/jsonapi/order/decorators/local
111
	 */
112
113
	/** client/jsonapi/order/decorators/local
114
	 * Adds a list of local decorators only to the JsonApi client
115
	 *
116
	 * Decorators extend the functionality of a class by adding new aspects
117
	 * (e.g. log what is currently done), executing the methods of the underlying
118
	 * class only in certain conditions (e.g. only for logged in users) or
119
	 * modify what is returned to the caller.
120
	 *
121
	 * This option allows you to wrap local decorators
122
	 * ("\Aimeos\Client\JsonApi\Order\Decorator\*") around the JsonApi
123
	 * client.
124
	 *
125
	 *  client/jsonapi/order/decorators/local = array( 'decorator2' )
126
	 *
127
	 * This would add the decorator named "decorator2" defined by
128
	 * "\Aimeos\Client\JsonApi\Order\Decorator\Decorator2" only to the
129
	 * "order" JsonApi client.
130
	 *
131
	 * @param array List of decorator names
132
	 * @since 2017.07
133
	 * @category Developer
134
	 * @see client/jsonapi/common/decorators/default
135
	 * @see client/jsonapi/order/decorators/excludes
136
	 * @see client/jsonapi/order/decorators/global
137
	 */
138
139
140
	/**
141
	 * Returns the resource or the resource list
142
	 *
143
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
144
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
145
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
146
	 */
147
	public function get( ServerRequestInterface $request, ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
148
	{
149
		$view = $this->view();
150
		$ref = $view->param( 'include', [] );
151
152
		if( is_string( $ref ) ) {
153
			$ref = explode( ',', str_replace( '.', '/', $ref ) );
154
		}
155
156
		try
157
		{
158
			$cntl = \Aimeos\Controller\Frontend::create( $this->context(), 'order' )->uses( $ref );
159
160
			if( ( $id = $view->param( 'id' ) ) != '' )
161
			{
162
				$view->items = $cntl->get( $id );
163
				$view->total = 1;
164
			}
165
			else
166
			{
167
				$total = 0;
168
				$items = $cntl->sort( $view->param( 'sort', '-order.id' ) )
169
					->slice( $view->param( 'page/offset', 0 ), $view->param( 'page/limit', 48 ) )
170
					->parse( (array) $view->param( 'filter', [] ) )
171
					->search( $total );
172
173
				$view->items = $items;
174
				$view->total = $total;
175
			}
176
177
			$status = 200;
178
		}
179
		catch( \Aimeos\Controller\Frontend\Exception $e )
180
		{
181
			$status = 403;
182
			$view->errors = $this->getErrorDetails( $e, 'controller/frontend' );
183
		}
184
		catch( \Aimeos\MShop\Exception $e )
185
		{
186
			$status = 404;
187
			$view->errors = $this->getErrorDetails( $e, 'mshop' );
188
		}
189
		catch( \Exception $e )
190
		{
191
			$status = $e->getCode() >= 100 && $e->getCode() < 600 ? $e->getCode() : 500;
192
			$view->errors = $this->getErrorDetails( $e );
193
		}
194
195
		return $this->render( $response, $view, $status );
196
	}
197
198
199
	/**
200
	 * Creates or updates the resource or the resource list
201
	 *
202
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
203
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
204
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
205
	 */
206
	public function post( ServerRequestInterface $request, ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
207
	{
208
		$view = $this->view();
209
210
		try
211
		{
212
			$body = (string) $request->getBody();
213
214
			if( ( $payload = json_decode( $body ) ) === null || !isset( $payload->data->attributes ) ) {
215
				throw new \Aimeos\Client\JsonApi\Exception( 'Invalid JSON in body', 400 );
216
			}
217
218
			if( !isset( $payload->data->attributes->{'order.id'} ) ) {
219
				throw new \Aimeos\Client\JsonApi\Exception( sprintf( 'No order ID found' ), 400 );
220
			}
221
222
			$item = $this->getOrder( $payload->data->attributes->{'order.id'} );
223
224
			$view->form = $this->getPaymentForm( $item, (array) $payload->data->attributes );
225
			$view->items = $item;
226
			$view->total = 1;
227
228
			\Aimeos\Controller\Frontend::create( $this->context(), 'order' )->save( $item );
229
			$status = 201;
230
		}
231
		catch( \Aimeos\Client\JsonApi\Exception $e )
232
		{
233
			$status = $e->getCode();
234
			$view->errors = $this->getErrorDetails( $e, 'client/jsonapi' );
235
		}
236
		catch( \Aimeos\Controller\Frontend\Exception $e )
237
		{
238
			$status = 403;
239
			$view->errors = $this->getErrorDetails( $e, 'controller/frontend' );
240
		}
241
		catch( \Aimeos\MShop\Exception $e )
242
		{
243
			$status = 404;
244
			$view->errors = $this->getErrorDetails( $e, 'mshop' );
245
		}
246
		catch( \Exception $e )
247
		{
248
			$status = $e->getCode() >= 100 && $e->getCode() < 600 ? $e->getCode() : 500;
249
			$view->errors = $this->getErrorDetails( $e );
250
		}
251
252
		return $this->render( $response, $view, $status );
253
	}
254
255
256
	/**
257
	 * Returns the available REST verbs and the available parameters
258
	 *
259
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
260
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
261
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
262
	 */
263
	public function options( ServerRequestInterface $request, ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
264
	{
265
		$view = $this->view();
266
267
		$view->attributes = [
268
			'order.id' => [
269
				'label' => 'ID of the stored basket/order (POST only)',
270
				'type' => 'string', 'default' => '', 'required' => true,
271
			],
272
		];
273
274
		$tplconf = 'client/jsonapi/template-options';
275
		$default = 'options-standard';
276
277
		$body = $view->render( $view->config( $tplconf, $default ) );
278
279
		return $response->withHeader( 'Allow', 'GET,OPTIONS,POST' )
280
			->withHeader( 'Cache-Control', 'max-age=300' )
281
			->withHeader( 'Content-Type', 'application/vnd.api+json' )
282
			->withBody( $view->response()->createStreamFromString( $body ) )
283
			->withStatus( 200 );
0 ignored issues
show
Bug introduced by
The method withStatus() does not exist on Psr\Http\Message\MessageInterface. It seems like you code against a sub-type of Psr\Http\Message\MessageInterface such as Psr\Http\Message\ResponseInterface or Aimeos\Base\View\Helper\Request\Standard. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

283
			->/** @scrutinizer ignore-call */ withStatus( 200 );
Loading history...
284
	}
285
286
287
	/**
288
	 * Returns the order object for the given ID
289
	 *
290
	 * @param string $orderId Unique order ID
291
	 * @return \Aimeos\MShop\Order\Item\Iface Order object including only the services
292
	 * @throws \Aimeos\Client\JsonApi\Exception If basket ID is not the same as stored before in the current session
293
	 */
294
	protected function getOrder( string $orderId ) : \Aimeos\MShop\Order\Item\Iface
295
	{
296
		$context = $this->context();
297
		$id = $context->session()->get( 'aimeos/order.id' );
298
299
		if( $id != $orderId )
300
		{
301
			$msg = sprintf( 'No order for the "order.id" ("%1$s") found', $orderId );
302
			throw new \Aimeos\Client\JsonApi\Exception( $msg, 403 );
303
		}
304
305
		return \Aimeos\Controller\Frontend::create( $context, 'basket' )->load( $id, ['order/address', 'order/service'], false );
306
	}
307
308
309
	/**
310
	 * Returns the form helper object for building the payment form in the frontend
311
	 *
312
	 * @param \Aimeos\MShop\Order\Item\Iface $orderItem Saved order item created for the basket object
313
	 * @param array $attributes Associative list of payment data pairs
314
	 * @return \Aimeos\MShop\Common\Helper\Form\Iface|null Form object with URL, parameters, etc. or null if no form data is required
315
	 */
316
	protected function getPaymentForm( \Aimeos\MShop\Order\Item\Iface $orderItem, array $attributes ) : ?\Aimeos\MShop\Common\Helper\Form\Iface
317
	{
318
		$view = $this->view();
319
		$context = $this->context();
320
321
		$total = $orderItem->getPrice()->getValue() + $orderItem->getPrice()->getCosts();
322
		$services = $orderItem->getService( \Aimeos\MShop\Order\Item\Service\Base::TYPE_PAYMENT );
323
324
		if( $services === [] || $total <= '0.00' && $this->isSubscription( $orderItem->getProducts() ) === false )
325
		{
326
			$cntl = \Aimeos\Controller\Frontend::create( $context, 'order' );
327
			$cntl->save( $orderItem->setStatusPayment( \Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED ) );
328
329
			$url = $this->getUrlConfirm( $view, [], ['absoluteUri' => true, 'namespace' => false] );
330
			return new \Aimeos\MShop\Common\Helper\Form\Standard( $url, 'GET' );
331
		}
332
333
		if( ( $service = reset( $services ) ) !== false )
334
		{
335
			$args = array( 'code' => $service->getCode(), 'orderid' => $orderItem->getId() );
336
			$config = array( 'absoluteUri' => true, 'namespace' => false );
337
			$urls = array(
338
				'payment.url-success' => $this->getUrlConfirm( $view, $args, $config ),
339
				'payment.url-update' => $this->getUrlUpdate( $view, $args, $config ),
340
			);
341
342
			foreach( $service->getAttributeItems() as $item ) {
343
				$attributes[$item->getCode()] = $item->getValue();
344
			}
345
346
			$serviceCntl = \Aimeos\Controller\Frontend::create( $context, 'service' );
347
			return $serviceCntl->process( $orderItem, $service->getServiceId(), $urls, $attributes );
348
		}
349
350
		return null;
351
	}
352
353
354
	/**
355
	 * Returns the URL to the confirm page.
356
	 *
357
	 * @param \Aimeos\Base\View\Iface $view View object
358
	 * @param array $params Parameters that should be part of the URL
359
	 * @param array $config Default URL configuration
360
	 * @return string URL string
361
	 */
362
	protected function getUrlConfirm( \Aimeos\Base\View\Iface $view, array $params, array $config ) : string
363
	{
364
		$target = $view->config( 'client/html/checkout/confirm/url/target' );
365
		$cntl = $view->config( 'client/html/checkout/confirm/url/controller', 'checkout' );
366
		$action = $view->config( 'client/html/checkout/confirm/url/action', 'confirm' );
367
		$config = $view->config( 'client/html/checkout/confirm/url/config', $config );
368
369
		return $view->url( $target, $cntl, $action, $params, [], $config );
370
	}
371
372
373
	/**
374
	 * Returns the URL to the update page.
375
	 *
376
	 * @param \Aimeos\Base\View\Iface $view View object
377
	 * @param array $params Parameters that should be part of the URL
378
	 * @param array $config Default URL configuration
379
	 * @return string URL string
380
	 */
381
	protected function getUrlUpdate( \Aimeos\Base\View\Iface $view, array $params, array $config ) : string
382
	{
383
		$target = $view->config( 'client/html/checkout/update/url/target' );
384
		$cntl = $view->config( 'client/html/checkout/update/url/controller', 'checkout' );
385
		$action = $view->config( 'client/html/checkout/update/url/action', 'update' );
386
		$config = $view->config( 'client/html/checkout/update/url/config', $config );
387
388
		return $view->url( $target, $cntl, $action, $params, [], $config );
389
	}
390
391
392
	/**
393
	 * Tests if one of the products is a subscription
394
	 *
395
	 * @param \Aimeos\Map $products Ordered products implementing \Aimeos\MShop\Order\Item\Product\Iface
396
	 * @return bool True if at least one product is a subscription, false if not
397
	 */
398
	protected function isSubscription( \Aimeos\Map $products ) : bool
399
	{
400
		foreach( $products as $orderProduct )
401
		{
402
			if( $orderProduct->getAttributeItem( 'interval', 'config' ) ) {
403
				return true;
404
			}
405
		}
406
407
		return false;
408
	}
409
410
411
	/**
412
	 * Returns the response object with the rendered header and body
413
	 *
414
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
415
	 * @param \Aimeos\Base\View\Iface $view View instance
416
	 * @param int $status HTTP status code
417
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
418
	 */
419
	protected function render( ResponseInterface $response, \Aimeos\Base\View\Iface $view, int $status ) : \Psr\Http\Message\ResponseInterface
420
	{
421
		/** client/jsonapi/order/template
422
		 * Relative path to the order JSON API template
423
		 *
424
		 * The template file contains the code and processing instructions
425
		 * to generate the result shown in the JSON API body. The
426
		 * configuration string is the path to the template file relative
427
		 * to the templates directory (usually in templates/client/jsonapi).
428
		 *
429
		 * You can overwrite the template file configuration in extensions and
430
		 * provide alternative templates. These alternative templates should be
431
		 * named like the default one but with the string "standard" replaced by
432
		 * an unique name. You may use the name of your project for this. If
433
		 * you've implemented an alternative client class as well, "standard"
434
		 * should be replaced by the name of the new class.
435
		 *
436
		 * @param string Relative path to the template creating the body of the JSON API
437
		 * @since 2017.03
438
		 * @category Developer
439
		 */
440
		$tplconf = 'client/jsonapi/order/template';
441
		$default = 'order/standard';
442
443
		$body = $view->render( $view->config( $tplconf, $default ) );
444
445
		return $response->withHeader( 'Allow', 'GET,OPTIONS,POST' )
446
			->withHeader( 'Cache-Control', 'no-cache, private' )
447
			->withHeader( 'Content-Type', 'application/vnd.api+json' )
448
			->withBody( $view->response()->createStreamFromString( $body ) )
449
			->withStatus( $status );
450
	}
451
}
452