Skip to content

Instantly share code, notes, and snippets.

@dawehner
Forked from damiankloip/StringBuilder.php
Last active April 20, 2016 14:31
Show Gist options
  • Save dawehner/a338c5f29ecd75522c6c6898edbe7c9f to your computer and use it in GitHub Desktop.
Save dawehner/a338c5f29ecd75522c6c6898edbe7c9f to your computer and use it in GitHub Desktop.
<?php
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
* The separator to use when casting the parts to a string.
*/
public function __construct($separator = '', array $parts = []) {
if (!is_string($separator)) {
throw new \InvalidArgumentException('Separator must be a string');
}
array_walk($parts, [$this, 'addPart']);
$this->separator = $separator;
}
/**
* {@inheritdoc}
*/
public function render() {
return implode($this->separator, $this->parts);
}
/**
* @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