Esempio n. 1
2
 /**
  * @inheritdoc
  */
 public function __construct(array $middleware)
 {
     $foundHandler = false;
     foreach ($middleware as $object) {
         if ($object instanceof MigrateHandler) {
             $foundHandler = true;
             break;
         }
     }
     if (!$foundHandler) {
         throw new MigrationBusException(sprintf('MigrationBus must have at least one instance of "%s"', MigrateHandler::class));
     }
     parent::__construct($middleware);
 }
Esempio n. 2
1
 private function middlewareHandler()
 {
     if (di()->has('middleware_aliases') === false) {
         return;
     }
     # get all the middlewares in the config/app.php
     $middleware = new Middleware(config()->app->middlewares);
     $instances = [];
     $aliases = di()->get('middleware_aliases')->toArray();
     foreach ($aliases as $alias) {
         $class = $middleware->get($alias);
         $instances[] = new $class();
     }
     # register all the middlewares
     $command_bus = new CommandBus($instances);
     $command_bus->handle($this->request);
 }
 /**
  * @test
  */
 public function should_update_read_model_using_projection()
 {
     $command = new IssueInvoiceCommand();
     $command->sellerName = 'Cocoders Sp. z o.o.';
     $command->sellerCity = 'Toruń';
     $command->sellerPostalCode = '87-100';
     $command->sellerCountry = 'Poland';
     $command->sellerTaxIdNumber = '9562307984';
     $command->sellerStreet = 'Królowej Jadwigi 1/3';
     $command->buyerName = 'Leszek Prabucki';
     $command->buyerCity = 'Gdańsk';
     $command->buyerPostalCode = '80-283';
     $command->buyerCountry = 'Poland';
     $command->buyerTaxIdNumber = '5932455641';
     $command->buyerStreet = 'Królewskie Wzgórze 21/9';
     $command->maxItemNumber = 3;
     $this->commandBus->handle($command);
     $command = new IssueInvoiceCommand();
     $command->sellerName = 'Cocoders Sp. z.o.o';
     $command->sellerCity = 'Toruń';
     $command->sellerPostalCode = '87-100';
     $command->sellerCountry = 'Poland';
     $command->sellerTaxIdNumber = '9562307984';
     $command->sellerStreet = 'Królowej Jadwigi 1/3';
     $command->buyerName = 'Leszek Prabucki';
     $command->buyerCity = 'Gdańsk';
     $command->buyerPostalCode = '80-283';
     $command->buyerCountry = 'Poland';
     $command->buyerTaxIdNumber = '5932455641';
     $command->buyerStreet = 'Królewskie Wzgórze 21/9';
     $command->maxItemNumber = 2;
     $this->commandBus->handle($command);
     $whoIssuedHowManyInvoicesReportArray = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'who-issued-how-many-invoices-report.json'), true);
     $this->assertEquals(2, $whoIssuedHowManyInvoicesReportArray['9562307984']['issuedInvoices']);
     $this->assertEquals('Cocoders Sp. z o.o.', $whoIssuedHowManyInvoicesReportArray['9562307984']['name']);
 }
Esempio n. 4
0
 /**
  * Handles fetching messages from the queue
  *
  * @param string $queue
  *
  * @return bool
  */
 protected function tick($queue)
 {
     if ($this->shutdown) {
         $this->event->shutdown();
         return false;
     }
     list($command, $job) = $this->driver->dequeue($queue);
     if (empty($command) && $this->drain) {
         $this->event->drained();
         return false;
     } elseif (empty($command)) {
         return true;
     }
     try {
         $this->event->acknowledge($command);
         $this->command_bus->handle($command);
         $this->event->finish($command);
     } catch (Exception $exception) {
         $this->queue->add(sprintf('%s-failed', $queue), $command);
         $this->event->reject($command, $exception);
     } finally {
         $this->driver->processed($job);
     }
     return true;
 }
 function it_should_throw_an_exception_if_sub_handle_fails(CommandBus $commandBus, \stdClass $command)
 {
     $this->beginTransaction();
     $this->handle($command);
     $commandBus->handle($command)->willThrow(new Exception());
     $this->shouldThrow(CommitException::class)->duringCommit();
 }
Esempio n. 6
0
 public function testSingleMiddlewareWorks()
 {
     $middleware = Mockery::mock(Middleware::class);
     $middleware->shouldReceive('execute')->once()->andReturn('foobar');
     $commandBus = new CommandBus([$middleware]);
     $this->assertEquals('foobar', $commandBus->handle(new AddTaskCommand()));
 }
