Skip to content

Instantly share code, notes, and snippets.

@bbrothers
Created August 19, 2015 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbrothers/c7c45291a8711d375f02 to your computer and use it in GitHub Desktop.
Save bbrothers/c7c45291a8711d375f02 to your computer and use it in GitHub Desktop.
<?php
use ArrayObject;
use OutOfBoundsException;
use SplObjectStorage;
class IdentityMap
{
/**
* @var ArrayObject
*/
protected $idToObject;
/**
* @var SplObjectStorage
*/
protected $objectToId;
/**
* Create an identity map to avoid race conditions
*/
public function __construct()
{
$this->objectToId = new SplObjectStorage();
$this->idToObject = new ArrayObject();
}
/**
* @param integer $id
* @param mixed $object
*/
public function set($id, $object)
{
$this->idToObject[$id] = $object;
$this->objectToId[$object] = $id;
}
/**
* @param mixed $object
*
* @throws OutOfBoundsException
* @return integer
*/
public function getId($object)
{
if (false === $this->hasObject($object)) {
throw new OutOfBoundsException();
}
return $this->objectToId[$object];
}
/**
* @param integer $id
*
* @return boolean
*/
public function hasId($id)
{
return isset($this->idToObject[$id]);
}
/**
* @param mixed $object
*
* @return boolean
*/
public function hasObject($object)
{
return isset($this->objectToId[$object]);
}
/**
* @param integer $id
*
* @throws OutOfBoundsException
* @return object
*/
public function getObject($id)
{
if (false === $this->hasId($id)) {
throw new OutOfBoundsException();
}
return $this->idToObject[$id];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment