diff --git a/src/HasChildren.php b/src/HasChildren.php index 47b382d..1606826 100644 --- a/src/HasChildren.php +++ b/src/HasChildren.php @@ -15,6 +15,11 @@ trait HasChildren */ protected static $parentBootMethods; + /** + * @var array + */ + protected static $parentClasses; + /** * @var bool */ @@ -57,11 +62,21 @@ protected static function parentIsBooting(): bool self::$parentBootMethods = array_flip(self::$parentBootMethods); } + if (! isset(self::$parentClasses)) { + foreach (class_parents(self::class) as $parent) { + self::$parentClasses[$parent] = true; + } + } + foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $trace) { - $class = isset($trace['class']) ? $trace['class'] : null; - $function = isset($trace['function']) ? $trace['function'] : ''; + if (! isset($trace['class']) || ! isset($trace['function'])) { + continue; + } + + $class = $trace['class']; + $function = $trace['function']; - if ($class === self::class && isset(self::$parentBootMethods[$function])) { + if (($class === self::class || isset(self::$parentClasses[$class])) && isset(self::$parentBootMethods[$function])) { return true; } } diff --git a/tests/Features/ParentsObserveChildrenTest.php b/tests/Features/ParentsObserveChildrenTest.php index ed99bc8..3a1f9bd 100644 --- a/tests/Features/ParentsObserveChildrenTest.php +++ b/tests/Features/ParentsObserveChildrenTest.php @@ -2,7 +2,10 @@ namespace Parental\Tests\Features; +use Parental\Tests\Models\Animal; use Parental\Tests\Models\Car; +use Parental\Tests\Models\Cat; +use Parental\Tests\Models\Dog; use Parental\Tests\Models\Train; use Parental\Tests\Models\Vehicle; use Parental\Tests\Observers\CarObserver; @@ -93,4 +96,13 @@ public function registering_events_in_parent_boot_only_triggers_once() $car = Car::create(); $this->assertEquals(1, $car->boot_count); } + + /** @test */ + public function registering_events_in_parent_trait_only_triggers_once() + { + Cat::create(); + Dog::create(); + + $this->assertEquals(2, Animal::$created); + } } diff --git a/tests/Models/Animal.php b/tests/Models/Animal.php new file mode 100644 index 0000000..28f193c --- /dev/null +++ b/tests/Models/Animal.php @@ -0,0 +1,15 @@ + Cat::class, + 'dog' => Dog::class, + ]; +} diff --git a/tests/Models/Cat.php b/tests/Models/Cat.php new file mode 100644 index 0000000..cc7b10f --- /dev/null +++ b/tests/Models/Cat.php @@ -0,0 +1,10 @@ +string('skill_level')->nullable(); $table->timestamps(); }); + + Schema::create('animals', function ($table) { + $table->increments('id'); + $table->string('type')->nullable(); + $table->string('name')->nullable(); + $table->timestamps(); + }); } protected function getEnvironmentSetUp($app) diff --git a/tests/Traits/CountsCreatedModels.php b/tests/Traits/CountsCreatedModels.php new file mode 100644 index 0000000..aeb0e30 --- /dev/null +++ b/tests/Traits/CountsCreatedModels.php @@ -0,0 +1,13 @@ +