From 3b61ecaa1c3b49bd9364af8ead8214b778df6b9c Mon Sep 17 00:00:00 2001 From: Toby Zerner Date: Mon, 11 May 2015 10:39:54 +0930 Subject: [PATCH] Extract mappedMorphTo function into a trait Not sure if this is the best thing to do, it could also just be put on the base Model class --- .../core/src/Core/Models/Notification.php | 29 ++------------ .../src/Core/Support/MappedMorphToTrait.php | 39 +++++++++++++++++++ 2 files changed, 43 insertions(+), 25 deletions(-) create mode 100644 framework/core/src/Core/Support/MappedMorphToTrait.php diff --git a/framework/core/src/Core/Models/Notification.php b/framework/core/src/Core/Models/Notification.php index 3d3962048..c22ce49e5 100644 --- a/framework/core/src/Core/Models/Notification.php +++ b/framework/core/src/Core/Models/Notification.php @@ -1,9 +1,11 @@ $typeColumn)) { - return new MappedMorphTo( - $this->newQuery(), $this, $idColumn, null, $typeColumn, $name, static::$subjects - ); - } - - // If we are not eager loading the relationship we will essentially treat this - // as a belongs-to style relationship since morph-to extends that class and - // we will pass in the appropriate values so that it behaves as expected. - else { - $class = static::$subjects[$type]; - $instance = new $class; - - return new MappedMorphTo( - $instance->newQuery(), $this, $idColumn, $instance->getKeyName(), $typeColumn, $name, static::$subjects - ); - } + return $this->mappedMorphTo(static::$subjects, 'subject', 'type', 'subject_id'); } public static function getTypes() diff --git a/framework/core/src/Core/Support/MappedMorphToTrait.php b/framework/core/src/Core/Support/MappedMorphToTrait.php new file mode 100644 index 000000000..f1054cba3 --- /dev/null +++ b/framework/core/src/Core/Support/MappedMorphToTrait.php @@ -0,0 +1,39 @@ +getMorphs($name, $type, $id); + + // If the type value is null it is probably safe to assume we're eager loading + // the relationship. When that is the case we will pass in a dummy query as + // there are multiple types in the morph and we can't use single queries. + if (is_null($typeValue = $this->$type)) { + return new MappedMorphTo( + $this->newQuery(), $this, $id, null, $type, $name, $classes + ); + } + + // If we are not eager loading the relationship we will essentially treat this + // as a belongs-to style relationship since morph-to extends that class and + // we will pass in the appropriate values so that it behaves as expected. + else { + $class = $classes[$typeValue]; + $instance = new $class; + + return new MappedMorphTo( + $instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name, $classes + ); + } + } +}