44
55namespace MongoDB \Laravel \Eloquent ;
66
7+ use Brick \Math \BigDecimal ;
8+ use Brick \Math \Exception \MathException as BrickMathException ;
9+ use Brick \Math \RoundingMode ;
710use DateTimeInterface ;
811use Illuminate \Contracts \Queue \QueueableCollection ;
912use Illuminate \Contracts \Queue \QueueableEntity ;
1013use Illuminate \Contracts \Support \Arrayable ;
14+ use Illuminate \Database \Eloquent \Casts \Json ;
1115use Illuminate \Database \Eloquent \Model as BaseModel ;
1216use Illuminate \Database \Eloquent \Relations \Relation ;
1317use Illuminate \Support \Arr ;
18+ use Illuminate \Support \Exceptions \MathException ;
1419use Illuminate \Support \Facades \Date ;
1520use Illuminate \Support \Str ;
1621use MongoDB \BSON \Binary ;
22+ use MongoDB \BSON \Decimal128 ;
1723use MongoDB \BSON \ObjectID ;
1824use MongoDB \BSON \UTCDateTime ;
1925use MongoDB \Laravel \Query \Builder as QueryBuilder ;
@@ -211,6 +217,11 @@ public function setAttribute($key, $value)
211217 {
212218 $ key = (string ) $ key ;
213219
220+ //Add casts
221+ if ($ this ->hasCast ($ key )) {
222+ $ value = $ this ->castAttribute ($ key , $ value );
223+ }
224+
214225 // Convert _id to ObjectID.
215226 if ($ key === '_id ' && is_string ($ value )) {
216227 $ builder = $ this ->newBaseQueryBuilder ();
@@ -237,6 +248,28 @@ public function setAttribute($key, $value)
237248 return parent ::setAttribute ($ key , $ value );
238249 }
239250
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+
240273 /** @inheritdoc */
241274 public function attributesToArray ()
242275 {
0 commit comments