Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
106 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
<?php | ||
|
||
/** | ||
* For the full copyright and license information, please view | ||
* the LICENSE file that was distributed with this source code. | ||
*/ | ||
|
||
declare(strict_types=1); | ||
|
||
namespace loophp\TypedGenerators\Types\Hybrid; | ||
|
||
use Closure; | ||
use Iterator; | ||
use loophp\TypedGenerators\Types\TypeGenerator; | ||
|
||
/** | ||
* @template T | ||
* | ||
* @implements TypeGenerator<T> | ||
*/ | ||
final class Custom implements TypeGenerator | ||
{ | ||
/** | ||
* @var Closure(TypeGenerator<T>): T | ||
*/ | ||
private Closure $generator; | ||
|
||
/** | ||
* @var TypeGenerator<T> | ||
*/ | ||
private TypeGenerator $type; | ||
|
||
/** | ||
* @param TypeGenerator<T> $type | ||
* @param Closure(TypeGenerator<T>): T $generator | ||
*/ | ||
public function __construct(TypeGenerator $type, Closure $generator) | ||
{ | ||
$this->type = $type; | ||
$this->generator = $generator; | ||
} | ||
|
||
/** | ||
* @return T | ||
*/ | ||
public function __invoke() | ||
{ | ||
return $this->identity(($this->generator)($this->type)); | ||
} | ||
|
||
/** | ||
* @return Iterator<int, T> | ||
*/ | ||
public function getIterator(): Iterator | ||
{ | ||
// @phpstan-ignore-next-line | ||
while (true) { | ||
yield $this->__invoke(); | ||
} | ||
} | ||
|
||
/** | ||
* @param T $input | ||
* | ||
* @return T | ||
*/ | ||
public function identity($input) | ||
{ | ||
return $this->type->identity($input); | ||
} | ||
|
||
/** | ||
* @template V | ||
* | ||
* @param TypeGenerator<V> $type | ||
* @param Closure(TypeGenerator<V>): V $generator | ||
* | ||
* @return Custom<V> | ||
*/ | ||
public static function new(TypeGenerator $type, Closure $generator): self | ||
{ | ||
return new self($type, $generator); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters