ActiveRecord.php 9.99 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 39 40 41 42 43 44 45 46 47
 * 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]].
 *
 * @property \MongoId|string $_id primary key.
 * @property string $filename name of stored file.
 * @property \MongoDate $uploadDate file upload date.
 * @property integer $length file size.
 * @property integer $chunkSize file chunk size.
 * @property string $md5 file md5 hash.
 * @property \MongoGridFSFile|\yii\web\UploadedFile|string $file associated file.
 * @property string $newFileContent new file content.
 *
Paul Klimov committed
48 49 50
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
51
abstract class ActiveRecord extends \yii\mongodb\ActiveRecord
Paul Klimov committed
52 53 54 55
{
	/**
	 * Creates an [[ActiveQuery]] instance.
	 * This method is called by [[find()]] to start a "find" command.
56 57
	 * You may override this method to return a customized query (e.g. `ImageFileQuery` specified
	 * written for querying `ImageFile` purpose.)
Paul Klimov committed
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 83 84 85 86 87 88
	 * @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.
89 90 91 92 93 94 95 96 97 98 99 100
	 * 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
101 102 103 104
	 * @return array list of attribute names.
	 */
	public function attributes()
	{
105 106 107 108 109 110 111 112 113 114
		return [
			'_id',
			'filename',
			'uploadDate',
			'length',
			'chunkSize',
			'md5',
			'file',
			'newFileContent'
		];
Paul Klimov committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
	}

	/**
	 * @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();
133 134
		if (isset($values['newFileContent'])) {
			$newFileContent = $values['newFileContent'];
135
			unset($values['newFileContent']);
136 137 138
		}
		if (isset($values['file'])) {
			$newFile = $values['file'];
139
			unset($values['file']);
140 141 142 143 144
		}
		if (isset($newFileContent)) {
			$newId = $collection->insertFileContent($newFileContent, $values);
		} elseif (isset($newFile)) {
			$fileName = $this->extractFileName($newFile);
145
			$newId = $collection->insertFile($fileName, $values);
146 147 148
		} else {
			$newId = $collection->insert($values);
		}
Paul Klimov committed
149 150 151 152 153 154 155 156 157
		$this->setAttribute('_id', $newId);
		foreach ($values as $name => $value) {
			$this->setOldAttribute($name, $value);
		}
		$this->afterSave(true);
		return true;
	}

	/**
158
	 * @see ActiveRecord::update()
Paul Klimov committed
159 160 161 162 163 164 165 166 167 168 169 170 171
	 * @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;
		}

172
		$collection = static::getCollection();
173 174
		if (isset($values['newFileContent'])) {
			$newFileContent = $values['newFileContent'];
175
			unset($values['newFileContent']);
176 177 178
		}
		if (isset($values['file'])) {
			$newFile = $values['file'];
179
			unset($values['file']);
180 181 182 183 184 185 186
		}
		if (isset($newFileContent) || isset($newFile)) {
			$rows = $this->deleteInternal();
			$insertValues = $values;
			$insertValues['_id'] = $this->getAttribute('_id');
			if (isset($newFileContent)) {
				$collection->insertFileContent($newFileContent, $insertValues);
187
			} else {
188 189
				$fileName = $this->extractFileName($newFile);
				$collection->insertFile($fileName, $insertValues);
190
			}
191 192
			$this->setAttribute('newFileContent', null);
			$this->setAttribute('file', null);
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
		} 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
208 209 210 211 212 213 214 215 216
		}

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

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
	/**
	 * 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.');
		}
	}

238 239 240 241 242 243 244 245 246 247 248
	/**
	 * 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;
	}

249 250 251
	/**
	 * Returns the associated file content.
	 * @return null|string file content.
252
	 * @throws \yii\base\InvalidParamException on invalid file attribute value.
253 254
	 */
	public function getFileContent()
Paul Klimov committed
255 256
	{
		$file = $this->getAttribute('file');
257 258 259
		if (empty($file) && !$this->getIsNewRecord()) {
			$file = $this->refreshFile();
		}
Paul Klimov committed
260 261
		if (empty($file)) {
			return null;
262
		} elseif ($file instanceof \MongoGridFSFile) {
263 264 265 266 267 268
			$fileSize = $file->getSize();
			if (empty($fileSize)) {
				return null;
			} else {
				return $file->getBytes();
			}
269 270 271 272 273
		} elseif ($file instanceof UploadedFile) {
			return file_get_contents($file->tempName);
		} elseif (is_string($file)) {
			if (file_exists($file)) {
				return file_get_contents($file);
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 329 330 331 332 333 334
			} 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.");
335 336 337
			}
		} else {
			throw new InvalidParamException('Unsupported type of "file" attribute.');
Paul Klimov committed
338 339 340
		}
	}
}