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
|
|
|
use hiqdev\billing\hiapi\models\Price; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Default price factory. |
17
|
|
|
* |
18
|
|
|
* @author Andrii Vasyliev <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class PriceFactory implements PriceFactoryInterface |
21
|
|
|
{ |
22
|
|
|
protected $creators = [ |
23
|
|
|
EnumPrice::class => 'createEnumPrice', |
24
|
|
|
SinglePrice::class => 'createSinglePrice', |
25
|
|
|
]; |
26
|
|
|
|
27
|
|
|
protected $types = [ |
28
|
|
|
'enum' => EnumPrice::class, |
29
|
|
|
'single' => SinglePrice::class, |
30
|
|
|
]; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var string default price class, when given will be used for not found types |
34
|
|
|
*/ |
35
|
|
|
protected $defaultClass = null; |
36
|
|
|
|
37
|
2 |
|
public function __construct(array $types = [], $defaultClass = null) |
38
|
|
|
{ |
39
|
2 |
|
$this->types = $types; |
40
|
2 |
|
$this->defaultClass = $defaultClass; |
41
|
2 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Creates price object. |
45
|
|
|
* |
46
|
|
|
* @param PriceCreationDto $dto |
47
|
|
|
* @return Price |
48
|
|
|
*/ |
49
|
2 |
|
public function create(PriceCreationDto $dto) |
50
|
|
|
{ |
51
|
2 |
|
$type = $dto->type->getName(); |
|
|
|
|
52
|
2 |
|
$class = $this->findClassForType($type); |
53
|
2 |
|
$method = $this->findMethodForClass($class); |
54
|
|
|
|
55
|
2 |
|
return $this->{$method}($dto); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
public function findClassForType($type) |
59
|
|
|
{ |
60
|
2 |
|
if (isset($this->types[$type])) { |
61
|
2 |
|
return $this->types[$type]; |
62
|
|
|
} |
63
|
|
|
if ($this->defaultClass) { |
64
|
|
|
return $this->defaultClass; |
65
|
|
|
} |
66
|
|
|
throw new FailedCreatePriceException("unknown type: $type"); |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
public function findMethodForClass($class) |
70
|
|
|
{ |
71
|
2 |
|
if (isset($this->creators[$class])) { |
72
|
2 |
|
return $this->creators[$class]; |
73
|
|
|
} |
74
|
|
|
throw new FailedCreatePriceException("unknown class: $class"); |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
public function createEnumPrice(PriceCreationDto $dto) |
78
|
|
|
{ |
79
|
1 |
|
return new EnumPrice($dto->id, $dto->type, $dto->target, $dto->plan, $dto->unit, $dto->currency, $dto->sums); |
80
|
|
|
} |
81
|
|
|
|
82
|
1 |
|
public function createSinglePrice(PriceCreationDto $dto) |
83
|
|
|
{ |
84
|
1 |
|
return new SinglePrice($dto->id, $dto->type, $dto->target, $dto->plan, $dto->prepaid, $dto->price); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|