PHP code example of signpostmarv / daft-typed-object
1. Go to this page and download the library: Download signpostmarv/daft-typed-object library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
signpostmarv / daft-typed-object example snippets
use SignpostMarv\DaftTypedObject\Immutable as Base;
use SignpostMarv\DaftTypedObject\Immutable as Base;
/**
* @psalm-type DATA = array{id:int, name:string}
*
* @template-extends Base<DATA, DATA>
*/
class Immutable extends Base
{
const TYPED_PROPERTIES = ['id', 'name'];
/**
* @readonly
*/
public int $id;
/**
* @readonly
*/
public string $name;
}
use SignpostMarv\DaftTypedObject\DaftTypedObject as Base;
/**
* @psalm-type DATA = array{id:int, name:string}
*
* @template-extends Base<DATA, DATA>
*/
class Mutable extends Base
{
const TYPED_PROPERTIES = ['id', 'name'];
public int $id;
public string $name;
}
use DateTimeImmutable;
use SignpostMarv\DaftTypedObject\DaftTypedObject as Base;
/**
* @template T as array{id:int, name:string, date:DateTimeImmutable|null}
* @template S as array{id:int, name:string, date:string|null}
*
* @template-extends Base<T, S>
*
* @property-read int $id
* @property-read string $name
* @property-read DateTimeImmutable $date
*/
class MutableWithNullables extends Base
{
const TYPED_PROPERTIES = ['id', 'name', 'date'];
const TYPED_NULLABLE_PROPERTIES = ['date'];
/**
* @var int
*/
protected $id;
/**
* @var string|null
*/
protected $name;
/**
* @var DateTimeImmutable|null
*/
protected $date;
/**
* @template K as key-of<T>
*
* @param K $property
* @param T[K] $value
*
* @return S[K]
*/
public static function PropertyValueToScalarOrNull(
string $property,
$value
) {
/**
* @var T[K]|DateTimeImmutable
*/
$value = $value;
if ($value instanceof DateTimeImmutable) {
/**
* @var S[K]
*/
return (string) $value->format('Y-m-d');
}
/**
* @var S[K]
*/
return parent::PropertyValueToScalarOrNull((string) $property, $value);
}
/**
* @template K as key-of<S>
*
* @param K|'date' $property
* @param S[K] $value
*
* @return T[K]
*/
public static function PropertyScalarOrNullToValue(
string $property,
$value
) {
/**
* @var S[K]|string
*/
$value = $value;
if ('date' === $property && is_string($value)) {
$out = new DateTimeImmutable($value);
} else {
/**
* @var S[K]
*/
$value = $value;
/**
* @var T[K]
*/
$out = parent::PropertyScalarOrNullToValue(
(string) $property,
$value
);
}
/**
* @var T[K]
*/
return $out;
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.