Created
July 9, 2018 19:53
-
-
Save gquemener/92aea50e32b8ce80e22931ab60b9a0a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__.'/vendor/autoload.php'; | |
use Rx\Observable; | |
use Rx\Observer\CallbackObserver; | |
$events = Observable::fromArray([ | |
['name' => 'account_was_created', 'payload' => ['id' => 1, 'owner' => 'Gildas Quéméner']], | |
['name' => 'deposit_was_performed', 'payload' => ['id' => 1, 'amount' => 100]], | |
['name' => 'withdrawal_was_performed', 'payload' => ['id' => 1, 'amount' => 100]], | |
['name' => 'deposit_was_performed', 'payload' => ['id' => 1, 'amount' => 40]], | |
]); | |
$events | |
->scan(function(array $state, array $event): array { | |
switch ($event['name']) { | |
case 'account_was_created': | |
return array_merge($state, $event['payload'], ['amount' => 0]); | |
case 'withdrawal_was_performed': | |
return array_merge($state, ['amount' => $state['amount'] - $event['payload']['amount']]); | |
case 'deposit_was_performed': | |
return array_merge($state, ['amount' => $state['amount'] + $event['payload']['amount']]); | |
} | |
return $state; | |
}, []) | |
->subscribe(new CallbackObserver( | |
function(array $state) { | |
echo json_encode($state) . PHP_EOL; | |
}, | |
function() { | |
printf('ERROR' . PHP_EOL); | |
}, | |
function() { | |
printf('COMPLETED' . PHP_EOL); | |
} | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment