Created
October 14, 2022 16:08
-
-
Save timw4mail/a0ab9325cd1ff22a27e3634d589cfd3f to your computer and use it in GitHub Desktop.
A trait for removing Doctrine Boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
namespace App\Entity; | |
use InvalidArgumentException; | |
/** | |
* Remove the need for all the Doctrine getter/setter Entity boilerplate | |
*/ | |
trait GetSetTrait { | |
public function __get(string $name): mixed | |
{ | |
if (property_exists($this, $name)) | |
{ | |
return $this->$name; | |
} | |
return NULL; | |
} | |
public function __set(string $name, mixed $value): void | |
{ | |
if ( ! property_exists($this, $name)) | |
{ | |
throw new InvalidArgumentException("Undefined property: {$name}"); | |
} | |
$this->$name = $value; | |
} | |
public function __call(string $name, array $arguments): mixed | |
{ | |
if (method_exists($this, $name)) | |
{ | |
return $this->$name(...$arguments); | |
} | |
// Getters | |
if (empty($arguments)) | |
{ | |
// The property as a method is required for Twig it appears | |
if (property_exists($this, $name)) | |
{ | |
return $this->$name; | |
} | |
if (str_starts_with($name, 'get')) | |
{ | |
return $this->__get(lcfirst(substr($name, 3))); | |
} | |
if (str_starts_with($name, 'is')) | |
{ | |
return $this->__get(lcfirst(substr($name, 2))); | |
} | |
throw new InvalidArgumentException("Undefined method: {$name}"); | |
} | |
// Setters | |
if (str_starts_with($name, 'set')) | |
{ | |
$var = lcfirst(substr($name, 3)); | |
$this->__set($var, ...$arguments); | |
return $this; | |
} | |
throw new InvalidArgumentException("Undefined method: {$name}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment