Advertisement
Guest User

Untitled

a guest
Feb 5th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.26 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Models\DataEntities;
  4.  
  5. abstract class BaseEntity implements EntityInterface
  6. {
  7.     /**
  8.      * @var \ReflectionClass
  9.      */
  10.     private static $reflection;
  11.  
  12.     /**
  13.      * @var array
  14.      */
  15.     private static $propertiesNames;
  16.  
  17.     public function toArray(): array
  18.     {
  19.         self::makePropertiesNames();
  20.  
  21.         $result = [];
  22.         foreach (self::$propertiesNames as $propertyName) {
  23.             $result[$propertyName] = $this->{$propertyName};
  24.         }
  25.  
  26.         return $result;
  27.     }
  28.  
  29.     public function toJson(): string
  30.     {
  31.         return \json_encode($this->toArray());
  32.     }
  33.  
  34.     private static function makeReflectionObject(): void
  35.     {
  36.         try {
  37.             static::$reflection = static::$reflection ?? new \ReflectionClass(static::class);
  38.         } catch (\ReflectionException $e) {
  39.             throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
  40.         }
  41.     }
  42.  
  43.     private static function makePropertiesNames(): void
  44.     {
  45.         self::makeReflectionObject();
  46.         $properties = static::$reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
  47.         foreach ($properties as $property) {
  48.             self::$propertiesNames[] = $property->getName();
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement