Match for PHP 7.3 and PHP 7.4
You can install the package using composer:
composer require lukasss93/smatch
Structure of a smatch function
$result = smatch('apple')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->get();
// $result = 'delicious'
Case methods value can accept a closure too.
$result = smatch('apple')
->case('pear', fn () => 'tasty')
->case('apple', fn () => 'delicious')
->case('banana', fn () => 'yellow')
->get();
// $result = 'delicious'
Case method may contain an array of values
$result = smatch('chair')
->case(['apple', 'pear', 'banana'], 'fruit')
->case(['table', 'chair'], 'furniture')
->get();
// $result = 'furniture'
A special case is the fallback pattern. This pattern matches anything that wasn't previously matched.
$result = smatch('strawberry')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->fallback('invalid')
->get();
// $result = 'invalid'
Fallback method can accept a closure too.
$result = smatch('strawberry')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->fallback(fn () => 'invalid')
->get();
// $result = 'invalid'
Note: Multiple fallback methods will override the last one.
A smatch function must be exhaustive. If the subject function is not handled by any case method an UnhandledSmatchException is thrown.
Example of an unhandled smatch function
try {
$result = smatch('strawberry')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->get();
} catch (UnhandledSmatchException $e){
echo $e->getMessage();
}
// $e->getMessage() = Unhandled smatch value of type string
Using getOr method to handle missing fallback method
$result = smatch('car')
->case('pear', 'tasty')
->case('apple', 'delicious')
->case('banana', 'yellow')
->getOr(fn () => 'complex logic');
// $result = 'complex logic'
It is possible to use a smatch function to handle non-identity conditional cases by using true as the subject function.
Using a generalized smatch function to branch on integer ranges
$age = 23;
$result = smatch(true)
->case($age >= 65, 'senior')
->case($age >= 25, 'adult')
->case($age >= 18, 'young adult')
->fallback('kid')
->get();
// $result = 'young adult'
Using a generalized smatch function to branch on string content
$text = 'Bienvenue chez nous';
$result = smatch(true)
->case(str_contains($text, 'Welcome') || str_contains($text, 'Hello'), 'en')
->case(str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour'), 'fr')
->get();
// $result = 'fr'
composer test
Please see the CHANGELOG.md for more information on what has changed recently.
Please see the LICENSE.md file for more information.