hoaproject / Ruler

The Hoa\Ruler library.
https://hoa-project.net
625 stars 66 forks source link

How can I check that array contain sub array? #103

Closed ManasAtabaev closed 7 years ago

ManasAtabaev commented 7 years ago

Hi, Need check that some array contain subarray, only way I find create rule for all items in subarray, like "item1 in ['item1', 'item2', 'item3', 'item4', 'item5'] and item2 in ['item1', 'item2', 'item3', 'item4', 'item5'] and item5 in ['item1', 'item2', 'item3', 'item4', 'item5']" Thanks!

Hywan commented 7 years ago

Hello 😄,

I think creating an operator for that would be appropriate, like is_subset_of:

$ruler->getDefaultAsserter()->setOperator('is_subset_of', function (array $needles, array $haystack): bool {
    foreach ($needles as $needle) {
        if (false === in_array($needle, $haystack)) {
            return false;
        }
    }

    return true;
});

then:

[item1, item2, item5] in ['item1', 'item2', 'item3', 'item4', 'item5']

Not tested, but it should work.

Is it clear?

ManasAtabaev commented 7 years ago

Thank you, it work perfect! Also one more question, is it possible to return on which value test was stopped? Is there a way to return the rule operator and the value in case error occurs during the check?

$ruler->getDefaultAsserter()->setOperator('is_subset_of', function (array $needles, array $haystack) {
    foreach ($needles as $needle) {
        if (false === in_array($needle, $haystack)) {
            if($this->returnError) {
               return $needle;
           }
            return false;
        }
    }
    return true;
});
Hywan commented 7 years ago

@Commander223 There is no error API yet. You might want to check #41. cc @vonglasow

ManasAtabaev commented 7 years ago

@Hywan Ok. Thx for help.

Hywan commented 7 years ago

You're welcome! Feel free to ask anything else! And thanks for using our libraries 😃.

Hywan commented 7 years ago

@Commander223 Are you still living in Kyrgizstan? If yes, can you come on IRC (freenode #hoaproject), I would have some questions for you 😉.