From bb6028f1979794e89c2e417ecf8a85a77a8cefb2 Mon Sep 17 00:00:00 2001 From: Rocco Howard Date: Wed, 27 Sep 2017 21:27:22 +1000 Subject: [PATCH] Added custom attribute types --- .../Eloquent/Concerns/HasAttributes.php | 22 ++++++++++++++++++- tests/Database/DatabaseEloquentModelTest.php | 16 ++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) mode change 100644 => 100755 src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php old mode 100644 new mode 100755 index 8a49c4a624f0..e58fe718fb84 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -465,7 +465,16 @@ protected function castAttribute($key, $value) return $value; } - switch ($this->getCastType($key)) { + $castType = $this->getCastType($key); + + // If the cast type has a cast mutator, we will call that then return what + // it returns as the value, which is useful for transforming values on + // retrieval from the model to a form that is more useful for usage. + if ($this->hasCastMutator($castType)) { + return $this->{'cast'.Str::studly($castType).'Value'}($value); + } + + switch ($castType) { case 'int': case 'integer': return (int) $value; @@ -507,6 +516,17 @@ protected function getCastType($key) return trim(strtolower($this->getCasts()[$key])); } + /** + * Determine if a cast mutator exists for an cast type. + * + * @param string $key + * @return bool + */ + public function hasCastMutator($key) + { + return method_exists($this, 'cast'.Str::studly($key).'Value'); + } + /** * Set a given attribute on the model. * diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 3faa6e473670..e8adfd8db182 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -1516,6 +1516,16 @@ public function testModelDateAttributeCastingResetsTime() $this->assertEquals('1969-07-20 00:00:00', $arr['dateAttribute']); } + public function testModelAttributeCustomCasting() + { + $model = new EloquentModelCastingStub; + $model->customAttribute = 'test'; + + $arr = $model->toArray(); + + $this->assertEquals('test1', $arr['customAttribute']); + } + public function testModelAttributeCastingPreservesNull() { $model = new EloquentModelCastingStub; @@ -2008,12 +2018,18 @@ class EloquentModelCastingStub extends Model 'dateAttribute' => 'date', 'datetimeAttribute' => 'datetime', 'timestampAttribute' => 'timestamp', + 'customAttribute' => 'custom', ]; public function jsonAttributeValue() { return $this->attributes['jsonAttribute']; } + + public function castCustomValue($value) + { + return $value.'1'; + } } class EloquentModelDynamicHiddenStub extends \Illuminate\Database\Eloquent\Model