Skip to content

Improvement converted json type #468

Open
@filippeb

Description

@filippeb

Is your feature request related to a problem?
Not a problem, a proposal for a convenience addition to \Psl\Json\typed conversion.

Describe the solution you'd like
A converted type function for json data (see below snippet) usable on convert shapes.

Describe alternatives you've considered
Can be achieved with current Psl but is a bit more verbose

Snippet

/**
 * @template D
 * @template O
 *
 * @param TypeInterface<D>     $decoded   decoded json type
 * @param TypeInterface<O>     $into
 * @param null|(Closure(D): O) $converter argument is the decoded json value of type $from
 *
 * @return TypeInterface<O>
 */
function convertedJson(TypeInterface $decoded, TypeInterface $into, ?\Closure $converter = null): TypeInterface
{
    return new Internal\ConvertedType(
        string(),
        $into,
        null === $converter
            ? static fn(string $json): mixed => $into->assert(typed($json, $decoded)) // if the decoded json type is the same as the 'into' type
            : static fn(string $json): mixed => $converter(typed($json, $decoded))
    );
}

Metadata

Metadata

Assignees

Labels

Type: EnhancementMost issues will probably ask for additions or changes.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions