Skip to content

Commit

Permalink
feat: setter/getter must be public
Browse files Browse the repository at this point in the history
This will allow developers to implement `protected function setRelation()`
 without accidentally triggering on `$entity->relation = $value`.
  • Loading branch information
kenjis committed Feb 1, 2023
1 parent 31a2e83 commit 7902b18
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
12 changes: 10 additions & 2 deletions system/Entity/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use DateTime;
use Exception;
use JsonSerializable;
use ReflectionMethod;
use ReturnTypeWillChange;

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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 $reflection->isPublic();
}

/**
* Magic method to allow retrieval of protected and private class properties
* either by their name, or through a `getCamelCasedProperty()` method.
Expand All @@ -501,7 +509,7 @@ public function __get(string $key)

// if a get* method exists for this key,
// use that method to insert this value.
if (method_exists($this, $method)) {
if (method_exists($this, $method) && $this->isPublic($method)) {
$result = $this->{$method}();
}

Expand Down
4 changes: 2 additions & 2 deletions tests/system/Entity/EntityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}
Expand Down

0 comments on commit 7902b18

Please sign in to comment.