Код: Выделить всё
class DummyEntity
{
use DeprecatedEntityPropertyNames;
// formerly private string $new_name;
private string $newName;
public function getNewName(): string
{
return $this->newName;
}
public function setNewName(string $newName): static
{
$this->newName = $newName;
return $this;
}
}
trait DeprecatedEntityPropertyNames
{
private function snakeToCamel(string $input): string
{
return lcfirst(str_replace('_', '', ucwords($input, '_')));
}
public function __get(string $name): mixed
{
$candidateName = $this->snakeToCamel($name, '_');
if (isset($this->$candidateName)) {
trigger_deprecation('my-library', 'x.x', "property $name accessed via old snake_case name");
return $this->$candidateName;
}
$traitName = static::class;
$className = $this::class;
throw new Error("undefined property $name in $className, this class has the trait $traitName, have tried and failed to use $candidateName");
}
public function __set(string $name, mixed $value): void
{
$candidateName = $this->snakeToCamel($name, '_');
// bad method name isDefault means is this property declared (instead of being created dynamically)
if ((new ReflectionProperty($this, $candidateName))->isDefault()) {
trigger_deprecation('my-library', 'x.x', "property $name accessed via old snake_case name");
$this->$candidateName = $value;
return;
}
$traitName = static::class;
$className = $this::class;
throw new Error("undefined property $name in $className, this class has the trait $traitName, have tried and failed to use $candidateName");
}
public function __isset(string $name): bool
{
$candidateName = $this->snakeToCamel($name, '_');
// bad method name isDefault means is this property declared (instead of being created dynamically)
if ((new ReflectionProperty($this, $candidateName))->isDefault()) {
if ($name !== $candidateName) {
trigger_deprecation('my-library', 'x.x', "property $name accessed via old snake_case name");
}
return isset($this->$candidateName);
} else {
return false;
}
}
public function __unset(string $name): void
{
$candidateName = $this->snakeToCamel($name, '_');
if ($name !== $candidateName) {
trigger_deprecation('my-library', 'x.x', "property $name accessed via old snake_case name");
}
unset($this->$candidateName);
}
}
Однако, поскольку доктрина использует отражение, чтобы получить и установить свойства обами.>
Подробнее здесь: https://stackoverflow.com/questions/796 ... -old-names