From eeccf4c765510e7b42c633a29ecdc8beae2a9665 Mon Sep 17 00:00:00 2001 From: Kieran Marshall Date: Thu, 11 Nov 2021 09:01:00 +0000 Subject: [PATCH] Allow child types to be set via a method. --- src/HasChildren.php | 22 ++++++++++++---------- tests/Unit/HasChildrenTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/HasChildren.php b/src/HasChildren.php index 97d977d..c720ad7 100644 --- a/src/HasChildren.php +++ b/src/HasChildren.php @@ -14,11 +14,13 @@ protected static function registerModelEvent($event, $callback) { parent::registerModelEvent($event, $callback); - if (static::class === self::class && property_exists(self::class, 'childTypes')) { + $childTypes = (new self)->getChildTypes(); + + if (static::class === self::class && $childTypes !== []) { // We don't want to register the callbacks that happen in the boot method of the parent, as they'll be called // from the child's boot method as well. if (! self::parentIsBooting()) { - foreach ((new self)->childTypes as $childClass) { + foreach ($childTypes as $childClass) { if ($childClass !== self::class) { $childClass::registerModelEvent($event, $callback); } @@ -193,10 +195,10 @@ protected function getChildModel(array $attributes) */ public function classFromAlias($aliasOrClass) { - if (property_exists($this, 'childTypes')) { - if (isset($this->childTypes[$aliasOrClass])) { - return $this->childTypes[$aliasOrClass]; - } + $childTypes = $this->getChildTypes(); + + if (isset($childTypes[$aliasOrClass])) { + return $childTypes[$aliasOrClass]; } return $aliasOrClass; @@ -208,10 +210,10 @@ public function classFromAlias($aliasOrClass) */ public function classToAlias($className) { - if (property_exists($this, 'childTypes')) { - if (in_array($className, $this->childTypes)) { - return array_search($className, $this->childTypes); - } + $childTypes = $this->getChildTypes(); + + if (in_array($className, $childTypes)) { + return array_search($className, $childTypes); } return $className; diff --git a/tests/Unit/HasChildrenTest.php b/tests/Unit/HasChildrenTest.php index d1a03c5..972ae25 100644 --- a/tests/Unit/HasChildrenTest.php +++ b/tests/Unit/HasChildrenTest.php @@ -18,6 +18,17 @@ function child_model_mutators_are_not_instigated() $this->assertEquals($model->mutatorWasCalled, false); } + + /** @test */ + function child_model_types_can_be_set_via_method() + { + $types = (new HasChildrenParentModelWithMethodTypes)->getChildTypes(); + + $this->assertEquals([ + 'foo' => Foo::class, + 'bar' => Bar::class, + ], $types); + } } class HasChildrenParentModel extends Model { @@ -34,3 +45,16 @@ public function setTestAttribute() $this->mutatorWasCalled = true; } } + +class HasChildrenParentModelWithMethodTypes extends Model +{ + use HasChildren; + + public function getChildTypes() + { + return [ + 'foo' => Foo::class, + 'bar' => Bar::class, + ]; + } +}