Skip to editor
Psalm
Docs
Playground
Plugins
Blog
Paid support
Share
Fix issues
Show original
PHP
Settings
<?php class DecodeError extends Exception { } /** * @template A */ class Decoder { /** @var callable(mixed):A $f */ private $f; /** * @psalm-param callable(mixed):A $f */ function __construct($f) { $this->f = $f; } /** * @psalm-param mixed $x * @psalm-return A * @throws DecodeError */ function decode($x) { return call_user_func($this->f, $x); } } /** * @psalm-return Decoder<string> */ function string_(): Decoder { return new Decoder( /** @psalm-param mixed $x */ function ($x): string { if (is_string($x)) { return $x; } throw new DecodeError('Not a string'); } ); } /** * @psalm-return Decoder<int> */ function int_(): Decoder { return new Decoder( /** @psalm-param mixed $x */ function ($x): int { if (is_int($x)) { return $x; } throw new DecodeError('Not an int'); } ); } /** * @template T * @psalm-param array<T, Decoder> $arr * @psalm-return Decoder<array<T, mixed>> */ function assoc(array $arr): Decoder { return new Decoder( /** @psalm-param mixed $x */ function ($x) use ($arr) { $ret = []; foreach ($arr as $field => $decoder) { $val = isset($x[$field]) ? $x[$field] : null; try { $parsed_val = $decoder->decode($val); $ret[$field] = $parsed_val; } catch (DecodeError $e) { throw new DecodeError('Unable to decode array'); } } return $ret; } ); } $x = assoc(['field' => string_(), 'other' => int_()])->decode('1'); $x;
Issues
Types
idle
Saved Jun 15 2020 00:06 UTC
⌘/Ctrl+Enter
run
⌘/Ctrl+S
share
F8
/
⇧F8
next/prev issue