'How to check if a property is an Enum in php 8.1

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 ?



Solution 1:[1]

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.

Solution 2:[2]

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());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J.BizMai
Solution 2 Rain