Esempio n. 7
0
 /**
  * return mixed
  */
 public function loginAction()
 {
     $command = new LoginCommand();
     $command->setUsername("admin");
     $command->setPassword("singo");
     $token = $this->bus->handle($command);
     return new JsonResponse(["data" => ["token" => $token]]);
 }
Esempio n. 8
0
 function it_will_deposit_on_target_when_withdraw_completed(CommandBus $bus)
 {
     $this->onTransferRequested($this->create_money_transfer_requested_envelope());
     $this->onWithdrawnFromSource($this->create_money_transfer_withdrawn_envelope());
     $this->onDepositedOnTarget($this->create_money_transfer_deposit_envelope());
     $command = new TransferDepositCommand('456DEF', 100, '000');
     $bus->handle($command)->shouldHaveBeenCalled();
 }
Esempio n. 9
0
 public function handle($index, array $parameters = [])
 {
     $action = $this[$index];
     if ($action === null) {
         return;
     }
     $this->messageBus->handle(new InvokeAction($action, $parameters));
 }
Esempio n. 10
0
 public function testCanProperlyLocateHandler()
 {
     $handler = Mockery::mock();
     $handler->shouldReceive('handle')->once();
     $container = new Container();
     $container->add(DummyHandler::class, $handler);
     $bus = new CommandBus([new CommandHandlerMiddleware(new ClassNameExtractor(), new ContainerLocator($container), new HandleInflector())]);
     $bus->handle(new DummyCommand());
 }
 /**
  * Publish a command to a exchange.
  *
  * @param object $command
  * @param CommandConfiguration $commandConfiguration
  */
 public function publish($command, CommandConfiguration $commandConfiguration)
 {
     $exchange = $this->getExchangeByName($commandConfiguration->getVhost(), $commandConfiguration->getExchange());
     $commandTransformer = $this->getCommandTransformer();
     $commandTransformer->registerCommand($commandConfiguration);
     $commandTransformerMiddleware = new CommandTransformerMiddleware($commandTransformer, [get_class($command)]);
     $publishMiddleware = new PublishMiddleware(new DirectPublisherLocator(new ExchangeDirectPublisher($exchange)));
     $bus = new CommandBus([$commandTransformerMiddleware, $publishMiddleware]);
     $bus->handle($command);
 }
Esempio n. 12
0
 public function onWithdrawnFromSource(MoneyWereWithdrawnEnvelope $event)
 {
     if (!($process = $this->getProcessForTransaction($event->getTransaction()))) {
         return;
     }
     $this->assertFinalized($process);
     $process->withdrawnFromSource();
     $process->depositOnTarget();
     $this->bus->handle(new TransferDepositCommand((string) $process->getTargetAccountNumber(), (int) $process->getAmount(), (string) $process->getTransaction()));
 }
Esempio n. 13
0
 /**
  * {@inheritDoc}
  */
 public function execute($command)
 {
     try {
         $this->commandBus->handle($command);
     } catch (TacticianException\MissingHandlerException $e) {
         throw new MissingHandlerException($e->getMessage(), $e->getCode(), $e);
     } catch (TacticianException\CanNotInvokeHandlerException $e) {
         throw new CanNotInvokeHandlerException($e->getMessage(), $e->getCode(), $e);
     }
 }
Esempio n. 14
0
 /**
  * @SWG\Api(
  *      path="/user/login",
  *      description="User login API",
  *      @SWG\Operation(
  *          method="POST",
  *          summary="User login API",
  *          notes="Return JSON",
  *          type="User",
  *          nickname="login",
  *          @SWG\Parameter(
  *              name="username",
  *              description="Username",
  *              paramType="query",
  *              required=true,
  *              allowMultiple=false,
  *              type="string"
  *          ),
  *          @SWG\Parameter(
  *              name="password",
  *              description="Password",
  *              paramType="query",
  *              required=true,
  *              allowMultiple=false,
  *              type="string"
  *          ),
  *          @SWG\ResponseMessage(
  *              code=200,
  *              message="Succes"
  *          ),
  *          @SWG\ResponseMessage(
  *              code=400,
  *              message="Invalid username or password"
  *          )
  *      )
  * )
  * @SLX\Route(
  *      @SLX\Request(method="POST", uri="login")
  * )
  * @param Request $request
  * @return JsonResponse
  */
 public function loginAction(Request $request)
 {
     $command = new LoginCommand();
     $command->setUsername($request->get("username"));
     $command->setPassword($request->get("password"));
     $token = $this->bus->handle($command);
     $object = new \ArrayObject();
     $object->offsetSet("data", ["token" => $token]);
     $response = new JsonResponse($object);
     return $response;
 }
 /**
  * @param AMQPMessage $message The message
  * @return mixed false to reject and requeue, any other value to aknowledge
  */
 public function execute(AMQPMessage $message)
 {
     $type = $message->get('type');
     if ('Lw\\Domain\\Model\\User\\UserRegistered' === $type) {
         $event = json_decode($message->body);
         $eventBody = json_decode($event->event_body);
         $this->commandBus->handle(new SignupCommand($eventBody->user_id->id));
         return true;
     }
     return false;
 }
