This repository has been archived by the owner on Nov 21, 2019. It is now read-only.
forked from tyohan/MongoRecord
-
Notifications
You must be signed in to change notification settings - Fork 58
/
EMongoGridFS.php
314 lines (292 loc) · 9.84 KB
/
EMongoGridFS.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
48
49
50
51
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
83
84
85
86
87
88
89
90
91
92
93
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
245
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
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
<?php
/**
* EMongoGridFS.php
*
* PHP version 5.2+
*
* @author Jose Martinez <[email protected]>
* @author Philippe Gaultier <[email protected]>
* @author Dariusz Górecki <[email protected]>
* @author Invenzzia Group, open-source division of CleverIT company http://www.invenzzia.org
* @copyright 2011 Ibitux
* @license http://www.yiiframework.com/license/ BSD license
* @version SVN: $Revision: $
* @category ext
* @package ext.YiiMongoDbSuite
* @since v1.3
*/
/**
* EMongoGridFS
*
* @author Jose Martinez <[email protected]>
* @author Philippe Gaultier <[email protected]>
* @author Dariusz Górecki <[email protected]>
* @author Invenzzia Group, open-source division of CleverIT company http://www.invenzzia.org
* @copyright 2011 Ibitux
* @license http://www.yiiframework.com/license/ BSD license
* @version SVN: $Revision: $
* @category ext
* @package ext.YiiMongoDbSuite
* @since v1.3
*
*/
abstract class EMongoGridFS extends EMongoDocument
{
/**
* MongoGridFSFile will be stored here
* @var MongoGridFSFile
*/
private $_gridFSFile;
/**
* Every EMongoGridFS object has to have one
* @var String $filename
* @since v1.3
*/
public $filename = null; // mandatory
/**
* Returns current MongoGridFS object
* By default this method use {@see getCollectionName()}
* @return MongoGridFS
* @since v1.3
*/
public function getCollection()
{
if(!isset(self::$_collections[$this->getCollectionName()]))
self::$_collections[$this->getCollectionName()] = $this->getDb()->getGridFS($this->getCollectionName());
return self::$_collections[$this->getCollectionName()];
}
/**
* Inserts a row into the table based on this active record attributes.
* If the table's primary key is auto-incremental and is null before insertion,
* it will be populated with the actual value after insertion.
* Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
* After the record is inserted to DB successfully, its {@link isNewRecord} property will be set false,
* and its {@link scenario} property will be set to be 'update'.
* @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the attributes are valid and the record is inserted successfully.
* @throws CException if the record is not new
* @since v1.3
*/
public function insert(array $attributes=null)
{
if(!$this->getIsNewRecord())
throw new CDbException(Yii::t('yii','The EMongoDocument cannot be inserted to database because it is not new.'));
if($this->beforeSave())
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
$rawData = $this->toArray();
// free the '_id' container if empty, mongo will not populate it if exists
if(empty($rawData['_id']))
unset($rawData['_id']);
// filter attributes if set in param
if($attributes!==null)
{
foreach($rawData as $key=>$value)
{
if(!in_array($key, $attributes))
unset($rawData[$key]);
}
}
// check file
$filename = "";
if(!array_key_exists('filename', $rawData))
throw new CException(Yii::t('yii', 'We need a filename'));
else
{
$filename = $rawData['filename'];
unset($rawData['filename']);
}
$result = $this->getCollection()->put($filename, $rawData);
if($result !== false) // strict comparsion driver may return empty array
{
$this->_id = $result;
//TODO: should be set in parent class
$this->_gridFSFile = $this->getCollection()->findOne(array('_id'=>$this->_id));
$this->setIsNewRecord(false);
$this->setScenario('update');
$this->afterSave();
return true;
}
throw new CException(Yii::t('yii', 'Can\t save document to disk, or try to save empty document!'));
}
return false;
}
/**
* Insertion by Primary Key inserts a MongoGridFSFile forcing the MongoID
* @param MongoId $pk
* @param array $attributes
* @throws CDbException
* @throws CException
* @return boolean whether the insert success
* @since v1.3
*/
public function insertWithPk($pk, array $attributes=null) {
if(!($pk instanceof MongoId))
throw new CDbException(Yii::t('yii','The EMongoDocument cannot be inserted to database primary key is not defined.'));
if($this->beforeSave())
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
$rawData = $this->toArray();
$rawData['_id'] = $pk;
// filter attributes if set in param
if($attributes!==null)
{
foreach($rawData as $key=>$value)
{
if(!in_array($key, $attributes))
unset($rawData[$key]);
}
}
// check file
$filename = "";
if(!array_key_exists('filename', $rawData))
throw new CException(Yii::t('yii', 'We need a filename'));
else
{
$filename = $rawData['filename'];
unset($rawData['filename']);
}
$result = $this->getCollection()->put($filename, $rawData);
if($result !== false) // strict comparsion driver may return empty array
{
$this->_id = $result;
//TODO: should be set in parent class
$this->_gridFSFile = $this->getCollection()->findOne(array('_id'=>$this->_id));
$this->setIsNewRecord(false);
$this->setScenario('update');
$this->afterSave();
return true;
}
throw new CException(Yii::t('yii', 'Can\'t save document to disk, or try to save empty document!'));
}
return false;
}
/**
* Updates the row represented by this active record.
* All loaded attributes will be saved to the database.
* Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
* @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the update is successful
* @throws CException if the record is new
* @since v1.3
*/
public function update(array $attributes=null)
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
if($this->getIsNewRecord())
throw new CDbException(Yii::t('yii','The EMongoDocument cannot be updated because it is new.'));
if(is_file($this->filename) === true) {
if($this->deleteByPk($this->_id) !== false)
{
$result = $this->insertWithPk($this->_id, $attributes);
if($result === true)
return true;
else
return false;
}
} else {
return parent::update($attributes, true);
}
}
/**
* Creates an EMongoGridFS with the given attributes.
* This method is internally used by the find methods.
* @param MongoGridFSFile $document mongo gridFSFile
* @param array $attributes attribute values (column name=>column value)
* @param boolean $callAfterFind whether to call {@link afterFind} after the record is populated.
* This parameter is added in version 1.0.3.
* @return EMongoDocument the newly created document. The class of the object is the same as the model class.
* Null is returned if the input data is false.
* @since v1.3
*/
public function populateRecord($document, $callAfterFind=true)
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
if($document instanceof MongoGridFSFile)
{
$model = parent::populateRecord($document->file, $callAfterFind);
$model->_gridFSFile = $document;
return $model;
}
else
return parent::populateRecord($document, $callAfterFind);
}
/**
* Returns the file size
* GetSize wrapper of MongoGridFSFile function
* @return integer file size
* False is returned if error
* @since v1.3
*/
public function getSize()
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
if(method_exists($this->_gridFSFile, 'getSize') === true)
return $this->_gridFSFile->getSize();
else
return false;
}
/**
* Returns the filename
* GetFilename wrapper of MongoGridFSFile function
* @return string filename
* False is returned if error
* @since v1.3
*/
public function getFilename()
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
if (method_exists($this->_gridFSFile, 'getFilename') === true)
return $this->_gridFSFile->getFilename();
else
return false;
}
/**
* Returns the file's contents as a string of bytes
* getBytes wrapper of MongoGridFSFile function
* @return string string of bytes
* False is returned if error
* @since v1.3
*/
public function getBytes()
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
if (method_exists($this->_gridFSFile, 'getBytes') === true)
return $this->_gridFSFile->getBytes();
else
return false;
}
/**
* Writes this file to the system
* @param string $filename The location to which to write the file. If none is given, the stored filename will be used.
* @return integer number of bytes written
* @since v1.3
*/
public function write($filename=null)
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
if (method_exists($this->_gridFSFile, 'write') === true)
return $this->_gridFSFile->write($filename);
else
return false;
}
/**
* Deletes documents with the specified primary keys.
* See {@link find()} for detailed explanation about $condition and $params.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @return array whether the delete succeeds
* @since v1.3
*/
public function deleteAll($criteria=null)
{
Yii::trace('Trace: '.__CLASS__.'::'.__FUNCTION__.'()', 'ext.MongoDb.EMongoGridFS');
$this->applyScopes($criteria);
return $this->getCollection()->remove($criteria->getConditions(), array(
'fsync'=>$this->getFsyncFlag(),
'safe'=>$this->getSafeFlag(),
));
}
}