Completed
Push — master ( 8e5b59...8530e7 )
by Andrii
01:51
created

PriceFactory::findMethodForClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2.0625
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\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
    /**
31
     * @var string default price class, when given will be used for not found types
32
     */
33
    protected $defaultClass = null;
34
35 2
    public function __construct(array $types = [], $defaultClass = null)
36
    {
37 2
        $this->types = $types;
38 2
        $this->defaultClass = $defaultClass;
39 2
    }
40
41
    /**
42
     * Creates price object.
43
     * @return Price
44
     */
45 2
    public function create(PriceCreationDto $dto)
46
    {
47 2
        $type = $dto->type->getName();
0 ignored issues
show
Bug introduced by
Consider using $dto->type->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
48 2
        $class = $this->findClassForType($type);
49 2
        $method = $this->findMethodForClass($class);
50
51 2
        return $this->{$method}($dto);
52
    }
53
54 2
    public function findClassForType($type)
55
    {
56 2
        if (isset($this->types[$type])) {
57 2
            return $this->types[$type];
58
        }
59
        if ($this->defaultClass) {
60
            return $this->defaultClass;
61
        }
62
        throw new FailedCreatePriceException("unknown type: $type");
63
    }
64
65 2
    public function findMethodForClass($class)
66
    {
67 2
        if (isset($this->creators[$class])) {
68 2
            return $this->creators[$class];
69
        }
70
        throw new FailedCreatePriceException("unknown class: $class");
71
    }
72
73 1
    public function createEnumPrice(PriceCreationDto $dto)
74
    {
75 1
        return new EnumPrice($dto->id, $dto->type, $dto->target, $dto->plan, $dto->unit, $dto->currency, $dto->sums);
76
    }
77
78 1
    public function createSinglePrice(PriceCreationDto $dto)
79
    {
80 1
        return new SinglePrice($dto->id, $dto->type, $dto->target, $dto->plan, $dto->prepaid, $dto->price);
81
    }
82
}
83