Advertisement
Guest User

BaseEntity

a guest
Feb 7th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.36 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.     protected static $reflection;
  11.  
  12.     /**
  13.      * @var array
  14.      */
  15.     protected static $propertiesNames;
  16.  
  17.     public function toArray(): array
  18.     {
  19.         static::makeReflectionObject();
  20.         static::makePropertiesNames();
  21.  
  22.         $result = [];
  23.         foreach (static::$propertiesNames as $propertyName) {
  24.             $result[$propertyName] = $this->{$propertyName};
  25.         }
  26.  
  27.         return $result;
  28.     }
  29.  
  30.     private static function makeReflectionObject(): void
  31.     {
  32.         if (static::$reflection !== null) {
  33.             return;
  34.         }
  35.  
  36.         try {
  37.             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.         if (static::$propertiesNames !== null) {
  46.             return;
  47.         }
  48.  
  49.         $properties = static::$reflection->getProperties();
  50.         foreach ($properties as $property) {
  51.             if ($property->isProtected() && !$property->isStatic()) {
  52.                 static::$propertiesNames[] = $property->getName();
  53.             }
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement