Query.php 1.52 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 20 21 22 23 24 25 26 27 28 29 30 31 32 33

/**
 * Class Query
 *
 * @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);
	}
34 35

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