Query.php 1.74 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 19 20 21
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
22
class Query extends \yii\mongodb\Query
Paul Klimov committed
23 24 25
{
	/**
	 * Returns the Mongo collection for this query.
26
	 * @param \yii\mongodb\Connection $db Mongo connection.
Paul Klimov committed
27 28 29 30 31
	 * @return Collection collection instance.
	 */
	public function getCollection($db = null)
	{
		if ($db === null) {
32
			$db = Yii::$app->getComponent('mongodb');
Paul Klimov committed
33 34 35
		}
		return $db->getFileCollection($this->from);
	}
36 37

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