diff --git a/private-classes/Object/ObjectReader.php b/private-classes/Object/ObjectReader.php index 3440c77..5e35bac 100644 --- a/private-classes/Object/ObjectReader.php +++ b/private-classes/Object/ObjectReader.php @@ -98,7 +98,11 @@ protected function getPropertyValues(object $instance, array $reflectionProperti return array_reduce( $reflectionProperties, function (array $variableValues, ReflectionProperty $reflection_property) use ($instance) { - $variableValues[ $reflection_property->getName() ] = $reflection_property->getValue($instance); + // make sure the property is initialized. + // Otherwise, we'll get "must not be accessed before initialization" error. + if (true === $reflection_property->isInitialized($instance)) { + $variableValues[ $reflection_property->getName() ] = $reflection_property->getValue($instance); + } return $variableValues; }, diff --git a/tests/pest/Feature/ViewsManagerTest.php b/tests/pest/Feature/ViewsManagerTest.php index 98c77e3..3657911 100644 --- a/tests/pest/Feature/ViewsManagerTest.php +++ b/tests/pest/Feature/ViewsManagerTest.php @@ -919,6 +919,36 @@ public function testMakeModelNotSetDefaultsForModelsWithoutDefaultsInterface(): $this->assertFalse(isset($model->message)); } + public function testMakeModelNotSetDefaultsForInnerInterfacedModel(): void + { + // given + $bladeRenderer = new ViewTemplateRenderer(); + $namespaceConfig = (new ViewNamespaceConfig($bladeRenderer)); + $views = new ViewsManager(); + + $modelNamespace = $this->defineRealModelClass( + __METHOD__, + 'FirstModel', + [ + [ + 'name' => 'inner', + 'type' => '\\' . TemplateModelInterface::class, + 'visibility' => 'public', + ] + ], + true + ); + + // when + $views->registerNamespace($modelNamespace, $namespaceConfig); + + $modelClass = $modelNamespace . '\\FirstModel'; + $model = $views->createModel($modelClass); + + // then + $this->assertFalse(isset($model->inner)); + } + public function testMakeModelSupportsDifferentNamespaces(): void { // given diff --git a/tests/pest/Unit/Object/ObjectReaderTest.php b/tests/pest/Unit/Object/ObjectReaderTest.php index 99d5cdf..b57f967 100644 --- a/tests/pest/Unit/Object/ObjectReaderTest.php +++ b/tests/pest/Unit/Object/ObjectReaderTest.php @@ -81,4 +81,22 @@ public function someMethod(): string 'someMethod' => [$testInstance, 'someMethod'], ], $variables); } + + public function testExcludesNotInitializedProperties(): void + { + // given + $objectReader = new ObjectReader(); + $testInstance = new class { + public int $typedProperty = 1; + public int $typedButNotInitializedProperty; + }; + + // when + $variables = $objectReader->extractObjectVariables($testInstance); + + // then + $this->assertEquals([ + 'typedProperty' => 1, + ], $variables); + } }