Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.