Skip to main content

Optional matches (Find first)

If you call first() on a subject that isn't matched by a pattern - SubjectNotMatchedException is thrown. We discussed that in the previous chapter.

But what if you expected the subject not to be matched? And how do you to react to it?

Optional matches with findFirst()#

Method findFirst() can be called with a callback (that accepts Detail) just like first(). The difference is: findFirst() never throws SubjectNotMatchedException, and allows you to control an unmatched subject by appropriate control methods: orThrow(), orReturn() and orElse().

For example:

return pattern('[0-9]+')->match("I'm 19 years old")
->findFirst()
->map(function (Detail $match) {
return "I was born $match years ago";
})
->orReturn('Unmatched :/');
'I was born 19 years ago'

If a match is found, then the result of findFirst() callback is returned. If a match is not found, however, then the handling of an unmatched subject lies in the chained method.

orReturn()#

If a match is not found, it returns a default value.

return pattern('[0-9]+')->match("I'm a dog")
->findFirst()
->map(function (Detail $match) {
return "I was born $match years ago";
})
->orReturn("Match is not found");
'Match is not found'

orElse()#

If a match is not found, it calls orElse() callback and uses it to evaluate a return value.

return pattern('[0-9]+')->search("I'm a dog")
->findFirst()
->map(function (string $match) {
return "I was born $match years ago";
})
->orElse(function () {
return "I couldn't match subject";
});
"I couldn't match subject"

orThrow()#

Returns the optional value, or throws the specified exception.

class MyException extends \Exception {}
try {
return pattern('[0-9]+')->match("I'm a dog")
->findFirst(function (Detail $detail) {
return "Match is found!";
})
->orThrow(new MyException());
}
catch (MyException $e) {
// React to an unmatched subject
echo "Not matched";
}
Last updated on