Skip to content

Commit

Permalink
Add IdentityTypeResolver and TypeResolvers composite
Browse files Browse the repository at this point in the history
  • Loading branch information
vudaltsov committed Aug 11, 2024
1 parent 41cd19f commit 7cea755
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Type/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.4.4]

### Added

- Add `IdentityTypeResolver` — a type resolver that resolves to the passed type.
- Add `TypeResolvers` — a composite for type resolvers.

## [0.4.3] 2024-08-06

### Added
Expand Down
19 changes: 19 additions & 0 deletions src/Type/Visitor/IdentityTypeResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace Typhoon\Type\Visitor;

use Typhoon\Type\Type;

/**
* @api
* @extends DefaultTypeVisitor<Type>
*/
final class IdentityTypeResolver extends DefaultTypeVisitor
{
protected function default(Type $type): Type
{
return $type;
}
}
44 changes: 44 additions & 0 deletions src/Type/Visitor/TypeResolvers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Typhoon\Type\Visitor;

use Typhoon\Type\Type;
use Typhoon\Type\TypeVisitor;

/**
* @api
* @extends DefaultTypeVisitor<Type>
*/
final class TypeResolvers extends DefaultTypeVisitor
{
/**
* @param list<TypeVisitor<Type>> $resolvers
* @return TypeVisitor<Type>
*/
public static function from(array $resolvers): TypeVisitor
{
return match (\count($resolvers)) {
0 => new IdentityTypeResolver(),
1 => $resolvers[0],
default => new self($resolvers),
};
}

/**
* @param non-empty-list<TypeVisitor<Type>> $resolvers
*/
private function __construct(
private readonly array $resolvers,
) {}

protected function default(Type $type): mixed
{
foreach ($this->resolvers as $resolver) {
$type = $type->accept($resolver);
}

return $type;
}
}

0 comments on commit 7cea755

Please sign in to comment.