<?php

/**
 * @file
 * Contains \Drupal\Component\Utility\StringBuilder.
 */

namespace Drupal\Component\Utility;

/**
 * Builds an array of strings for printing.
 */
class StringBuilder {

  use ToStringTrait;

  /**
   * The separator to use when casting the parts to a string.
   *
   * @var string
   */
  protected $separator;

  /**
   * The content parts.
   *
   * @var string[]
   */
  protected $parts = [];

  /**
   * StringBuilder constructor.
   *
   * @param string $separator
   *   (optional) The separator to use when casting the parts to a string.
   *   Defaults to ''.
   * @param string[] $parts
   *   (optional) Add array of parts to add on creation. Defaults to none.
   */
  public function __construct($separator = '', array $parts = []) {
    if (!is_string($separator)) {
      throw new \InvalidArgumentException('Separator must be a string');
    }

    $this->separator = $separator;
    $this->addParts($parts);
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    return implode($this->separator, $this->parts);
  }

  /**
   * Adds a single content part.
   *
   * @param string $part
   *   The content part to add.
   *
   * @return self
   */
  public function addPart($part) {
    return $this->addParts([$part]);
  }

  /**
   * Adds an array of content parts
   *
   * @param string[] $parts
   *
   * @return self
   */
  public function addParts(array $parts) {
    array_walk($parts, function($part) {
      if (!is_string($part)) {
        throw new \InvalidArgumentException('All parts must be strings');
      }
    });

    $this->parts = array_merge($this->parts, $parts);
    return $this;
  }

}