ActiveRecord.php 11.2 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
use Yii;
11 12 13 14
use yii\base\InvalidParamException;
use yii\db\StaleObjectException;
use yii\web\UploadedFile;

Paul Klimov committed
15 16 17
/**
 * ActiveRecord is the base class for classes representing Mongo GridFS files in terms of objects.
 *
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 * 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
40 41
 * @property null|string $fileContent File content. This property is read-only.
 * @property resource $fileResource File stream resource. This property is read-only.
42
 *
Paul Klimov committed
43 44 45
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
46
abstract class ActiveRecord extends \yii\mongodb\ActiveRecord
Paul Klimov committed
47
{
48
    /**
Alexander Makarov committed
49
     * @inheritdoc
50
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
51
     */
Alexander Makarov committed
52
    public static function find()
53
    {
54
        return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
55
    }
Paul Klimov committed
56

57 58 59 60 61 62 63 64
    /**
     * Return the Mongo GridFS collection instance for this AR class.
     * @return Collection collection instance.
     */
    public static function getCollection()
    {
        return static::getDb()->getFileCollection(static::collectionName());
    }
Paul Klimov committed
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    /**
     * Returns the list of all attribute names of the model.
     * This method could be overridden by child classes to define available attributes.
     * 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']
     *     );
     * }
     * ~~~
     * @return array list of attribute names.
     */
    public function attributes()
    {
        return [
            '_id',
            'filename',
            'uploadDate',
            'length',
            'chunkSize',
            'md5',
            'file',
            'newFileContent'
        ];
    }
Paul Klimov committed
96

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    /**
     * @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();
        if (isset($values['newFileContent'])) {
            $newFileContent = $values['newFileContent'];
            unset($values['newFileContent']);
        }
        if (isset($values['file'])) {
            $newFile = $values['file'];
            unset($values['file']);
        }
        if (isset($newFileContent)) {
            $newId = $collection->insertFileContent($newFileContent, $values);
        } elseif (isset($newFile)) {
            $fileName = $this->extractFileName($newFile);
            $newId = $collection->insertFile($fileName, $values);
        } else {
            $newId = $collection->insert($values);
        }
        $this->setAttribute('_id', $newId);
130
        $values['_id'] = $newId;
131

132
        $changedAttributes = array_fill_keys(array_keys($values), null);
133
        $this->setOldAttributes($values);
134
        $this->afterSave(true, $changedAttributes);
Paul Klimov committed
135

136 137
        return true;
    }
Paul Klimov committed
138

139 140 141 142 143 144 145 146 147 148 149
    /**
     * @see ActiveRecord::update()
     * @throws StaleObjectException
     */
    protected function updateInternal($attributes = null)
    {
        if (!$this->beforeSave(false)) {
            return false;
        }
        $values = $this->getDirtyAttributes($attributes);
        if (empty($values)) {
150
            $this->afterSave(false, $values);
151 152
            return 0;
        }
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        $collection = static::getCollection();
        if (isset($values['newFileContent'])) {
            $newFileContent = $values['newFileContent'];
            unset($values['newFileContent']);
        }
        if (isset($values['file'])) {
            $newFile = $values['file'];
            unset($values['file']);
        }
        if (isset($newFileContent) || isset($newFile)) {
            $fileAssociatedAttributeNames = [
                'filename',
                'uploadDate',
                'length',
                'chunkSize',
                'md5',
                'file',
                'newFileContent'
            ];
            $values = array_merge($this->getAttributes(null, $fileAssociatedAttributeNames), $values);
            $rows = $this->deleteInternal();
            $insertValues = $values;
            $insertValues['_id'] = $this->getAttribute('_id');
            if (isset($newFileContent)) {
                $collection->insertFileContent($newFileContent, $insertValues);
            } else {
                $fileName = $this->extractFileName($newFile);
                $collection->insertFile($fileName, $insertValues);
            }
            $this->setAttribute('newFileContent', null);
            $this->setAttribute('file', null);
        } 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.');
            }
        }
201

202
        $changedAttributes = [];
203
        foreach ($values as $name => $value) {
204
            $changedAttributes[$name] = $this->getOldAttribute($name);
Carsten Brandt committed
205
            $this->setOldAttribute($name, $value);
206
        }
207
        $this->afterSave(false, $changedAttributes);
208

209 210
        return $rows;
    }
211

212 213
    /**
     * Extracts filename from given raw file value.
214 215
     * @param mixed $file raw file value.
     * @return string file name.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
     * @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.');
        }
    }

    /**
     * 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;
    }

    /**
     * Returns the associated file content.
247
     * @return null|string file content.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
     * @throws \yii\base\InvalidParamException on invalid file attribute value.
     */
    public function getFileContent()
    {
        $file = $this->getAttribute('file');
        if (empty($file) && !$this->getIsNewRecord()) {
            $file = $this->refreshFile();
        }
        if (empty($file)) {
            return null;
        } elseif ($file instanceof \MongoGridFSFile) {
            $fileSize = $file->getSize();
            if (empty($fileSize)) {
                return null;
            } else {
                return $file->getBytes();
            }
        } elseif ($file instanceof UploadedFile) {
            return file_get_contents($file->tempName);
        } elseif (is_string($file)) {
            if (file_exists($file)) {
                return file_get_contents($file);
            } 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.
280 281
     * @param string $filename full filename to be written.
     * @return boolean whether the operation was successful.
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
     * @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.
311
     * @return resource file stream resource.
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
     * @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.");
            }
        } else {
            throw new InvalidParamException('Unsupported type of "file" attribute.');
        }
    }
336
}