Completed
Push — master ( d75f5b...e2e89f )
by Andrii
14:28
created

Collector::collect()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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