datashaman/array-filter

将数组与过滤器匹配

0.1.1 2014-07-11 16:26 UTC

This package is auto-updated.

Last update: 2024-09-24 16:06:14 UTC


README

将优秀的JavaScript库mmckegg/json-filter直接移植到PHP。

感谢Matt McKegg创建了这样一个非常有用、经过良好测试的软件。

匹配PHP数组与过滤器。

Build Status

安装

$ composer require datashaman/array-filter

过滤器

过滤器只是具有您想要最终数组具有的键和值的数组。例如,如果您希望字段 type 总是 person,则过滤器将是 {type: 'person'}

如果情况不是那么黑白分明,以下条件可用

$present

指定值必须不为null或false(即'truthy')。

array(
  'name' => array( '$present' => true )
)

$any

指定值可以是任何东西。当匹配所有键时很有用。

array(
  'description' => array( '$any' => true )
)

$contains

用于与数组匹配。数组必须包含指定的所有值。

array(
  'tags' => array( '$contains' => array( 'cat', 'animal' ) )
)

$excludes

用于与数组匹配。数组不能包含指定的任何值。

array(
  'permissions' => array( '$excludes' => array( 'admin', 'mod' ) )
)

$only

值只能是指定的其中一个。

array(
  'gender' => array( '$only' => array( 'male', 'female', 'unknown' ) )
)

$not

值可以是除了指定的任何一个之外的任何值。

array(
  'browser' => array( '$not' => array( 'IE', 'Firefox' ) )
)

$matchAny

允许过滤器在至少有一个匹配时分支到多个过滤器。

array(
  '$matchAny' => array(
    array( 'type' => "Post",
      'state' => array( '$only' => array( 'draft', 'published' ) )
    ),
    array( 'type' => "Comment",
      'state' => array( '$only' => array( 'pending', 'approved', 'spam' ) )
    )
  )
)

$query

指定一个查询以获取匹配的值。使用 options.queryHandler

array(
  'type' => 'item',
  'user_id' => array( '$query' => 'user.id' )
)

$optional

同时指定多个$any过滤器的快捷方式。

array(
  '$optional' => array( 'description', 'color', 'age' )
)

相当于

array(
  'description' => array( '$any' => true ),
  'color' => array( '$any' => true ),
  'age' => array( '$any' => true )
)

API

use DataShaman\ArrayFilter;

$filter = new ArrayFilter;
$filter->checkFilter($source, $filter, $options);

checkFilter(source, filter, options)

options

  • match: 指定: 'filter', 'source', 'any', 'all'
    • filter: 每个过滤器权限都必须满足(即必填字段)
    • source: 每个源键都必须在过滤器中指定
    • any: 键不重要,但如果匹配,它们必须通过
    • all: 所有键必须完全相同,否则失败 - 用于查找更改的项目 - 此模式中不工作任何$conditionals
  • queryHandler: 接受一个函数(query, localContext)返回结果值
  • context: 传递给查询处理器的数组