-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
BalanceDb.php
260 lines (226 loc) · 6.56 KB
/
BalanceDb.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php
/**
* @link https://github.com/illuminatech
* @copyright Copyright (c) 2019 Illuminatech
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace Illuminatech\Balance;
use Illuminate\Database\Connection;
/**
* BalanceDb is a balance manager, which uses relational database as data storage.
*
* Configuration example:
*
* ```php
* return [
* '__class' => Illuminatech\Balance\BalanceDb::class,
* 'accountTable' => 'balance_accounts',
* 'transactionTable' => 'balance_transactions',
* 'accountBalanceAttribute' => 'balance',
* 'extraAccountLinkAttribute' => 'extra_account_id',
* 'dataAttribute' => 'data',
* ];
* ```
*
* Database migration example:
*
* ```php
* Schema::create('balance_accounts', function (Blueprint $table) {
* $table->id('id');
* $table->bigInteger('balance')->default(0);
* // ...
* });
*
* Schema::create('balance_transactions', function (Blueprint $table) {
* $table->id('id');
* $table->timestamp('created_at');
* $table->unsignedBigInteger('account_id');
* $table->unsignedBigInteger('extra_account_id');
* $table->integer('amount');
* $table->text('data')->nullable();
* // ...
* });
* ```
*
* You can publish the predefined migration using following command:
*
* ```
* php artisan vendor:publish --provider="Illuminatech\Balance\BalanceServiceProvider" --tag="migrations"
* ```
*
* This manager will attempt to save value from transaction data in the table column, which name matches data key.
* If such column does not exist data will be saved in {@see dataAttribute} column in serialized state.
*
* > Note: watch for the keys you use in transaction data: make sure they do not conflict with columns, which are
* reserved for other purposes, like primary keys.
*
* @see Balance
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 1.0
*/
class BalanceDb extends BalanceDbTransaction
{
use DataSerializable;
/**
* @var string name of the database table, which should store account records.
*/
public $accountTable = 'balance_accounts';
/**
* @var string name of the database table, which should store transaction records.
*/
public $transactionTable = 'balance_transactions';
/**
* @var string name of the account ID attribute at {@see accountTable}
*/
public $accountIdAttribute = 'id';
/**
* @var string name of the transaction ID attribute at {@see transactionTable}
*/
public $transactionIdAttribute = 'id';
/**
* @var \Illuminate\Database\Connection the DB connection instance.
*/
private $connection;
/**
* Constructor.
*
* @param \Illuminate\Database\Connection $connection DB connection to be used.
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* @return \Illuminate\Database\Connection DB connection instance.
*/
public function getConnection(): Connection
{
return $this->connection;
}
/**
* @param \Illuminate\Database\Connection $connection DB connection to be used.
* @return static self reference.
*/
public function setConnection(Connection $connection)
{
$this->connection = $connection;
return $this;
}
/**
* {@inheritdoc}
*/
protected function findAccountId($attributes)
{
$id = $this->connection->query()
->select([$this->accountIdAttribute])
->from($this->accountTable)
->where($attributes)
->value($this->accountIdAttribute);
if ($id === false) {
return null;
}
return $id;
}
/**
* {@inheritdoc}
*/
protected function findTransaction($id)
{
$idAttribute = $this->transactionIdAttribute;
$row = $this->connection->query()
->from($this->transactionTable)
->where([$idAttribute => $id])
->first();
if ($row === null) {
return null;
}
return $this->unserializeAttributes((array)$row);
}
/**
* {@inheritdoc}
*/
protected function findLastTransaction($accountId)
{
$row = $this->connection->query()
->from($this->transactionTable)
->where([$this->accountLinkAttribute => $accountId])
->orderBy($this->dateAttribute, 'DESC')
->orderBy($this->transactionIdAttribute, 'DESC')
->first();
if ($row === null) {
return null;
}
return $this->unserializeAttributes((array)$row);
}
/**
* {@inheritdoc}
*/
protected function createAccount($attributes)
{
return $this->connection->table($this->accountTable)->insertGetId($attributes);
}
/**
* {@inheritdoc}
*/
protected function createTransaction($attributes)
{
$allowedAttributes = [];
foreach ($this->connection->getSchemaBuilder()->getColumnListing($this->transactionTable) as $column) {
if ($column === $this->transactionIdAttribute) {
continue;
}
$allowedAttributes[] = $column;
}
$attributes = $this->serializeAttributes($attributes, $allowedAttributes);
return $this->connection->table($this->transactionTable)->insertGetId($attributes);
}
/**
* {@inheritdoc}
*/
protected function incrementAccountBalance($accountId, $amount)
{
$this->connection->table($this->accountTable)
->where([$this->accountIdAttribute => $accountId])
->increment($this->accountBalanceAttribute, $amount);
}
/**
* {@inheritdoc}
*/
public function calculateBalance($account)
{
$accountId = $this->fetchAccountId($account);
return $this->connection->query()
->from($this->transactionTable)
->where([$this->accountLinkAttribute => $accountId])
->sum($this->amountAttribute);
}
/**
* {@inheritdoc}
*/
protected function beginDbTransaction()
{
$this->connection->beginTransaction();
}
/**
* {@inheritdoc}
*/
protected function commitDbTransaction()
{
$this->connection->commit();
}
/**
* {@inheritdoc}
*/
protected function rollBackDbTransaction()
{
$this->connection->rollBack();
}
/**
* {@inheritdoc}
*/
protected function getDbTransactionLevel()
{
return $this->connection->transactionLevel();
}
}