Completed
Push — master ( d02bdd...0a5fc3 )
by Andrii
02:11
created

PriceFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\price;
12
13
/**
14
 * Default price factory.
15
 *
16
 * @author Andrii Vasyliev <[email protected]>
17
 */
18
class PriceFactory implements PriceFactoryInterface
19
{
20
    protected $creators = [
21
        EnumPrice::class    => 'createEnumPrice',
22
        SinglePrice::class  => 'createSinglePrice',
23
    ];
24
25
    protected $types = [
26
        'enum'      => EnumPrice::class,
27
        'single'    => SinglePrice::class,
28
    ];
29
30 2
    public function __construct(array $types = []) {
31
        $this->types = $types;
32 2
    }
33 2
34
    /**
35
     * Creates price object.
36
     * @return Price
37
     */
38
    public function create(PriceCreationDto $dto)
39 2
    {
40
        $type = $dto->type->getName();
41 2
        if (!isset($this->types[$type])) {
42 2
            throw new FailedCreatePriceException("unknown type: $type");
43
        }
44
        $class = $this->types[$type];
45 2
        if (!isset($this->creators[$class])) {
46 2
            throw new FailedCreatePriceException("unknown class: $class");
47
        }
48
        $method = $this->creators[$class];
49 2
        return $this->{$method}($dto);
50 2
    }
51
52
    public function createEnumPrice(PriceCreationDto $dto)
53 1
    {
54
        return new EnumPrice($dto->id, $dto->type, $dto->target, $dto->unit, $dto->prices);
55 1
    }
56
57
    public function createSinglePrice(PriceCreationDto $dto)
58 1
    {
59
        return new SinglePrice($dto->id, $dto->type, $dto->target, $dto->prepaid, $dto->price);
60 1
    }
61
}
62