在Laravel中自定义验证功能

时间:2019-02-18 08:39:46

标签: algorithm validation laravel-5

我很好奇($value & ($value - 1)) != 0,它在下面的验证中如何工作以知道数字是2的幂?!

function ($attribute, $value, $fail) {
                    if ($value == 0 || ($value & ($value - 1)) != 0) {
                        $fail($attribute . ' is not power of 2!');
                    }
                }

如果我想获得除2的幂之外的2的幂之间的数字,我该怎么办?我可以使用和修改此命令吗? (例如数字:1、2、3、4、6、8、12、16等)

2 个答案:

答案 0 :(得分:1)

根据Bit Twiddling HacksPHP Bitwise Operators

public function rules()
{
    return [
        'threshold' => [
            'required',
            'between:1,1000',
            function ($attribute, $value, $fail) {
                $err_message = "Given Value is not acceptable";
                $next_power_of_2 = $value-1;
                $next_power_of_2 |= $next_power_of_2 >> 1;
                $next_power_of_2 |= $next_power_of_2 >> 2;
                $next_power_of_2 |= $next_power_of_2 >> 4;
                $next_power_of_2 |= $next_power_of_2 >> 8;
                $next_power_of_2 |= $next_power_of_2 >> 16;
                //closest upper power 2 to given number
                $next_power_of_2++;
                //closes lower power 2 number to given value
                $previous_power_of_2 = $next_power_of_2 >> 1;

                if ($value == 0) $fail($err_message);//check number is zero

                else if (($value & ($value - 1)) == 0) {}//check number is power of 2

                else if (($next_power_of_2 + $previous_power_of_2) / 2 != $value) //check number is between two power of 2
                    $fail($err_message);
            },
        ]
    ];
}

答案 1 :(得分:0)

我解决了算法。我为算法创建了一个规则对象:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class DoubleThreshold implements Rule
{
    public function passes($attribute, $value)
    {
        $issue = floor(log($value, 2));
        $power1 = pow(2, $issue);
        $power2 = pow(2, $issue - 1);
        $power3 = $power1 + $power2;

        if ($value == 1 || $value == $power1 || $value == $power2 || $value == $power3)
            return true;
        return false;
    }

    public function message()
    {
        return 'The :attribute is not in consider numbers!';
    }
}

要使用上述规则,我做了这样的事情:

public function rules()
{
    return [
        'threshold' => ['required', 'between:1,1000', new DoubleThreshold]
     ];
}