Skip to content

Infinite recursion when setting parent in childTypes #83

@theofanisv

Description

@theofanisv

Hello
To make myself clear look at the following example

class User extends Model
{
    use \Parental\HasChildren;
    protected $childTypes = [
        'admin' => App\Admin::class,
        'guest' => App\Guest::class,
        'simple' => App\User::class, // parent as child
    ];
}

At this line
src/HasChildren.php(22): $childClass::registerModelEvent($event, $callback);
an infinite recursion occurs because the parent is added to the child types.

I was already using this configuration with the previous tightenco/parental and now I moved to this package.
You can fix this by adding a check right above that line so the function will look like this

protected static function registerModelEvent($event, $callback)
    {
        parent::registerModelEvent($event, $callback);

        if (static::class === self::class && property_exists(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) {
                    if ($childClass == self::class) // checking for self-inheritance
                        continue; 
                    $childClass::registerModelEvent($event, $callback);
                }
            }
        }
    }

Are you going to add a fix like this in the next version?
Do you think there are any other problems with self inheritance?
Thank you for you time

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions