-
Notifications
You must be signed in to change notification settings - Fork 17
/
BagStoreMediator.php
106 lines (90 loc) · 2.24 KB
/
BagStoreMediator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace DesignPatterns\Behavioral\MediatorPattern;
use InvalidArgumentException;
/**
* Class BagStoreMediator.
*/
class BagStoreMediator implements MediatorInterface
{
/**
* @var Bag
*/
protected Bag $bag;
/**
* @var Store
*/
protected Store $store;
/**
* BagStoreMediator constructor.
*
* @param Bag $bag
* @param Store $store
*/
public function __construct(Bag $bag, Store $store)
{
$this->bag = $bag;
$this->store = $store;
$this->bag->setMediator($this);
$this->store->setMediator($this);
}
/**
* @return int
*/
public function getBells(): int
{
return $this->bag->getBells();
}
/**
* @return int
*/
public function getTurnips(): int
{
return $this->bag->getTurnips();
}
/**
* @param int $bells
*/
public function setBells(int $bells)
{
$this->bag->setBells($bells);
}
/**
* @param int $count
*/
public function setTurnips(int $count)
{
$this->bag->setTurnips($count);
}
/**
* @param int $price
* @param int $count
*
* @throws InvalidArgumentException
*/
public function buyTurnips(int $price, int $count)
{
$total = $price * $count;
if ($this->bag->getBells() >= $total) {
echo "[玩家] 您購買了 $count 顆大頭菜,每顆單價 $price 鈴錢,總共 $total 鈴錢。";
$this->store->buyTurnips($price, $count);
return;
}
throw new InvalidArgumentException('[錯誤] 您的大頭菜不足,無法購買大頭菜。');
}
/**
* @param int $price
* @param int $count
*
* @throws InvalidArgumentException
*/
public function sellTurnips(int $price, int $count)
{
$total = $price * $count;
if ($this->bag->getTurnips() >= $count) {
echo "[玩家] 您販賣了 $count 顆大頭菜,每顆單價 $price 鈴錢,總共 $total 鈴錢。";
$this->store->sellTurnips($price, $count);
return;
}
throw new InvalidArgumentException('[錯誤] 您的大頭菜不足,無法販賣大頭菜。');
}
}