1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace hipanel\modules\finance\cart; |
4
|
|
|
|
5
|
|
|
use hipanel\modules\finance\logic\Calculator; |
6
|
|
|
use hipanel\modules\finance\models\CalculableModelInterface; |
7
|
|
|
use hiqdev\yii2\cart\CartPositionInterface; |
8
|
|
|
use hiqdev\yii2\cart\Module; |
9
|
|
|
use hiqdev\yii2\cart\ShoppingCart; |
10
|
|
|
use yii\base\Widget; |
11
|
|
|
|
12
|
|
|
abstract class RelatedPosition implements RelatedPositionInterface |
13
|
|
|
{ |
14
|
|
|
/** @var CartPositionInterface */ |
15
|
|
|
public $mainPosition; |
16
|
|
|
|
17
|
|
|
/** @var ShoppingCart */ |
18
|
|
|
public $cart; |
19
|
|
|
|
20
|
|
|
/** @var CalculableModelInterface */ |
21
|
|
|
public $relatedPosition; |
22
|
|
|
|
23
|
|
|
/** @var Widget */ |
24
|
|
|
private $widget; |
25
|
|
|
|
26
|
|
|
public function __construct(CartPositionInterface $mainPosition) |
27
|
|
|
{ |
28
|
|
|
$this->cart = Module::getInstance()->getCart(); |
29
|
|
|
$this->mainPosition = $mainPosition; |
30
|
|
|
$this->relatedPosition = $this->createRelatedPosition(); |
31
|
|
|
$currentPositions = $this->cart->getPositions(); |
32
|
|
|
if (isset($currentPositions[$this->relatedPosition->getId()])) { |
|
|
|
|
33
|
|
|
$relatedPosition = $currentPositions[$this->relatedPosition->getId()]; |
|
|
|
|
34
|
|
|
$this->relatedPosition = $relatedPosition; |
35
|
|
|
} else { |
36
|
|
|
$this->calculate(); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** @inheritDoc */ |
41
|
|
|
public function render(): string |
42
|
|
|
{ |
43
|
|
|
if (!$this->widget) { |
44
|
|
|
$this->widget = $this->getWidget(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $this->widget->run(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function calculate(): void |
51
|
|
|
{ |
52
|
|
|
$position = $this->relatedPosition; |
53
|
|
|
$calculator = new Calculator([$position]); |
|
|
|
|
54
|
|
|
$calculationId = $position->getId(); |
|
|
|
|
55
|
|
|
$calculation = $calculator->getCalculation($calculationId); |
56
|
|
|
$value = $calculation->forCurrency($this->cart->getCurrency()); |
57
|
|
|
$position->setPrice($value->price); |
|
|
|
|
58
|
|
|
$position->setValue($value->value); |
|
|
|
|
59
|
|
|
$position->setCurrency($value->currency); |
|
|
|
|
60
|
|
|
$this->relatedPosition = $position; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: