1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 
<?php


namespace SAREhub\Client\Processor;

use SAREhub\Client\Message\BasicExchange;
use SAREhub\Client\Message\Exchange;

/**
 * Implements the Multicast pattern to send a message exchange to a number of processors,
 * each processor receiving a copy of the message exchange.
 */
class MulticastProcessor implements Processor
{
    /**
     * @var Processor[]
     */
    private $processors = [];

    public function process(Exchange $exchange)
    {
        foreach ($this->getProcessors() as $p) {
            $p->process($this->copyExchange($exchange));
        }
    }

    public function copyExchange(Exchange $exchange): Exchange
    {
        return BasicExchange::withIn($exchange->getIn()->copy())->setException($exchange->getException());
    }

    public function add(Processor $processor)
    {
        $this->processors[] = $processor;
    }

    public function set(string $id, Processor $processor)
    {
        $this->processors[$id] = $processor;
    }

    public function remove(string $id)
    {
        unset($this->processors[$id]);
    }

    /**
     * @return Processor[]
     */
    public function getProcessors(): array
    {
        return $this->processors;
    }

    public function __toString()
    {
        $processors = [];
        foreach ($this->getProcessors() as $id => $p) {
            $processors[] = $id . ' => ' . $p;
        }

        return 'Multicast[ {' . implode('}, {', $processors) . '} ]';
    }
}