Hello list,
I would like to propose new methods for ReflectionType, that would
allow treating ReflectionNamedType and ReflectionUnionType in a
unified way.
This would eliminate the need for if (.. instanceof) in many use cases.

Some details can still be discussed, e.g. whether 'null' should be
included in builtin type names, whether there should be a canonical
ordering of type names, whether we should use class names as array
keys, etc.


abstract class ReflectionType {

  [..] // existing methods.

  /**
   * @return string[]
   */
  public function getClassNames(): array;

  /**
   * @return \ReflectionClass[]
   */
  public function getClasses(): array {
    $classes = [];
    foreach ($this->getClassNames() as $className) {
      $classes[] = new ReflectionClass($className);
    }
    return $classes;
  }

  /**
   * @return string[]
   */
  public function getBuiltinNames(): array;
}

class ReflectionNamedType extends ReflectionType {

  [..] // existing methods.

  public function getClassNames(): array {
    return $this->isBuiltin() ? [] : $this->getName();
  }

  public function getBuiltinNames(): array {
    $names = $this->isBuiltin() ? [] : $this->getName();
    if ($this->allowsNull()) {
      $names[] = 'null';
    }
    return $names;
  }
}

class ReflectionUnionType extends ReflectionType {

  [..] // existing methods.

  public function getClassNames(): array {
    $namess = [];
    foreach ($this->getTypes() as $type) {
      $namess[] = $type->getClassNames();
    }
    return array_unique(array_merge(...$types));
  }

  public function getBuiltinNames(): array {
    $namess = [];
    foreach ($this->getTypes() as $type) {
      $namess[] = $type->getBuiltinNames();
    }
    return array_unique(array_merge(...$types));
  }
}


What do you think?

-- Andreas

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to