Passed
Push — master ( d59596...9d2c64 )
by Adrien
27:21 queued 13:39
created

Invoicer::createOrder()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3.0009

Importance

Changes 0
Metric Value
cc 3
eloc 19
nc 2
nop 1
dl 0
loc 29
ccs 20
cts 21
cp 0.9524
crap 3.0009
rs 9.6333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Service;
6
7
use Application\Model\AbstractProduct;
8
use Application\Model\Order;
9
use Application\Model\OrderLine;
10
use Application\Model\Product;
11
use Application\Model\Subscription;
12
use Application\Model\User;
13
use Application\Repository\UserRepository;
14
use Doctrine\ORM\EntityManager;
15
use Ecodev\Felix\Api\Exception;
16
use Money\Money;
17
18
/**
19
 * Service to create order and transactions for products and their quantity.
20
 */
21
class Invoicer
22
{
23
    private readonly UserRepository $userRepository;
24
25 1
    public function __construct(private readonly EntityManager $entityManager)
26
    {
27 1
        $this->userRepository = $this->entityManager->getRepository(User::class);
0 ignored issues
show
Bug introduced by
The property userRepository is declared read-only in Application\Service\Invoicer.
Loading history...
28
    }
29
30 14
    public function createOrder(array $orderInput): ?Order
31
    {
32 14
        $lines = $orderInput['orderLines'];
33 14
        if (!$lines) {
34
            return null;
35
        }
36
37 14
        $order = new Order();
38 14
        $order->setPaymentMethod($orderInput['paymentMethod']);
39 14
        $order->setFirstName($orderInput['firstName'] ?? '');
40 14
        $order->setLastName($orderInput['lastName'] ?? '');
41 14
        $order->setStreet($orderInput['street'] ?? '');
42 14
        $order->setLocality($orderInput['locality'] ?? '');
43 14
        $order->setPostcode($orderInput['postcode'] ?? '');
44 14
        $order->setCountry($orderInput['country'] ?? null);
45
46 14
        $this->userRepository->getAclFilter()->runWithoutAcl(function () use ($lines, $order): void {
47 14
            $this->entityManager->persist($order);
48
49 14
            $total = Money::CHF(0);
50 14
            foreach ($lines as $line) {
51 14
                $args = $this->extractArgsFromLine($line);
52
53 13
                $orderLine = $this->createOrderLine($order, ...$args);
0 ignored issues
show
Bug introduced by
It seems like $args can also be of type Money\Money; however, parameter $product of Application\Service\Invoicer::createOrderLine() does only seem to accept Application\Model\AbstractProduct|null, maybe add an additional type check? ( Ignorable by Annotation )

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

53
                $orderLine = $this->createOrderLine($order, /** @scrutinizer ignore-type */ ...$args);
Loading history...
54 13
                $total = $total->add($orderLine->getBalanceCHF());
55
            }
56 14
        });
57
58 13
        return $order;
59
    }
60
61 13
    private function createOrderLine(Order $order, ?AbstractProduct $product, Money $pricePerUnit, int $quantity, bool $isCHF, string $type, array $additionalEmails): OrderLine
62
    {
63 13
        $orderLine = new OrderLine();
64 13
        $this->entityManager->persist($orderLine);
65 13
        $orderLine->setOrder($order);
66
67 13
        $this->updateOrderLine($orderLine, $product, $pricePerUnit, $quantity, $isCHF, $type, $additionalEmails);
68
69 13
        return $orderLine;
70
    }
71
72 15
    private function extractArgsFromLine($input): array
73
    {
74 15
        $product = $input['product'] ?? null;
75 15
        $subscription = $input['subscription'] ?? null;
76 15
        $quantity = $input['quantity'];
77 15
        $isCHF = $input['isCHF'];
78 15
        $type = $input['type'];
79 15
        $additionalEmails = $input['additionalEmails'];
80 15
        $pricePerUnit = $input['pricePerUnit'] ?? null;
81 15
        $this->assertExactlyOneNotNull($product, $subscription, $pricePerUnit);
82
83 15
        $abstractProduct = $product ?? $subscription;
84 15
        $pricePerUnit = $this->getPricePerUnit($abstractProduct, $pricePerUnit, $isCHF);
85
86 14
        if ($additionalEmails && !$subscription) {
87
            throw new Exception('Cannot submit additionalEmails without a subscription');
88
        }
89
90 14
        if ($additionalEmails && !$subscription->isPro()) {
91
            throw new Exception('Cannot submit additionalEmails with a subscription that is not pro');
92
        }
93
94
        // User cannot choose type of a subscription
95 14
        if ($subscription) {
96 2
            $type = $subscription->getType();
97
        }
98
99 14
        return [
100 14
            $abstractProduct,
101 14
            $pricePerUnit,
102 14
            $quantity,
103 14
            $isCHF,
104 14
            $type,
105 14
            $additionalEmails,
106 14
        ];
107
    }
108
109 15
    private function assertExactlyOneNotNull(...$args): void
110
    {
111 15
        $onlyNotNull = array_filter($args, fn ($val) => $val !== null);
112
113 15
        if (count($onlyNotNull) !== 1) {
114
            throw new Exception('Must have a product, or a subscription, or a pricePerUnit. And not a mixed of those.');
115
        }
116
    }
117
118 4
    public function updateOrderLineAndTransactionLine(OrderLine $orderLine, array $line): void
119
    {
120 4
        $this->userRepository->getAclFilter()->runWithoutAcl(function () use ($orderLine, $line): void {
121 4
            $args = $this->extractArgsFromLine($line);
122 4
            $this->updateOrderLine($orderLine, ...$args);
0 ignored issues
show
Bug introduced by
It seems like $args can also be of type Money\Money; however, parameter $product of Application\Service\Invoicer::updateOrderLine() does only seem to accept Application\Model\AbstractProduct|null, maybe add an additional type check? ( Ignorable by Annotation )

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

122
            $this->updateOrderLine($orderLine, /** @scrutinizer ignore-type */ ...$args);
Loading history...
123 4
        });
124
    }
125
126 14
    private function updateOrderLine(OrderLine $orderLine, ?AbstractProduct $product, Money $pricePerUnit, int $quantity, bool $isCHF, string $type, array $additionalEmails): void
127
    {
128 14
        if ($isCHF) {
129 13
            $balanceCHF = $pricePerUnit->multiply($quantity);
130 13
            $balanceEUR = Money::EUR(0);
131
        } else {
132 2
            $balanceCHF = Money::CHF(0);
133 2
            $balanceEUR = $pricePerUnit->multiply($quantity);
134
        }
135
136 14
        if (!$product) {
137 3
            $orderLine->setDonation();
138 11
        } elseif ($product instanceof Product) {
139 9
            $orderLine->setProduct($product);
140 2
        } elseif ($product instanceof Subscription) {
141 2
            $orderLine->setSubscription($product);
142
        } else {
143
            throw new Exception('Unsupported subclass of product');
144
        }
145
146 14
        $orderLine->setIsCHF($isCHF);
147 14
        $orderLine->setType($type);
148 14
        $orderLine->setQuantity($quantity);
149 14
        $orderLine->setBalanceCHF($balanceCHF);
150 14
        $orderLine->setBalanceEUR($balanceEUR);
151 14
        $orderLine->setAdditionalEmails($additionalEmails);
152
    }
153
154 15
    private function getPricePerUnit(?AbstractProduct $product, ?Money $pricePerUnit, bool $isCHF): Money
155
    {
156 15
        if ($product && $isCHF) {
157 11
            return $product->getPricePerUnitCHF();
158
        }
159
160 5
        if ($product) {
161 1
            return $product->getPricePerUnitEUR();
162
        }
163
164 4
        if ($pricePerUnit === null || !$pricePerUnit->isPositive()) {
165 1
            throw new Exception('A donation must have strictly positive price');
166
        }
167
168
        // The API always assume CHF, but if the client specifically say it is EUR, we need to convert
169 3
        if (!$isCHF) {
170 1
            return Money::EUR($pricePerUnit->getAmount());
171
        }
172
173 2
        return $pricePerUnit;
174
    }
175
}
176