Skip to content
Search
Examples

Types

Description

Type assertions validate values at runtime and throw InvalidArgumentException if the value doesn't match the expected type.
The assert() method returns the validated value with proper type narrowing, enabling static analysis tools like
PHPStan to understand the resulting type. This provides IDE autocompletion and catches type errors during analysis.

<?php

$value = takeFromUser(); // $value is type mixed here

$stringValue = type_string()->assert($value); 

// $valueString is type string here, it's called types narrowing 

Read more about types narrowing


Assert JSON data from strings or arrays. Converts to the Json value object for safe data access and manipulation.

Documentation

Code

<?php

declare(strict_types=1);

use function Flow\Types\DSL\type_json;
use Flow\Types\Value\Json;

require __DIR__ . '/vendor/autoload.php';

echo 'From Json string: ' . type_json()->assert(Json::fromString('{"user":"john","active":true}'))->toString() . "\n";
echo 'From Json array: ' . type_json()->assert(Json::fromArray(['product' => 'Widget', 'price' => 29.99]))->toString() . "\n";
Contributors

Built in the open.

Join us on GitHub
scroll back to top