Search code examples
phpenumsphp-8.1

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

  • 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.