Completed
Push — master ( 87cabe...26ac79 )
by Andrii
02:26
created

PriceFactory::createEnumPrice()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
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
    public function __construct(array $types = []) {
31
        $this->types = $types;
32
    }
33
34
    /**
35
     * Creates price object.
36
     * @return Price
37
     */
38
    public function create(PriceCreationDto $dto)
39
    {
40
        $type = $dto->type->getName();
41
        if (!isset($this->types[$type])) {
42
            throw new FailedCreatePriceException("unknown type: $type");
43
        }
44
        $class = $this->types[$type];
45
        if (!isset($this->creators[$class])) {
46
            throw new FailedCreatePriceException("unknown class: $class");
47
        }
48
        $method = $this->creators[$class];
49
        return $this->{$method}($dto);
50
    }
51
52
    public function createEnumPrice(PriceCreationDto $dto)
53
    {
54
        return new EnumPrice($dto->id, $dto->type, $dto->target, $dto->unit, $dto->prices);
55
    }
56
57
    public function createSinglePrice(PriceCreationDto $dto)
58
    {
59
        return new SinglePrice($dto->id, $dto->type, $dto->target, $dto->prepaid, $dto->price);
60
    }
61
}
62