0

I´ve got a function to build dynamically the object from the database.

My class extends a DBModel Class with a build function :

/* Function to setup the object dynamically from database */
protected function build(){
    global $db;
    if( !empty( $this->query ) ){
      $data_from_db = $db->raw( $this->query );

      if( !empty( $data_from_db ) ){
        foreach ( $data_from_db as $property => $value ){
          $class = get_called_class();
          if( property_exists( $class, $property ) ){
            $rp = new ReflectionProperty( $class, $property);
            if( isset( $rp ) && $rp->getType() ){
              // print_r($rp->getType()->getName() );
              $this->{$property} = $value;
            }
          }
        }
      }
    }
  }

I´m trying to detect if the property is an Enum, otherwise I got this error :

Fatal error: Uncaught TypeError: Cannot assign string to property MyClass::$myEnumProperty of type MyEnumNameType

For the moment I can get MyEnumNameType with $rp->getType()->getName() but I don´t manage to check if MyEnumNameType is an Enum in order to set the value as Enum and not as a string which makes an error.

Someone knows the way to do this ?

IMSoP
  • 89,526
  • 13
  • 117
  • 169
J.BizMai
  • 2,621
  • 3
  • 25
  • 49
  • 2
    Does this answer your question? [How to check if enum type?](https://stackoverflow.com/questions/70237057/how-to-check-if-enum-type) – IMSoP May 05 '22 at 10:30

2 Answers2

1

I can think of two ways to do this

1:

var_dump($this->{$property} instanceof \UnitEnum );

2:

if (is_object($this->{$property})) {
    $rc = new ReflectionClass($this->{$property});
    var_dump($rc->isEnum());
}
Rain
  • 3,416
  • 3
  • 24
  • 40
0

My solution based on @IMSoP answer and this question, basically is based on enum_exists() :

protected function build(){
    global $db;
    if( !empty( $this->query ) ){
      $data_from_db = $db->raw( $this->query );

      if( !empty( $data_from_db ) ){
        foreach ( $data_from_db as $property => $value ){
          $class = get_called_class();
          if( property_exists( $class, $property ) ){
            $rp = new ReflectionProperty( $class, $property);

            if( isset( $rp ) && enum_exists( $rp->getType()->getName() ) ){
              $this->{$property} = call_user_func( [$rp->getType()->getName(), 'from'], $value );
            }else{
              $this->{$property} = $value;
            }
          }else{
            $this->{$property} = $value;
          }
        }
      }
    }
  }

Notice : $rc->isEnum() does not exist.

J.BizMai
  • 2,621
  • 3
  • 25
  • 49