Created
November 6, 2013 19:51
-
-
Save mcrumley/7342995 to your computer and use it in GitHub Desktop.
PHP Map object
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 | |
/* | |
EXAMPLES: | |
$map = new Map(array('foo' => 'bar', 'baz' => 'quux')); | |
$map = $map->withDefaultValue('default value'); | |
$map = $map->withDefault('strtoupper'); | |
var_dump($map->apply(array('foo', 'baz', 'quux'))); // bar, quux, QUUX | |
var_dump(array_map($map, array('foo', 'baz', 'quux'))); // bar, quux, QUUX | |
var_dump($map['foo']); // bar | |
var_dump($map('quux')); // QUUX | |
*/ | |
class Map implements ArrayAccess | |
{ | |
private $store = array(); | |
private $deftype = false; | |
private $def = null; | |
public function __construct(array $data = null) | |
{ | |
if ($data !== null) { | |
$this->store = $data; | |
} | |
} | |
public function __invoke($offset) | |
{ | |
return $this->offsetGet($offset); | |
} | |
public function offsetExists($offset) | |
{ | |
return array_key_exists($offset, $this->store); | |
} | |
public function offsetGet($offset) | |
{ | |
if (array_key_exists($offset, $this->store)) { | |
return $this->store[$offset]; | |
} | |
switch ($this->deftype) { | |
case 'val': return $this->def; | |
case 'fun': return call_user_func($this->def, $offset); | |
default: throw new Exception('Key does not exist: '.$offset); | |
} | |
} | |
public function offsetSet($offset, $value) | |
{ | |
$this->store[$offset] = $value; | |
} | |
public function offsetUnset($offset) | |
{ | |
unset($this->store[$offset]); | |
} | |
public function withDefaultValue($value) | |
{ | |
$new = clone $this; | |
$new->deftype = 'val'; | |
$new->def = $value; | |
return $new; | |
} | |
public function withDefault(callable $value) | |
{ | |
$new = clone $this; | |
$new->deftype = 'fun'; | |
$new->def = $value; | |
return $new; | |
} | |
public function apply(array $values) | |
{ | |
return array_map($this, $values); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment