4
4
5
5
namespace MongoDB \Laravel \Eloquent ;
6
6
7
+ use Brick \Math \BigDecimal ;
8
+ use Brick \Math \Exception \MathException as BrickMathException ;
9
+ use Brick \Math \RoundingMode ;
7
10
use DateTimeInterface ;
8
11
use Illuminate \Contracts \Queue \QueueableCollection ;
9
12
use Illuminate \Contracts \Queue \QueueableEntity ;
10
13
use Illuminate \Contracts \Support \Arrayable ;
14
+ use Illuminate \Database \Eloquent \Casts \Json ;
11
15
use Illuminate \Database \Eloquent \Model as BaseModel ;
12
16
use Illuminate \Database \Eloquent \Relations \Relation ;
13
17
use Illuminate \Support \Arr ;
18
+ use Illuminate \Support \Exceptions \MathException ;
14
19
use Illuminate \Support \Facades \Date ;
15
20
use Illuminate \Support \Str ;
16
21
use MongoDB \BSON \Binary ;
22
+ use MongoDB \BSON \Decimal128 ;
17
23
use MongoDB \BSON \ObjectID ;
18
24
use MongoDB \BSON \UTCDateTime ;
19
25
use MongoDB \Laravel \Query \Builder as QueryBuilder ;
@@ -211,6 +217,11 @@ public function setAttribute($key, $value)
211
217
{
212
218
$ key = (string ) $ key ;
213
219
220
+ //Add casts
221
+ if ($ this ->hasCast ($ key )) {
222
+ $ value = $ this ->castAttribute ($ key , $ value );
223
+ }
224
+
214
225
// Convert _id to ObjectID.
215
226
if ($ key === '_id ' && is_string ($ value )) {
216
227
$ builder = $ this ->newBaseQueryBuilder ();
@@ -237,6 +248,28 @@ public function setAttribute($key, $value)
237
248
return parent ::setAttribute ($ key , $ value );
238
249
}
239
250
251
+ /** @inheritdoc */
252
+ protected function asDecimal ($ value , $ decimals )
253
+ {
254
+ try {
255
+ $ value = (string ) BigDecimal::of ((string ) $ value )->toScale ((int ) $ decimals , RoundingMode::HALF_UP );
256
+
257
+ return new Decimal128 ($ value );
258
+ } catch (BrickMathException $ e ) {
259
+ throw new MathException ('Unable to cast value to a decimal. ' , previous: $ e );
260
+ }
261
+ }
262
+
263
+ /** @inheritdoc */
264
+ public function fromJson ($ value , $ asObject = false )
265
+ {
266
+ if (! is_string ($ value )) {
267
+ $ value = Json::encode ($ value ?? '' );
268
+ }
269
+
270
+ return Json::decode ($ value ?? '' , ! $ asObject );
271
+ }
272
+
240
273
/** @inheritdoc */
241
274
public function attributesToArray ()
242
275
{
0 commit comments