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: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 
<?php

namespace SAREhub\Client\Amqp;


/**
 * Routing key is string in format: part1[.partN]
 */
class RoutingKey implements \IteratorAggregate
{

    /** @var array */
    protected $parts;

    /**
     * Defaults create empty routing key.
     * String will be converted to array(explode by dot).
     * Array of routing key parts.
     * @param string|array|null $routingKey
     */
    public function __construct($routingKey = null)
    {
        $routingKey = ($routingKey === null) ? [] : $routingKey;
        $this->parts = is_array($routingKey) ? $routingKey : explode('.', $routingKey);
    }

    /**
     * @param string $routingKey
     * @return RoutingKey
     */
    public static function createFromString($routingKey)
    {
        return new self($routingKey);
    }

    /**
     * @param string part
     * @return $this
     */
    public function addPart($part)
    {
        $this->parts[] = $part;
        return $this;
    }

    /**
     * @param int index
     * @return string
     */
    public function getPart($index)
    {
        return isset($this->parts[$index]) ? $this->parts[$index] : '';
    }

    /**
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->parts);
    }

    /**
     * @return array
     */
    public function getParts()
    {
        return $this->parts;
    }

    public function getIterator()
    {
        return $this->parts;
    }

    public function __toString()
    {
        return implode('.', $this->parts);
    }

}