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

namespace yii\mongo\file;

use Yii;
11 12
use yii\helpers\Json;
use yii\mongo\Exception;
Paul Klimov committed
13 14

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

	/**
40
	 * @param \MongoGridFSCursor $cursor Mongo cursor instance to fetch data from.
41
	 * @param boolean $all whether to fetch all rows or only first one.
42
	 * @param string|callable $indexBy value to index by.
43
	 * @return array|boolean result.
44
	 * @see Query::fetchRows()
45
	 */
46
	protected function fetchRowsInternal($cursor, $all, $indexBy)
47
	{
48 49 50 51 52 53 54 55
		$result = [];
		if ($all) {
			foreach ($cursor as $file) {
				$row = $file->file;
				$row['file'] = $file;
				if ($indexBy !== null) {
					if (is_string($indexBy)) {
						$key = $row[$indexBy];
56
					} else {
57
						$key = call_user_func($indexBy, $row);
58
					}
59
					$result[$key] = $row;
60
				} else {
61
					$result[] = $row;
62 63
				}
			}
64 65 66 67 68 69 70 71
		} else {
			if ($cursor->hasNext()) {
				$file = $cursor->getNext();
				$result = $file->file;
				$result['file'] = $file;
			} else {
				$result = false;
			}
72
		}
73
		return $result;
74
	}
Paul Klimov committed
75
}