ActiveRecord.php 11.1 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
    /**
Alexander Makarov committed
48
     * @inheritdoc
49
     */
Alexander Makarov committed
50
    public static function find()
51
    {
52
        return new ActiveQuery(get_called_class());
53
    }
Paul Klimov committed
54

55 56 57 58 59 60 61 62
    /**
     * 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
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 89 90 91 92 93
    /**
     * 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
94

95 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
    /**
     * @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);
128
        $values['_id'] = $newId;
129

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

134 135
        return true;
    }
Paul Klimov committed
136

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

152 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
        $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.');
            }
        }
199

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

207 208
        return $rows;
    }
209

210 211
    /**
     * Extracts filename from given raw file value.
212 213
     * @param mixed $file raw file value.
     * @return string file name.
214 215 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
     * @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.
245
     * @return null|string file content.
246 247 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
     * @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.
278 279
     * @param string $filename full filename to be written.
     * @return boolean whether the operation was successful.
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
     * @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.
309
     * @return resource file stream resource.
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
     * @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.');
        }
    }
334
}