Created
August 19, 2015 14:36
-
-
Save bbrothers/c7c45291a8711d375f02 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 | |
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