├── .circleci
└── config.yml
├── .env.example
├── .gitattributes
├── .gitignore
├── LICENSE
├── Makefile
├── app
├── Action
│ ├── DDDStyleTransferMoney
│ │ ├── DDDStyleTransferMoneyAction.php
│ │ └── DDDStyleTransferMoneyAdapter.php
│ ├── GetAccount
│ │ ├── GetAccountAction.php
│ │ └── GetAccountAdapter.php
│ ├── ProcedureStyleTransferMoney
│ │ ├── ProcedureStyleTransferMoneyAction.php
│ │ └── ProcedureStyleTransferMoneyAdapter.php
│ └── TransferMoney
│ │ ├── TransferMoneyAction.php
│ │ └── TransferMoneyAdapter.php
├── Console
│ ├── Commands
│ │ └── GetAccountCommand.php
│ └── Kernel.php
├── Eloquents
│ ├── EloquentAccount.php
│ └── EloquentTransaction.php
├── Event
│ └── QueryLogger.php
├── Exceptions
│ └── Handler.php
├── Http
│ ├── Kernel.php
│ ├── Middleware
│ │ ├── EncryptCookies.php
│ │ ├── RedirectIfAuthenticated.php
│ │ ├── TrimStrings.php
│ │ ├── TrustProxies.php
│ │ └── VerifyCsrfToken.php
│ └── Requests
│ │ └── TransferMoneyRequest.php
├── Mail
│ └── TransferMoneyMail.php
├── Providers
│ ├── AppServiceProvider.php
│ ├── AuthServiceProvider.php
│ ├── CoreApplicationServiceProvider.php
│ ├── DatabaseServiceProvider.php
│ ├── EventServiceProvider.php
│ ├── RouteServiceProvider.php
│ └── ValidationServiceProvider.php
└── User.php
├── artisan
├── bootstrap
├── app.php
└── cache
│ └── .gitignore
├── composer.json
├── composer.lock
├── config
├── app.php
├── application.php
├── auth.php
├── broadcasting.php
├── cache.php
├── database.php
├── filesystems.php
├── hashing.php
├── logging.php
├── mail.php
├── queue.php
├── services.php
├── session.php
└── view.php
├── database
├── .gitignore
├── factories
│ └── UserFactory.php
├── migrations
│ ├── 2018_04_13_142835_create_accounts_table.php
│ └── 2018_05_05_122357_create-transactions-table.php
└── seeds
│ ├── AccountSeeder.php
│ └── DatabaseSeeder.php
├── docker-compose.yml
├── docker
├── nginx
│ ├── conf.d
│ │ ├── default.conf
│ │ ├── php-upstream.conf
│ │ └── status.conf
│ └── nginx.conf
└── php-fpm
│ ├── Dockerfile
│ ├── php-fpm.conf
│ └── php.ini
├── package.json
├── packages
└── Acme
│ ├── Account
│ ├── Domain
│ │ ├── Aggregates
│ │ │ └── TransferMoneyAggregate.php
│ │ ├── Exceptions
│ │ │ ├── DomainException.php
│ │ │ ├── DomainRuleException.php
│ │ │ ├── InvariantException.php
│ │ │ └── NotFoundException.php
│ │ ├── Models
│ │ │ ├── Account.php
│ │ │ ├── AccountNumber.php
│ │ │ ├── Balance.php
│ │ │ ├── Email.php
│ │ │ ├── Enum.php
│ │ │ ├── Money.php
│ │ │ ├── Transaction.php
│ │ │ ├── TransactionTime.php
│ │ │ ├── TransactionType.php
│ │ │ ├── ValueObjectFloat.php
│ │ │ ├── ValueObjectInt.php
│ │ │ ├── ValueObjectOf.php
│ │ │ └── ValueObjectString.php
│ │ └── Specifications
│ │ │ ├── DifferentAccountSpec.php
│ │ │ ├── TransferMoneySpec.php
│ │ │ └── WithdrawSpec.php
│ └── UseCase
│ │ ├── DDDStyleTransferMoney
│ │ └── DDDStyleTransferMoney.php
│ │ ├── GetAccount
│ │ └── GetAccount.php
│ │ ├── Ports
│ │ └── TransactionPort.php
│ │ ├── ProcedureStyleTransferMoney
│ │ └── ProcedureStyleTransferMoney.php
│ │ └── TransportMoney
│ │ └── TransferMoney.php
│ └── Test
│ └── Account
│ ├── Domain
│ └── Models
│ │ └── BalanceTest.php
│ └── UseCase
│ ├── ArrayRepository.php
│ ├── GetAccountTest.php
│ └── TransferMoneyTest.php
├── phpunit.xml
├── public
├── .htaccess
├── css
│ └── app.css
├── favicon.ico
├── index.php
├── js
│ └── app.js
├── robots.txt
└── web.config
├── readme.md
├── resources
├── assets
│ ├── js
│ │ ├── app.js
│ │ ├── bootstrap.js
│ │ └── components
│ │ │ └── ExampleComponent.vue
│ └── sass
│ │ ├── _variables.scss
│ │ └── app.scss
├── lang
│ └── en
│ │ ├── auth.php
│ │ ├── pagination.php
│ │ ├── passwords.php
│ │ └── validation.php
└── views
│ ├── emails
│ └── transfer_money.blade.php
│ └── welcome.blade.php
├── routes
├── api.php
├── channels.php
├── console.php
└── web.php
├── ruleset.xml
├── server.php
├── storage
├── app
│ ├── .gitignore
│ └── public
│ │ └── .gitignore
├── framework
│ ├── .gitignore
│ ├── cache
│ │ └── .gitignore
│ ├── sessions
│ │ └── .gitignore
│ ├── testing
│ │ └── .gitignore
│ └── views
│ │ └── .gitignore
└── logs
│ └── .gitignore
├── tests
├── CreatesApplication.php
├── Feature
│ ├── DDDStyleTransferMoneyTest.php
│ ├── ExampleTest.php
│ ├── GetAccountTest.php
│ ├── ProcedureStyleTransferMoneyTest.php
│ └── TransferMoneyTest.php
├── Seeder
│ └── TestSeeder.php
├── SetupDatabase.php
├── TestCase.php
└── Unit
│ └── ExampleTest.php
└── webpack.mix.js
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | machine: true
5 |
6 | steps:
7 | - checkout
8 |
9 | - run: docker-compose -v
10 | - run: docker-compose run php-fpm php -v
11 |
12 | - run: make install
13 | - run: make phpstan
14 | - run: make phpcs
15 | - run: make test
16 |
17 | workflows:
18 | version: 2
19 | build:
20 | jobs:
21 | - build
22 |
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | APP_NAME=Laravel
2 | APP_ENV=local
3 | APP_KEY=
4 | APP_DEBUG=true
5 | APP_URL=http://localhost
6 |
7 | LOG_CHANNEL=stack
8 |
9 | DB_CONNECTION=pgsql
10 | DB_HOST=db
11 | DB_PORT=5432
12 | DB_DATABASE=app
13 | DB_USERNAME=app
14 | DB_PASSWORD=pass
15 |
16 | BROADCAST_DRIVER=log
17 | CACHE_DRIVER=file
18 | SESSION_DRIVER=file
19 | SESSION_LIFETIME=120
20 | QUEUE_DRIVER=sync
21 |
22 | REDIS_HOST=127.0.0.1
23 | REDIS_PASSWORD=null
24 | REDIS_PORT=6379
25 |
26 | MAIL_DRIVER=log
27 | MAIL_HOST=smtp.mailtrap.io
28 | MAIL_PORT=2525
29 | MAIL_USERNAME=null
30 | MAIL_PASSWORD=null
31 | MAIL_ENCRYPTION=null
32 |
33 | PUSHER_APP_ID=
34 | PUSHER_APP_KEY=
35 | PUSHER_APP_SECRET=
36 | PUSHER_APP_CLUSTER=mt1
37 |
38 | MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
39 | MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
40 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.css linguist-vendored
3 | *.scss linguist-vendored
4 | *.js linguist-vendored
5 | CHANGELOG.md export-ignore
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | /public/hot
3 | /public/storage
4 | /storage/*.key
5 | /vendor
6 | /.idea
7 | /.vscode
8 | /.vagrant
9 | Homestead.json
10 | Homestead.yaml
11 | npm-debug.log
12 | yarn-error.log
13 | .env
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Masashi Shinbara
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all: install test
2 | .PHONY: all
3 |
4 | install: start
5 | cp .env.example .env
6 | chmod -R a+w storage/*
7 | docker-compose run composer install --prefer-dist --no-interaction
8 | docker-compose exec php-fpm php artisan key:generate
9 | docker-compose exec php-fpm php artisan migrate
10 | docker-compose exec php-fpm php artisan db:seed
11 | .PHONY: install
12 |
13 | start:
14 | docker-compose up -d
15 | .PHONY: start
16 |
17 | test:
18 | docker-compose run php-fpm ./vendor/bin/phpunit
19 | .PHONY: test
20 |
21 | phpcs:
22 | docker-compose run php-fpm ./vendor/bin/phpcs --standard=/var/www/html/ruleset.xml
23 | .PHONY: phpcs
24 |
25 | phpcbf:
26 | docker-compose run php-fpm ./vendor/bin/phpcbf --standard=/var/www/html/ruleset.xml
27 | .PHONY: phpcbf
28 |
29 | clean:
30 | docker-compose down
31 | .PHONY: clean
32 |
33 | phpstan:
34 | docker-compose run phpstan analyze --level 7 packages
35 | .PHONY: phpstan
36 |
--------------------------------------------------------------------------------
/app/Action/DDDStyleTransferMoney/DDDStyleTransferMoneyAction.php:
--------------------------------------------------------------------------------
1 | useCase = $useCase;
20 | }
21 |
22 | /**
23 | * @param TransferMoneyRequest $request
24 | * @param string $accountNumber
25 | * @return \Illuminate\Http\JsonResponse
26 | */
27 | public function __invoke(TransferMoneyRequest $request, string $accountNumber)
28 | {
29 | $validated = $request->validated();
30 |
31 | $balance = $this->useCase->execute(
32 | AccountNumber::of($accountNumber),
33 | AccountNumber::of($validated['destination_number']),
34 | Money::of((int)$validated['money']),
35 | TransactionTime::now()
36 | );
37 |
38 | return response()->json([
39 | 'balance' => $balance->asInt(),
40 | ]);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/Action/DDDStyleTransferMoney/DDDStyleTransferMoneyAdapter.php:
--------------------------------------------------------------------------------
1 | account = $account;
37 | $this->transaction = $transaction;
38 | $this->mailer = $mail;
39 | }
40 |
41 | /**
42 | * @param AccountNumber $sourceNumber
43 | * @param AccountNumber $destinationNumber
44 | * @return TransferMoneyAggregate
45 | * @throws NotFoundException
46 | */
47 | public function find(AccountNumber $sourceNumber, AccountNumber $destinationNumber): TransferMoneyAggregate
48 | {
49 | if ($sourceNumber->lessThan($destinationNumber)) {
50 | $source = $this->findAndLockAccount($sourceNumber);
51 | $destination = $this->findAndLockAccount($destinationNumber);
52 | } else {
53 | $destination = $this->findAndLockAccount($destinationNumber);
54 | $source = $this->findAndLockAccount($sourceNumber);
55 | }
56 |
57 | return new TransferMoneyAggregate($source, $destination);
58 | }
59 |
60 | /**
61 | * @param TransferMoneyAggregate $aggregate
62 | */
63 | public function store(TransferMoneyAggregate $aggregate): void
64 | {
65 | $source = $aggregate->source();
66 | $destination = $aggregate->destination();
67 |
68 | $this->account->updateBalance($source->accountNumber(), $source->balance());
69 | $this->account->updateBalance($destination->accountNumber(), $destination->balance());
70 |
71 | $this->addTransaction($aggregate->sourceTransaction());
72 | $this->addTransaction($aggregate->destinationTransaction());
73 | }
74 |
75 | /**
76 | * @param AccountNumber $accountNumber
77 | * @return Account
78 | * @throws NotFoundException
79 | */
80 | public function findAccount(AccountNumber $accountNumber): Account
81 | {
82 | /** @var EloquentAccount $account */
83 | $account = $this->account->findByAccountNumber($accountNumber);
84 | if (is_null($account)) {
85 | throw $this->notFoundException($accountNumber);
86 | }
87 |
88 | return $account->toModel();
89 | }
90 |
91 | /**
92 | * @param Account $account
93 | */
94 | public function notify(Account $account): void
95 | {
96 | $this->mailer->to($account->email()->asString())->send(new TransferMoneyMail($account));
97 | }
98 |
99 | /**
100 | * @param AccountNumber $accountNumber
101 | * @return Account
102 | * @throws NotFoundException
103 | */
104 | private function findAndLockAccount(AccountNumber $accountNumber): Account
105 | {
106 | /** @var EloquentAccount $account */
107 | $account = $this->account->findByAccountNumberWithLockForUpdate($accountNumber);
108 | if (is_null($account)) {
109 | throw $this->notFoundException($accountNumber);
110 | }
111 |
112 | return $account->toModel();
113 | }
114 |
115 | /**
116 | * @param AccountNumber $accountNumber
117 | * @return NotFoundException
118 | */
119 | private function notFoundException(AccountNumber $accountNumber): NotFoundException
120 | {
121 | return new NotFoundException(sprintf('account_number %s not found', $accountNumber->__toString()));
122 | }
123 |
124 | /**
125 | * @param Transaction $transaction
126 | */
127 | private function addTransaction(Transaction $transaction): void
128 | {
129 | $this->transaction->store($transaction);
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/app/Action/GetAccount/GetAccountAction.php:
--------------------------------------------------------------------------------
1 | useCase = $useCase;
21 | }
22 |
23 | /**
24 | * @param Request $request
25 | * @param string $accountNumber
26 | * @return \Illuminate\Http\JsonResponse
27 | * @throws \Acme\Account\Domain\Exceptions\NotFoundException
28 | */
29 | public function __invoke(Request $request, string $accountNumber)
30 | {
31 | $account = $this->useCase->execute(AccountNumber::of($accountNumber));
32 |
33 | return response()->json([
34 | 'account_number' => $account->accountNumber()->asString(),
35 | 'balance' => $account->balance()->asInt(),
36 | ]);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/Action/GetAccount/GetAccountAdapter.php:
--------------------------------------------------------------------------------
1 | account = $account;
23 | }
24 |
25 | /**
26 | * @param AccountNumber $accountNumber
27 | * @return Account
28 | * @throws NotFoundException
29 | */
30 | public function findAccount(AccountNumber $accountNumber): Account
31 | {
32 | /** @var EloquentAccount $account */
33 | $account = $this->account->findByAccountNumber($accountNumber);
34 | if (is_null($account)) {
35 | throw new NotFoundException(sprintf('account_number %s not found', $accountNumber->__toString()));
36 | }
37 |
38 | return $account->toModel();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/Action/ProcedureStyleTransferMoney/ProcedureStyleTransferMoneyAction.php:
--------------------------------------------------------------------------------
1 | useCase = $useCase;
18 | }
19 |
20 | /**
21 | * @param TransferMoneyRequest $request
22 | * @param string $accountNumber
23 | * @return \Illuminate\Http\JsonResponse
24 | */
25 | public function __invoke(TransferMoneyRequest $request, string $accountNumber)
26 | {
27 | $validated = $request->validated();
28 |
29 | $balance = $this->useCase->execute(
30 | $accountNumber,
31 | $validated['destination_number'],
32 | (int)$validated['money'],
33 | Chronos::now()
34 | );
35 |
36 | return response()->json([
37 | 'balance' => $balance,
38 | ]);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/Action/ProcedureStyleTransferMoney/ProcedureStyleTransferMoneyAdapter.php:
--------------------------------------------------------------------------------
1 | account = $account;
32 | $this->transaction = $transaction;
33 | $this->mailer = $mail;
34 | }
35 |
36 | /**
37 | * @param string $accountNumber
38 | * @return array
39 | * @throws NotFoundException
40 | */
41 | public function findAndLockAccount(string $accountNumber): array
42 | {
43 | $account = $this->account->newQuery()
44 | ->where('account_number', $accountNumber)
45 | ->lockForUpdate()
46 | ->first();
47 |
48 | if (is_null($account)) {
49 | throw $this->notFoundException($accountNumber);
50 | }
51 |
52 | return $account->toArray();
53 | }
54 |
55 | /**
56 | * @param string $accountNumber
57 | * @return array
58 | * @throws NotFoundException
59 | */
60 | public function findAccount(string $accountNumber): array
61 | {
62 | $account = $this->account->newQuery()
63 | ->where('account_number', $accountNumber)
64 | ->first();
65 |
66 | if (is_null($account)) {
67 | throw $this->notFoundException($accountNumber);
68 | }
69 |
70 | return $account->toArray();
71 | }
72 |
73 | /**
74 | * @param string $accountNumber
75 | * @param int $balance
76 | */
77 | public function storeBalance(string $accountNumber, int $balance): void
78 | {
79 | $this->account->newQuery()
80 | ->where('account_number', $accountNumber)
81 | ->update(['balance' => $balance]);
82 | }
83 |
84 | /**
85 | * @param array $transaction
86 | */
87 | public function addTransaction(array $transaction): void
88 | {
89 | $eloquent = $this->transaction->newInstance();
90 | $eloquent->account_number = $transaction['account_number'];
91 | $eloquent->transaction_type = $transaction['transaction_type'];
92 | $eloquent->transaction_time = $transaction['transaction_time'];
93 | $eloquent->amount = $transaction['amount'];
94 | $eloquent->comment = $transaction['comment'];
95 | $eloquent->save();
96 | }
97 |
98 | /**
99 | * @param array $account
100 | */
101 | public function notify(array $account): void
102 | {
103 | // not yet
104 | }
105 |
106 | /**
107 | * @param string $accountNumber
108 | * @return NotFoundException
109 | */
110 | private function notFoundException(string $accountNumber): NotFoundException
111 | {
112 | return new NotFoundException(sprintf('account_number %s not found', $accountNumber));
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/app/Action/TransferMoney/TransferMoneyAction.php:
--------------------------------------------------------------------------------
1 | useCase = $useCase;
20 | }
21 |
22 | /**
23 | * @param TransferMoneyRequest $request
24 | * @param string $accountNumber
25 | * @return \Illuminate\Http\JsonResponse
26 | */
27 | public function __invoke(TransferMoneyRequest $request, string $accountNumber)
28 | {
29 | $validated = $request->validated();
30 |
31 | $balance = $this->useCase->execute(
32 | AccountNumber::of($accountNumber),
33 | AccountNumber::of($validated['destination_number']),
34 | Money::of((int)$validated['money']),
35 | TransactionTime::now()
36 | );
37 |
38 | return response()->json([
39 | 'balance' => $balance->asInt(),
40 | ]);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/Action/TransferMoney/TransferMoneyAdapter.php:
--------------------------------------------------------------------------------
1 | account = $account;
37 | $this->transaction = $transaction;
38 | $this->mailer = $mail;
39 | }
40 |
41 | /**
42 | * @param AccountNumber $accountNumber
43 | * @return Account
44 | * @throws NotFoundException
45 | */
46 | public function findAndLockAccount(AccountNumber $accountNumber): Account
47 | {
48 | /** @var EloquentAccount $account */
49 | $account = $this->account->findByAccountNumberWithLockForUpdate($accountNumber);
50 | if (is_null($account)) {
51 | throw $this->notFoundException($accountNumber);
52 | }
53 |
54 | return $account->toModel();
55 | }
56 |
57 | /**
58 | * @param AccountNumber $accountNumber
59 | * @return Account
60 | * @throws NotFoundException
61 | */
62 | public function findAccount(AccountNumber $accountNumber): Account
63 | {
64 | /** @var EloquentAccount $account */
65 | $account = $this->account->findByAccountNumber($accountNumber);
66 | if (is_null($account)) {
67 | throw $this->notFoundException($accountNumber);
68 | }
69 |
70 | return $account->toModel();
71 | }
72 |
73 | /**
74 | * @param AccountNumber $accountNumber
75 | * @return NotFoundException
76 | */
77 | private function notFoundException(AccountNumber $accountNumber): NotFoundException
78 | {
79 | return new NotFoundException(sprintf('account_number %s not found', $accountNumber->__toString()));
80 | }
81 |
82 | /**
83 | * @param AccountNumber $accountNumber
84 | * @param Balance $balance
85 | */
86 | public function storeBalance(AccountNumber $accountNumber, Balance $balance): void
87 | {
88 | $this->account->updateBalance($accountNumber, $balance);
89 | }
90 |
91 | /**
92 | * @param Transaction $transaction
93 | */
94 | public function addTransaction(Transaction $transaction): void
95 | {
96 | $this->transaction->store($transaction);
97 | }
98 |
99 | /**
100 | * @param Account $account
101 | */
102 | public function notify(Account $account): void
103 | {
104 | $this->mailer->to($account->email()->asString())->send(new TransferMoneyMail($account));
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/app/Console/Commands/GetAccountCommand.php:
--------------------------------------------------------------------------------
1 | getAccount = $getAccount;
32 | }
33 |
34 | /**
35 | * @throws \Acme\Account\Domain\Exceptions\NotFoundException
36 | */
37 | public function handle()
38 | {
39 | $account = $this->getAccount->execute(
40 | AccountNumber::of($this->argument('account_number'))
41 | );
42 |
43 | $this->info(json_encode([
44 | 'account_number' => $account->accountNumber()->asString(),
45 | 'name' => $account->name(),
46 | 'email' => $account->email()->asString(),
47 | 'balance' => $account->balance()->asInt(),
48 | ]));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/Console/Kernel.php:
--------------------------------------------------------------------------------
1 | command('inspire')
30 | // ->hourly();
31 | }
32 |
33 | /**
34 | * Register the commands for the application.
35 | *
36 | * @return void
37 | */
38 | protected function commands()
39 | {
40 | $this->load(__DIR__ . '/Commands');
41 |
42 | /** @noinspection PhpIncludeInspection */
43 | require base_path('routes/console.php');
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/app/Eloquents/EloquentAccount.php:
--------------------------------------------------------------------------------
1 | newQuery()
28 | ->where('account_number', $accountNumber->asString())
29 | ->lockForUpdate()
30 | ->first();
31 | }
32 |
33 | /**
34 | * @param AccountNumber $accountNumber
35 | * @return Model|\Illuminate\Database\Query\Builder|null|object
36 | */
37 | public function findByAccountNumber(AccountNumber $accountNumber)
38 | {
39 | return $this->newQuery()
40 | ->where('account_number', $accountNumber->asString())
41 | ->first();
42 | }
43 |
44 | /**
45 | * @param Balance $balance
46 | * @param AccountNumber $accountNumber
47 | */
48 | public function updateBalance(AccountNumber $accountNumber, Balance $balance)
49 | {
50 | $this->newQuery()
51 | ->where('account_number', $accountNumber->asString())
52 | ->update(['balance' => $balance->asInt()]);
53 | }
54 |
55 | /**
56 | * @return Account
57 | */
58 | public function toModel(): Account
59 | {
60 | return Account::ofByArray($this->attributesToArray());
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/Eloquents/EloquentTransaction.php:
--------------------------------------------------------------------------------
1 | newInstance();
27 | $eloquent->account_number = $transaction->accountNumber()->asString();
28 | $eloquent->transaction_type = $transaction->transactionType()->asString();
29 | $eloquent->transaction_time = $transaction->transactionTime();
30 | $eloquent->amount = $transaction->amount()->asInt();
31 | $eloquent->comment = $transaction->comment();
32 | $eloquent->save();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/Event/QueryLogger.php:
--------------------------------------------------------------------------------
1 | logger = $logger;
22 | }
23 |
24 | /**
25 | * @param QueryExecuted $event
26 | */
27 | public function handle(QueryExecuted $event)
28 | {
29 | $message = sprintf(
30 | '[%s] %s %s %dms',
31 | $event->connectionName,
32 | $event->sql,
33 | json_encode($event->bindings),
34 | $event->time
35 | );
36 |
37 | $this->logger->info($message);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/Exceptions/Handler.php:
--------------------------------------------------------------------------------
1 | json(['message' => $exception->getMessage()], Response::HTTP_BAD_REQUEST);
57 | }
58 |
59 | return parent::render($request, $exception);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/app/Http/Kernel.php:
--------------------------------------------------------------------------------
1 | [
50 | EncryptCookies::class,
51 | AddQueuedCookiesToResponse::class,
52 | StartSession::class,
53 | // \Illuminate\Session\Middleware\AuthenticateSession::class,
54 | ShareErrorsFromSession::class,
55 | VerifyCsrfToken::class,
56 | SubstituteBindings::class,
57 | ],
58 |
59 | 'api' => [
60 | 'throttle:60,1',
61 | 'bindings',
62 | ],
63 | ];
64 |
65 | /**
66 | * The application's route middleware.
67 | *
68 | * These middleware may be assigned to groups or used individually.
69 | *
70 | * @var array
71 | */
72 | protected $routeMiddleware = array(
73 | 'auth' => Authenticate::class,
74 | 'auth.basic' => AuthenticateWithBasicAuth::class,
75 | 'bindings' => SubstituteBindings::class,
76 | 'cache.headers' => SetCacheHeaders::class,
77 | 'can' => Authorize::class,
78 | 'guest' => RedirectIfAuthenticated::class,
79 | 'signed' => ValidateSignature::class,
80 | 'throttle' => ThrottleRequests::class,
81 | );
82 | }
83 |
--------------------------------------------------------------------------------
/app/Http/Middleware/EncryptCookies.php:
--------------------------------------------------------------------------------
1 | check()) {
22 | return redirect('/home');
23 | }
24 |
25 | return $next($request);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/Http/Middleware/TrimStrings.php:
--------------------------------------------------------------------------------
1 | 'required|account_number',
29 | 'money' => 'required|int'
30 | ];
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/Mail/TransferMoneyMail.php:
--------------------------------------------------------------------------------
1 | account = $account;
24 | }
25 |
26 | /**
27 | * Build the message.
28 | *
29 | * @return $this
30 | */
31 | public function build()
32 | {
33 | return $this->subject('TransferMoney')
34 | ->text('emails.transfer_money', [
35 | 'balance' => $this->account->balance()->asInt(),
36 | ]);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/Providers/AppServiceProvider.php:
--------------------------------------------------------------------------------
1 | 'App\Policies\ModelPolicy',
17 | ];
18 |
19 | /**
20 | * Register any authentication / authorization services.
21 | *
22 | * @return void
23 | */
24 | public function boot()
25 | {
26 | $this->registerPolicies();
27 |
28 | //
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/Providers/CoreApplicationServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->bind(TransactionPort::class, function () {
28 | return new class implements TransactionPort
29 | {
30 | /**
31 | * @param callable $callee
32 | * @return mixed
33 | * @throws \Throwable
34 | */
35 | public function transaction(callable $callee)
36 | {
37 | /** @var Connection $connection */
38 | $connection = app(Connection::class);
39 |
40 | return $connection->transaction($callee);
41 | }
42 | };
43 | });
44 |
45 | $this->app->bind(GetAccount::class, function () {
46 | $adapter = app(GetAccountAdapter::class);
47 |
48 | return new GetAccount($adapter);
49 | });
50 |
51 | $this->app->bind(TransferMoney::class, function () {
52 | $adapter = app(TransferMoneyAdapter::class);
53 |
54 | return new TransferMoney(
55 | $adapter,
56 | $adapter,
57 | app(TransactionPort::class)
58 | );
59 | });
60 |
61 | $this->app->bind(DDDStyleTransferMoney::class, function () {
62 | $adapter = app(DDDStyleTransferMoneyAdapter::class);
63 |
64 | return new DDDStyleTransferMoney(
65 | $adapter,
66 | $adapter,
67 | app(TransactionPort::class)
68 | );
69 | });
70 |
71 | $this->app->bind(ProcedureStyleTransferMoney::class, function () {
72 | $adapter = app(ProcedureStyleTransferMoneyAdapter::class);
73 |
74 | return new ProcedureStyleTransferMoney(
75 | $adapter,
76 | $adapter,
77 | app(TransactionPort::class)
78 | );
79 | });
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/app/Providers/DatabaseServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->make(Connection::class);
19 | $connection->listen(function (QueryExecuted $event) {
20 | /** @var LoggerInterface $logger */
21 | $logger = $this->app->make(LoggerInterface::class);
22 |
23 | $message = sprintf(
24 | '[%s] %s %s %dms',
25 | $event->connectionName,
26 | $event->sql,
27 | json_encode($event->bindings),
28 | $event->time
29 | );
30 | $logger->debug($message);
31 | });
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/Providers/EventServiceProvider.php:
--------------------------------------------------------------------------------
1 | [
19 | 'App\Listeners\EventListener',
20 | ],
21 | QueryExecuted::class => [
22 | QueryLogger::class,
23 | ],
24 | ];
25 |
26 | /**
27 | * Register any events for your application.
28 | *
29 | * @return void
30 | */
31 | public function boot()
32 | {
33 | parent::boot();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/app/Providers/RouteServiceProvider.php:
--------------------------------------------------------------------------------
1 | mapApiRoutes();
40 |
41 | $this->mapWebRoutes();
42 |
43 | //
44 | }
45 |
46 | /**
47 | * Define the "web" routes for the application.
48 | *
49 | * These routes all receive session state, CSRF protection, etc.
50 | *
51 | * @return void
52 | */
53 | protected function mapWebRoutes()
54 | {
55 | Route::middleware('web')
56 | ->group(base_path('routes/web.php'));
57 | }
58 |
59 | /**
60 | * Define the "api" routes for the application.
61 | *
62 | * These routes are typically stateless.
63 | *
64 | * @return void
65 | */
66 | protected function mapApiRoutes()
67 | {
68 | Route::prefix('api')
69 | ->middleware('api')
70 | ->group(base_path('routes/api.php'));
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/Providers/ValidationServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->make('validator');
16 |
17 | $validator->extend('account_number', function (
18 | $attribute,
19 | $value
20 | ) {
21 | return AccountNumber::validate($value);
22 | });
23 | }
24 |
25 | public function register(): void
26 | {
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/User.php:
--------------------------------------------------------------------------------
1 | make(Illuminate\Contracts\Console\Kernel::class);
34 |
35 | $status = $kernel->handle(
36 | $input = new Symfony\Component\Console\Input\ArgvInput,
37 | new Symfony\Component\Console\Output\ConsoleOutput
38 | );
39 |
40 | /*
41 | |--------------------------------------------------------------------------
42 | | Shutdown The Application
43 | |--------------------------------------------------------------------------
44 | |
45 | | Once Artisan has finished running, we will fire off the shutdown events
46 | | so that any final work may be done by the application before we shut
47 | | down the process. This is the last thing to happen to the request.
48 | |
49 | */
50 |
51 | $kernel->terminate($input, $status);
52 |
53 | exit($status);
54 |
--------------------------------------------------------------------------------
/bootstrap/app.php:
--------------------------------------------------------------------------------
1 | singleton(
30 | Illuminate\Contracts\Http\Kernel::class,
31 | App\Http\Kernel::class
32 | );
33 |
34 | $app->singleton(
35 | Illuminate\Contracts\Console\Kernel::class,
36 | App\Console\Kernel::class
37 | );
38 |
39 | $app->singleton(
40 | Illuminate\Contracts\Debug\ExceptionHandler::class,
41 | App\Exceptions\Handler::class
42 | );
43 |
44 | /*
45 | |--------------------------------------------------------------------------
46 | | Return The Application
47 | |--------------------------------------------------------------------------
48 | |
49 | | This script returns the application instance. The instance is given to
50 | | the calling script so we can separate the building of the instances
51 | | from the actual running of the application and sending responses.
52 | |
53 | */
54 |
55 | return $app;
56 |
--------------------------------------------------------------------------------
/bootstrap/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "laravel/laravel",
3 | "description": "The Laravel Framework.",
4 | "keywords": [
5 | "framework",
6 | "laravel"
7 | ],
8 | "license": "MIT",
9 | "type": "project",
10 | "require": {
11 | "php": "^7.1.3",
12 | "cakephp/chronos": "^1.1",
13 | "fideloper/proxy": "^4.0",
14 | "laravel/framework": "5.6.*",
15 | "laravel/tinker": "^1.0"
16 | },
17 | "require-dev": {
18 | "filp/whoops": "^2.0",
19 | "fzaninotto/faker": "^1.4",
20 | "mockery/mockery": "^1.0",
21 | "nunomaduro/collision": "^2.0",
22 | "phpunit/phpunit": "^7.0",
23 | "squizlabs/php_codesniffer": "^3.2"
24 | },
25 | "autoload": {
26 | "classmap": [
27 | "database/seeds",
28 | "database/factories"
29 | ],
30 | "psr-4": {
31 | "Acme\\": "packages/Acme/",
32 | "App\\": "app/"
33 | }
34 | },
35 | "autoload-dev": {
36 | "psr-4": {
37 | "Tests\\": "tests/"
38 | }
39 | },
40 | "extra": {
41 | "laravel": {
42 | "dont-discover": [
43 | ]
44 | }
45 | },
46 | "scripts": {
47 | "post-root-package-install": [
48 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
49 | ],
50 | "post-create-project-cmd": [
51 | "@php artisan key:generate"
52 | ],
53 | "post-autoload-dump": [
54 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
55 | "@php artisan package:discover"
56 | ]
57 | },
58 | "config": {
59 | "preferred-install": "dist",
60 | "sort-packages": true,
61 | "optimize-autoloader": true
62 | },
63 | "minimum-stability": "dev",
64 | "prefer-stable": true
65 | }
66 |
--------------------------------------------------------------------------------
/config/app.php:
--------------------------------------------------------------------------------
1 | env('APP_NAME', 'Laravel'),
18 |
19 | /*
20 | |--------------------------------------------------------------------------
21 | | Application Environment
22 | |--------------------------------------------------------------------------
23 | |
24 | | This value determines the "environment" your application is currently
25 | | running in. This may determine how you prefer to configure various
26 | | services your application utilizes. Set this in your ".env" file.
27 | |
28 | */
29 |
30 | 'env' => env('APP_ENV', 'production'),
31 |
32 | /*
33 | |--------------------------------------------------------------------------
34 | | Application Debug Mode
35 | |--------------------------------------------------------------------------
36 | |
37 | | When your application is in debug mode, detailed error messages with
38 | | stack traces will be shown on every error that occurs within your
39 | | application. If disabled, a simple generic error page is shown.
40 | |
41 | */
42 |
43 | 'debug' => env('APP_DEBUG', false),
44 |
45 | /*
46 | |--------------------------------------------------------------------------
47 | | Application URL
48 | |--------------------------------------------------------------------------
49 | |
50 | | This URL is used by the console to properly generate URLs when using
51 | | the Artisan command line tool. You should set this to the root of
52 | | your application so that it is used when running Artisan tasks.
53 | |
54 | */
55 |
56 | 'url' => env('APP_URL', 'http://localhost'),
57 |
58 | /*
59 | |--------------------------------------------------------------------------
60 | | Application Timezone
61 | |--------------------------------------------------------------------------
62 | |
63 | | Here you may specify the default timezone for your application, which
64 | | will be used by the PHP date and date-time functions. We have gone
65 | | ahead and set this to a sensible default for you out of the box.
66 | |
67 | */
68 |
69 | 'timezone' => 'Asia/Tokyo',
70 |
71 | /*
72 | |--------------------------------------------------------------------------
73 | | Application Locale Configuration
74 | |--------------------------------------------------------------------------
75 | |
76 | | The application locale determines the default locale that will be used
77 | | by the translation service provider. You are free to set this value
78 | | to any of the locales which will be supported by the application.
79 | |
80 | */
81 |
82 | 'locale' => 'en',
83 |
84 | /*
85 | |--------------------------------------------------------------------------
86 | | Application Fallback Locale
87 | |--------------------------------------------------------------------------
88 | |
89 | | The fallback locale determines the locale to use when the current one
90 | | is not available. You may change the value to correspond to any of
91 | | the language folders that are provided through your application.
92 | |
93 | */
94 |
95 | 'fallback_locale' => 'en',
96 |
97 | /*
98 | |--------------------------------------------------------------------------
99 | | Encryption Key
100 | |--------------------------------------------------------------------------
101 | |
102 | | This key is used by the Illuminate encrypter service and should be set
103 | | to a random, 32 character string, otherwise these encrypted strings
104 | | will not be safe. Please do this before deploying an application!
105 | |
106 | */
107 |
108 | 'key' => env('APP_KEY'),
109 |
110 | 'cipher' => 'AES-256-CBC',
111 |
112 | /*
113 | |--------------------------------------------------------------------------
114 | | Autoloaded Service Providers
115 | |--------------------------------------------------------------------------
116 | |
117 | | The service providers listed here will be automatically loaded on the
118 | | request to your application. Feel free to add your own services to
119 | | this array to grant expanded functionality to your applications.
120 | |
121 | */
122 |
123 | 'providers' => [
124 |
125 | /*
126 | * Laravel Framework Service Providers...
127 | */
128 | Illuminate\Auth\AuthServiceProvider::class,
129 | Illuminate\Broadcasting\BroadcastServiceProvider::class,
130 | Illuminate\Bus\BusServiceProvider::class,
131 | Illuminate\Cache\CacheServiceProvider::class,
132 | Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
133 | Illuminate\Cookie\CookieServiceProvider::class,
134 | Illuminate\Database\DatabaseServiceProvider::class,
135 | Illuminate\Encryption\EncryptionServiceProvider::class,
136 | Illuminate\Filesystem\FilesystemServiceProvider::class,
137 | Illuminate\Foundation\Providers\FoundationServiceProvider::class,
138 | Illuminate\Hashing\HashServiceProvider::class,
139 | Illuminate\Mail\MailServiceProvider::class,
140 | Illuminate\Notifications\NotificationServiceProvider::class,
141 | Illuminate\Pagination\PaginationServiceProvider::class,
142 | Illuminate\Pipeline\PipelineServiceProvider::class,
143 | Illuminate\Queue\QueueServiceProvider::class,
144 | Illuminate\Redis\RedisServiceProvider::class,
145 | Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
146 | Illuminate\Session\SessionServiceProvider::class,
147 | Illuminate\Translation\TranslationServiceProvider::class,
148 | Illuminate\Validation\ValidationServiceProvider::class,
149 | Illuminate\View\ViewServiceProvider::class,
150 |
151 | /*
152 | * Package Service Providers...
153 | */
154 |
155 | /*
156 | * Application Service Providers...
157 | */
158 | App\Providers\AppServiceProvider::class,
159 | App\Providers\AuthServiceProvider::class,
160 | // App\Providers\BroadcastServiceProvider::class,
161 | App\Providers\EventServiceProvider::class,
162 | App\Providers\RouteServiceProvider::class,
163 | App\Providers\CoreApplicationServiceProvider::class,
164 | App\Providers\ValidationServiceProvider::class,
165 | App\Providers\DatabaseServiceProvider::class,
166 |
167 | ],
168 |
169 | /*
170 | |--------------------------------------------------------------------------
171 | | Class Aliases
172 | |--------------------------------------------------------------------------
173 | |
174 | | This array of class aliases will be registered when this application
175 | | is started. However, feel free to register as many as you wish as
176 | | the aliases are "lazy" loaded so they don't hinder performance.
177 | |
178 | */
179 |
180 | 'aliases' => [
181 |
182 | 'App' => Illuminate\Support\Facades\App::class,
183 | 'Artisan' => Illuminate\Support\Facades\Artisan::class,
184 | 'Auth' => Illuminate\Support\Facades\Auth::class,
185 | 'Blade' => Illuminate\Support\Facades\Blade::class,
186 | 'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
187 | 'Bus' => Illuminate\Support\Facades\Bus::class,
188 | 'Cache' => Illuminate\Support\Facades\Cache::class,
189 | 'Config' => Illuminate\Support\Facades\Config::class,
190 | 'Cookie' => Illuminate\Support\Facades\Cookie::class,
191 | 'Crypt' => Illuminate\Support\Facades\Crypt::class,
192 | 'DB' => Illuminate\Support\Facades\DB::class,
193 | 'Eloquent' => Illuminate\Database\Eloquent\Model::class,
194 | 'Event' => Illuminate\Support\Facades\Event::class,
195 | 'File' => Illuminate\Support\Facades\File::class,
196 | 'Gate' => Illuminate\Support\Facades\Gate::class,
197 | 'Hash' => Illuminate\Support\Facades\Hash::class,
198 | 'Lang' => Illuminate\Support\Facades\Lang::class,
199 | 'Log' => Illuminate\Support\Facades\Log::class,
200 | 'Mail' => Illuminate\Support\Facades\Mail::class,
201 | 'Notification' => Illuminate\Support\Facades\Notification::class,
202 | 'Password' => Illuminate\Support\Facades\Password::class,
203 | 'Queue' => Illuminate\Support\Facades\Queue::class,
204 | 'Redirect' => Illuminate\Support\Facades\Redirect::class,
205 | 'Redis' => Illuminate\Support\Facades\Redis::class,
206 | 'Request' => Illuminate\Support\Facades\Request::class,
207 | 'Response' => Illuminate\Support\Facades\Response::class,
208 | 'Route' => Illuminate\Support\Facades\Route::class,
209 | 'Schema' => Illuminate\Support\Facades\Schema::class,
210 | 'Session' => Illuminate\Support\Facades\Session::class,
211 | 'Storage' => Illuminate\Support\Facades\Storage::class,
212 | 'URL' => Illuminate\Support\Facades\URL::class,
213 | 'Validator' => Illuminate\Support\Facades\Validator::class,
214 | 'View' => Illuminate\Support\Facades\View::class,
215 |
216 | ],
217 |
218 | ];
219 |
--------------------------------------------------------------------------------
/config/application.php:
--------------------------------------------------------------------------------
1 | env('APPLICATION_INTEREST_RATE', 0.08),
6 | ];
7 |
--------------------------------------------------------------------------------
/config/auth.php:
--------------------------------------------------------------------------------
1 | [
17 | 'guard' => 'web',
18 | 'passwords' => 'users',
19 | ],
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | Authentication Guards
24 | |--------------------------------------------------------------------------
25 | |
26 | | Next, you may define every authentication guard for your application.
27 | | Of course, a great default configuration has been defined for you
28 | | here which uses session storage and the Eloquent user provider.
29 | |
30 | | All authentication drivers have a user provider. This defines how the
31 | | users are actually retrieved out of your database or other storage
32 | | mechanisms used by this application to persist your user's data.
33 | |
34 | | Supported: "session", "token"
35 | |
36 | */
37 |
38 | 'guards' => [
39 | 'web' => [
40 | 'driver' => 'session',
41 | 'provider' => 'users',
42 | ],
43 |
44 | 'api' => [
45 | 'driver' => 'token',
46 | 'provider' => 'users',
47 | ],
48 | ],
49 |
50 | /*
51 | |--------------------------------------------------------------------------
52 | | User Providers
53 | |--------------------------------------------------------------------------
54 | |
55 | | All authentication drivers have a user provider. This defines how the
56 | | users are actually retrieved out of your database or other storage
57 | | mechanisms used by this application to persist your user's data.
58 | |
59 | | If you have multiple user tables or models you may configure multiple
60 | | sources which represent each model / table. These sources may then
61 | | be assigned to any extra authentication guards you have defined.
62 | |
63 | | Supported: "database", "eloquent"
64 | |
65 | */
66 |
67 | 'providers' => [
68 | 'users' => [
69 | 'driver' => 'eloquent',
70 | 'model' => App\User::class,
71 | ],
72 |
73 | // 'users' => [
74 | // 'driver' => 'database',
75 | // 'table' => 'users',
76 | // ],
77 | ],
78 |
79 | /*
80 | |--------------------------------------------------------------------------
81 | | Resetting Passwords
82 | |--------------------------------------------------------------------------
83 | |
84 | | You may specify multiple password reset configurations if you have more
85 | | than one user table or model in the application and you want to have
86 | | separate password reset settings based on the specific user types.
87 | |
88 | | The expire time is the number of minutes that the reset token should be
89 | | considered valid. This security feature keeps tokens short-lived so
90 | | they have less time to be guessed. You may change this as needed.
91 | |
92 | */
93 |
94 | 'passwords' => [
95 | 'users' => [
96 | 'provider' => 'users',
97 | 'table' => 'password_resets',
98 | 'expire' => 60,
99 | ],
100 | ],
101 |
102 | ];
103 |
--------------------------------------------------------------------------------
/config/broadcasting.php:
--------------------------------------------------------------------------------
1 | env('BROADCAST_DRIVER', 'null'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Broadcast Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the broadcast connections that will be used
26 | | to broadcast events to other systems or over websockets. Samples of
27 | | each available type of connection are provided inside this array.
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'pusher' => [
34 | 'driver' => 'pusher',
35 | 'key' => env('PUSHER_APP_KEY'),
36 | 'secret' => env('PUSHER_APP_SECRET'),
37 | 'app_id' => env('PUSHER_APP_ID'),
38 | 'options' => [
39 | 'cluster' => env('PUSHER_APP_CLUSTER'),
40 | 'encrypted' => true,
41 | ],
42 | ],
43 |
44 | 'redis' => [
45 | 'driver' => 'redis',
46 | 'connection' => 'default',
47 | ],
48 |
49 | 'log' => [
50 | 'driver' => 'log',
51 | ],
52 |
53 | 'null' => [
54 | 'driver' => 'null',
55 | ],
56 |
57 | ],
58 |
59 | ];
60 |
--------------------------------------------------------------------------------
/config/cache.php:
--------------------------------------------------------------------------------
1 | env('CACHE_DRIVER', 'file'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Cache Stores
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the cache "stores" for your application as
26 | | well as their drivers. You may even define multiple stores for the
27 | | same cache driver to group types of items stored in your caches.
28 | |
29 | */
30 |
31 | 'stores' => [
32 |
33 | 'apc' => [
34 | 'driver' => 'apc',
35 | ],
36 |
37 | 'array' => [
38 | 'driver' => 'array',
39 | ],
40 |
41 | 'database' => [
42 | 'driver' => 'database',
43 | 'table' => 'cache',
44 | 'connection' => null,
45 | ],
46 |
47 | 'file' => [
48 | 'driver' => 'file',
49 | 'path' => storage_path('framework/cache/data'),
50 | ],
51 |
52 | 'memcached' => [
53 | 'driver' => 'memcached',
54 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
55 | 'sasl' => [
56 | env('MEMCACHED_USERNAME'),
57 | env('MEMCACHED_PASSWORD'),
58 | ],
59 | 'options' => [
60 | // Memcached::OPT_CONNECT_TIMEOUT => 2000,
61 | ],
62 | 'servers' => [
63 | [
64 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'),
65 | 'port' => env('MEMCACHED_PORT', 11211),
66 | 'weight' => 100,
67 | ],
68 | ],
69 | ],
70 |
71 | 'redis' => [
72 | 'driver' => 'redis',
73 | 'connection' => 'default',
74 | ],
75 |
76 | ],
77 |
78 | /*
79 | |--------------------------------------------------------------------------
80 | | Cache Key Prefix
81 | |--------------------------------------------------------------------------
82 | |
83 | | When utilizing a RAM based store such as APC or Memcached, there might
84 | | be other applications utilizing the same cache. So, we'll specify a
85 | | value to get prefixed to all our keys so we can avoid collisions.
86 | |
87 | */
88 |
89 | 'prefix' => env(
90 | 'CACHE_PREFIX',
91 | str_slug(env('APP_NAME', 'laravel'), '_') . '_cache'
92 | ),
93 |
94 | ];
95 |
--------------------------------------------------------------------------------
/config/database.php:
--------------------------------------------------------------------------------
1 | env('DB_CONNECTION', 'mysql'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Database Connections
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here are each of the database connections setup for your application.
24 | | Of course, examples of configuring each database platform that is
25 | | supported by Laravel is shown below to make development simple.
26 | |
27 | |
28 | | All database work in Laravel is done through the PHP PDO facilities
29 | | so make sure you have the driver for your particular database of
30 | | choice installed on your machine before you begin development.
31 | |
32 | */
33 |
34 | 'connections' => [
35 |
36 | 'sqlite' => [
37 | 'driver' => 'sqlite',
38 | 'database' => env('DB_DATABASE', database_path('database.sqlite')),
39 | 'prefix' => '',
40 | ],
41 |
42 | 'mysql' => [
43 | 'driver' => 'mysql',
44 | 'host' => env('DB_HOST', '127.0.0.1'),
45 | 'port' => env('DB_PORT', '3306'),
46 | 'database' => env('DB_DATABASE', 'forge'),
47 | 'username' => env('DB_USERNAME', 'forge'),
48 | 'password' => env('DB_PASSWORD', ''),
49 | 'unix_socket' => env('DB_SOCKET', ''),
50 | 'charset' => 'utf8mb4',
51 | 'collation' => 'utf8mb4_unicode_ci',
52 | 'prefix' => '',
53 | 'strict' => true,
54 | 'engine' => null,
55 | ],
56 |
57 | 'pgsql' => [
58 | 'driver' => 'pgsql',
59 | 'host' => env('DB_HOST', '127.0.0.1'),
60 | 'port' => env('DB_PORT', '5432'),
61 | 'database' => env('DB_DATABASE', 'forge'),
62 | 'username' => env('DB_USERNAME', 'forge'),
63 | 'password' => env('DB_PASSWORD', ''),
64 | 'charset' => 'utf8',
65 | 'prefix' => '',
66 | 'schema' => 'public',
67 | 'sslmode' => 'prefer',
68 | ],
69 |
70 | 'sqlsrv' => [
71 | 'driver' => 'sqlsrv',
72 | 'host' => env('DB_HOST', 'localhost'),
73 | 'port' => env('DB_PORT', '1433'),
74 | 'database' => env('DB_DATABASE', 'forge'),
75 | 'username' => env('DB_USERNAME', 'forge'),
76 | 'password' => env('DB_PASSWORD', ''),
77 | 'charset' => 'utf8',
78 | 'prefix' => '',
79 | ],
80 |
81 | ],
82 |
83 | /*
84 | |--------------------------------------------------------------------------
85 | | Migration Repository Table
86 | |--------------------------------------------------------------------------
87 | |
88 | | This table keeps track of all the migrations that have already run for
89 | | your application. Using this information, we can determine which of
90 | | the migrations on disk haven't actually been run in the database.
91 | |
92 | */
93 |
94 | 'migrations' => 'migrations',
95 |
96 | /*
97 | |--------------------------------------------------------------------------
98 | | Redis Databases
99 | |--------------------------------------------------------------------------
100 | |
101 | | Redis is an open source, fast, and advanced key-value store that also
102 | | provides a richer set of commands than a typical key-value systems
103 | | such as APC or Memcached. Laravel makes it easy to dig right in.
104 | |
105 | */
106 |
107 | 'redis' => [
108 |
109 | 'client' => 'predis',
110 |
111 | 'default' => [
112 | 'host' => env('REDIS_HOST', '127.0.0.1'),
113 | 'password' => env('REDIS_PASSWORD', null),
114 | 'port' => env('REDIS_PORT', 6379),
115 | 'database' => 0,
116 | ],
117 |
118 | ],
119 |
120 | ];
121 |
--------------------------------------------------------------------------------
/config/filesystems.php:
--------------------------------------------------------------------------------
1 | env('FILESYSTEM_DRIVER', 'local'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Default Cloud Filesystem Disk
21 | |--------------------------------------------------------------------------
22 | |
23 | | Many applications store files both locally and in the cloud. For this
24 | | reason, you may specify a default "cloud" driver here. This driver
25 | | will be bound as the Cloud disk implementation in the container.
26 | |
27 | */
28 |
29 | 'cloud' => env('FILESYSTEM_CLOUD', 's3'),
30 |
31 | /*
32 | |--------------------------------------------------------------------------
33 | | Filesystem Disks
34 | |--------------------------------------------------------------------------
35 | |
36 | | Here you may configure as many filesystem "disks" as you wish, and you
37 | | may even configure multiple disks of the same driver. Defaults have
38 | | been setup for each driver as an example of the required options.
39 | |
40 | | Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
41 | |
42 | */
43 |
44 | 'disks' => [
45 |
46 | 'local' => [
47 | 'driver' => 'local',
48 | 'root' => storage_path('app'),
49 | ],
50 |
51 | 'public' => [
52 | 'driver' => 'local',
53 | 'root' => storage_path('app/public'),
54 | 'url' => env('APP_URL') . '/storage',
55 | 'visibility' => 'public',
56 | ],
57 |
58 | 's3' => [
59 | 'driver' => 's3',
60 | 'key' => env('AWS_ACCESS_KEY_ID'),
61 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
62 | 'region' => env('AWS_DEFAULT_REGION'),
63 | 'bucket' => env('AWS_BUCKET'),
64 | 'url' => env('AWS_URL'),
65 | ],
66 |
67 | ],
68 |
69 | ];
70 |
--------------------------------------------------------------------------------
/config/hashing.php:
--------------------------------------------------------------------------------
1 | 'bcrypt',
19 |
20 | ];
21 |
--------------------------------------------------------------------------------
/config/logging.php:
--------------------------------------------------------------------------------
1 | env('LOG_CHANNEL', 'stack'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Log Channels
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure the log channels for your application. Out of
24 | | the box, Laravel uses the Monolog PHP logging library. This gives
25 | | you a variety of powerful log handlers / formatters to utilize.
26 | |
27 | | Available Drivers: "single", "daily", "slack", "syslog",
28 | | "errorlog", "custom", "stack"
29 | |
30 | */
31 |
32 | 'channels' => [
33 | 'stack' => [
34 | 'driver' => 'stack',
35 | 'channels' => ['single'],
36 | ],
37 |
38 | 'single' => [
39 | 'driver' => 'single',
40 | 'path' => storage_path('logs/laravel.log'),
41 | 'level' => 'debug',
42 | ],
43 |
44 | 'daily' => [
45 | 'driver' => 'daily',
46 | 'path' => storage_path('logs/laravel.log'),
47 | 'level' => 'debug',
48 | 'days' => 7,
49 | ],
50 |
51 | 'slack' => [
52 | 'driver' => 'slack',
53 | 'url' => env('LOG_SLACK_WEBHOOK_URL'),
54 | 'username' => 'Laravel Log',
55 | 'emoji' => ':boom:',
56 | 'level' => 'critical',
57 | ],
58 |
59 | 'syslog' => [
60 | 'driver' => 'syslog',
61 | 'level' => 'debug',
62 | ],
63 |
64 | 'errorlog' => [
65 | 'driver' => 'errorlog',
66 | 'level' => 'debug',
67 | ],
68 | ],
69 |
70 | ];
71 |
--------------------------------------------------------------------------------
/config/mail.php:
--------------------------------------------------------------------------------
1 | env('MAIL_DRIVER', 'smtp'),
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | SMTP Host Address
24 | |--------------------------------------------------------------------------
25 | |
26 | | Here you may provide the host address of the SMTP server used by your
27 | | applications. A default option is provided that is compatible with
28 | | the Mailgun mail service which will provide reliable deliveries.
29 | |
30 | */
31 |
32 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
33 |
34 | /*
35 | |--------------------------------------------------------------------------
36 | | SMTP Host Port
37 | |--------------------------------------------------------------------------
38 | |
39 | | This is the SMTP port used by your application to deliver e-mails to
40 | | users of the application. Like the host we have set this value to
41 | | stay compatible with the Mailgun e-mail application by default.
42 | |
43 | */
44 |
45 | 'port' => env('MAIL_PORT', 587),
46 |
47 | /*
48 | |--------------------------------------------------------------------------
49 | | Global "From" Address
50 | |--------------------------------------------------------------------------
51 | |
52 | | You may wish for all e-mails sent by your application to be sent from
53 | | the same address. Here, you may specify a name and address that is
54 | | used globally for all e-mails that are sent by your application.
55 | |
56 | */
57 |
58 | 'from' => [
59 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
60 | 'name' => env('MAIL_FROM_NAME', 'Example'),
61 | ],
62 |
63 | /*
64 | |--------------------------------------------------------------------------
65 | | E-Mail Encryption Protocol
66 | |--------------------------------------------------------------------------
67 | |
68 | | Here you may specify the encryption protocol that should be used when
69 | | the application send e-mail messages. A sensible default using the
70 | | transport layer security protocol should provide great security.
71 | |
72 | */
73 |
74 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'),
75 |
76 | /*
77 | |--------------------------------------------------------------------------
78 | | SMTP Server Username
79 | |--------------------------------------------------------------------------
80 | |
81 | | If your SMTP server requires a username for authentication, you should
82 | | set it here. This will get used to authenticate with your server on
83 | | connection. You may also set the "password" value below this one.
84 | |
85 | */
86 |
87 | 'username' => env('MAIL_USERNAME'),
88 |
89 | 'password' => env('MAIL_PASSWORD'),
90 |
91 | /*
92 | |--------------------------------------------------------------------------
93 | | Sendmail System Path
94 | |--------------------------------------------------------------------------
95 | |
96 | | When using the "sendmail" driver to send e-mails, we will need to know
97 | | the path to where Sendmail lives on this server. A default path has
98 | | been provided here, which will work well on most of your systems.
99 | |
100 | */
101 |
102 | 'sendmail' => '/usr/sbin/sendmail -bs',
103 |
104 | /*
105 | |--------------------------------------------------------------------------
106 | | Markdown Mail Settings
107 | |--------------------------------------------------------------------------
108 | |
109 | | If you are using Markdown based email rendering, you may configure your
110 | | theme and component paths here, allowing you to customize the design
111 | | of the emails. Or, you may simply stick with the Laravel defaults!
112 | |
113 | */
114 |
115 | 'markdown' => [
116 | 'theme' => 'default',
117 |
118 | 'paths' => [
119 | resource_path('views/vendor/mail'),
120 | ],
121 | ],
122 |
123 | ];
124 |
--------------------------------------------------------------------------------
/config/queue.php:
--------------------------------------------------------------------------------
1 | env('QUEUE_DRIVER', 'sync'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Queue Connections
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure the connection information for each server that
24 | | is used by your application. A default configuration has been added
25 | | for each back-end shipped with Laravel. You are free to add more.
26 | |
27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'sync' => [
34 | 'driver' => 'sync',
35 | ],
36 |
37 | 'database' => [
38 | 'driver' => 'database',
39 | 'table' => 'jobs',
40 | 'queue' => 'default',
41 | 'retry_after' => 90,
42 | ],
43 |
44 | 'beanstalkd' => [
45 | 'driver' => 'beanstalkd',
46 | 'host' => 'localhost',
47 | 'queue' => 'default',
48 | 'retry_after' => 90,
49 | ],
50 |
51 | 'sqs' => [
52 | 'driver' => 'sqs',
53 | 'key' => env('SQS_KEY', 'your-public-key'),
54 | 'secret' => env('SQS_SECRET', 'your-secret-key'),
55 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
56 | 'queue' => env('SQS_QUEUE', 'your-queue-name'),
57 | 'region' => env('SQS_REGION', 'us-east-1'),
58 | ],
59 |
60 | 'redis' => [
61 | 'driver' => 'redis',
62 | 'connection' => 'default',
63 | 'queue' => 'default',
64 | 'retry_after' => 90,
65 | 'block_for' => null,
66 | ],
67 |
68 | ],
69 |
70 | /*
71 | |--------------------------------------------------------------------------
72 | | Failed Queue Jobs
73 | |--------------------------------------------------------------------------
74 | |
75 | | These options configure the behavior of failed queue job logging so you
76 | | can control which database and table are used to store the jobs that
77 | | have failed. You may change them to any database / table you wish.
78 | |
79 | */
80 |
81 | 'failed' => [
82 | 'database' => env('DB_CONNECTION', 'mysql'),
83 | 'table' => 'failed_jobs',
84 | ],
85 |
86 | ];
87 |
--------------------------------------------------------------------------------
/config/services.php:
--------------------------------------------------------------------------------
1 | [
18 | 'domain' => env('MAILGUN_DOMAIN'),
19 | 'secret' => env('MAILGUN_SECRET'),
20 | ],
21 |
22 | 'ses' => [
23 | 'key' => env('SES_KEY'),
24 | 'secret' => env('SES_SECRET'),
25 | 'region' => 'us-east-1',
26 | ],
27 |
28 | 'sparkpost' => [
29 | 'secret' => env('SPARKPOST_SECRET'),
30 | ],
31 |
32 | 'stripe' => [
33 | 'model' => App\User::class,
34 | 'key' => env('STRIPE_KEY'),
35 | 'secret' => env('STRIPE_SECRET'),
36 | ],
37 |
38 | ];
39 |
--------------------------------------------------------------------------------
/config/session.php:
--------------------------------------------------------------------------------
1 | env('SESSION_DRIVER', 'file'),
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | Session Lifetime
24 | |--------------------------------------------------------------------------
25 | |
26 | | Here you may specify the number of minutes that you wish the session
27 | | to be allowed to remain idle before it expires. If you want them
28 | | to immediately expire on the browser closing, set that option.
29 | |
30 | */
31 |
32 | 'lifetime' => env('SESSION_LIFETIME', 120),
33 |
34 | 'expire_on_close' => false,
35 |
36 | /*
37 | |--------------------------------------------------------------------------
38 | | Session Encryption
39 | |--------------------------------------------------------------------------
40 | |
41 | | This option allows you to easily specify that all of your session data
42 | | should be encrypted before it is stored. All encryption will be run
43 | | automatically by Laravel and you can use the Session like normal.
44 | |
45 | */
46 |
47 | 'encrypt' => false,
48 |
49 | /*
50 | |--------------------------------------------------------------------------
51 | | Session File Location
52 | |--------------------------------------------------------------------------
53 | |
54 | | When using the native session driver, we need a location where session
55 | | files may be stored. A default has been set for you but a different
56 | | location may be specified. This is only needed for file sessions.
57 | |
58 | */
59 |
60 | 'files' => storage_path('framework/sessions'),
61 |
62 | /*
63 | |--------------------------------------------------------------------------
64 | | Session Database Connection
65 | |--------------------------------------------------------------------------
66 | |
67 | | When using the "database" or "redis" session drivers, you may specify a
68 | | connection that should be used to manage these sessions. This should
69 | | correspond to a connection in your database configuration options.
70 | |
71 | */
72 |
73 | 'connection' => null,
74 |
75 | /*
76 | |--------------------------------------------------------------------------
77 | | Session Database Table
78 | |--------------------------------------------------------------------------
79 | |
80 | | When using the "database" session driver, you may specify the table we
81 | | should use to manage the sessions. Of course, a sensible default is
82 | | provided for you; however, you are free to change this as needed.
83 | |
84 | */
85 |
86 | 'table' => 'sessions',
87 |
88 | /*
89 | |--------------------------------------------------------------------------
90 | | Session Cache Store
91 | |--------------------------------------------------------------------------
92 | |
93 | | When using the "apc" or "memcached" session drivers, you may specify a
94 | | cache store that should be used for these sessions. This value must
95 | | correspond with one of the application's configured cache stores.
96 | |
97 | */
98 |
99 | 'store' => null,
100 |
101 | /*
102 | |--------------------------------------------------------------------------
103 | | Session Sweeping Lottery
104 | |--------------------------------------------------------------------------
105 | |
106 | | Some session drivers must manually sweep their storage location to get
107 | | rid of old sessions from storage. Here are the chances that it will
108 | | happen on a given request. By default, the odds are 2 out of 100.
109 | |
110 | */
111 |
112 | 'lottery' => [2, 100],
113 |
114 | /*
115 | |--------------------------------------------------------------------------
116 | | Session Cookie Name
117 | |--------------------------------------------------------------------------
118 | |
119 | | Here you may change the name of the cookie used to identify a session
120 | | instance by ID. The name specified here will get used every time a
121 | | new session cookie is created by the framework for every driver.
122 | |
123 | */
124 |
125 | 'cookie' => env(
126 | 'SESSION_COOKIE',
127 | str_slug(env('APP_NAME', 'laravel'), '_') . '_session'
128 | ),
129 |
130 | /*
131 | |--------------------------------------------------------------------------
132 | | Session Cookie Path
133 | |--------------------------------------------------------------------------
134 | |
135 | | The session cookie path determines the path for which the cookie will
136 | | be regarded as available. Typically, this will be the root path of
137 | | your application but you are free to change this when necessary.
138 | |
139 | */
140 |
141 | 'path' => '/',
142 |
143 | /*
144 | |--------------------------------------------------------------------------
145 | | Session Cookie Domain
146 | |--------------------------------------------------------------------------
147 | |
148 | | Here you may change the domain of the cookie used to identify a session
149 | | in your application. This will determine which domains the cookie is
150 | | available to in your application. A sensible default has been set.
151 | |
152 | */
153 |
154 | 'domain' => env('SESSION_DOMAIN', null),
155 |
156 | /*
157 | |--------------------------------------------------------------------------
158 | | HTTPS Only Cookies
159 | |--------------------------------------------------------------------------
160 | |
161 | | By setting this option to true, session cookies will only be sent back
162 | | to the server if the browser has a HTTPS connection. This will keep
163 | | the cookie from being sent to you if it can not be done securely.
164 | |
165 | */
166 |
167 | 'secure' => env('SESSION_SECURE_COOKIE', false),
168 |
169 | /*
170 | |--------------------------------------------------------------------------
171 | | HTTP Access Only
172 | |--------------------------------------------------------------------------
173 | |
174 | | Setting this value to true will prevent JavaScript from accessing the
175 | | value of the cookie and the cookie will only be accessible through
176 | | the HTTP protocol. You are free to modify this option if needed.
177 | |
178 | */
179 |
180 | 'http_only' => true,
181 |
182 | /*
183 | |--------------------------------------------------------------------------
184 | | Same-Site Cookies
185 | |--------------------------------------------------------------------------
186 | |
187 | | This option determines how your cookies behave when cross-site requests
188 | | take place, and can be used to mitigate CSRF attacks. By default, we
189 | | do not enable this as other CSRF protection services are in place.
190 | |
191 | | Supported: "lax", "strict"
192 | |
193 | */
194 |
195 | 'same_site' => null,
196 |
197 | ];
198 |
--------------------------------------------------------------------------------
/config/view.php:
--------------------------------------------------------------------------------
1 | [
17 | resource_path('views'),
18 | ],
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Compiled View Path
23 | |--------------------------------------------------------------------------
24 | |
25 | | This option determines where all the compiled Blade templates will be
26 | | stored for your application. Typically, this is within the storage
27 | | directory. However, as usual, you are free to change this value.
28 | |
29 | */
30 |
31 | 'compiled' => realpath(storage_path('framework/views')),
32 |
33 | ];
34 |
--------------------------------------------------------------------------------
/database/.gitignore:
--------------------------------------------------------------------------------
1 | *.sqlite
2 |
--------------------------------------------------------------------------------
/database/factories/UserFactory.php:
--------------------------------------------------------------------------------
1 | define(App\User::class, function (Faker $faker) {
17 | return [
18 | 'name' => $faker->name,
19 | 'email' => $faker->unique()->safeEmail,
20 | 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
21 | 'remember_token' => str_random(10),
22 | ];
23 | });
24 |
--------------------------------------------------------------------------------
/database/migrations/2018_04_13_142835_create_accounts_table.php:
--------------------------------------------------------------------------------
1 | increments('id');
18 | /** @noinspection PhpUndefinedMethodInspection */
19 | $table->string('account_number', 10)->unique();
20 | /** @noinspection PhpUndefinedMethodInspection */
21 | $table->string('email', 255)->unique();
22 | $table->string('name');
23 | /** @noinspection PhpUndefinedMethodInspection */
24 | $table->bigInteger('balance')->default(0);
25 | });
26 | }
27 |
28 | /**
29 | * Reverse the migrations.
30 | *
31 | * @return void
32 | */
33 | public function down()
34 | {
35 | Schema::dropIfExists('accounts');
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/database/migrations/2018_05_05_122357_create-transactions-table.php:
--------------------------------------------------------------------------------
1 | string('type')->primary();
23 | });
24 |
25 | DB::table('transaction_types')->insert([
26 | 'type' => TransactionType::WITHDRAW()->asString(),
27 | ]);
28 | DB::table('transaction_types')->insert([
29 | 'type' => TransactionType::DEPOSIT()->asString(),
30 | ]);
31 |
32 | Schema::create('transactions', function (Blueprint $table) {
33 | $table->increments('id');
34 | $table->string('account_number');
35 | $table->string('transaction_type');
36 | $table->dateTime('transaction_time');
37 | $table->integer('amount');
38 | $table->text('comment');
39 |
40 | /** @noinspection PhpUndefinedMethodInspection */
41 | $table->foreign('account_number')
42 | ->references('account_number')
43 | ->on('accounts');
44 | /** @noinspection PhpUndefinedMethodInspection */
45 | $table->foreign('transaction_type')
46 | ->references('type')
47 | ->on('transaction_types');
48 | });
49 | });
50 | }
51 |
52 | /**
53 | * Reverse the migrations.
54 | *
55 | * @return void
56 | */
57 | public function down()
58 | {
59 | Schema::drop('transactions');
60 | Schema::drop('transaction_types');
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/database/seeds/AccountSeeder.php:
--------------------------------------------------------------------------------
1 | 'A00001',
14 | 'email' => 'a@example.com',
15 | 'name' => 'Mike',
16 | 'balance' => 3000,
17 | ],
18 | [
19 | 'account_number' => 'B00001',
20 | 'email' => 'b@example.com',
21 | 'name' => 'John',
22 | 'balance' => 1000,
23 | ],
24 | ])->each(function ($values) use ($connection) {
25 | $connection->table('accounts')->insert($values);
26 | });
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/database/seeds/DatabaseSeeder.php:
--------------------------------------------------------------------------------
1 | call(AccountSeeder::class);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '2'
2 | services:
3 | nginx:
4 | image: nginx:1.12
5 | ports:
6 | - '8000:80'
7 | - '8001:8001'
8 | volumes:
9 | - .:/var/www/html
10 | - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
11 | - ./docker/nginx/conf.d:/etc/nginx/conf.d
12 | links:
13 | - php-fpm
14 | restart: always
15 | php-fpm:
16 | build: "./docker/php-fpm/"
17 | volumes:
18 | - .:/var/www/html
19 | - ./docker/php-fpm/php.ini:/usr/local/etc/php/conf.d/zzmyphp.ini
20 | - ./docker/php-fpm/php-fpm.conf:/usr/local/etc/php-fpm.d/zzmyphp-fpm.conf
21 | links:
22 | - db
23 | - db-test
24 | restart: always
25 | composer:
26 | image: composer
27 | volumes:
28 | - .:/var/www/html
29 | working_dir: /var/www/html
30 | phpstan:
31 | image: phpstan/phpstan
32 | volumes:
33 | - .:/var/www/html
34 | working_dir: /var/www/html
35 | db:
36 | image: postgres:10-alpine
37 | environment:
38 | - POSTGRES_USER=app
39 | - POSTGRES_PASSWORD=pass
40 | - POSTGRES_DB=app
41 | - LC_ALL=C
42 | db-test:
43 | image: postgres:10-alpine
44 | environment:
45 | - POSTGRES_USER=app
46 | - POSTGRES_PASSWORD=pass
47 | - POSTGRES_DB=app
48 | - LC_ALL=C
49 |
--------------------------------------------------------------------------------
/docker/nginx/conf.d/default.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 80 default_server;
3 | listen [::]:80 default_server ipv6only=on;
4 |
5 | root /var/www/html/public;
6 | index index.php index.html index.htm;
7 | charset utf-8;
8 |
9 | location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar|svg|mp3)$ {
10 | try_files $uri =404;
11 | }
12 |
13 | location / {
14 | try_files $uri $uri/ /index.php$is_args$args;
15 | }
16 |
17 | location ~ \.php$ {
18 | fastcgi_pass php-upstream;
19 | fastcgi_index index.php;
20 | fastcgi_buffers 16 16k;
21 | fastcgi_buffer_size 32k;
22 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
23 | include fastcgi_params;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/docker/nginx/conf.d/php-upstream.conf:
--------------------------------------------------------------------------------
1 | upstream php-upstream {
2 | server php-fpm:9000;
3 | }
--------------------------------------------------------------------------------
/docker/nginx/conf.d/status.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 8001;
3 | server_name localhost;
4 | location /nginx_status {
5 | stub_status on;
6 | access_log off;
7 | allow 127.0.0.1;
8 | allow 172.16.0.0/12;
9 | deny all;
10 | }
11 |
12 | location /phpfpm_status {
13 | include fastcgi_params;
14 | fastcgi_pass php-upstream;
15 |
16 | fastcgi_index index.php;
17 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
18 |
19 | access_log off;
20 | allow 127.0.0.1;
21 | allow 172.16.0.0/12;
22 | deny all;
23 | }
24 | }
--------------------------------------------------------------------------------
/docker/nginx/nginx.conf:
--------------------------------------------------------------------------------
1 | user nginx;
2 | worker_processes 1;
3 |
4 | error_log /var/log/nginx/error.log warn;
5 | pid /var/run/nginx.pid;
6 |
7 | events {
8 | worker_connections 1024;
9 | }
10 |
11 | http {
12 | include /etc/nginx/mime.types;
13 | default_type application/octet-stream;
14 |
15 | log_format json_combined escape=json '{ "time_local": "$time_local", '
16 | '"remote_addr": "$remote_addr", '
17 | '"remote_user": "$remote_user", '
18 | '"request": "$request", '
19 | '"status": "$status", '
20 | '"body_bytes_sent": "$body_bytes_sent", '
21 | '"request_time": "$request_time", '
22 | '"http_referrer": "$http_referer", '
23 | '"http_user_agent": "$http_user_agent" }';
24 |
25 | access_log /var/log/nginx/access.log json_combined;
26 |
27 | sendfile on;
28 | #tcp_nopush on;
29 |
30 | keepalive_timeout 65;
31 |
32 | gzip on;
33 | server_tokens off;
34 |
35 | server_names_hash_max_size 512;
36 |
37 | include /etc/nginx/conf.d/*.conf;
38 | }
--------------------------------------------------------------------------------
/docker/php-fpm/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM php:7.2-fpm
2 |
3 | # Install PHP extensions
4 | RUN apt-get update && apt-get install -y \
5 | libpq-dev \
6 | && rm -r /var/lib/apt/lists/* \
7 | && docker-php-ext-install \
8 | pdo_pgsql \
9 | pgsql \
10 | opcache
11 |
--------------------------------------------------------------------------------
/docker/php-fpm/php-fpm.conf:
--------------------------------------------------------------------------------
1 | [www]
2 | pm.status_path = /phpfpm_status
3 |
--------------------------------------------------------------------------------
/docker/php-fpm/php.ini:
--------------------------------------------------------------------------------
1 | ; timezone
2 | date.timezone = Asia/Tokyo
3 |
4 | ; error reporing
5 | log_errors = On
6 | error_log = /dev/stderr
7 | display_errors = Off
8 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "dev": "npm run development",
5 | "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
6 | "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
7 | "watch-poll": "npm run watch -- --watch-poll",
8 | "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
9 | "prod": "npm run production",
10 | "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
11 | },
12 | "devDependencies": {
13 | "axios": "^0.18",
14 | "bootstrap": "^4.0.0",
15 | "popper.js": "^1.12",
16 | "cross-env": "^5.1",
17 | "jquery": "^3.2",
18 | "laravel-mix": "^2.0",
19 | "lodash": "^4.17.4",
20 | "vue": "^2.5.7"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Aggregates/TransferMoneyAggregate.php:
--------------------------------------------------------------------------------
1 | source = $source;
31 | $this->destination = $destination;
32 | }
33 |
34 | /**
35 | * @param Money $amount
36 | * @param TransactionTime $now
37 | * @throws \Acme\Account\Domain\Exceptions\InvariantException
38 | */
39 | public function transfer(Money $amount, TransactionTime $now)
40 | {
41 | $this->source->withdraw($amount);
42 | $this->destination->deposit($amount);
43 |
44 | $this->sourceTransaction = new Transaction(
45 | $this->source->accountNumber(),
46 | TransactionType::WITHDRAW(),
47 | $now,
48 | $amount,
49 | 'transferred to ' . $this->destination->accountNumber()->asString()
50 | );
51 |
52 | $this->destinationTransaction = new Transaction(
53 | $this->destination->accountNumber(),
54 | TransactionType::DEPOSIT(),
55 | $now,
56 | $amount,
57 | 'transferred from ' . $this->source->accountNumber()->asString()
58 | );
59 | }
60 |
61 | /**
62 | * @return Account
63 | */
64 | public function source(): Account
65 | {
66 | return $this->source;
67 | }
68 |
69 | /**
70 | * @return Account
71 | */
72 | public function destination(): Account
73 | {
74 | return $this->destination;
75 | }
76 |
77 | /**
78 | * @return Transaction
79 | */
80 | public function sourceTransaction(): Transaction
81 | {
82 | return $this->sourceTransaction;
83 | }
84 |
85 | /**
86 | * @return Transaction
87 | */
88 | public function destinationTransaction(): Transaction
89 | {
90 | return $this->destinationTransaction;
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Exceptions/DomainException.php:
--------------------------------------------------------------------------------
1 | accountNumber = $accountNumber;
20 | $this->email = $email;
21 | $this->name = $name;
22 | $this->balance = $balance;
23 | }
24 |
25 | public function accountNumber(): AccountNumber
26 | {
27 | return $this->accountNumber;
28 | }
29 |
30 | /**
31 | * @return Email
32 | */
33 | public function email(): Email
34 | {
35 | return $this->email;
36 | }
37 |
38 | public function name(): string
39 | {
40 | return $this->name;
41 | }
42 |
43 | public function balance(): Balance
44 | {
45 | return clone $this->balance;
46 | }
47 |
48 | /**
49 | * @param Money $money
50 | * @throws \Acme\Account\Domain\Exceptions\InvariantException
51 | */
52 | public function deposit(Money $money)
53 | {
54 | $this->balance = $this->balance->deposit($money);
55 | }
56 |
57 | /**
58 | * @param Money $money
59 | * @throws \Acme\Account\Domain\Exceptions\InvariantException
60 | */
61 | public function withdraw(Money $money)
62 | {
63 | $this->balance = $this->balance->withdraw($money);
64 | }
65 |
66 | public static function ofByArray(array $values): self
67 | {
68 | return new self(
69 | AccountNumber::of($values['account_number'] ?? ''),
70 | Email::of($values['email'] ?? ''),
71 | $values['name'] ?? '',
72 | Balance::of($values['balance'] ?? 0)
73 | );
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/AccountNumber.php:
--------------------------------------------------------------------------------
1 | value = $value;
19 | }
20 |
21 | /**
22 | * @param string $value
23 | * @return bool
24 | */
25 | public static function validate(string $value)
26 | {
27 | return preg_match('/\A[A-Z][0-9]{4,10}\z/', $value) > 0;
28 | }
29 |
30 | /**
31 | * @param self $accountNumber
32 | * @return bool
33 | */
34 | public function lessThan(AccountNumber $accountNumber): bool
35 | {
36 | return $this->value < $accountNumber->value;
37 | }
38 |
39 | /**
40 | * @param self $accountNumber
41 | * @return bool
42 | */
43 | public function equals(AccountNumber $accountNumber): bool
44 | {
45 | return $this->value === $accountNumber->value;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/Balance.php:
--------------------------------------------------------------------------------
1 | value = $value;
22 | }
23 |
24 | /**
25 | * @param Money $money
26 | * @return Balance
27 | * @throws InvariantException
28 | */
29 | public function deposit(Money $money): self
30 | {
31 | return new self($this->value + $money->asInt());
32 | }
33 |
34 | /**
35 | * @param Money $money
36 | * @return Balance
37 | * @throws InvariantException
38 | */
39 | public function withdraw(Money $money): self
40 | {
41 | return new self($this->value - $money->asInt());
42 | }
43 |
44 | /**
45 | * @param Money $money
46 | * @return bool
47 | */
48 | public function lessThan(Money $money): bool
49 | {
50 | return $this->value < $money->asInt();
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/Email.php:
--------------------------------------------------------------------------------
1 | value = $value;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/Enum.php:
--------------------------------------------------------------------------------
1 | value = $value;
19 | }
20 |
21 | /**
22 | * @return string
23 | */
24 | public function asString(): string
25 | {
26 | return $this->value;
27 | }
28 |
29 | /**
30 | * @return string
31 | */
32 | public function __toString(): string
33 | {
34 | return $this->asString();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/Money.php:
--------------------------------------------------------------------------------
1 | accountNumber = $accountNumber;
34 | $this->transactionType = $transactionType;
35 | $this->transactionTime = $transactionTime;
36 | $this->amount = $amount;
37 | $this->comment = $comment;
38 | }
39 |
40 | /**
41 | * @return AccountNumber
42 | */
43 | public function accountNumber(): AccountNumber
44 | {
45 | return $this->accountNumber;
46 | }
47 |
48 | /**
49 | * @return TransactionType
50 | */
51 | public function transactionType(): TransactionType
52 | {
53 | return $this->transactionType;
54 | }
55 |
56 | /**
57 | * @return TransactionTime
58 | */
59 | public function transactionTime(): TransactionTime
60 | {
61 | return $this->transactionTime;
62 | }
63 |
64 | /**
65 | * @return Money
66 | */
67 | public function amount(): Money
68 | {
69 | return $this->amount;
70 | }
71 |
72 | /**
73 | * @return string
74 | */
75 | public function comment(): string
76 | {
77 | return $this->comment;
78 | }
79 |
80 | /**
81 | * @param array $values
82 | * @return Transaction
83 | */
84 | public static function ofByArray(array $values): self
85 | {
86 | return new self(
87 | AccountNumber::of($values['account_number'] ?? ''),
88 | TransactionType::of($values['transaction_type'] ?? ''),
89 | TransactionTime::of($values['transaction_time'] ?? ''),
90 | Money::of($values['amount'] ?? 0),
91 | $values['comment'] ?? ''
92 | );
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/TransactionTime.php:
--------------------------------------------------------------------------------
1 | date = $date;
21 | }
22 |
23 | /**
24 | * @return TransactionTime
25 | */
26 | public static function now(): self
27 | {
28 | return new self(Chronos::now());
29 | }
30 |
31 | /**
32 | * @return string
33 | */
34 | public function __toString(): string
35 | {
36 | return $this->date->toDateTimeString();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/TransactionType.php:
--------------------------------------------------------------------------------
1 | value = $value;
16 | }
17 |
18 | public function asFloat(): float
19 | {
20 | return $this->value;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/ValueObjectInt.php:
--------------------------------------------------------------------------------
1 | value = $value;
19 | }
20 |
21 | public function asInt(): int
22 | {
23 | return $this->value;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Models/ValueObjectOf.php:
--------------------------------------------------------------------------------
1 | value = $value;
19 | }
20 |
21 | /**
22 | * @return string
23 | */
24 | public function asString(): string
25 | {
26 | return $this->value;
27 | }
28 |
29 | /**
30 | * @return string
31 | */
32 | public function __toString(): string
33 | {
34 | return $this->asString();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Specifications/DifferentAccountSpec.php:
--------------------------------------------------------------------------------
1 | accountNumber()->equals($accountB->accountNumber());
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Specifications/TransferMoneySpec.php:
--------------------------------------------------------------------------------
1 | isSatisfiedBy($aggregate->source(), $aggregate->destination())
19 | && (new WithdrawSpec())->isSatisfiedBy($aggregate->source(), $amount);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/packages/Acme/Account/Domain/Specifications/WithdrawSpec.php:
--------------------------------------------------------------------------------
1 | balance()->lessThan($amount);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/packages/Acme/Account/UseCase/DDDStyleTransferMoney/DDDStyleTransferMoney.php:
--------------------------------------------------------------------------------
1 | query = $query;
37 | $this->command = $command;
38 | $this->transaction = $transaction;
39 | }
40 |
41 | /**
42 | * @param AccountNumber $sourceNumber
43 | * @param AccountNumber $destinationNumber
44 | * @param Money $amount
45 | * @param TransactionTime $now
46 | * @return Balance
47 | */
48 | public function execute(
49 | AccountNumber $sourceNumber,
50 | AccountNumber $destinationNumber,
51 | Money $amount,
52 | TransactionTime $now
53 | ): Balance {
54 | return $this->transaction->transaction(function () use ($sourceNumber, $destinationNumber, $amount, $now) {
55 | $aggregate = $this->query->find($sourceNumber, $destinationNumber);
56 |
57 | if (!(new TransferMoneySpec())->isSatisfiedBy($aggregate, $amount)) {
58 | throw new DomainRuleException('TransferMoneySpec is not satisfied.');
59 | }
60 |
61 | $aggregate->transfer($amount, $now);
62 |
63 | $this->command->store($aggregate);
64 | $this->command->notify($aggregate->source());
65 |
66 | return $this->query->findAccount($sourceNumber)->balance();
67 | });
68 | }
69 | }
70 |
71 | interface DDDStyleTransferMoneyQuery
72 | {
73 | /**
74 | * @param AccountNumber $sourceNumber
75 | * @param AccountNumber $destinationNumber
76 | * @return TransferMoneyAggregate
77 | */
78 | public function find(AccountNumber $sourceNumber, AccountNumber $destinationNumber): TransferMoneyAggregate;
79 |
80 | /**
81 | * @param AccountNumber $accountNumber
82 | * @return Account
83 | * @throws NotFoundException
84 | */
85 | public function findAccount(AccountNumber $accountNumber): Account;
86 | }
87 |
88 | interface DDDStyleTransferMoneyCommandPort
89 | {
90 | /**
91 | * @param TransferMoneyAggregate $aggregate
92 | */
93 | public function store(TransferMoneyAggregate $aggregate): void;
94 |
95 | /**
96 | * @param Account $account
97 | */
98 | public function notify(Account $account): void;
99 | }
100 |
--------------------------------------------------------------------------------
/packages/Acme/Account/UseCase/GetAccount/GetAccount.php:
--------------------------------------------------------------------------------
1 | query = $query;
21 | }
22 |
23 | /**
24 | * @param AccountNumber $accountNumber
25 | * @return Account
26 | * @throws NotFoundException
27 | */
28 | public function execute(AccountNumber $accountNumber): Account
29 | {
30 | return $this->query->findAccount($accountNumber);
31 | }
32 | }
33 |
34 | interface GetAccountQueryPort
35 | {
36 | /**
37 | * @param AccountNumber $accountNumber
38 | * @return Account
39 | * @throws NotFoundException
40 | */
41 | public function findAccount(AccountNumber $accountNumber): Account;
42 | }
43 |
--------------------------------------------------------------------------------
/packages/Acme/Account/UseCase/Ports/TransactionPort.php:
--------------------------------------------------------------------------------
1 | query = $query;
34 | $this->command = $command;
35 | $this->transaction = $transaction;
36 | }
37 |
38 | /**
39 | * @param string $sourceNumber
40 | * @param string $destinationNumber
41 | * @param int $amount
42 | * @param Chronos $now
43 | * @return int
44 | */
45 | public function execute(
46 | string $sourceNumber,
47 | string $destinationNumber,
48 | int $amount,
49 | Chronos $now
50 | ): int {
51 | return $this->transaction->transaction(function () use ($sourceNumber, $destinationNumber, $amount, $now) {
52 | [$source, $destination] = $this->query($sourceNumber, $destinationNumber);
53 |
54 | if ($sourceNumber === $destinationNumber) {
55 | throw new DomainRuleException('source can not transfer to same account');
56 | }
57 |
58 | if ($source['balance'] < $amount) {
59 | $message = sprintf('source account does not have enough balance for transfer %s', $amount);
60 | throw new DomainRuleException($message);
61 | }
62 |
63 | $source['balance'] -= $amount;
64 | $destination['balance'] += $amount;
65 |
66 | $this->store($source, $destination, $amount, $now);
67 |
68 | $this->command->notify($source);
69 |
70 | return $this->query->findAccount($sourceNumber)['balance'];
71 | });
72 | }
73 |
74 | /**
75 | * @param string $sourceNumber
76 | * @param string $destinationNumber
77 | * @return array
78 | */
79 | private function query(string $sourceNumber, string $destinationNumber): array
80 | {
81 | if ($sourceNumber < $destinationNumber) {
82 | $source = $this->query->findAndLockAccount($sourceNumber);
83 | $destination = $this->query->findAndLockAccount($destinationNumber);
84 | } else {
85 | $destination = $this->query->findAndLockAccount($destinationNumber);
86 | $source = $this->query->findAndLockAccount($sourceNumber);
87 | }
88 |
89 | return [$source, $destination];
90 | }
91 |
92 | /**
93 | * @param array $source
94 | * @param array $destination
95 | * @param int $amount
96 | * @param Chronos $now
97 | */
98 | private function store(array $source, array $destination, int $amount, Chronos $now): void
99 | {
100 | $this->command->storeBalance($source['account_number'], $source['balance']);
101 | $this->command->storeBalance($destination['account_number'], $destination['balance']);
102 |
103 | $this->command->addTransaction([
104 | 'account_number' => $source['account_number'],
105 | 'transaction_type' => self::TRANSACTION_TYPE_WITHDRAW,
106 | 'transaction_time' => $now,
107 | 'amount' => $amount,
108 | 'comment' => 'transferred to ' . $destination['account_number'],
109 | ]);
110 | $this->command->addTransaction([
111 | 'account_number' => $destination['account_number'],
112 | 'transaction_type' => self::TRANSACTION_TYPE_DEPOSIT,
113 | 'transaction_time' => $now,
114 | 'amount' => $amount,
115 | 'comment' => 'transferred from ' . $source['account_number'],
116 | ]);
117 | }
118 | }
119 |
120 | interface ProcedureStyleTransferMoneyQueryPort
121 | {
122 | /**
123 | * @param string $accountNumber
124 | * @return array
125 | */
126 | public function findAndLockAccount(string $accountNumber): array;
127 |
128 | /**
129 | * @param string $accountNumber
130 | * @return array
131 | * @throws NotFoundException
132 | */
133 | public function findAccount(string $accountNumber): array;
134 | }
135 |
136 | interface ProcedureStyleTransferMoneyCommandPort
137 | {
138 | /**
139 | * @param string $accountNumber
140 | * @param int $balance
141 | */
142 | public function storeBalance(string $accountNumber, int $balance): void;
143 |
144 | /**
145 | * @param array $transaction
146 | */
147 | public function addTransaction(array $transaction): void;
148 |
149 | /**
150 | * @param array $account
151 | */
152 | public function notify(array $account): void;
153 | }
154 |
--------------------------------------------------------------------------------
/packages/Acme/Account/UseCase/TransportMoney/TransferMoney.php:
--------------------------------------------------------------------------------
1 | query = $query;
37 | $this->command = $command;
38 | $this->transaction = $transaction;
39 | }
40 |
41 | /**
42 | * @param AccountNumber $sourceNumber
43 | * @param AccountNumber $destinationNumber
44 | * @param Money $amount
45 | * @param TransactionTime $now
46 | * @return Balance
47 | */
48 | public function execute(
49 | AccountNumber $sourceNumber,
50 | AccountNumber $destinationNumber,
51 | Money $amount,
52 | TransactionTime $now
53 | ): Balance {
54 | return $this->transaction->transaction(function () use ($sourceNumber, $destinationNumber, $amount, $now) {
55 | /** @var Account $source */
56 | /** @var Account $destination */
57 | [$source, $destination] = $this->query($sourceNumber, $destinationNumber);
58 |
59 | if ($source->accountNumber()->equals($destination->accountNumber())) {
60 | throw new DomainRuleException('source can not transfer to same account');
61 | }
62 |
63 | if ($source->balance()->lessThan($amount)) {
64 | $message = sprintf('source account does not have enough balance for transfer %s', $amount->asInt());
65 | throw new DomainRuleException($message);
66 | }
67 |
68 | $source->withdraw($amount);
69 | $destination->deposit($amount);
70 |
71 | $this->store($source, $destination, $amount, $now);
72 |
73 | $this->command->notify($source);
74 |
75 | return $this->query->findAccount($sourceNumber)->balance();
76 | });
77 | }
78 |
79 | /**
80 | * @param AccountNumber $sourceNumber
81 | * @param AccountNumber $destinationNumber
82 | * @return array
83 | */
84 | private function query(AccountNumber $sourceNumber, AccountNumber $destinationNumber): array
85 | {
86 | if ($sourceNumber->lessThan($destinationNumber)) {
87 | $source = $this->query->findAndLockAccount($sourceNumber);
88 | $destination = $this->query->findAndLockAccount($destinationNumber);
89 | } else {
90 | $destination = $this->query->findAndLockAccount($destinationNumber);
91 | $source = $this->query->findAndLockAccount($sourceNumber);
92 | }
93 |
94 | return [$source, $destination];
95 | }
96 |
97 | /**
98 | * @param Account $source
99 | * @param Account $destination
100 | * @param Money $amount
101 | * @param TransactionTime $now
102 | */
103 | private function store(Account $source, Account $destination, Money $amount, TransactionTime $now): void
104 | {
105 | $this->command->storeBalance($source->accountNumber(), $source->balance());
106 | $this->command->storeBalance($destination->accountNumber(), $destination->balance());
107 |
108 | $this->command->addTransaction(new Transaction(
109 | $source->accountNumber(),
110 | TransactionType::WITHDRAW(),
111 | $now,
112 | $amount,
113 | 'transferred to ' . $destination->accountNumber()->asString()
114 | ));
115 | $this->command->addTransaction(new Transaction(
116 | $destination->accountNumber(),
117 | TransactionType::DEPOSIT(),
118 | $now,
119 | $amount,
120 | 'transferred from ' . $source->accountNumber()->asString()
121 | ));
122 | }
123 | }
124 |
125 | interface TransferMoneyQueryPort
126 | {
127 | /**
128 | * @param AccountNumber $accountNumber
129 | * @return Account
130 | */
131 | public function findAndLockAccount(AccountNumber $accountNumber): Account;
132 |
133 | /**
134 | * @param AccountNumber $accountNumber
135 | * @return Account
136 | * @throws NotFoundException
137 | */
138 | public function findAccount(AccountNumber $accountNumber): Account;
139 | }
140 |
141 | interface TransferMoneyCommandPort
142 | {
143 | /**
144 | * @param AccountNumber $accountNumber
145 | * @param Balance $balance
146 | */
147 | public function storeBalance(AccountNumber $accountNumber, Balance $balance): void;
148 |
149 | /**
150 | * @param Transaction $transaction
151 | */
152 | public function addTransaction(Transaction $transaction): void;
153 |
154 | /**
155 | * @param Account $account
156 | */
157 | public function notify(Account $account): void;
158 | }
159 |
--------------------------------------------------------------------------------
/packages/Acme/Test/Account/Domain/Models/BalanceTest.php:
--------------------------------------------------------------------------------
1 | assertSame(0, $sut->asInt());
18 | }
19 |
20 | /**
21 | * @test
22 | * @expectedException \Acme\Account\Domain\Exceptions\InvariantException
23 | */
24 | public function of_with_invalid_value()
25 | {
26 | Balance::of(-1);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/packages/Acme/Test/Account/UseCase/ArrayRepository.php:
--------------------------------------------------------------------------------
1 | items[$offset]);
12 | }
13 |
14 | public function offsetGet($offset)
15 | {
16 | return $this->items[$offset] ?: null;
17 | }
18 |
19 | public function offsetSet($offset, $value)
20 | {
21 | if (is_null($offset)) {
22 | $this->items[] = $value;
23 | } else {
24 | $this->items[$offset] = $value;
25 | }
26 | }
27 |
28 | public function offsetUnset($offset)
29 | {
30 | unset($this->items[$offset]);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/packages/Acme/Test/Account/UseCase/GetAccountTest.php:
--------------------------------------------------------------------------------
1 | $accountNumber,
28 | 'email' => 'a@example.com',
29 | 'balance' => 1000,
30 | ]);
31 | }
32 | }
33 | );
34 |
35 | $accountNumber = 'A0001';
36 | $actual = $sut->execute(AccountNumber::of($accountNumber));
37 |
38 | $this->assertSame($accountNumber, $actual->accountNumber()->asString());
39 | $this->assertSame(1000, $actual->balance()->asInt());
40 | }
41 |
42 | /**
43 | * @test
44 | * @expectedException \Acme\Account\Domain\Exceptions\NotFoundException
45 | */
46 | public function error_account_not_found()
47 | {
48 | $sut = new GetAccount(
49 | new class implements GetAccountQueryPort
50 | {
51 | public function findAccount(AccountNumber $accountNumber): Account
52 | {
53 | throw new NotFoundException();
54 | }
55 | }
56 | );
57 |
58 | $sut->execute(AccountNumber::of('Z9999'));
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/packages/Acme/Test/Account/UseCase/TransferMoneyTest.php:
--------------------------------------------------------------------------------
1 | storedBalance = new ArrayRepository();
36 | $this->storedTransaction = new ArrayRepository();
37 |
38 | $now = Chronos::now();
39 | Chronos::setTestNow($this->now);
40 |
41 | $this->now = TransactionTime::of($now);
42 | }
43 |
44 | /**
45 | * @test
46 | */
47 | public function execute()
48 | {
49 | $sut = new TransferMoney(
50 | $this->mockQuery(),
51 | $this->mockCommand(),
52 | $this->mockTransaction()
53 | );
54 |
55 | $actual = $sut->execute(
56 | AccountNumber::of('A0001'),
57 | AccountNumber::of('B0001'),
58 | Money::of(100),
59 | $this->now
60 | );
61 |
62 | $this->assertSame(900, $actual->asInt());
63 |
64 | $this->assertSame($actual->asInt(), $this->storedBalance['A0001']->asInt());
65 | $this->assertSame(2100, $this->storedBalance['B0001']->asInt());
66 |
67 | $this->assertEquals(Transaction::ofByArray([
68 | 'account_number' => 'A0001',
69 | 'transaction_type' => 'WITHDRAW',
70 | 'transaction_time' => $this->now,
71 | 'amount' => 100,
72 | 'comment' => 'transferred to B0001',
73 | ]), $this->storedTransaction[0]);
74 |
75 | $this->assertEquals(Transaction::ofByArray([
76 | 'account_number' => 'B0001',
77 | 'transaction_type' => 'DEPOSIT',
78 | 'transaction_time' => $this->now,
79 | 'amount' => 100,
80 | 'comment' => 'transferred from A0001',
81 | ]), $this->storedTransaction[1]);
82 |
83 | $this->assertEquals(AccountNumber::of('A0001'), $this->notifyAccount->accountNumber());
84 | }
85 |
86 | /**
87 | * @test
88 | * @expectedException \Acme\Account\Domain\Exceptions\NotFoundException
89 | */
90 | public function error_account_not_found()
91 | {
92 | $sut = new TransferMoney(
93 | new class implements TransferMoneyQueryPort
94 | {
95 | public function findAndLockAccount(AccountNumber $accountNumber): Account
96 | {
97 | throw new NotFoundException();
98 | }
99 |
100 | public function findAccount(AccountNumber $accountNumber): Account
101 | {
102 | return Account::ofByArray([
103 | 'account_number' => 'A0001',
104 | 'balance' => 1000,
105 | ]);
106 | }
107 | },
108 | $this->mockCommand(),
109 | $this->mockTransaction()
110 | );
111 |
112 | $sut->execute(
113 | AccountNumber::of('A9999'),
114 | AccountNumber::of('B0001'),
115 | Money::of(1001),
116 | $this->now
117 | );
118 | }
119 |
120 | /**
121 | * @test
122 | * @expectedException \Acme\Account\Domain\Exceptions\DomainRuleException
123 | */
124 | public function error_same_account_number()
125 | {
126 | $sut = new TransferMoney(
127 | $this->mockQuery(),
128 | $this->mockCommand(),
129 | $this->mockTransaction()
130 | );
131 |
132 | $sut->execute(
133 | AccountNumber::of('A0001'),
134 | AccountNumber::of('A0001'),
135 | Money::of(1001),
136 | $this->now
137 | );
138 | }
139 |
140 | /**
141 | * @test
142 | * @expectedException \Acme\Account\Domain\Exceptions\DomainRuleException
143 | */
144 | public function error_lack_balance()
145 | {
146 | $sut = new TransferMoney(
147 | $this->mockQuery(),
148 | $this->mockCommand(),
149 | $this->mockTransaction()
150 | );
151 |
152 | $sut->execute(
153 | AccountNumber::of('A0001'),
154 | AccountNumber::of('B0001'),
155 | Money::of(1001),
156 | $this->now
157 | );
158 | }
159 |
160 | private function mockQuery(): TransferMoneyQueryPort
161 | {
162 | $storedBalance = $this->storedBalance;
163 |
164 | return new class($storedBalance) implements TransferMoneyQueryPort
165 | {
166 | /** @var ArrayRepository */
167 | private $result;
168 |
169 | public function __construct(ArrayRepository $result)
170 | {
171 | $this->result = $result;
172 | }
173 |
174 | public function findAndLockAccount(AccountNumber $accountNumber): Account
175 | {
176 | if ($accountNumber->equals(AccountNumber::of('A0001'))) {
177 | return Account::ofByArray([
178 | 'account_number' => 'A0001',
179 | 'email' => 'a@example.com',
180 | 'balance' => 1000,
181 | ]);
182 | }
183 | if ($accountNumber->equals(AccountNumber::of('B0001'))) {
184 | return Account::ofByArray([
185 | 'account_number' => 'B0001',
186 | 'email' => 'b@example.com',
187 | 'balance' => 2000,
188 | ]);
189 | }
190 |
191 | throw new NotFoundException();
192 | }
193 |
194 | public function findAccount(AccountNumber $accountNumber): Account
195 | {
196 | return Account::ofByArray([
197 | 'account_number' => $accountNumber,
198 | 'email' => 'a@example.com',
199 | 'balance' => $this->result[$accountNumber->asString()],
200 | ]);
201 | }
202 | };
203 | }
204 |
205 | private function mockCommand(): TransferMoneyCommandPort
206 | {
207 | $self = $this;
208 |
209 | return new class($self) implements TransferMoneyCommandPort
210 | {
211 | /** @var TransferMoneyTest */
212 | private $test;
213 |
214 | public function __construct(TransferMoneyTest $test)
215 | {
216 | $this->test = $test;
217 | }
218 |
219 | public function storeBalance(AccountNumber $accountNumber, Balance $balance): void
220 | {
221 | $this->test->storedBalance[$accountNumber->asString()] = $balance;
222 | }
223 |
224 | public function addTransaction(Transaction $transaction): void
225 | {
226 | $this->test->storedTransaction[] = $transaction;
227 | }
228 |
229 | public function notify(Account $account): void
230 | {
231 | $this->test->notifyAccount = $account;
232 | }
233 | };
234 | }
235 |
236 | private function mockTransaction(): TransactionPort
237 | {
238 | return new class implements TransactionPort
239 | {
240 | public function transaction(callable $callee)
241 | {
242 | return call_user_func($callee);
243 | }
244 | };
245 | }
246 | }
247 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |