ActiveRecord.php 9.75 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 13
use yii\base\InvalidParamException;
use yii\db\StaleObjectException;
use yii\web\UploadedFile;

Paul Klimov committed
14 15 16
/**
 * ActiveRecord is the base class for classes representing Mongo GridFS files in terms of objects.
 *
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 * To specify source file use the [[file]] attribute. It can be specified in one of the following ways:
 *  - string - full name of the file, which content should be stored in GridFS
 *  - \yii\web\UploadedFile - uploaded file instance, which content should be stored in GridFS
 *
 * For example:
 *
 * ~~~
 * $record = new ImageFile();
 * $record->file = '/path/to/some/file.jpg';
 * $record->save();
 * ~~~
 *
 * You can also specify file content via [[newFileContent]] attribute:
 *
 * ~~~
 * $record = new ImageFile();
 * $record->newFileContent = 'New file content';
 * $record->save();
 * ~~~
 *
 * Note: [[newFileContent]] always takes precedence over [[file]].
 *
Qiang Xue committed
39 40
 * @property null|string $fileContent File content. This property is read-only.
 * @property resource $fileResource File stream resource. This property is read-only.
41
 *
Paul Klimov committed
42 43 44
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
45
abstract class ActiveRecord extends \yii\mongodb\ActiveRecord
Paul Klimov committed
46 47 48 49
{
	/**
	 * Creates an [[ActiveQuery]] instance.
	 * This method is called by [[find()]] to start a "find" command.
50 51
	 * You may override this method to return a customized query (e.g. `ImageFileQuery` specified
	 * written for querying `ImageFile` purpose.)
Paul Klimov committed
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 77 78 79 80 81 82
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance.
	 */
	public static function createQuery()
	{
		return new ActiveQuery(['modelClass' => get_called_class()]);
	}

	/**
	 * Return the Mongo GridFS collection instance for this AR class.
	 * @return Collection collection instance.
	 */
	public static function getCollection()
	{
		return static::getDb()->getFileCollection(static::collectionName());
	}

	/**
	 * Creates an [[ActiveRelation]] instance.
	 * This method is called by [[hasOne()]] and [[hasMany()]] to create a relation instance.
	 * You may override this method to return a customized relation.
	 * @param array $config the configuration passed to the ActiveRelation class.
	 * @return ActiveRelation the newly created [[ActiveRelation]] instance.
	 */
	public static function createActiveRelation($config = [])
	{
		return new ActiveRelation($config);
	}

	/**
	 * Returns the list of all attribute names of the model.
	 * This method could be overridden by child classes to define available attributes.
83 84 85 86 87 88 89 90 91 92 93 94
	 * Note: all attributes defined in base Active Record class should be always present
	 * in returned array.
	 * For example:
	 * ~~~
	 * public function attributes()
	 * {
	 *     return array_merge(
	 *         parent::attributes(),
	 *         ['tags', 'status']
	 *     );
	 * }
	 * ~~~
Paul Klimov committed
95 96 97 98
	 * @return array list of attribute names.
	 */
	public function attributes()
	{
99 100 101 102 103 104 105 106 107 108
		return [
			'_id',
			'filename',
			'uploadDate',
			'length',
			'chunkSize',
			'md5',
			'file',
			'newFileContent'
		];
Paul Klimov committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	}

	/**
	 * @see ActiveRecord::insert()
	 */
	protected function insertInternal($attributes = null)
	{
		if (!$this->beforeSave(true)) {
			return false;
		}
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
			$currentAttributes = $this->getAttributes();
			foreach ($this->primaryKey() as $key) {
				$values[$key] = isset($currentAttributes[$key]) ? $currentAttributes[$key] : null;
			}
		}
		$collection = static::getCollection();
127 128
		if (isset($values['newFileContent'])) {
			$newFileContent = $values['newFileContent'];
129
			unset($values['newFileContent']);
130 131 132
		}
		if (isset($values['file'])) {
			$newFile = $values['file'];
133
			unset($values['file']);
134 135 136 137 138
		}
		if (isset($newFileContent)) {
			$newId = $collection->insertFileContent($newFileContent, $values);
		} elseif (isset($newFile)) {
			$fileName = $this->extractFileName($newFile);
139
			$newId = $collection->insertFile($fileName, $values);
140 141 142
		} else {
			$newId = $collection->insert($values);
		}
Paul Klimov committed
143 144 145 146 147 148 149 150 151
		$this->setAttribute('_id', $newId);
		foreach ($values as $name => $value) {
			$this->setOldAttribute($name, $value);
		}
		$this->afterSave(true);
		return true;
	}

	/**
152
	 * @see ActiveRecord::update()
Paul Klimov committed
153 154 155 156 157 158 159 160 161 162 163 164 165
	 * @throws StaleObjectException
	 */
	protected function updateInternal($attributes = null)
	{
		if (!$this->beforeSave(false)) {
			return false;
		}
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
			$this->afterSave(false);
			return 0;
		}

166
		$collection = static::getCollection();
167 168
		if (isset($values['newFileContent'])) {
			$newFileContent = $values['newFileContent'];
169
			unset($values['newFileContent']);
170 171 172
		}
		if (isset($values['file'])) {
			$newFile = $values['file'];
173
			unset($values['file']);
174 175 176 177 178 179 180
		}
		if (isset($newFileContent) || isset($newFile)) {
			$rows = $this->deleteInternal();
			$insertValues = $values;
			$insertValues['_id'] = $this->getAttribute('_id');
			if (isset($newFileContent)) {
				$collection->insertFileContent($newFileContent, $insertValues);
181
			} else {
182 183
				$fileName = $this->extractFileName($newFile);
				$collection->insertFile($fileName, $insertValues);
184
			}
185 186
			$this->setAttribute('newFileContent', null);
			$this->setAttribute('file', null);
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
		} else {
			$condition = $this->getOldPrimaryKey(true);
			$lock = $this->optimisticLock();
			if ($lock !== null) {
				if (!isset($values[$lock])) {
					$values[$lock] = $this->$lock + 1;
				}
				$condition[$lock] = $this->$lock;
			}
			// We do not check the return value of update() because it's possible
			// that it doesn't change anything and thus returns 0.
			$rows = $collection->update($condition, $values);
			if ($lock !== null && !$rows) {
				throw new StaleObjectException('The object being updated is outdated.');
			}
Paul Klimov committed
202 203 204 205 206 207 208 209 210
		}

		foreach ($values as $name => $value) {
			$this->setOldAttribute($name, $this->getAttribute($name));
		}
		$this->afterSave(false);
		return $rows;
	}

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	/**
	 * Extracts filename from given raw file value.
	 * @param mixed $file raw file value.
	 * @return string file name.
	 * @throws \yii\base\InvalidParamException on invalid file value.
	 */
	protected function extractFileName($file)
	{
		if ($file instanceof UploadedFile) {
			return $file->tempName;
		} elseif (is_string($file)) {
			if (file_exists($file)) {
				return $file;
			} else {
				throw new InvalidParamException("File '{$file}' does not exist.");
			}
		} else {
			throw new InvalidParamException('Unsupported type of "file" attribute.');
		}
	}

232 233 234 235 236 237 238 239 240 241 242
	/**
	 * Refreshes the [[file]] attribute from file collection, using current primary key.
	 * @return \MongoGridFSFile|null refreshed file value.
	 */
	public function refreshFile()
	{
		$mongoFile = $this->getCollection()->get($this->getPrimaryKey());
		$this->setAttribute('file', $mongoFile);
		return $mongoFile;
	}

243 244 245
	/**
	 * Returns the associated file content.
	 * @return null|string file content.
246
	 * @throws \yii\base\InvalidParamException on invalid file attribute value.
247 248
	 */
	public function getFileContent()
Paul Klimov committed
249 250
	{
		$file = $this->getAttribute('file');
251 252 253
		if (empty($file) && !$this->getIsNewRecord()) {
			$file = $this->refreshFile();
		}
Paul Klimov committed
254 255
		if (empty($file)) {
			return null;
256
		} elseif ($file instanceof \MongoGridFSFile) {
257 258 259 260 261 262
			$fileSize = $file->getSize();
			if (empty($fileSize)) {
				return null;
			} else {
				return $file->getBytes();
			}
263 264 265 266 267
		} elseif ($file instanceof UploadedFile) {
			return file_get_contents($file->tempName);
		} elseif (is_string($file)) {
			if (file_exists($file)) {
				return file_get_contents($file);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
			} else {
				throw new InvalidParamException("File '{$file}' does not exist.");
			}
		} else {
			throw new InvalidParamException('Unsupported type of "file" attribute.');
		}
	}

	/**
	 * Writes the the internal file content into the given filename.
	 * @param string $filename full filename to be written.
	 * @return boolean whether the operation was successful.
	 * @throws \yii\base\InvalidParamException on invalid file attribute value.
	 */
	public function writeFile($filename)
	{
		$file = $this->getAttribute('file');
		if (empty($file) && !$this->getIsNewRecord()) {
			$file = $this->refreshFile();
		}
		if (empty($file)) {
			throw new InvalidParamException('There is no file associated with this object.');
		} elseif ($file instanceof \MongoGridFSFile) {
			return ($file->write($filename) == $file->getSize());
		} elseif ($file instanceof UploadedFile) {
			return copy($file->tempName, $filename);
		} elseif (is_string($file)) {
			if (file_exists($file)) {
				return copy($file, $filename);
			} else {
				throw new InvalidParamException("File '{$file}' does not exist.");
			}
		} else {
			throw new InvalidParamException('Unsupported type of "file" attribute.');
		}
	}

	/**
	 * This method returns a stream resource that can be used with all file functions in PHP,
	 * which deal with reading files. The contents of the file are pulled out of MongoDB on the fly,
	 * so that the whole file does not have to be loaded into memory first.
	 * @return resource file stream resource.
	 * @throws \yii\base\InvalidParamException on invalid file attribute value.
	 */
	public function getFileResource()
	{
		$file = $this->getAttribute('file');
		if (empty($file) && !$this->getIsNewRecord()) {
			$file = $this->refreshFile();
		}
		if (empty($file)) {
			throw new InvalidParamException('There is no file associated with this object.');
		} elseif ($file instanceof \MongoGridFSFile) {
			return $file->getResource();
		} elseif ($file instanceof UploadedFile) {
			return fopen($file->tempName, 'r');
		} elseif (is_string($file)) {
			if (file_exists($file)) {
				return fopen($file, 'r');
			} else {
				throw new InvalidParamException("File '{$file}' does not exist.");
329 330 331
			}
		} else {
			throw new InvalidParamException('Unsupported type of "file" attribute.');
Paul Klimov committed
332 333 334
		}
	}
}