Skip to content

Commit 2c6a195

Browse files
HP-1751 refactored BillingRegistry::getBehavior() method
1 parent d7d838a commit 2c6a195

File tree

2 files changed

+40
-7
lines changed

2 files changed

+40
-7
lines changed

src/product/BillingRegistry.php

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
namespace hiqdev\php\billing\product;
44

5+
use hiqdev\php\billing\product\behavior\InvalidBehaviorException;
56
use hiqdev\php\billing\product\invoice\RepresentationInterface;
7+
use hiqdev\php\billing\product\price\PriceTypeDefinition;
68
use hiqdev\php\billing\product\quantity\QuantityFormatterNotFoundException;
79
use hiqdev\php\billing\product\quantity\FractionQuantityData;
810
use hiqdev\php\billing\product\behavior\BehaviorInterface;
@@ -82,22 +84,44 @@ private function convertStringTypeToType(string $type): TypeInterface
8284
* @param string $behaviorClassWrapper
8385
* @return BehaviorInterface
8486
* @throws BehaviorNotFoundException
87+
* @throws InvalidBehaviorException
8588
*/
8689
public function getBehavior(string $type, string $behaviorClassWrapper): BehaviorInterface
8790
{
88-
$type = $this->convertStringTypeToType($type);
91+
if (!class_exists($behaviorClassWrapper)) {
92+
throw new InvalidBehaviorException(
93+
sprintf('Behavior class "%s" does not exist', $behaviorClassWrapper)
94+
);
95+
}
96+
97+
$billingType = $this->convertStringTypeToType($type);
8998

9099
foreach ($this->priceTypes() as $priceTypeDefinition) {
91-
if ($priceTypeDefinition->hasType($type)) {
92-
foreach ($priceTypeDefinition->withBehaviors() as $behavior) {
93-
if ($behavior instanceof $behaviorClassWrapper) {
94-
return $behavior;
95-
}
100+
if ($priceTypeDefinition->hasType($billingType)) {
101+
$behavior = $this->findBehaviorInPriceType($priceTypeDefinition, $behaviorClassWrapper);
102+
103+
if ($behavior) {
104+
return $behavior;
96105
}
97106
}
98107
}
99108

100-
throw new BehaviorNotFoundException('Behaviour was not found');
109+
throw new BehaviorNotFoundException(
110+
sprintf('Behavior of class "%s" not found for type "%s"', $behaviorClassWrapper, $type),
111+
);
112+
}
113+
114+
private function findBehaviorInPriceType(
115+
PriceTypeDefinition $priceTypeDefinition,
116+
string $behaviorClassWrapper
117+
): ?BehaviorInterface {
118+
foreach ($priceTypeDefinition->withBehaviors() as $behavior) {
119+
if ($behavior instanceof $behaviorClassWrapper) {
120+
return $behavior;
121+
}
122+
}
123+
124+
return null;
101125
}
102126

103127
public function getBehaviors(string $behaviorClassWrapper): \Generator
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace hiqdev\php\billing\product\behavior;
4+
5+
use InvalidArgumentException;
6+
7+
class InvalidBehaviorException extends InvalidArgumentException
8+
{
9+
}

0 commit comments

Comments
 (0)