<?php
/**
 * ORM (Data Access Layer) Array of Base ORM objects (Data Acceess Object)
 *
 * @author Alexey Belyaev <abelyaev@swsoft.com>
 * @author Kirill Kudriavtsev <kkudriavtsev@swsoft.com>
 * @version $Id: ArrayObject.php 23394 2007-06-19 06:14:08Z abelyaev $
 * @since 2006/03/23
 * @package Base
 * @subpackage ORM
 * @copyright (c) 2004-2006, SWsoft
 */
class Base_ORM_ArrayObject extends ArrayObject {

	/**
	 * List of removed objects
	 *
	 * @var array
	 */
	private $_removedList;

	/**
	 * Constructor
	 *
	 * @param array $array  the array to use.
	 * @param int $flags  see setFlags().
	 * @param string $iterator_class  class used in getIterator()
	 */
	public function __construct($array = array(), $flags = 0, $iteratorClass = 'ArrayIterator') {
		parent::__construct($array, $flags, $iteratorClass);

		$this->_removedList = new ArrayObject();
	}

	/**
	 * Returns array of removed objects list
	 *
	 * @throws Base_ORM_Object_Exception
	 * @return array of removed objects list
	 */
	public function getRemovedObjectsList() {
		//:INFO: abelyaev 20070329: it is a hack for new objects (see serialize and unserialize) see bug #115244
		if (!isset($this->_removedList)) {
			$this->_removedList = new ArrayObject();
		}
		return $this->_removedList;
	}

	/**
	 * Removes object from the list
	 *
	 * @param Base_ORM_Object $object
	 * @throws Base_ORM_Object_Exception
	 */
	public function remove(Base_ORM_Object $object) {
		foreach ($this as $key => $item) {
			if ($object->equals($item)) {
				unset($this[$key]);
				$object->delete();
				break;
			}
		}
	}

	/**
	 * Removes object from the list
	 *
	 * @param int $index
	 * @throws Base_ORM_Object_Exception
	 */
	public function offsetUnset($index) {
		if($this->offsetExists($index)) {
			$this->_removedList[] = $this[$index];
			parent::offsetUnset($index);
		}
	}

	/**
	 *
	 * @param int $id
	 * @return object|null
	 */
	public function getByProperty($property, $value) {
		foreach ($this as $key => $item) {
			if ($item->$property == $value) {
				return $item;
			}
		}

		return null;
	}

	/**
	 *
	 */
	function delete() {
		foreach($this as $item) {
			if ($item instanceof Base_ORM_Object) {
				$item->delete();
			}
		}
		$this->clean();
	}

	function clean() {
		$iterator = $this->getIterator();
		$iterator->rewind();
		while($iterator->valid()) {
			$this->offsetUnset($iterator->key());
			$iterator = $this->getIterator();
			$iterator->rewind();
		}
		$this->_removedList = new ArrayObject();
	}
}