Cursor.php 2.69 KB
<?php
/**
 * Created by PhpStorm.
 * User: Zip
 * Date: 15/6/13
 * Time: 下午4:51
 */

namespace Hood\Dao\MongoDB;


class Cursor
{

    /**
     * @var \MongoCursor
     */
    protected $_cursor;

    /**
     * @var \MongoCollection
     */
    protected $_collection;

    /**
     * 条件
     * @var array
     */
    protected $_attrs = array();

    protected $_conds = array();

    protected $_offset = -1;

    protected $_limit = 0;

    protected $_sort = array();

    protected $_hints = array();

    protected $_results = array();

    protected function _cursor()
    {
        $cursor = $this->_collection->find($this->criteria(), $this->_results);
        if ($this->_offset >= 0) {
            $cursor->skip($this->_offset);
        }
        if ($this->_limit > 0) {
            $cursor->limit($this->_limit);
        }
        if ($this->_sort) {
            $cursor->sort($this->_sort);
        }
        if (!empty($this->_hints)) {
            foreach ($this->_hints as $hint) {
                $cursor->hint($hint);
            }
        }
        return $cursor;
    }

    /**
     * 组合查询条件
     * @return array
     */
    private function criteria()
    {
        $attrs = $this->_attrs;
        foreach ($this->_attrs as $attr => $values) {
            if (!empty($values)) {
                if (count($values) == 1) {
                    $attrs[$attr] = $values[0];
                } else {
                    $attrs[$attr]['$in'] = $values;
                }
            }
        }
        foreach ($this->_conds as $key => $value) {
            $attrs[$key] = $value;
        }
        return $attrs;
    }


    public function offset($num)
    {
        $this->_offset = (int)$num;
        return $this;
    }

    public function limit($num)
    {
        $this->_limit = (int)$num;
        return $this;
    }

    public function skip($num)
    {
        $this->_offset = (int)$num;
        return $this;
    }

    public function sort(array $fields)
    {
        foreach ($fields as $key => $val) {
            if (is_string($key)) {
                $this->_sort[$key] = $val;
            }
        }
        return $this;
    }

    /**
     * 设置正排序条件
     *
     * @param string $attr 需要排序的属性
     * @return $this
     */
    public function asc($attr = "_id")
    {
        $this->_sort[$attr] = 1;
        return $this;
    }

    /**
     * 设置倒排序条件
     *
     * @param string $attr 需要排序的属性
     * @return $this
     */
    public function desc($attr = "_id")
    {
        $this->_sort[$attr] = -1;
        return $this;
    }

    public function hint($hint)
    {
        $this->_hints[] = $hint;
        return $this;
    }
}