Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Models\DataEntities;
- abstract class BaseEntity implements EntityInterface
- {
- /**
- * @var \ReflectionClass
- */
- private static $reflection;
- /**
- * @var array
- */
- private static $propertiesNames;
- public function toArray(): array
- {
- self::makePropertiesNames();
- $result = [];
- foreach (self::$propertiesNames as $propertyName) {
- $result[$propertyName] = $this->{$propertyName};
- }
- return $result;
- }
- public function toJson(): string
- {
- return \json_encode($this->toArray());
- }
- private static function makeReflectionObject(): void
- {
- try {
- static::$reflection = static::$reflection ?? new \ReflectionClass(static::class);
- } catch (\ReflectionException $e) {
- throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
- }
- }
- private static function makePropertiesNames(): void
- {
- self::makeReflectionObject();
- $properties = static::$reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
- foreach ($properties as $property) {
- self::$propertiesNames[] = $property->getName();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement