Morf 用于批量过滤请求参数。它通过一个定义数组来配置每个感兴趣的参数,并返回有效的类型转换值;当出现明显错误时,它会抛出异常。

v1.1.0 2023-11-13 13:21 UTC

This package is auto-updated.

Last update: 2024-09-13 14:57:46 UTC


README

Morf 用于批量过滤请求参数 en masse。它通过一个定义数组描述您感兴趣的每个参数,并返回有效的类型转换值;当出现明显错误时,它会抛出异常。

出于安全考虑,Morf 严格且具有意见,尽可能使用 PHP 内置函数。

示例

正如这个示例所展示的,它相当简单

use DanBettles\Morf\Filter;

$definitions = [
    [
        'name' => 'anything',  // N.B. `name` is the only required element
        // 'type' => 'string',  // The default output-type
    ],
    [
        'name' => 'show_retirement',
        'type' => 'bool',  // Or use `"boolean"`
        // 'default' => false,  // The built-in default value
    ],
    [
        'name' => 'show_under_offer',
        'type' => 'bool',
        'default' => true,  // N.B. the same type as named in `type`
    ],
    [
        'name' => 'location_id',
        'type' => 'int',  // Or use `"integer"`
        'default' => 7,
        'validator' => 'positiveInteger',  // The name of a validator method in `DanBettles\Morf\Validators`
    ],
    [
        'name' => 'num_rooms',
        'type' => 'int',
        'default' => 0,  // Indicates "any" in this example
        'validValues' => [0, 1, 2, 3],  // `validValues` will override `validator` if both elements are present
    ],
    [
        'name' => 'a_floating_point_number',
        'type' => 'float',  // Or use `"double"`
    ],
    [
        'name' => 'an_array',
        'type' => 'array',
    ],
];

// Empty request, defaults applied:

$actual = Filter::create($definitions)->filter([]);

$expected = [
    'anything' => '',
    'show_retirement' => false,
    'show_under_offer' => true,
    'location_id' => 7,
    'num_rooms' => 0,
    'a_floating_point_number' => 0.0,
    'an_array' => [],
];

assert($expected === $actual);

// Form submitted, say:

$actual = Filter::create($definitions)->filter([
    'anything' => 'Hello, World!',
    'show_retirement' => '0',
    'show_under_offer' => '0',
    'location_id' => '2',
    'num_rooms' => '2',
    'a_floating_point_number' => '3.142',
    'an_array' => ['foo', 'bar', 'baz'],
]);

$expected = [
    'anything' => 'Hello, World!',
    'show_retirement' => false,
    'show_under_offer' => false,
    'location_id' => 2,
    'num_rooms' => 2,
    'a_floating_point_number' => 3.142,
    'an_array' => ['foo', 'bar', 'baz'],
];

assert($expected === $actual);

有效输入

默认值

每个输出类型的内置默认值(当参数未设置时返回的值)与在 Symfony\Component\HttpFoundation\ParameterBag 中使用的相同,我们认为这些值是直观的。如果您不同意,或者您的应用程序需要不同的值,没有问题,因为您可以指定参数级别的默认值—见上面的示例