Esempio n. 16
0
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Check that user is authorized to edit this resource
     $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity'), 'edit', 'shifts');
     //Validate input
     $inputValidator = v::key('break', v::floatVal())->key('start_time', v::stringType())->key('end_time', v::stringType())->key('id', v::intVal());
     $inputValidator->assert($input);
     //Update shift data
     $shift = $this->commandBus->handle(new UpdateShiftCommand($input['id'], $input['break'], $input['start_time'], $input['end_time']));
     $shiftItem = new Item($shift, new ShiftTransformer());
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->createData($shiftItem)->toArray());
 }
 /**
  * @inheritDoc
  */
 public function commit()
 {
     $this->checkTransactionIsRunning();
     foreach ($this->commandsToCommit as $command) {
         try {
             $this->commandBus->handle($command);
         } catch (\Exception $e) {
             throw new CommitException($e->getMessage(), $e->getCode(), $e);
         }
     }
     $this->reset();
 }
Esempio n. 18
0
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Check that user has permission to edit this resource
     $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('entity'), 'edit', 'shifts');
     //Validate input
     $inputValidator = v::key('id', v::intVal())->key('employee_id', v::intVal());
     $inputValidator->assert($input);
     //Execute command to update employee on shift
     $shift = $this->commandBus->handle(new AssignShiftCommand($input['id'], $input['employee_id']));
     $shiftItem = new Item($shift, new ShiftTransformer());
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($shiftItem)->toArray());
 }
Esempio n. 19
0
 /**
  * Handle domain logic for an action.
  *
  * @param array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Ensure that the use has permission to create shifts
     $user = $input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity');
     $this->authorizeUser($user, 'create', 'shifts');
     //If no manager_id is specified in request, default to user creating shift
     if (!array_key_exists('manager_id', $input)) {
         $input['manager_id'] = $user->getId();
     }
     //Validate input
     $inputValidator = v::key('break', v::floatVal())->key('start_time', v::date())->key('end_time', v::date()->min($input['start_time']))->key('manager_id', v::intVal());
     $inputValidator->assert($input);
     //Execute command to create shift
     $shift = $this->commandBus->handle(new CreateShift($input['manager_id'], $input['employee_id'], $input['break'], $input['start_time'], $input['end_time']));
     $this->item->setData($shift)->setTransformer($this->shiftTransformer);
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($this->item)->toArray());
 }
Esempio n. 20
0
 /**
  * Executes a command in the command bus.
  *
  * @param  object  $command
  * @return mixed
  */
 public function execute($command)
 {
     return $this->bus->handle($command);
 }
Esempio n. 21
0
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\Locator\InMemoryLocator;
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
use League\Tactician\Plugins\LockingMiddleware;
use Symfony\Component\EventDispatcher\EventDispatcher;
error_reporting(E_ALL);
require __DIR__ . '/../vendor/autoload.php';
$persistence = new InMemory();
$eventStore = new EventStore($persistence);
$dispatcher = new EventDispatcher();
$eventEmitter = new DispatcherEmitter($dispatcher);
$unitOfWork = new UnitOfWork($eventStore, $eventEmitter);
$accounting = new Accounting($unitOfWork);
$locator = new InMemoryLocator();
$bus = new CommandBus([new LockingMiddleware(), new CommandHandlerMiddleware(new ClassNameExtractor(), $locator, new HandleInflector())]);
$locator->addHandler(new OpenAccountHandler($accounting), OpenAccountCommand::class);
$locator->addHandler(new DepositHandler($accounting), DepositCommand::class);
$locator->addHandler(new WithdrawHandler($accounting), WithdrawCommand::class);
$locator->addHandler(new TransferHandler($accounting), TransferCommand::class);
$locator->addHandler(new TransferDepositHandler($accounting), TransferDepositCommand::class);
$locator->addHandler(new TransferWithdrawHandler($accounting), TransferWithdrawCommand::class);
$accountHistory = new AccountHistoryProjector();
$accountBalance = new AccountBalanceProjector();
$transferManager = new TransferManager($bus);
$dispatcher->addSubscriber($accountHistory);
$dispatcher->addSubscriber($accountBalance);
$dispatcher->addSubscriber($transferManager);
/*
 * Normal event propagation
 *
Esempio n. 22
0
 /**
  * Consumes a message
  *
  * @param  string $message
  * @return string|null|void
  */
 public function consume($message)
 {
     return $this->commandBus->handle($this->deserializer->deserialize($message));
 }
