* @package taoQTI * @see http://www.imsglobal.org/question/qti_v2p0/imsqti_infov2p0.html#section10042 */ class IdentifierCollection { /** * The multi dimension array containing identified elements * array(identifier => serial => oat\taoQtiItem\model\qti\IdentifiedElement) * * */ protected $elements = []; /** * Short description of method __construct * * @access public * @author Sam, * @param string identifier * @param array options * @return mixed */ public function __construct($identifiedElements = []) { $this->elements = []; if (is_array($identifiedElements)) { $this->addMultiple($identifiedElements); } } public function add(IdentifiedElement $element) { $identifier = $element->getIdentifier(false); if (!empty($identifier)) { if (!isset($this->elements[$identifier])) { $this->elements[$identifier] = []; } $this->elements[$identifier][$element->getSerial()] = $element; } } public function exists($identifier) { $returnValue = false; if (is_string($identifier)) { $returnValue = isset($this->elements[$identifier]); } else { throw new InvalidArgumentException('the identifier must be a string'); } return $returnValue; } public function get($identifier = '') { $returnValue = []; if (empty($identifier)) { $returnValue = $this->elements; } elseif ($this->exists($identifier)) { $returnValue = $this->elements[$identifier]; } return $returnValue; } public function getUnique($identifier, $elementClass = '') { $returnValue = null; if ($this->exists($identifier)) { if (empty($elementClass)) { if (count($this->elements[$identifier]) > 1) { throw new QtiModelException('More than one identifier found, please try specifying the class of the element'); } elseif (!empty($this->elements[$identifier])) { $returnValue = reset($this->elements[$identifier]); } } else { $found = []; foreach ($this->elements[$identifier] as $elt) { if ($elt instanceof $elementClass) { $found[] = $elt; } } if (count($found) > 1) { throw new QtiModelException('More than one identifier found with the class: ' . $elementClass); } elseif (count($found) == 1) { $returnValue = reset($found); } } } return $returnValue; } public function addMultiple($identifiedElements) { if (!is_array($identifiedElements)) { throw new InvalidArgumentException('the argument "identifiedElements" must be an array'); } foreach ($identifiedElements as $identifiedElement) { if ($identifiedElement instanceof IdentifiedElement) { $this->add($identifiedElement); } elseif (is_array($identifiedElement)) { $this->addMultiple($identifiedElement); } else { throw new InvalidArgumentException('must be either an identifier or an array'); } } } public function merge(IdentifierCollection $identifierCollection) { foreach ($identifierCollection->get() as $elements) { $this->addMultiple($elements); } } }