-
-
Save oaass/4577325 to your computer and use it in GitHub Desktop.
<?php | |
$required = array('hostname', 'username', 'password', 'database', 'driver'); | |
$config = array( | |
'password' => 'pass', | |
'database' => 'mydb', | |
'charset' => 'utf8', | |
'port' => '1234' | |
); | |
$errors = array_diff($required, array_flip($config)); | |
$last = array_pop($errors); | |
$errmsg = 'Missing required configurations. No %s or %s has been configured'; | |
var_dump(sprintf($errmsg, implode(', ', $errors), $last)); |
Oh, what you shouldn't rely on is the order of the parameters (you do that when you use array_pop). Because the basic idea is "having a map", but a map has no ordered elements.
This could lead to bugs at a later point, when someone who modifies the order is not aware that he has to pay attention to the implementation.
Think about what another team member would do in a project to the code: he'd simply add a new value in $required. Then you're screwed.
Side-note: I'm talking about writing not only correct code, but also code that is resistent to bugs. Most bugs appear when you edit code, not when you write it for the first time.
Why is that? Because the programmer has to recreate a specific state of his brain when he edits that function/method.
And that one is hard.
PS: scratch some stuff I've said, they're not applicable in this case, now I've actually read the last line of code. I'll leave the comments here though, perhaps they help.
What stuff is it you think I should scratch? :)
@oaass starting with the second comment I said unapplicable stuff to this code. Using $last
could become dangerous and the principles I've outlined after the second comment would kick in, only if you use that variable for some "business logic", and not just error string formatting.
For instance, if you would also be doing:
if($last == 80) {
//assuming that $last is always the port number
}
@flavius yeah I agree $last can a "dangerous" variable for this. This was just for showing. It also requires for two elements to be missing as well. But it was just to illustrate that this was simpler than array_map. I wasn't actually able to make array_map work in this situation, which was why I looked elsewhere for a solution.
Sure, you can do many things in different ways. This is just an implementation detail, the basic idea is the same, and if you put it in a method, and then change its implementation, it won't have an effect on the overall architecture, there will be no BC breaks.