Esempio n. 23
0
 /**
  * Handle the command
  *
  * @param  $command
  * @param  $input
  * @param  $middleware
  * @return mixed
  */
 protected function handleTheCommand($command, $input, array $middleware)
 {
     $this->bus = new CommandBus(array_merge([new LockingMiddleware()], $this->resolveMiddleware($middleware), [new CommandHandlerMiddleware($this->CommandNameExtractor, $this->HandlerLocator, $this->MethodNameInflector)]));
     return $this->bus->handle($this->mapInputToCommand($command, $input));
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function helloWorld(Request $request)
 {
     $message = $this->commandBus->handle(new SayHello($request->query->get('name')));
     return new Response($message);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $message = $this->commandBus->handle(new SayHello($input->getArgument('name')));
     $output->writeln($message);
 }
Esempio n. 26
0
    private $mailer;
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }
    public function handleMyCommand($command)
    {
        $format = <<<MSG
Hi %s,

Your email address is %s.

--
Cheers
MSG;
        echo sprintf($format, $command->name, $command->emailAddress);
    }
}
$containerLocator = new ContainerLocator((new Container())->delegate(new ReflectionContainer()), $mapping);
$handlerMiddleware = new CommandHandlerMiddleware(new ClassNameExtractor(), $containerLocator, new HandleClassNameInflector());
$commandBus = new CommandBus([$handlerMiddleware]);
$command = new MyCommand('Joe Bloggs', '*****@*****.**');
echo '<pre>';
try {
    $commandBus->handle($command);
} catch (\Exception $e) {
    echo $e->getMessage();
    echo '<pre>';
    print_r($e->getTraceAsString());
    echo '</pre>';
}
        if ($command instanceof ExternalCommand) {
            return $this->commandBus->handle($command);
        }
        return $next($command);
    }
}
// and we'll create a custom command handler/middleware
final class ExternalCommandHandler implements Middleware
{
    public function execute($command, callable $next)
    {
        echo sprintf("Dispatched %s!\n", get_class($command));
    }
}
// and we'll create our example command
class MyExternalCommand implements ExternalCommand
{
}
// Now  let's instantiate our ExternalCommandHandler, CommandBus and ExternalCommandMiddleware
$externalCommandHandler = new ExternalCommandHandler();
$externalCommandBus = new CommandBus([$externalCommandHandler]);
$externalMiddleware = new ExternalCommandMiddleware($externalCommandBus);
// Time to create our main CommandBus
$commandBus = new CommandBus([$externalMiddleware, $handlerMiddleware]);
// Controller Code time!
$externalCommand = new MyExternalCommand();
$commandBus->handle($externalCommand);
$command = new RegisterUserCommand();
$command->emailAddress = '*****@*****.**';
$command->password = '******';
$commandBus->handle($command);
 /**
  * @param AMQPMessage $message The message
  * @return mixed false to reject and requeue, any other value to aknowledge
  */
 public function execute(AMQPMessage $message)
 {
     $type = $message->get('type');
     if ('Lw\\Domain\\Model\\Wish\\WishWasMade' === $type) {
         $event = json_decode($message->body);
         $eventBody = json_decode($event->event_body);
         try {
             $this->commandBus->handle(new RewardUserCommand($eventBody->user_id->id, 5));
         } catch (AggregateDoesNotExist $e) {
             // Noop
         }
         return true;
     }
     return false;
 }
Esempio n. 29
-1
 /**
  * Handles a Command that is passed to the Kernel.
  *
  * A Command is an indication to the command bus that a specific command needs to be executed. An example of this
  * is that via a command we can indicate that a HTTP request needs to be dealt with, or that authentication needs
  * to be applied.
  *
  * @param object $command
  * @param string $scope   A scope to which this handler belongs; may have multiple scopes separated by a comma. In
  *     case of multiple scopes all scopes must match for the handler to trigger.
  *
  * @return $this
  */
 public function handle($command, $scope = null)
 {
     if ($this->isInScope($scope)) {
         $this->messagebus->handle($command);
     }
     return $this;
 }
Esempio n. 30
-2
 /**
  * Handles the command
  *
  * @param NamedCommand $command
  */
 private function handleCommand(NamedCommand $command = null)
 {
     if ($command === null) {
         $this->logger->info('Message ignored');
         return;
     }
     $this->commandBus->handle($command);
 }