Skip to content

Instantly share code, notes, and snippets.

@kapitanluffy
Created May 7, 2018 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kapitanluffy/d4ba9a86581cb1e872707d950e232f5b to your computer and use it in GitHub Desktop.
Save kapitanluffy/d4ba9a86581cb1e872707d950e232f5b to your computer and use it in GitHub Desktop.
StringList for PHP
<?php
class StringList extends \ArrayObject
{
protected $data = [];
public function __construct($data, $delimiter = " ")
{
self::checkNonScalarValues($data);
if (self::isIterable($data)) {
$this->data = $data;
} else {
$this->data = explode($delimiter, $data);
}
$this->delimiter = $delimiter;
parent::__construct($this->data);
}
protected static function checkNonScalarValues($data)
{
if (self::isIterable($data) == true) {
foreach ($data as $value) {
self::checkNonScalarValues($value);
}
} elseif (is_scalar($data) == false) {
throw new \InvalidArgumentException("Cannot convert first parameter to string");
}
}
protected static function isIterable($data)
{
return is_array($data) || ($data instanceof \Traversable);
}
public function __toString()
{
return implode($this->delimiter, $this->data);
}
}
@kapitanluffy
Copy link
Author

For type-hinting parameters that can either be string or array.

Instead of checking the parameter if iterable..

function setTags($tags)
{
    if (is_array($tags) == false) {
        $tags = explode(',', $tags);
    }

    foreach ($tags as $tag) {
        // do stuff here
    }
}

setTags("foo,bar,baz");
// or
setTags(["foo","bar","baz"]);

You can just type-hint the parameter with StringList

function setTags(StringList $tags)
{
    foreach ($tags as $tag) {
        // do stuff here
    }
}

$tags = new StringList("foo,bar,baz", ",");
// or
$tags = new StringList(["foo","bar","baz"], ",");

setTags($tags);

You can also create a StringList inside the method

function setTags($tags)
{
    $tags = new StringList($tags, ",");

    foreach ($tags as $tag) {
        // do stuff here
    }
}

setTags("foo,bar,baz");
// or
setTags(["foo","bar","baz"]);

The advantage of this is you can type-hint StringList on your methods.
Making sure of what parameter is passed instead of validating it manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment