tighten / parental

Use single table inheritance in your Laravel app
MIT License
1.36k stars 98 forks source link

Infinite recursion when setting parent in childTypes #83

Closed theofanisv closed 4 years ago

theofanisv commented 4 years ago

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

theofanisv commented 4 years ago

It seems this has already been reported and already fixed. Sorry for reposting.