Last active
May 6, 2017 19:11
-
-
Save divinity76/b8041e073b74bdeab562a075fc94217f 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 | |
// modeled after SplObjectStorage | |
// license: WTFPL, The Unlicense, CC0, whatever | |
/* | |
example usage: | |
$r1=tmpfile(); | |
$r2=tmpfile(); | |
$rs=new ResourceStorage(); | |
$rs[$r1]='foo'; | |
$rs->attach($r2,'bar'); | |
foreach($rs as $foo){ | |
var_dump($foo); | |
} | |
var_dump($rs); | |
unset($rs[$r1]); | |
var_dump($rs,isset($rs[$r1]),isset($rs[$r2])); | |
$rs->detach($r2); | |
var_dump($rs); | |
*/ | |
class ResourceStorage implements ArrayAccess, Countable, IteratorAggregate { | |
protected $data = [ ]; | |
public function count() { | |
return count ( $this->data ); | |
} | |
public function getIterator() { | |
return new ArrayIterator ( $this->data ); | |
} | |
public function offsetSet($resource, $data) { | |
if (! is_resource ( $resource )) { | |
throw new \UnexpectedValueException ( 'expected resource, got ' . static::return_var_dump ( $resource ) ); | |
} else { | |
$this->data [( int ) $resource] = $data; | |
} | |
} | |
public function offsetExists($resource): bool { | |
return array_key_exists ( ( int ) $resource, $this->data ); | |
} | |
public function offsetUnset($resource) { | |
unset ( $this->data [$resource] ); | |
} | |
public function offsetGet($resource) { | |
return array_key_exists ( ( int ) $resource, $this->data ) ? $this->data [( int ) $resource] : null; | |
} | |
function attach($resource, $data) { | |
if (! is_resource ( $resource )) { | |
throw new \InvalidArgumentException (); | |
} | |
$this->offsetSet ( $resource, $data ); | |
return; | |
} | |
function detach($resource) { | |
if (! is_resource ( $resource )) { | |
throw new \InvalidArgumentException (); | |
} | |
$this->offsetUnset ( $resource ); | |
return; | |
} | |
protected static function return_var_dump(): string { | |
$args = func_get_args (); | |
ob_start (); | |
call_user_func_array ( 'var_dump', $args ); | |
return ob_get_clean (); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment