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?
findFirst()
Optional matches with Method findFirst()
can be called with a callback (that accepts Match
details) 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:
- T-Regx
- PHP
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 relies in the chained method.
orReturn()
If a match is not found, it returns a default value.
- T-Regx
- PHP
orElse()
If a match is not found, it calls orElse()
callback and uses it to evaluate a return value.
- T-Regx
- PHP
Callback of orElse()
is called with NotMatched
, which contains only a handful of methods
present in Match
: subject()
, groupNames()
, groupsCount()
and hasGroup($nameOrIndex)
.
orThrow()
If a match is not found, it throws SubjectNotMatchedException
by default.
- T-Regx
- PHP
orThrow()
Custom exceptions for You can also supply your own exception class name.
- T-Regx
- PHP
Of course, your custom exception must meet certain requirements:
It has to be a class
Trying to instantiate interfaces or abstract classes would break our "Explicity rule" The class must be concrete and explicit.
It has to implement
\Throwable
Obviously.
It must have a suitable constructor
The class must be instantiable with one of the following signatures and parameter types.
__construct()
__construct($message)
, where$message
can be a string__construct($message, $subject)
, where$message
and$subject
can be strings
Notice, that using
findFirst()->orThrow()
without your custom exception is identical tofirst()
.
I don't like functional
If you don't like functional programming style, you are free to use first()
(which throws an exception) and just catch it.
- T-Regx
- PHP