<?php
/**
 * Created by PhpStorm.
 * User: Zip
 * Date: 15/6/14
 * Time: 上午12:07
 */

namespace Hood\Dao\MongoDB;


class MongoObject implements \ArrayAccess
{
    private $_attrs = array();

    private $_id;

    public function setID($id)
    {
        $this->_id = new \MongoId($id);
        return $this;
    }

    public function offsetExists($index)
    {
        return !is_null($this->attr($index));
    }

    public function offsetGet($index)
    {
        return $this->attr($index);
    }

    public function offsetSet($index, $item)
    {
        $this->setAttr($index, $item);
    }

    public function offsetUnset($index)
    {
        $this->setAttr($index, null);
    }

    public function __get($name)
    {
        return $this->attr($name);
    }

    public function attr($name)
    {
        return $this->arrayGet($this->_attrs, $name);
    }

    function arrayGet(array $array, $keys)
    {
        if (is_array($keys) && empty($keys)) {
            return $array;
        }
        if (!is_array($keys)) {
            if (strstr($keys, "`")) {
                $keys = preg_replace_callback("/`(.+)`/U", create_function('$match', 'return str_replace(".", "\.", $match[1]);'), $keys);
            }
            $keys = preg_split("/(?<!\\\\)\\./", $keys);
        }
        if (count($keys) == 1) {
            $firstKey = array_pop($keys);
            $firstKey = str_replace("\\.", ".", $firstKey);
            return array_key_exists($firstKey, $array) ? $array[$firstKey] : null;
        }
        $lastKey = array_pop($keys);
        $lastKey = str_replace("\\.", ".", $lastKey);
        $lastArray = $array;
        foreach ($keys as $key) {
            $key = str_replace("\\.", ".", $key);
            if (is_array($lastArray) && array_key_exists($key, $lastArray)) {
                $lastArray = $lastArray[$key];
            } else {
                return null;
            }
        }

        return (is_array($lastArray) && array_key_exists($lastKey, $lastArray)) ? $lastArray[$lastKey] : null;
    }
}