/**
  * Executes the given command and optionally returns a value
  *
  * @param object $command
  * @param callable $next
  * @return mixed
  * @throws \Error
  * @throws \Exception
  */
 public function execute($command, callable $next)
 {
     if ($this->transactionLevel > 0) {
         $this->storeMessages();
     }
     ++$this->transactionLevel;
     end($this->transactionMessages);
     $savepoint = key($this->transactionMessages);
     $savepoint = $savepoint === null ? 0 : ++$savepoint;
     try {
         $returnValue = $next($command);
         $this->storeMessages();
         --$this->transactionLevel;
     } catch (\Exception $e) {
         $this->capturer->clear();
         array_splice($this->transactionMessages, $savepoint);
         --$this->transactionLevel;
         throw $e;
     } catch (\Error $e) {
         $this->capturer->clear();
         array_splice($this->transactionMessages, $savepoint);
         --$this->transactionLevel;
         throw $e;
     }
     if ($this->transactionLevel === 0) {
         $this->publish();
     }
     return $returnValue;
 }
 /**
  * @test
  */
 public function it_should_clear_capture_messages()
 {
     $message1 = new MessageCommand('message', 'key');
     $message2 = new MessageCommand('message', 'key');
     $expectedMessage = [$message1, $message2];
     $this->publisher->publish($message1);
     $this->publisher->publish($message2);
     // Avoid fetch messages from clearing
     $this->assertSame($expectedMessage, $this->publisher->fetchMessages(false));
     $this->assertSame($expectedMessage, $this->publisher->fetchMessages(false));
     // Clear the messages
     $this->publisher->clear();
     $this->assertSame([], $this->publisher->fetchMessages());
 }