Skip to content

Commit

Permalink
Merge pull request #99 from kayrunm/define-child-tasks-via-method
Browse files Browse the repository at this point in the history
Allow child types to be set via a method.
  • Loading branch information
JustSteveKing authored Jun 21, 2022
2 parents 2779b83 + eeccf4c commit 381d8bc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/HasChildren.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/HasChildrenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
];
}
}

0 comments on commit 381d8bc

Please sign in to comment.