Collector::collect()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
nc 6
nop 2
dl 0
loc 19
ccs 0
cts 18
cp 0
crap 42
rs 9.2222
c 1
b 0
f 0
1
<?php
2
/**
3
 * PHP Billing Library
4
 *
5
 * @link      https://github.com/hiqdev/php-billing
6
 * @package   php-billing
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\order;
12
13
use DateTimeImmutable;
14
use hiqdev\php\billing\action\ActionInterface;
15
use hiqdev\php\billing\Exception\NotSupportedException;
16
17
/**
18
 * Creates order from given source:
19
 * - Order: just pass by. Can be prepared more in other implementations.
20
 * - Action or Action[]: create order from given action(s)
21
 * @author Andrii Vasyliev <[email protected]>
22
 */
23
class Collector implements CollectorInterface
24
{
25
    public function collect($source, DateTimeImmutable $time = null): OrderInterface
26
    {
27
        if ($source instanceof OrderInterface) {
28
            return $source;
29
        }
30
        if ($source instanceof ActionInterface) {
31
            return Order::fromAction($source);
32
        }
33
        if (is_array($source)) {
34
            $item = reset($source);
35
            if ($item instanceof OrderInterface) {
36
                return $this->mergeOrders($source);
37
            }
38
            if ($item instanceof ActionInterface) {
39
                return Order::fromActions($source);
40
            }
41
        }
42
43
        throw new NotSupportedException('unknown order source');
44
    }
45
46
    protected function mergeOrders(array $orders): OrderInterface
47
    {
48
        $actions = [];
49
        foreach ($orders as $order) {
50
            $actions = array_merge($actions, $order->getActions());
51
        }
52
53
        return Order::fromActions($actions);
54
    }
55
}
56