yuloh / pattern-recognition
此包已被废弃且不再维护。未建议替代包。
数组模式的匹配库
v0.1.0
2016-03-28 18:32 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ^5.2
This package is auto-updated.
Last update: 2021-11-23 07:25:22 UTC
README
PHP数组的模式匹配器。
需要根据数组的键值对子集选择数组吗?比如说你有
['x' => 1] -> A ['x' => 1, 'y' => 1] -> B ['x' => 1, 'y' => 2 ] -> C
那么这个库会给你
['x' => 1] -> A ['x' => 2] -> no match ['x' => 1, 'y' => 1] -> B ['x' => 1, 'y' => 2] -> C ['x' => 2, 'y' => 2] -> no match ['y' => 1] -> no match
快速示例
$pm = new Yuloh\PatternRecognition\Matcher; $pm ->add(['a' => 1], 'A') ->add(['b' => 2], 'B'); $pm->find(['a' => 1]); // returns 'A' $pm->find(['a' => 2]); // returns null $pm->find(['a' => 1, 'b' => 1]); // returns 'A'. 'b' => 1 is ignored, it was never registered.
由于你匹配的是子集,所以要查找的模式可以包含任意数量的额外键值对。
安装
composer require yuloh/pattern-recognition
原因
由于这个库是javascript库patrun的移植,其理由相同。这个库让你构建简单的决策树以避免编写if语句。
规则
- 更具体的匹配胜过更不具体的匹配。也就是说,更多的键值对胜过更少的。
- 数组键按字母顺序检查。
- 精确匹配比通配符匹配更具体。
- 匹配比根匹配更具体。
$pm = (new Matcher()) ->add(['a' => 0], 'A') ->add(['c' => 2], 'C') ->add(['a' => 0, 'b' => 1], 'AB') ->(['a' => '*'], 'AG') ->add([], 'R'); $pm->find(['a' => 0, 'b' => 1]); // 'AB', because more specific matches beat less specific matches. $pm->find(['a' => 0, 'c' => 2]); // 'A', because a comes before c and keys are checked in alphabetical order. $pm->find(['a' => 0]); // 'A' as exact match, because exact matches are more specific than globs. $pm->find(['a' => 2]); // 'AG' as glob match, as matches are more specific than root matches. $pm->find(['b' => 2]); // 'R', as root match.
API
add(array $pattern, mixed $data)
注册一个模式,并返回如果输入匹配的数据。键和值都被视为字符串。其他类型被转换为字符串。
remove(array $pattern)
从匹配器中删除此模式及其数据。
find(array $pattern)
查找给定的模式并返回其数据。
jsonSerialize()
将对象序列化为可以被json_encode()原生序列化的值。
toArray()
将匹配器序列化为已注册匹配和数据的数组。