Created
May 31, 2010 10:34
-
-
Save dhotson/419722 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
$english = arr( | |
strr('Hello X'), | |
strr('Goodbye X') | |
); | |
$pirate = $english | |
->replace('/Hello/', 'Avast') | |
->replace('/Goodbye/', 'Was good te see ye') | |
->replace('/X/', 'matey!') | |
->split('/\s+/') | |
; | |
foreach($pirate as $saying) | |
echo $saying."\n"; | |
// --- | |
function arr() | |
{ | |
return new PirateArray(func_get_args()); | |
} | |
function strr($str) | |
{ | |
return new PirateString($str); | |
} | |
class PirateArray extends ArrayObject | |
{ | |
public function __invoke($callback) | |
{ | |
return new self(array_map($callback, $this->getArrayCopy())); | |
} | |
public function __call($name, $args) | |
{ | |
return new self(array_map( | |
function ($e) use ($name, $args) { | |
return call_user_func_array(array($e, $name), $args); | |
}, | |
$this->getArrayCopy())); | |
} | |
public function __get($name) | |
{ | |
return new self(array_map(function($e) use ($name) { return $e->$name; }, $this->getArrayCopy())); | |
} | |
public function __toString() | |
{ | |
return '['.implode(', ', $this->getArrayCopy()).']'; | |
} | |
} | |
class PirateString | |
{ | |
private $_string; | |
public function __construct($str = '') | |
{ | |
$this->_string = $str; | |
} | |
public function match($regex) | |
{ | |
if (preg_match($regex, $this->_string, $matches)) | |
return new PirateArray($matches); | |
return null; | |
} | |
public function replace($regex, $replacement) | |
{ | |
return new self(preg_replace($regex, $replacement, $this->_string)); | |
} | |
public function split($regex) | |
{ | |
return new PirateArray(preg_split($regex, $this->_string)); | |
} | |
public function __call($name, $args) | |
{ | |
return new self(call_user_func($name, $this->_string)); | |
} | |
public function __toString() | |
{ | |
return (string)$this->_string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment