alexeyshockov/pattern-matcher

为 PHP 设计的模式匹配。

v0.1.1 2019-02-11 13:06 UTC

This package is auto-updated.

Last update: 2024-09-12 03:10:22 UTC


README

从函数式语言中提取的简单模式匹配技术。适用于 PHP。

示例

来自 schmittjoh/php-option 的 Option

use function PatternMatcher\option_matcher;

$matcher = option_matcher(function ($className, ReflectionClass $class) {
    return ($class->getName() == $className) || $class->isSubclassOf($className);
})
    ->addCase(InputInterface::class, $input)
    ->addCase(OutputInterface::class, $output)
    ->addCase(Output::class, new Output($output))
    ->addCase(HelperInterface::class, function (ReflectionClass $class) {
        foreach ($this->getHelperSet() as $helper) {
            if ($class->isInstance($helper)) {
                return $helper;
            }
        }

        throw new InvalidArgumentException("Helper with type " . $class->getName() . " is not registered.");
    })
;

$argument = $argumentDefinition->getClass()
    ->flatMap($matcher)
    ->getOrThrow(new InvalidArgumentException(
        'Parameter $' . $argumentDefinition->getName() . ': type is missed or not supported.'
    ));

或使用 ColadaX

use PatternMatcher\matcher;
use PatternMatcher\all;
use Colada\x;

matcher()
    ->addCase(all(x()->isActive(), x()->hasFriends()), )

或纯

$matcher = (new PatternMatcher(function ($className, ReflectionClass $class) {
    return ($class->getName() == $className) || $class->isSubclassOf($className);
}))
    ->addCase(InputInterface::class, $input)
    ->addCase(OutputInterface::class, $output)
    ->addCase(Output::class, new Output($output))
    ->addCase(HelperInterface::class, function (ReflectionClass $class) {
        foreach ($this->getHelperSet() as $helper) {
            if ($class->isInstance($helper)) {
                return $helper;
            }
        }

        throw new InvalidArgumentException("Helper with type " . $class->getName() . " is not registered.");
    })
;

$argument = $argumentDefinition->getClass()
    ->flatMap($matcher)
    ->getOrThrow(new InvalidArgumentException(
        'Parameter $' . $argumentDefinition->getName() . ': type is missed or not supported.'
    ));