Nette Documentation Preview

syntax
Tipi di PHP
***********

.[perex]
[api:Nette\Utils\Type] rappresenta un tipo di dato di PHP. Serve ad analizzare, confrontare e manipolare i tipi, che provengano da una stringa o dalla reflection.

PHP ha oggi un sistema di tipi molto ricco: dai tipi scalari (`int`, `string`), agli oggetti e alle interfacce, fino ai tipi complessi (unione `A|B`, intersezione `A&B` o forme normali disgiuntive `(A&B)|D`). Esistono inoltre tipi speciali come `void`, `never`, `mixed` oppure i tipi relativi `self` e `static`.

Lavorare con questi tipi in modo nativo, soprattutto tramite `ReflectionType`, è spesso macchinoso, perché dovete distinguere ricorsivamente tra `ReflectionNamedType`, `ReflectionUnionType` e altri oggetti. La classe `Nette\Utils\Type` racchiude tutto questo e offre un'**API unificata e intuitiva** per lavorare con qualsiasi tipo supportato da PHP.

Vi permette per esempio di controllare facilmente se un tipo ne [accetta|#allows()] un altro (compatibilità), di [estendere i tipi|#with()] o di convertire le reflection in una notazione leggibile.

Installazione:

```shell
composer require nette/utils
```

Tutti gli esempi presuppongono che sia definito questo alias di classe:

```php
use Nette\Utils\Type;
```


fromReflection($reflection): ?Type .[method]
--------------------------------------------

Questo metodo statico crea un oggetto `Type` a partire da una reflection. Il parametro può essere un oggetto `ReflectionMethod` o `ReflectionFunction` (restituisce il tipo del valore di ritorno), oppure un oggetto `ReflectionParameter` o `ReflectionProperty`. Risolve `self`, `static` e `parent` nel nome di classe effettivo. Se il soggetto non ha alcun tipo, restituisce `null`.

```php
class DemoClass
{
	public self $foo;
}

$prop = new ReflectionProperty(DemoClass::class, 'foo');
echo Type::fromReflection($prop); // 'DemoClass'
```


fromString(string $type): Type .[method]
----------------------------------------

Questo metodo statico crea un oggetto `Type` dalla sua rappresentazione testuale.

```php
$type = Type::fromString('Foo|Bar');
echo $type;      // 'Foo|Bar'
```


fromValue(mixed $value): Type .[method]{data-version:4.0.10}
------------------------------------------------------------

Metodo statico che crea un oggetto Type in base al tipo del valore passato.

```php
$type = Type::fromValue('hello'); // 'string'
$type = Type::fromValue(123);     // 'int'
$type = Type::fromValue(new stdClass); // 'stdClass'
```

Per le risorse restituisce `mixed`, perché PHP non supporta il tipo `resource`. Per le classi anonime restituisce il nome dell'antenato più vicino oppure `object`.

```php
$obj = new class extends Foo { };
$type = Type::fromValue($obj);    // 'Foo'
```


getNames(): (string|array)[] .[method]
--------------------------------------

Restituisce un array di stringhe che rappresentano i sottotipi di cui è composto un tipo complesso. Per i tipi intersezione restituisce un array di array.

```php
$type = Type::fromString('string|null'); // oppure '?string'
$type->getNames();  // ['string', 'null']

$type = Type::fromString('(Foo&Bar)|string');
$type->getNames();  // [['Foo', 'Bar'], 'string']
```


getTypes(): Type[] .[method]
----------------------------

Restituisce un array di oggetti `Type` che rappresentano i sottotipi di cui è composto un tipo complesso:

```php
$type = Type::fromString('string|null'); // oppure '?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]
----------------------------------

Per i tipi semplici (compresi i semplici tipi nullable come `?string`) restituisce il nome del tipo. Altrimenti restituisce 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 (è un tipo unione)
```


isSimple(): bool .[method]
--------------------------

Indica se si tratta di un tipo semplice. Tra i tipi semplici rientrano anche i semplici tipi nullable (per esempio `?string`, `?Foo`):

```php
$type = Type::fromString('string');
$type->isSimple();       // true
$type->isUnion();        // false

$type = Type::fromString('?Foo'); // oppure 'Foo|null'
$type->isSimple();       // true
$type->isUnion();        // true (perché contiene null)
```


isUnion(): bool .[method]
-------------------------

Indica se si tratta di un tipo unione (contiene `|`).

```php
$type = Type::fromString('Foo&Bar');
$type->isUnion();        // true
```


isIntersection(): bool .[method]
--------------------------------

Indica se si tratta di un tipo intersezione (contiene `&`).


```php
$type = Type::fromString('Foo&Bar');
$type->isIntersection(); // true
```


isBuiltin(): bool .[method]
---------------------------

Indica se il tipo è semplice ed è anche un tipo integrato di PHP (come `string`, `int`, `array`, `callable` ecc.).

```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 se il tipo è semplice ed è anche un nome di classe (non un tipo integrato come `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 se il tipo è una delle parole chiave interne `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]
-----------------------------------------

Il metodo `allows()` controlla la compatibilità dei tipi. Può per esempio stabilire se un valore di un certo tipo può essere passato come parametro a una funzione che si aspetta questo 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}
------------------------------------------------------------

Restituisce un oggetto Type che accetta sia il tipo originale sia quello aggiunto. Crea cioè un tipo unione.

Il metodo è intelligente e non duplica inutilmente i tipi. Se aggiungete un tipo già presente, oppure che è un sovrainsieme del tipo corrente (per esempio aggiungendo `mixed` a `string`), il risultato viene semplificato.

```php
$type = Type::fromString('string');

// estensione a string nullable
echo $type->with('null'); // '?string'

// creazione di un tipo unione
echo $type->with('int');  // 'string|int'

// aggiunta di un tipo che ingloba tutto
echo $type->with('mixed'); // 'mixed'
```

Tipi di PHP

Nette\Utils\Type rappresenta un tipo di dato di PHP. Serve ad analizzare, confrontare e manipolare i tipi, che provengano da una stringa o dalla reflection.

PHP ha oggi un sistema di tipi molto ricco: dai tipi scalari (int, string), agli oggetti e alle interfacce, fino ai tipi complessi (unione A|B, intersezione A&B o forme normali disgiuntive (A&B)|D). Esistono inoltre tipi speciali come void, never, mixed oppure i tipi relativi self e static.

Lavorare con questi tipi in modo nativo, soprattutto tramite ReflectionType, è spesso macchinoso, perché dovete distinguere ricorsivamente tra ReflectionNamedType, ReflectionUnionType e altri oggetti. La classe Nette\Utils\Type racchiude tutto questo e offre un'API unificata e intuitiva per lavorare con qualsiasi tipo supportato da PHP.

Vi permette per esempio di controllare facilmente se un tipo ne accetta un altro (compatibilità), di estendere i tipi o di convertire le reflection in una notazione leggibile.

Installazione:

composer require nette/utils

Tutti gli esempi presuppongono che sia definito questo alias di classe:

use Nette\Utils\Type;

fromReflection($reflection): ?Type

Questo metodo statico crea un oggetto Type a partire da una reflection. Il parametro può essere un oggetto ReflectionMethod o ReflectionFunction (restituisce il tipo del valore di ritorno), oppure un oggetto ReflectionParameter o ReflectionProperty. Risolve self, static e parent nel nome di classe effettivo. Se il soggetto non ha alcun tipo, restituisce null.

class DemoClass
{
	public self $foo;
}

$prop = new ReflectionProperty(DemoClass::class, 'foo');
echo Type::fromReflection($prop); // 'DemoClass'

fromString(string $type)Type

Questo metodo statico crea un oggetto Type dalla sua rappresentazione testuale.

$type = Type::fromString('Foo|Bar');
echo $type;      // 'Foo|Bar'

fromValue(mixed $value): Type

Metodo statico che crea un oggetto Type in base al tipo del valore passato.

$type = Type::fromValue('hello'); // 'string'
$type = Type::fromValue(123);     // 'int'
$type = Type::fromValue(new stdClass); // 'stdClass'

Per le risorse restituisce mixed, perché PHP non supporta il tipo resource. Per le classi anonime restituisce il nome dell'antenato più vicino oppure object.

$obj = new class extends Foo { };
$type = Type::fromValue($obj);    // 'Foo'

getNames(): (string|array)[]

Restituisce un array di stringhe che rappresentano i sottotipi di cui è composto un tipo complesso. Per i tipi intersezione restituisce un array di array.

$type = Type::fromString('string|null'); // oppure '?string'
$type->getNames();  // ['string', 'null']

$type = Type::fromString('(Foo&Bar)|string');
$type->getNames();  // [['Foo', 'Bar'], 'string']

getTypes(): Type[]

Restituisce un array di oggetti Type che rappresentano i sottotipi di cui è composto un tipo complesso:

$type = Type::fromString('string|null'); // oppure '?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

Per i tipi semplici (compresi i semplici tipi nullable come ?string) restituisce il nome del tipo. Altrimenti restituisce 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 (è un tipo unione)

isSimple(): bool

Indica se si tratta di un tipo semplice. Tra i tipi semplici rientrano anche i semplici tipi nullable (per esempio ?string, ?Foo):

$type = Type::fromString('string');
$type->isSimple();       // true
$type->isUnion();        // false

$type = Type::fromString('?Foo'); // oppure 'Foo|null'
$type->isSimple();       // true
$type->isUnion();        // true (perché contiene null)

isUnion(): bool

Indica se si tratta di un tipo unione (contiene |).

$type = Type::fromString('Foo&Bar');
$type->isUnion();        // true

isIntersection(): bool

Indica se si tratta di un tipo intersezione (contiene &).

$type = Type::fromString('Foo&Bar');
$type->isIntersection(); // true

isBuiltin(): bool

Indica se il tipo è semplice ed è anche un tipo integrato di PHP (come string, int, array, callable ecc.).

$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 se il tipo è semplice ed è anche un nome di classe (non un tipo integrato come 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 se il tipo è una delle parole chiave interne self, parent o static.

$type = Type::fromString('self');
$type->isClassKeyword();   // true

$type = Type::fromString('Foo');
$type->isClassKeyword();   // false

allows(string|Type $type)bool

Il metodo allows() controlla la compatibilità dei tipi. Può per esempio stabilire se un valore di un certo tipo può essere passato come parametro a una funzione che si aspetta questo 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

Restituisce un oggetto Type che accetta sia il tipo originale sia quello aggiunto. Crea cioè un tipo unione.

Il metodo è intelligente e non duplica inutilmente i tipi. Se aggiungete un tipo già presente, oppure che è un sovrainsieme del tipo corrente (per esempio aggiungendo mixed a string), il risultato viene semplificato.

$type = Type::fromString('string');

// estensione a string nullable
echo $type->with('null'); // '?string'

// creazione di un tipo unione
echo $type->with('int');  // 'string|int'

// aggiunta di un tipo che ingloba tutto
echo $type->with('mixed'); // 'mixed'