Blame view

Hood/Dao/MongoDB/MongoObject.php 2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
<?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;
    }
}