collection-crud/src/Entity/GetSetTrait.php

60 lines
1.2 KiB
PHP
Raw Normal View History

2022-09-29 20:09:31 -04:00
<?php declare(strict_types=1);
namespace App\Entity;
2022-09-30 10:49:02 -04:00
use InvalidArgumentException;
2022-09-29 20:09:31 -04:00
/**
* Remove the need for all the Doctrine getter/setter Entity boilerplate
*/
2022-09-30 10:49:02 -04:00
trait GetSetTrait
{
public function __call(string $name, array $arguments): mixed
{
if (method_exists($this, $name)) {
return $this->{$name}(...$arguments);
}
2022-09-29 20:09:31 -04:00
// Getters
if (empty($arguments))
{
// Apparently Doctrine first tries the method with the same
// name as the property
if (property_exists($this, $name))
{
return $this->{$name};
}
if (str_starts_with($name, 'get'))
{
$var = lcfirst(substr($name, 3));
if (property_exists($this, $var))
{
return $this->{$var};
}
}
if (str_starts_with($name, 'is'))
{
$var = lcfirst(substr($name, 2));
if (property_exists($this, $var))
{
return $this->{$var};
}
}
}
2022-09-29 20:09:31 -04:00
// Setters
if (str_starts_with($name, 'set')) {
$var = lcfirst(substr($name, 3));
2022-09-30 10:49:02 -04:00
if (property_exists($this, $var)) {
$this->{$name} = $arguments[0];
}
2022-09-29 20:09:31 -04:00
2022-09-30 10:49:02 -04:00
return $this;
}
throw new InvalidArgumentException("Undefined method: {$name}");
}
2022-09-29 20:09:31 -04:00
}