Created
May 7, 2018 10:06
-
-
Save kapitanluffy/d4ba9a86581cb1e872707d950e232f5b to your computer and use it in GitHub Desktop.
StringList for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For type-hinting parameters that can either be string or array.
Instead of checking the parameter if iterable..
You can just type-hint the parameter with StringList
You can also create a StringList inside the method
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.