index/src/Type.php

127 lines
2.4 KiB
PHP

<?php
// Type.php
// Created: 2021-04-26
// Updated: 2022-02-28
namespace Index;
use ReflectionClass;
use RuntimeException;
final class Type {
/**
* Boolean type id.
*
* @var string
*/
public const BOOL = 'boolean';
/**
* Integer type id.
*
* @var string
*/
public const INTEGER = 'integer';
/**
* Floating point type id.
*
* @var string
*/
public const FLOAT = 'double';
/**
* String type id.
*
* @var string
*/
public const STRING = 'string';
/**
* Array type id.
*
* @var string
*/
public const ARRAY = 'array';
/**
* Object type id.
*
* @var string
*/
public const OBJECT = 'object';
/**
* Resource type id.
*
* @var string
*/
public const RESOURCE = 'resource';
/**
* Closed resource type id.
*
* @var string
*/
public const CLOSED_RESOURCE = 'resource (closed)';
/**
* NULL type id.
*
* @var string
*/
public const NULL = 'NULL';
/**
* Unknown type id.
*
* @var string
*/
public const UNKNOWN = 'unknown type';
/**
* Gets the default value for this type.
*
* @return mixed Default value for the given base type.
*/
public static function default(string $type): mixed {
switch($type) {
case self::BOOL:
return false;
case self::INTEGER:
return 0;
case self::FLOAT:
return 0.0;
case self::STRING:
return '';
case self::ARRAY:
return [];
default:
return null;
}
}
/**
* Gets a list of all class names this Type inherits.
*
* @param string|object $target Target object.
* @return array Array containing the names.
*/
public static function classTree(string|object $target): array {
if(is_object($target))
$target = get_class($target);
$tree = [];
$classInfo = new ReflectionClass($target);
foreach($classInfo->getInterfaceNames() as $interface)
$tree[] = $interface;
do {
$tree[] = $classInfo->getName();
} while(($classInfo = $classInfo->getParentClass()) !== false);
return $tree;
}
}