Skip to content

Instantly share code, notes, and snippets.

@damiankloip
Last active April 20, 2016 14:37
Show Gist options
  • Save damiankloip/12570145fb9f528da1b7bdb071f80a79 to your computer and use it in GitHub Desktop.
Save damiankloip/12570145fb9f528da1b7bdb071f80a79 to your computer and use it in GitHub Desktop.
<?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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment