app-verk / php-matcher
PHP Matcher 的 AppVerk 扩展,它允许您使用模式匹配值
6.x-dev
2022-11-15 09:27 UTC
Requires
- php: ^7.4.2 || ~8.0 || ~8.1
- ext-filter: *
- ext-json: *
- ext-simplexml: *
- aeon-php/calendar: ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0 || ^0.18.0 || ^1.0
- coduo/php-to-string: ^3
- doctrine/lexer: ^1.0
Requires (Dev)
- openlss/lib-array2xml: ^1.0
- symfony/expression-language: ^2.3|^3.0|^4.0|^5.0
Suggests
- openlss/lib-array2xml: In order ot use AppVerk\PHPMatcher\Matcher\XmlMatcher
- symfony/expression-language: In order to use AppVerk\PHPMatcher\Matcher\ExpressionMatcher
This package is auto-updated.
Last update: 2024-09-15 13:27:26 UTC
README
创建库以测试所有种类的 JSON/XML/TXT/标量值与模式的匹配。
API
PHPMatcher::match($value = '{"foo": "bar"}', $pattern = '{"foo": "@string@"}') : bool; PHPMatcher::backtrace() : Backtrace; PHPMatcher::error() : ?string;
它被构建来简化 API 的功能测试。
安装
使用 composer 需要新的开发依赖
composer require --dev "app-verk/php-matcher"
基本用法
直接 PHPMatcher 使用
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $match = $matcher->match("lorem ipsum dolor", "@string@"); if (!$match) { echo "Error: " . $matcher->error(); echo "Backtrace: \n"; echo (string) $matcher->backtrace(); }
PHPUnit 扩展 PHPMatcherTestCase
<?php use AppVerk\PHPMatcher\PHPUnit\PHPMatcherTestCase; class MatcherTest extends PHPMatcherTestCase { public function test_matcher_that_value_matches_pattern() { $this->assertMatchesPattern('{"name": "@string@"}', '{"name": "Norbert"}'); } }
PHPUnit 使用 PHPMatcherAssertions 特性
<?php use AppVerk\PHPMatcher\PHPUnit\PHPMatcherAssertions; use PHPUnit\Framework\TestCase; class MatcherTest extends TestCase { use PHPMatcherAssertions; public function test_matcher_that_value_matches_pattern() { $this->assertMatchesPattern('{"name": "@string@"}', '{"name": "Norbert"}'); } }
可用模式
@string@
@integer@
@number@
@double@
@boolean@
@time@
@date@
@datetime@
@timezone@
或@tz
@array@
@array_previous@
- 使用前一个元素的匹配模式匹配下一个数组元素@array_previous_repeat@
- 使用前一个元素的匹配模式匹配所有剩余的数组元素@...@
- 无界数组,一旦使用匹配器,将跳过任何进一步的数组元素@null@
@*@
或@wildcard@
expr(expression)
- 可选,需要存在symfony/expression-language: ^2.3|^3.0|^4.0|^5.0
@uuid@
@ulid@
@json@
@string@||@integer@
- 字符串 或 整数@enum@
- 用于 PHP 后端枚举@tax_number@
- 匹配税识别号(仅 PL 格式)@regon@
- 匹配注册号(仅 PL 格式)
可用模式扩展器
startsWith($stringBeginning, $ignoreCase = false)
endsWith($stringEnding, $ignoreCase = false)
contains($string, $ignoreCase = false)
notContains($string, $ignoreCase = false)
isDateTime()
isInDateFormat($format)
- 示例"@datetime@.isInDateFormat('Y-m-d H:i:s')
before(string $date)
- 示例"@string@.isDateTime().before(\"2020-01-01 00:00:00\")"
after(string $date)
- 示例"@string@.isDateTime().after(\"2020-01-01 00:00:00\")"
isTzOffset()
isTzIdentifier()
isTzAbbreviation()
isEmail()
isUrl()
isIp()
isEmpty()
isNotEmpty()
lowerThan($boundry)
greaterThan($boundry)
inArray($value)
- 示例"@array@.inArray(\"ROLE_USER\")"
hasProperty($propertyName)
- 示例"@json@.hasProperty(\"property_name\")"
oneOf(...$expanders)
- 示例"@string@.oneOf(contains('foo'), contains('bar'), contains('baz'))"
matchRegex($regex)
- 示例"@string@.matchRegex('/^lorem.+/')
optional()
- 仅与ArrayMatcher
、JsonMatcher
和XmlMatcher
一起使用count()
- 仅与ArrayMatcher
一起使用 - 示例"@array@.count(5)"
repeat($pattern, $isStrict = true)
- 示例'@array@.repeat({"name": "foe"})'
或"@array@.repeat('@string@')
match($pattern)
- 示例{ "image":"@json@.match({\"url\":\"@string@.isUrl()\"})"}
isOneOf(class)
- 仅与EnumMatcher
一起使用,作为参数接受带命名空间的类名,例如@enum@.isOneOf('App\Domain\OrderStatus::class')
示例用法
标量匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(1, 1); $matcher->match('string', 'string');
字符串匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('Norbert', '@string@'); $matcher->match("lorem ipsum dolor", "@string@.startsWith('lorem').contains('ipsum').endsWith('dolor')");
时间匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('00:00:00', '@time@'); $matcher->match('00:01:00.000000', '@time@'); $matcher->match('00:01:00', '@time@.after("00:00:00")'); $matcher->match('00:00:00', '@time@.before("01:00:00")');
日期匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('2014-08-19', '@date@'); $matcher->match('2020-01-11', '@date@'); $matcher->match('2014-08-19', '@date@.before("2016-08-19")'); $matcher->match('2014-08-19', '@date@.before("today").after("+ 100year")');
日期时间匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('2014-08-19', '@datetime@'); $matcher->match('2020-01-11 00:00:00', '@datetime@'); $matcher->match('2014-08-19', '@datetime@.before("2016-08-19")'); $matcher->match('2014-08-19', '@datetime@.before("today").after("+ 100year")');
时区匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('Europe/Warsaw', '@timezone@'); $matcher->match('Europe/Warsaw', '@tz@'); $matcher->match('GMT', '@tz@'); $matcher->match('01:00', '@tz@'); $matcher->match('01:00', '@tz@.isTzOffset()'); $matcher->match('GMT', '@tz@.isTzAbbreviation()'); $matcher->match('Europe/Warsaw', '@tz@.isTzIdentifier()');
整数匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(100, '@integer@'); $matcher->match(100, '@integer@.lowerThan(200).greaterThan(10)');
数字匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(100, '@number@'); $matcher->match('200', '@number@'); $matcher->match(1.25, '@number@'); $matcher->match('1.25', '@number@'); $matcher->match(0b10100111001, '@number@');
双精度匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(10.1, "@double@"); $matcher->match(10.1, "@double@.lowerThan(50.12).greaterThan(10)");
布尔匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(true, "@boolean@"); $matcher->match(false, "@boolean@");
通配符匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match("@integer@", "@*@"); $matcher->match("foobar", "@*@"); $matcher->match(true, "@*@"); $matcher->match(6.66, "@*@"); $matcher->match(array("bar"), "@wildcard@"); $matcher->match(new \stdClass, "@wildcard@");
表达式匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(new \DateTime('2014-04-01'), "expr(value.format('Y-m-d') == '2014-04-01'"); $matcher->match("Norbert", "expr(value === 'Norbert')");
UUID 匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('9f4db639-0e87-4367-9beb-d64e3f42ae18', '@uuid@');
ULID 匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match('01BX5ZZKBKACTAV9WEVGEMMVS0', '@ulid@');
数组匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match( array( 'users' => array( array( 'id' => 1, 'firstName' => 'Norbert', 'lastName' => 'Orzechowicz', 'roles' => array('ROLE_USER'), 'position' => 'Developer', ), array( 'id' => 2, 'firstName' => 'Michał', 'lastName' => 'Dąbrowski', 'roles' => array('ROLE_USER') ), array( 'id' => 3, 'firstName' => 'Johnny', 'lastName' => 'DąbrowsBravoki', 'roles' => array('ROLE_HANDSOME_GUY') ) ), true, 6.66 ), array( 'users' => array( array( 'id' => '@integer@.greaterThan(0)', 'firstName' => '@string@', 'lastName' => 'Orzechowicz', 'roles' => '@array@', 'position' => '@string@.optional()' ), array( 'id' => '@integer@', 'firstName' => '@string@', 'lastName' => 'Dąbrowski', 'roles' => '@array@' ), '@...@' ), '@boolean@', '@double@' ) );
数组前一个
@array_previous@ 也可以用于匹配 JSON 和 XML
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match( array( 'users' => array( array( 'id' => 1, 'firstName' => 'Norbert', 'lastName' => 'Orzechowicz', 'roles' => array('ROLE_USER'), 'position' => 'Developer', ), array( 'id' => 2, 'firstName' => 'Michał', 'lastName' => 'Dąbrowski', 'roles' => array('ROLE_USER') ), array( 'id' => 3, 'firstName' => 'Johnny', 'lastName' => 'DąbrowsBravoki', 'roles' => array('ROLE_HANDSOME_GUY') ) ), true, 6.66 ), array( 'users' => array( array( 'id' => '@integer@.greaterThan(0)', 'firstName' => '@string@', 'lastName' => 'Orzechowicz', 'roles' => '@array@', 'position' => '@string@.optional()' ), '@array_previous@', '@array_previous@' ), '@boolean@', '@double@' ) );
数组前一个重复
@array_previous_repeat@ 也可以用于匹配 JSON 和 XML
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match( array( 'users' => array( array( 'id' => 1, 'firstName' => 'Norbert', 'lastName' => 'Orzechowicz', 'roles' => array('ROLE_USER'), 'position' => 'Developer', ), array( 'id' => 2, 'firstName' => 'Michał', 'lastName' => 'Dąbrowski', 'roles' => array('ROLE_USER') ), array( 'id' => 3, 'firstName' => 'Johnny', 'lastName' => 'DąbrowsBravoki', 'roles' => array('ROLE_HANDSOME_GUY') ) ), true, 6.66 ), array( 'users' => array( array( 'id' => '@integer@.greaterThan(0)', 'firstName' => '@string@', 'lastName' => 'Orzechowicz', 'roles' => '@array@', 'position' => '@string@.optional()' ), '@array_previous_repeat@' ), '@boolean@', '@double@' ) );
JSON 匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match( '{ "users":[ { "firstName": "Norbert", "lastName": "Orzechowicz", "created": "2014-01-01", "roles":["ROLE_USER", "ROLE_DEVELOPER"] } ] }', '{ "users":[ { "firstName": "@string@", "lastName": "@string@", "created": "@string@.isDateTime()", "roles": "@array@", "position": "@string@.optional()" } ] }' );
带有无界数组和对象的 JSON 匹配
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match( '{ "users":[ { "firstName": "Norbert", "lastName": "Orzechowicz", "created": "2014-01-01", "roles":["ROLE_USER", "ROLE_DEVELOPER"], "attributes": { "isAdmin": false, "dateOfBirth": null, "hasEmailVerified": true }, "avatar": { "url": "http://avatar-image.com/avatar.png" } }, { "firstName": "Michał", "lastName": "Dąbrowski", "created": "2014-01-01", "roles":["ROLE_USER", "ROLE_DEVELOPER", "ROLE_ADMIN"], "attributes": { "isAdmin": true, "dateOfBirth": null, "hasEmailVerified": true }, "avatar": null } ] }', '{ "users":[ { "firstName": "@string@", "lastName": "@string@", "created": "@string@.isDateTime()", "roles": [ "ROLE_USER", "@...@" ], "attributes": { "isAdmin": @boolean@, "@*@": "@*@" }, "avatar": "@json@.match({\"url\":\"@string@.isUrl()\"})" } , @...@ ] }' );
XML 匹配
可选 - 需要存在 openlss/lib-array2xml: ^1.0
。
<?php use AppVerk\PHPMatcher\PHPMatcher; $matcher = new PHPMatcher(); $matcher->match(<<<XML <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock"> <m:GetStockPrice> <m:StockName>IBM</m:StockName> <m:StockValue>Any Value</m:StockValue> </m:GetStockPrice> </soap:Body> </soap:Envelope> XML , <<<XML <?xml version="1.0"?> <soap:Envelope xmlns:soap="@string@" soap:encodingStyle="@string@"> <soap:Body xmlns:m="@string@"> <m:GetStockPrice> <m:StockName>@string@</m:StockName> <m:StockValue>@string@</m:StockValue> <m:StockQty>@integer@.optional()</m:StockQty> </m:GetStockPrice> </soap:Body> </soap:Envelope> XML );
使用 mongo 的 behat api 的示例场景。
@profile, @user Feature: Listing user toys As a user I want to list my toys Background: Given I send and accept JSON Scenario: Listing toys Given the following users exist: | firstName | lastName | | Chuck | Norris | And the following toys user "Chuck Norris" exist: | name | | Barbie | | GI Joe | | Optimus Prime | When I set valid authorization code oauth header for user "Chuck Norris" And I send a GET request on "/api/toys" Then the response status code should be 200 And the JSON response should match: """ [ { "id": "@string@", "name": "Barbie", "_links: "@*@" }, { "id": "@string@", "name": "GI Joe", "_links": "@*@" }, { "id": "@string@", "name": "Optimus Prime", "_links": "@*@" } ] """
PHPUnit 集成
assertMatchesPattern()
是一个实用的断言,用于在 PHPUnit 测试中匹配值。要使用它,请包含 AppVerk\PHPMatcher\PHPUnit\PHPMatcherAssertions
特性,或扩展 AppVerk\PHPMatcher\PHPUnit\PHPMatcherTestCase
namespace AppVerk\PHPMatcher\Tests\PHPUnit; use AppVerk\PHPMatcher\PHPUnit\PHPMatcherAssertions; use PHPUnit\Framework\TestCase; class PHPMatcherAssertionsTest extends TestCase { use PHPMatcherAssertions; public function test_it_asserts_if_a_value_matches_the_pattern() { $this->assertMatchesPattern('@string@', 'foo'); } }
在 PHPUnit 存根或模拟中可以使用 matchesPattern()
方法。
$mock = $this->createMock(Foo::class); $mock->method('bar') ->with($this->matchesPattern('@string@')) ->willReturn('foo');
许可证
此库遵循 MIT 许可证发布。请参阅 LICENSE 文件。