Tipos de PHP
************
.[perex]
[api:Nette\Utils\Type] representa un tipo de dato de PHP. Sirve para analizar, comparar y manipular tipos, tanto si proceden de una cadena como de la reflexión.
PHP tiene hoy un sistema de tipos muy rico: desde los tipos escalares (`int`, `string`), pasando por objetos e interfaces, hasta los tipos complejos (union `A|B`, intersection `A&B` o las formas normales disyuntivas `(A&B)|D`). Se añaden además tipos especiales como `void`, `never`, `mixed` o los tipos relativos `self` y `static`.
Trabajar con estos tipos de forma nativa, sobre todo mediante `ReflectionType`, resulta a menudo incómodo, porque hay que distinguir recursivamente entre `ReflectionNamedType`, `ReflectionUnionType` y otros objetos. La clase `Nette\Utils\Type` encapsula todo eso y ofrece una **API unificada e intuitiva** para trabajar con cualquier tipo admitido por PHP.
Le permite, por ejemplo, comprobar con facilidad si un tipo [acepta|#allows()] otro (compatibilidad), [ampliar tipos|#with()] o convertir reflexiones en una notación legible.
Instalación:
```shell
composer require nette/utils
```
Todos los ejemplos suponen que está definido el siguiente alias de clase:
```php
use Nette\Utils\Type;
```
fromReflection($reflection): ?Type .[method]
--------------------------------------------
Este método estático crea un objeto `Type` a partir de la reflexión. El parámetro puede ser un objeto `ReflectionMethod` o `ReflectionFunction` (devuelve el tipo del valor de retorno), o un objeto `ReflectionParameter` o `ReflectionProperty`. Resuelve `self`, `static` y `parent` en el nombre real de la clase. Si el sujeto no tiene tipo, devuelve `null`.
```php
class DemoClass
{
public self $foo;
}
$prop = new ReflectionProperty(DemoClass::class, 'foo');
echo Type::fromReflection($prop); // 'DemoClass'
```
fromString(string $type): Type .[method]
----------------------------------------
Este método estático crea un objeto `Type` a partir de su representación textual.
```php
$type = Type::fromString('Foo|Bar');
echo $type; // 'Foo|Bar'
```
fromValue(mixed $value): Type .[method]{data-version:4.0.10}
------------------------------------------------------------
Método estático que crea un objeto Type a partir del tipo del valor pasado.
```php
$type = Type::fromValue('hello'); // 'string'
$type = Type::fromValue(123); // 'int'
$type = Type::fromValue(new stdClass); // 'stdClass'
```
Para los recursos devuelve `mixed`, ya que PHP no admite el tipo `resource`. Para las clases anónimas devuelve el nombre del ancestro más cercano, o `object`.
```php
$obj = new class extends Foo { };
$type = Type::fromValue($obj); // 'Foo'
```
getNames(): (string|array)[] .[method]
--------------------------------------
Devuelve un array de cadenas que representan los subtipos que componen un tipo compuesto. En los tipos intersection devuelve un array de arrays.
```php
$type = Type::fromString('string|null'); // o '?string'
$type->getNames(); // ['string', 'null']
$type = Type::fromString('(Foo&Bar)|string');
$type->getNames(); // [['Foo', 'Bar'], 'string']
```
getTypes(): Type[] .[method]
----------------------------
Devuelve un array de objetos `Type` que representan los subtipos que componen un tipo compuesto:
```php
$type = Type::fromString('string|null'); // o '?string'
$type->getTypes(); // [Type::fromString('string'), Type::fromString('null')]
$type = Type::fromString('(Foo&Bar)|string');
$type->getTypes(); // [Type::fromString('Foo&Bar'), Type::fromString('string')]
$type = Type::fromString('Foo&Bar');
$type->getTypes(); // [Type::fromString('Foo'), Type::fromString('Bar')]
```
getSingleName(): ?string .[method]
----------------------------------
En los tipos simples (incluidos los nullable simples, como `?string`) devuelve el nombre del tipo. En caso contrario devuelve null.
```php
$type = Type::fromString('string|null');
echo $type; // '?string'
echo $type->getSingleName(); // 'string'
$type = Type::fromString('?Foo');
echo $type; // '?Foo'
echo $type->getSingleName(); // 'Foo'
$type = Type::fromString('Foo|Bar');
echo $type; // 'Foo|Bar'
echo $type->getSingleName(); // null (es un tipo unión)
```
isSimple(): bool .[method]
--------------------------
Indica si es un tipo simple. Los tipos nullable simples (por ejemplo, `?string`, `?Foo`) cuentan también como simples:
```php
$type = Type::fromString('string');
$type->isSimple(); // true
$type->isUnion(); // false
$type = Type::fromString('?Foo'); // o 'Foo|null'
$type->isSimple(); // true
$type->isUnion(); // true (porque contiene null)
```
isUnion(): bool .[method]
-------------------------
Indica si es un tipo union (contiene `|`).
```php
$type = Type::fromString('Foo&Bar');
$type->isUnion(); // true
```
isIntersection(): bool .[method]
--------------------------------
Indica si es un tipo intersection (contiene `&`).
```php
$type = Type::fromString('Foo&Bar');
$type->isIntersection(); // true
```
isBuiltin(): bool .[method]
---------------------------
Indica si el tipo es simple y, a la vez, un tipo nativo de PHP (como `string`, `int`, `array`, `callable`, etc.).
```php
$type = Type::fromString('string');
$type->isBuiltin(); // true
$type = Type::fromString('string|int');
$type->isBuiltin(); // false
$type = Type::fromString('Foo');
$type->isBuiltin(); // false
```
isClass(): bool .[method]
-------------------------
Indica si el tipo es simple y, a la vez, un nombre de clase (y no un tipo nativo como `string` o `int`).
```php
$type = Type::fromString('string');
$type->isClass(); // false
$type = Type::fromString('Foo|null');
$type->isClass(); // true
$type = Type::fromString('Foo|Bar');
$type->isClass(); // false
```
isClassKeyword(): bool .[method]
--------------------------------
Indica si el tipo es una de las palabras clave internas `self`, `parent` o `static`.
```php
$type = Type::fromString('self');
$type->isClassKeyword(); // true
$type = Type::fromString('Foo');
$type->isClassKeyword(); // false
```
allows(string|Type $type): bool .[method]
-----------------------------------------
El método `allows()` comprueba la compatibilidad de tipos. Puede determinar, por ejemplo, si un valor de cierto tipo podría pasarse como parámetro a una función que espera este tipo.
```php
$type = Type::fromString('string|null');
$type->allows('string'); // true
$type->allows('null'); // true
$type->allows('Foo'); // false
$type = Type::fromString('mixed');
$type->allows('null'); // true
```
with(string|Type $type): Type .[method]{data-version:4.0.10}
------------------------------------------------------------
Devuelve un objeto Type que acepta tanto el tipo original como el que se añade. Crea lo que se conoce como tipo union.
El método es listo y no duplica tipos innecesariamente. Si añade un tipo que ya está presente, o que es un superconjunto del actual (por ejemplo, añadir `mixed` a `string`), el resultado se simplifica.
```php
$type = Type::fromString('string');
// Ampliación a string nullable
echo $type->with('null'); // '?string'
// Creación de un tipo unión
echo $type->with('int'); // 'string|int'
// Añadir un tipo que reemplaza a todo
echo $type->with('mixed'); // 'mixed'
```
Tipos de PHP
Nette\Utils\Type representa un tipo de
dato de PHP. Sirve para analizar, comparar y manipular tipos, tanto si proceden de una cadena como de la reflexión.
PHP tiene hoy un sistema de tipos muy rico: desde los tipos escalares (int, string), pasando por
objetos e interfaces, hasta los tipos complejos (union A|B, intersection A&B o las formas normales
disyuntivas (A&B)|D). Se añaden además tipos especiales como void, never,
mixed o los tipos relativos self y static.
Trabajar con estos tipos de forma nativa, sobre todo mediante ReflectionType, resulta a menudo incómodo, porque
hay que distinguir recursivamente entre ReflectionNamedType, ReflectionUnionType y otros objetos. La
clase Nette\Utils\Type encapsula todo eso y ofrece una API unificada e intuitiva para trabajar con cualquier
tipo admitido por PHP.
Le permite, por ejemplo, comprobar con facilidad si un tipo acepta otro (compatibilidad), ampliar tipos o convertir reflexiones en una notación legible.
Instalación:
composer require nette/utils
Todos los ejemplos suponen que está definido el siguiente alias de clase:
use Nette\Utils\Type;
fromReflection ($reflection): ?Type
Este método estático crea un objeto Type a partir de la reflexión. El parámetro puede ser un objeto
ReflectionMethod o ReflectionFunction (devuelve el tipo del valor de retorno), o un objeto
ReflectionParameter o ReflectionProperty. Resuelve self, static y
parent en el nombre real de la clase. Si el sujeto no tiene tipo, devuelve null.
class DemoClass
{
public self $foo;
}
$prop = new ReflectionProperty(DemoClass::class, 'foo');
echo Type::fromReflection($prop); // 'DemoClass'
fromString (string $type): Type
Este método estático crea un objeto Type a partir de su representación textual.
$type = Type::fromString('Foo|Bar');
echo $type; // 'Foo|Bar'
fromValue (mixed
$value): Type
Método estático que crea un objeto Type a partir del tipo del valor pasado.
$type = Type::fromValue('hello'); // 'string'
$type = Type::fromValue(123); // 'int'
$type = Type::fromValue(new stdClass); // 'stdClass'
Para los recursos devuelve mixed, ya que PHP no admite el tipo resource. Para las clases anónimas
devuelve el nombre del ancestro más cercano, o object.
$obj = new class extends Foo { };
$type = Type::fromValue($obj); // 'Foo'
getNames ():
(string|array)[]
Devuelve un array de cadenas que representan los subtipos que componen un tipo compuesto. En los tipos intersection devuelve un
array de arrays.
$type = Type::fromString('string|null'); // o '?string'
$type->getNames(); // ['string', 'null']
$type = Type::fromString('(Foo&Bar)|string');
$type->getNames(); // [['Foo', 'Bar'], 'string']
getTypes(): Type[]
Devuelve un array de objetos Type que representan los subtipos que componen un tipo compuesto:
$type = Type::fromString('string|null'); // o '?string'
$type->getTypes(); // [Type::fromString('string'), Type::fromString('null')]
$type = Type::fromString('(Foo&Bar)|string');
$type->getTypes(); // [Type::fromString('Foo&Bar'), Type::fromString('string')]
$type = Type::fromString('Foo&Bar');
$type->getTypes(); // [Type::fromString('Foo'), Type::fromString('Bar')]
getSingleName(): ?string
En los tipos simples (incluidos los nullable simples, como ?string) devuelve el nombre del tipo. En caso contrario
devuelve null.
$type = Type::fromString('string|null');
echo $type; // '?string'
echo $type->getSingleName(); // 'string'
$type = Type::fromString('?Foo');
echo $type; // '?Foo'
echo $type->getSingleName(); // 'Foo'
$type = Type::fromString('Foo|Bar');
echo $type; // 'Foo|Bar'
echo $type->getSingleName(); // null (es un tipo unión)
isSimple(): bool
Indica si es un tipo simple. Los tipos nullable simples (por ejemplo, ?string, ?Foo) cuentan también
como simples:
$type = Type::fromString('string');
$type->isSimple(); // true
$type->isUnion(); // false
$type = Type::fromString('?Foo'); // o 'Foo|null'
$type->isSimple(); // true
$type->isUnion(); // true (porque contiene null)
isUnion(): bool
Indica si es un tipo union (contiene |).
$type = Type::fromString('Foo&Bar');
$type->isUnion(); // true
isIntersection(): bool
Indica si es un tipo intersection (contiene &).
$type = Type::fromString('Foo&Bar');
$type->isIntersection(); // true
isBuiltin(): bool
Indica si el tipo es simple y, a la vez, un tipo nativo de PHP (como string, int, array,
callable, etc.).
$type = Type::fromString('string');
$type->isBuiltin(); // true
$type = Type::fromString('string|int');
$type->isBuiltin(); // false
$type = Type::fromString('Foo');
$type->isBuiltin(); // false
isClass(): bool
Indica si el tipo es simple y, a la vez, un nombre de clase (y no un tipo nativo como string o
int).
$type = Type::fromString('string');
$type->isClass(); // false
$type = Type::fromString('Foo|null');
$type->isClass(); // true
$type = Type::fromString('Foo|Bar');
$type->isClass(); // false
isClassKeyword(): bool
Indica si el tipo es una de las palabras clave internas self, parent o static.
$type = Type::fromString('self');
$type->isClassKeyword(); // true
$type = Type::fromString('Foo');
$type->isClassKeyword(); // false
allows (string|Type $type): bool
El método allows() comprueba la compatibilidad de tipos. Puede determinar, por ejemplo, si un valor de cierto
tipo podría pasarse como parámetro a una función que espera este tipo.
$type = Type::fromString('string|null');
$type->allows('string'); // true
$type->allows('null'); // true
$type->allows('Foo'); // false
$type = Type::fromString('mixed');
$type->allows('null'); // true
with (string|Type
$type): Type
Devuelve un objeto Type que acepta tanto el tipo original como el que se añade. Crea lo que se conoce como tipo union.
El método es listo y no duplica tipos innecesariamente. Si añade un tipo que ya está presente, o que es un superconjunto
del actual (por ejemplo, añadir mixed a string), el resultado se simplifica.
$type = Type::fromString('string');
// Ampliación a string nullable
echo $type->with('null'); // '?string'
// Creación de un tipo unión
echo $type->with('int'); // 'string|int'
// Añadir un tipo que reemplaza a todo
echo $type->with('mixed'); // 'mixed'