I have an example array:
$array = [
[
FirstClass,
SecondClass,
ThirdClass,
],
[
ThirdClass,
MaxClass
],
[
FirstClass,
ThirdClass
],
[
SecondClass,
FirstClass,
]
];
I would like to check if MaxClass exists and additionally throw an error if there is more than one.
So I do:
foreach ($array as $class) {
if (get_class($class) == 'MaxClass') {
//different operations
}
}
For checking I'm adding:
$count = 0;
foreach ($array as $class) {
if (get_class($class) == 'MaxClass') {
if ($count < 2) {
//different operations
} else {
throw new Exception('Too many MaxClass!');
}
}
}
But maybe is better way than using variable $count?
Second question - what Exception class should I use? Maybe RuntimeException?
You can use flag variable to check : Try this solution :
$found_max_class=false;
foreach ($array as $class) {
if (get_class($class) == 'MaxClass') {
if($found_max_class)
{
throw new Exception('Too many MaxClass!');
}
$found_max_class =true;
}
}
I'd go for something like this with a functional approach:
class ReachedMaxLimitException extends LogicException {}
$count = array_reduce(
call_user_func_array('array_merge', $array), // flatten array
function ($count, $o) { return $count + ($o instanceof MaxClass); },
0
);
if ($count > 1) {
raise new ReachedMaxLimitException;
}
Obviously that divorces the sanity check from your "// different operations", but that's also exactly the point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With