1. Go to this page and download the library: Download decodelabs/coercion 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/ */
decodelabs / coercion example snippets
use DecodeLabs\Coercion;
class MyClass {
protected string $string;
protected ?string $optionalString;
protected int $int;
public function __construct(array $params) {
$this->string = Coercion::asString($params['maybeString']); // Throw on error
$this->string = Coercion::toString($params['maybeString']); // Convert to empty string on error
$this->optionalString = Coercion::tryString($params['maybeString']);
}
}
// String
Coercion::asString($value): string // Throws exception on error
Coercion::tryString($value, bool $nonEmpty = true): ?string
Coercion::toString($value): string
Coercion::isStringable($value): bool
// Bool
Coercion::toBool($value): bool
Coercion::tryBool($value): ?bool
Coercion::parseBool($value): ?bool // Only returns true for strings if string is boolsy
// Int
Coercion::asInt($value): int // Throws exception on error
Coercion::tryInt($value): ?int
Coercion::toInt($value): int
Coercion::clampInt($value, int $min, int $max): int
// Float
Coercion::asFloat($value): float // Throws exception on error
Coercion::tryFloat($value): ?float
Coercion::toFloat($value): float
Coercion::clampFloat($value, float $min, float $max): float
Coercion::clampDegrees($value, float $min, float $max): float
// Array
Coercion::asArray($value): array // Throws exception on error
Coercion::tryArray($value): ?array
Coercion::toArray($value): array
// Iterable
Coercion::asIterable($value): iterable // Throws exception on error
Coercion::tryIterable($value): ?iterable
Coercion::toIterable($value): iterable
Coercion::iterableToArray($value): array
// Object
Coercion::asObject($value): object // Throws exception on error
Coercion::tryObject($value): ?object
Coercion::toObject($value): object
// stdClass
Coercion::asStdClass($value): stdClass // Throws exception on error
Coercion::tryStdClass($value): ?stdClass
Coercion::toStdClass($value): stdClass
// Type
Coercion::asType($value, class-string<T> $type): T // Throws exception on error
Coercion::tryType($value, class-string<T> $type): ?T
// Lazy
Coercion::newLazyGhost(class-string<T> $type, callable $callback): T
Coercion::newLazyProxy(class-string<T> $type, callable $callback): T
// DateTime
Coercion::asDateTime($value): DateTimeInterface // Throws exception on error
Coercion::tryDateTime($value): ?DateTimeInterface
Coercion::toDateTime($value): DateTimeInterface // Defaults to now
// DateInterval
Coercion::asDateInterval($value): DateInterval // Throws exception on error
Coercion::tryDateInterval($value): ?DateInterval
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.