From adc2f127da2874a3f92451b7417636fe201f2da3 Mon Sep 17 00:00:00 2001 From: kenjis Date: Wed, 1 Feb 2023 14:46:43 +0900 Subject: [PATCH] feat: setter/getter must be public This will allow developers to implement `protected function setRelation()` without accidentally triggering on `$entity->relation = $value`. --- system/Entity/Entity.php | 10 +++++++++- tests/system/Entity/EntityTest.php | 4 ++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/system/Entity/Entity.php b/system/Entity/Entity.php index 5220ae5b0aa8..b9b1b9df5415 100644 --- a/system/Entity/Entity.php +++ b/system/Entity/Entity.php @@ -29,6 +29,7 @@ use DateTime; use Exception; use JsonSerializable; +use ReflectionMethod; use ReturnTypeWillChange; /** @@ -461,7 +462,7 @@ public function __set(string $key, $value = null) // so maybe wants to do sth with null value automatically $method = 'set' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $key))); - if (method_exists($this, $method) && $method !== 'setAttributes') { + if (method_exists($this, $method) && $method !== 'setAttributes' && $this->isPublic($method)) { $this->{$method}($value); return $this; @@ -476,6 +477,13 @@ public function __set(string $key, $value = null) return $this; } + private function isPublic(string $method): bool + { + $reflection = new ReflectionMethod($this, $method); + + return (bool) ($reflection->isPublic()); + } + /** * Magic method to allow retrieval of protected and private class properties * either by their name, or through a `getCamelCasedProperty()` method. diff --git a/tests/system/Entity/EntityTest.php b/tests/system/Entity/EntityTest.php index 3e4a196fc2ed..ca9e1583be97 100644 --- a/tests/system/Entity/EntityTest.php +++ b/tests/system/Entity/EntityTest.php @@ -1114,12 +1114,12 @@ protected function getMappedEntity() 'orig' => 'simple', ]; - protected function setSimple(string $val) + public function setSimple(string $val) { $this->attributes['simple'] = 'oo:' . $val; } - protected function getSimple() + public function getSimple() { return $this->attributes['simple'] . ':oo'; }