Completed
Push — master ( bc8cc8...6e347a )
by Dmitry
04:49
created

OneByOnePurchaseStrategy::addPosition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace hipanel\modules\finance\cart;
4
5
use hiqdev\hiart\ResponseErrorException;
6
use hiqdev\yii2\cart\ShoppingCart;
7
8
/**
9
 * Class OneByOnePurchaseStrategy is used to purchase positions one-by-one.
10
 *
11
 * @author Dmytro Naumenko <[email protected]>
12
 */
13
class OneByOnePurchaseStrategy implements PurchaseStrategyInterface
14
{
15
    use PurchaseResultTrait;
16
17
    /**
18
     * @var ShoppingCart
19
     */
20
    protected $cart;
21
22
    /**
23
     * @var AbstractCartPosition[]
24
     */
25
    protected $positions = [];
26
27
    /**
28
     * OneByOnePurchaseStrategy constructor.
29
     *
30
     * @param ShoppingCart $cart
31
     */
32
    public function __construct(ShoppingCart $cart)
33
    {
34
        $this->cart = $cart;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function addPosition(AbstractCartPosition $position)
41
    {
42
        $this->positions[$position->getId()] = $position;
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function run()
49
    {
50
        $this->resetPurchaseResults();
51
52
        foreach ($this->positions as $position) {
53
            $this->purchase($position);
54
        }
55
    }
56
57
    protected function purchase(AbstractCartPosition $position)
58
    {
59
        $purchase = $position->getPurchaseModel();
60
61
        try {
62
            if ($purchase->execute()) {
63
                $this->success[] = $purchase;
64
                return;
65
            }
66
67
            $this->error[] = new ErrorPurchaseException(reset(reset($purchase->getErrors())), $purchase);
0 ignored issues
show
Bug introduced by
$purchase->getErrors() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
Bug introduced by
reset($purchase->getErrors()) cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
68
        } catch (PendingPurchaseException $e) {
69
            $this->pending[] = $e;
70
        } catch (ResponseErrorException $e) {
71
            $this->error[] = new ErrorPurchaseException($e->getMessage(), $purchase, $e);
72
        } catch (\hiqdev\hiart\Exception $e) {
73
            $this->error[] = new ErrorPurchaseException($e->getMessage(), $purchase, $e);
74
        }
75
    }
76
}
77