Query.php 2.19 KB
Newer Older
Paul Klimov committed
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\mongodb\file;
Paul Klimov committed
9 10 11 12

use Yii;

/**
13 14
 * Query represents Mongo "find" operation for GridFS collection.
 *
15
 * Query behaves exactly as regular [[\yii\mongodb\Query]].
16 17
 * Found files will be represented as arrays of file document attributes with
 * additional 'file' key, which stores [[\MongoGridFSFile]] instance.
Paul Klimov committed
18
 *
Qiang Xue committed
19 20
 * @property Collection $collection Collection instance. This property is read-only.
 *
Paul Klimov committed
21 22 23
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
24
class Query extends \yii\mongodb\Query
Paul Klimov committed
25
{
26 27
    /**
     * Returns the Mongo collection for this query.
28 29
     * @param \yii\mongodb\Connection $db Mongo connection.
     * @return Collection collection instance.
30 31 32 33
     */
    public function getCollection($db = null)
    {
        if ($db === null) {
34
            $db = Yii::$app->get('mongodb');
35
        }
36

37 38 39 40
        return $db->getFileCollection($this->from);
    }

    /**
41 42 43 44
     * @param \MongoGridFSCursor $cursor Mongo cursor instance to fetch data from.
     * @param boolean $all whether to fetch all rows or only first one.
     * @param string|callable $indexBy value to index by.
     * @return array|boolean result.
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
     * @see Query::fetchRows()
     */
    protected function fetchRowsInternal($cursor, $all, $indexBy)
    {
        $result = [];
        if ($all) {
            foreach ($cursor as $file) {
                $row = $file->file;
                $row['file'] = $file;
                if ($indexBy !== null) {
                    if (is_string($indexBy)) {
                        $key = $row[$indexBy];
                    } else {
                        $key = call_user_func($indexBy, $row);
                    }
                    $result[$key] = $row;
                } else {
                    $result[] = $row;
                }
            }
        } else {
            if ($cursor->hasNext()) {
                $file = $cursor->getNext();
                $result = $file->file;
                $result['file'] = $file;
            } else {
                $result = false;
            }
        }

        return $result;
    }
AlexGx committed
77
}