Last active
September 19, 2016 23:21
-
-
Save michaelachrisco/5c44f628e118ddf4744267bdda36e94b to your computer and use it in GitHub Desktop.
Segments for String Mapping
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 | |
namespace App\Models; | |
/* SegmentString: Interface between collection of strings with delimiters and the collections | |
* Used within eligibility files. | |
* Use: | |
* $seg = new SegmentString('|', '~', ['a', 'b']) | |
* 'a|b~' == (string)$seg | |
* ['a', 'b'] == (array)$seg | |
*/ | |
class SegmentString{ | |
private $delimiter; | |
private $terminator; | |
private $collection; | |
private $result; | |
public function __construct($delimiter, $terminator, $collection = []){ | |
$this->delimiter = $delimiter; | |
$this->terminator = $terminator; | |
$this->collection = $collection; | |
if($collection == []){ | |
$this->result = ''; | |
} | |
else{ | |
$this->delimit()->terminate(); | |
} | |
} | |
public function __toString(){ | |
return $this->result; | |
} | |
public function __toArray(){ | |
return $this->collection; | |
} | |
private function delimit(){ | |
$this->result = array_reduce($this->collection, function($carry, $subline){ | |
return $carry.$subline.$this->delimiter; | |
}); | |
return $this; | |
} | |
private function terminate(){ | |
$this->result = $this->removeTrailing($this->result).$this->terminator; | |
return $this; | |
} | |
//TODO: Revisit | |
//Removes any occurances of trailing delimiters such as: | |
//a**~ turns into a~ | |
private function removeTrailing($str){ | |
if(substr($str, -1) == $this->delimiter) { | |
return $this->removeTrailing(substr($str, 0, -1)); | |
} | |
return $str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment