1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Sylius package. |
5
|
|
|
* |
6
|
|
|
* (c) Paweł Jędrzejewski |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sylius\Component\Promotion\Generator; |
13
|
|
|
|
14
|
|
|
use Sylius\Component\Promotion\Repository\CouponRepositoryInterface; |
15
|
|
|
use Webmozart\Assert\Assert; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @author Arkadiusz Krakowiak <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
final class PercentageGenerationPolicy implements GenerationPolicyInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var CouponRepositoryInterface |
24
|
|
|
*/ |
25
|
|
|
private $couponRepository; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var float |
29
|
|
|
*/ |
30
|
|
|
private $ratio; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* {@inheritdoc} |
34
|
|
|
*/ |
35
|
|
|
public function __construct(CouponRepositoryInterface $couponRepository, $ratio = 0.5) |
36
|
|
|
{ |
37
|
|
|
$this->couponRepository = $couponRepository; |
38
|
|
|
$this->ratio = $ratio; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* {@inheritdoc} |
43
|
|
|
*/ |
44
|
|
|
public function isGenerationPossible(InstructionInterface $instruction) |
45
|
|
|
{ |
46
|
|
|
$expectedGenerationAmount = $instruction->getAmount(); |
47
|
|
|
$possibleGenerationAmount = $this->calculatePossibleGenerationAmount($instruction); |
48
|
|
|
|
49
|
|
|
return $possibleGenerationAmount >= $expectedGenerationAmount; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* {@inheritdoc} |
54
|
|
|
*/ |
55
|
|
|
public function getPossibleGenerationAmount(InstructionInterface $instruction) |
56
|
|
|
{ |
57
|
|
|
return $this->calculatePossibleGenerationAmount($instruction); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param InstructionInterface $instruction |
62
|
|
|
* |
63
|
|
|
* @return int |
64
|
|
|
*/ |
65
|
|
|
private function calculatePossibleGenerationAmount(InstructionInterface $instruction) |
66
|
|
|
{ |
67
|
|
|
$expectedAmount = $instruction->getAmount(); |
68
|
|
|
$expectedCodeLength = $instruction->getCodeLength(); |
69
|
|
|
|
70
|
|
|
Assert::allNotNull( |
71
|
|
|
[$expectedAmount, $expectedCodeLength], |
72
|
|
|
'Code length or amount cannot be null.' |
73
|
|
|
); |
74
|
|
|
$generatedAmount = $this->couponRepository->countCouponsByCodeLength($expectedCodeLength); |
75
|
|
|
|
76
|
|
|
return floor(pow(16, $expectedCodeLength) * $this->ratio - $generatedAmount); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|