elodgy/parity-checker

此包已被废弃且不再维护。作者建议使用benjaminmal/parity-checker包。

奇偶校验器

v2.0.0 2022-09-05 20:49 UTC

README

Continuous integration

PHP奇偶校验器。当您想检查多个对象是否具有相同的属性时非常有用。它具有许多选项,您可以根据需要配置行为,特别是针对对象递归。

安装

$ composer require benjaminmal/parity-checker

入门

使用工厂创建奇偶校验器

$parityChecker = ParityChecker::create();

或者使用Symfony的PropertyAccessPropertyInfo组件实现您的版本

/** @var PropertyAccessorInterface $propertyAccessor */
/** @var PropertyInfoExtractorInterface $propertyInfoExtractor */

$parityChecker = new ParityChecker($propertyAccessor, $propertyInfoExtractor);

检查您的对象

$errors = $parityChecker->checkParity([$object1, $object2]);
if (! $errors->hasErrors()) {
    // You're all set !
}

用法

选项

$errors = $parityChecker->checkParity([$object1, $object2], [
    // Do not perform check on these types
    'ignore_types' => ['object', 'resource', \DateTimeInterface::class, '$objectProperty1'],
    
    // Perform check only on these types
    'only_types' => ['string', 'float'],

    // Perform a loose check ('==' instead of '===') on theses types
    'loose_types' => 'array',

    // Set the recursion limit for objects
    'deep_object_limit' => 0,
    
    // Set DateTime format to check
    'datetime_check_format' => false,
    
    // Set DateInterval format to check
    'date_interval_format' => '%R %Y %M %D %H %I %S %F',
    
    // Set DateTime zone mapping to name
    'datetime_zone' => true,
    
    // Set a data mapper closure
    'data_mapper' => [
        'my-mapper' => new ParityCheckerCallback(
            'array',
            fn ($value, string $property, array $options): mixed => $value['something'],
        ),
    ],
    
    // Custom checkers. You can set you own checker which replace other.
    'custom_checkers' => [
        'my-checker' => new ParityCheckerCallback(
            ['$property'],
            fn ($value1, $value2, string $property, array $options): bool => true,
        ),
    ],
]);

错误

$errors = $parityChecker->checkParity([$object1, $object2], $options);

if ($errors->hasError()) {
    foreach ($errors as $error) {
        $property = $error->getProperty();
        $object1 = $error->getObject1();
        $object2 = $error->getObject2();

        $errorValue1 = $error->getObject1Value();
        $errorValue2 = $error->getObject2Value();
    }
}