$keys = array( "layerName", "lat", "lon", "radius","CHECKBOXLIST");
$value = array();
try {
foreach( $keys as $key ) {
if ( isset($_GET[$key]) )
$value[$key] = $_GET[$key];
else
throw new Exception($key ." parameter is not passed in GetPOI request.");
}//foreach
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
This code written is to get values of the parameters from GET requests. If Any of these parameters is not passed in GET request, it should raise an exception. but in this case, it doesnot. What could be the problem?
$_GET[$key] is probably set but has no value, so it will assign an empty string value to $value[$key] instead of throwing a new exception. I would rewrite your if statement to check for empty value instead.
if ( isset($_GET[$key]) === true && empty($_GET[$key]) === false )
{
$value[$key] = $_GET[$key];
}
elseif ( isset($_GET[$key]) === true && empty($_GET[$key]) === true)
{
throw new Exception($key ." parameter is not passed in GetPOI request.");
break;
}
Try adding a break after throwing the exception. Like this:
if ( isset($_GET[$key]) )
$value[$key] = $_GET[$key];
else{
throw new Exception($key ." parameter is not passed in GetPOI request.");
break;
}
--EDIT--
I have to quickly add that i tried running your code and raised an exception as expected.
Related
Problem
Hey, my array $isActiefErr and $naamErr doesn't fill up after I throw an exception, but the foreach loop does continue to validate the values. I know the foreach loop keeps on looping, because the array which should have all the values is filled, but the error array stops after it encounters its first error.
What I have tried:
I've tried to print the array but it only pushes the first error into my array. It then stops validating. This also shows in my error log. I think the problem would be the try/catch, but I simply cannot confirm this, because of my lack of knowledge regarding try/catches.
Question
How can I get the array to push and display all the errors with a try/catch block surrounding it? Or am I simply missing something and isn't the problem related to the try/catch?
This is my code:
$validateOk = 0;
$setVar = new SetVariable();
$teller = 1;
$save = null;
$validateOk = 0;
$con->beginTransaction();
$weg = TypeQuery::create()->find();
$weg->delete();
try {
foreach ($_POST as $key => $value) {
if (isEven($teller)) {
$validateOk += $setVar->nameval($key)
->onerror($isActiefErr[]) //errors aren't being pushed into this array, besides the first one.
->validator(v::numericVal())
->go();
if ($validateOk == 0) {
$save->setCode(substr($key, 1));
$save->setIsActief($value);
$save->save();
} else {
//ROLLBACK/CATCH
throw new Exception($error);
}
} else {
$validateOk += $setVar->nameval($key)
->onerror($naamErr[])
->validator(v::alpha('/()éá&., '))
->go();
if ($validateOk == 0) {
$save = new Type();
$save->setCode(substr($key, 1));
$save->setNaam($value);
} else {
//ROLLBACK/CATCH
throw new Exception($error);
}
}
$teller += 1;
}
$con->commit();
} catch (Exception $e) {
$error = "Het opslaan is fout gegaan!";
} {
$con->rollback();
}
I try to listen for the value of a variable and execute some code if it has a specific value.
e.g. I execute the function element() inside a switch statement and I have to execute break if the value of $element is false.
At the moment I do it like this:
switch(strtolower($testcase)) {
case 'test':
$element = $sel->element("class name", "btn-primary", true);
if ($element == false) { break; }
$element->click("");
...
public function element($using, $value, $takeScreenshot=false, $customMessage="")
{
try {
$element = $this->driver->element($using, $value);
} catch(PHPWebDriver_UnhandledWebDriverError $exception) {
$msg = "<b>PHPWebDriver_UnhandledWebDriverError: $using</b> is "
. "not a valid value for the parameter <b>\$using</b>!";
if ($customMessage !== "") {
$msg = "<b>$customMessage</b><br>$msg";
}
$this->setMessage(1, $msg, $exception, $takeScreenshot, $value);
return false;
} catch(PHPWebDriver_NoSuchElementWebDriverError $exception) {
$msg = "<b>PHPWebDriver_NoSuchElementWebDriverError:</b> No "
. "Element with <b>'$using'</b> and value <b>'$value'</b> found !";
if ($customMessage !== "") {
$msg = "<b>$customMessage</b><br>$msg";
}
$this->setMessage(1, $msg, $exception, $takeScreenshot, $value);
return false;
}
return $element;
}
But I would like to simplify it so that the line if ($element == false) { break; } is not needed anymore. e.g.
switch(strtolower($testcase)) {
case 'test':
$element = $this->element("class name", "btn-primary", true);
$element->click("");
...
I tried to return break; but this failed. Is there another way? e.g. can I add an EventListener which executes break automatically in the switch case if the value of $element is false?
When building functions, it's usually best to design them to be de-coupled, not coupled. This means, element() shouldn't care about what is calling it.
Therefore, attempting to break a switch from within element() would be a bad programming design.
If element() should always stop execution when it hits a certain spot, regardless of what called it, you should consider throwing an exception. However, this won't simplify the code in your switch statement as you'd have to use try, catch blocks.
With that said, since PHP allows assignments in conditionals, you could simplify the code you have written as:
if ($element = $sel->element("class name", "btn-primary", true)) {
$element->click("");
}
This is a long shot question, but is there a way in php to exit an "if" statement and continue on to the "else" statement if an error occurs inside the if block?
example
if ($condition == "good")
{
//do method one
//error occurs during method one, need to exit and continue to else
}
else
{
//do method two
}
Of course it is possible to do a nested if inside the first if, but that seems hacky.
TIA
try {
//do method one
//error occurs during method one, need to exit and continue to else
if ($condition != "good") {
throw new Exception('foo');
}
} catch (Exception $e) {
//do method two
}
I would just use a function so you don't duplicate code:
if ($condition == "good") {
//do method one
//error occurs during method one
if($error == true) {
elsefunction();
}
} else {
elsefunction();
}
function elsefunction() {
//else code here
}
Should that be possible?
Anyway you might consider changing it to.
$error = "";
if ($condition == "good") {
if (/*errorhappens*/) { $error = "somerror"; }
}
if (($condition != "good") || ($error != "") ) {
//dostuff
}
You could modify methodOne() such that it returns true on success and false on error:
if($condition == "good" && methodOne()){
// Both $condition == "good" and methodOne() returned true
}else{
// Either $condition != "good" or methodOne() returned false
}
Assuming that methodOne returns false on error :
if !($condition == "good" && methodOne())
{
//do method two
}
you really need this? i think no... but you can hack..
do{
$repeat = false;
if ($condition == "good")
{
//do method one
$condition = "bad";
$repeat = true;
}
else
{
//do method two
}
}while( $ok ) ;
I advise on methods to separate...
I find using switches instead of if...else are handy for doing this: Omitting a break statement makes the switch fall through to the next case:
switch ($condition) {
case 'good':
try {
// method to handle good case.
break;
}
catch (Exception $e) {
// method to handle exception
// No break, so switch continues to default case.
}
default:
// 'else' method
// got here if condition wasn't good, or good method failed.
}
if ($condition == "good") {
try{
method_1();
}
catch(Exception $e){
method_2();
}
}
else {
method_2();
}
function method_2(){
//some statement
}
I'd like some help please, if its possible.
I have created two functions in order to display some messages when is set a $_GET after a redirect.Here's the code:
function display(){
if(isset($_GET['cnf_upd']) && $_GET['cnf_upd'] == '1'){
$value = "The update was successful!";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_upd']) && $_GET['err_upd'] == '1'){
$value = "The Update failed.";
$type = "error";
construct_the_div($value, $type);
}
if(isset($_GET['cnf_del']) && $_GET['cnf_del'] == '1'){
$value = "Deleted completely.";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_del']) && $_GET['err_del'] == '1'){
$value = "Unable to delete.";
$type = "error";
construct_the_div($value, $type);
}
}
function construct_the_div($value, $type){
// creating a div to display the message results
$div = "<div class=\"{$type}Msg\">\n";
$div .= "<p>{$value}</p>\n";
$div .= "</div><!-- end of {$type}Msg -->\n";
echo $div;
}
What I'd like to make is to try to improve the display function, as it gets longer and longer, so that there whould be only one (or two at most) if statement(s) if possible. So the value of the GET will be dynamicly inside the if condition and also if it has the preffix 'cnf_' it wil be a 'confirmMsg' and if it has the preffix 'err_' it wil be a 'errorMsg'.
Is it possible to make something like this???
function display() {
$messages = array(
'cnf_upd' => 'The update was successful!',
'cnf_err' => 'The Update failed.!',
// ...
// add all error and confirm there
// ...
);
foreach($_GET as $key => $value) {
if(strpos($key, 'cnf_')===0) {
$type = 'confirm';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
if(strpos($key, 'err_')===0) {
$type = 'error';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
}
}
The approach is not correct, it seems that only one message should occur at once (there cannot be "deleted completely" and "unable to delete" at once).
Try construct the parameters this way: ?msg=upd&msgType=cnf
function display(){
if (isset($_GET['msg']) && isset($_GET['msgType']))
{
$messages = array('cnf_upd'=>'The update was successful!',
'err_upd'=>'The update failed!',
'cnf_del'=>'The deletion was successful!',
'cnf_upd'=>'The deletion failed!',
);
if (isset($messages[$_GET['msgType'].'_'.$_GET['msg']))
construct_the_div($messages[$_GET['msgType'].'_'.$_GET['msg']], htmlspecialchars($_GET['msgType']));
}
there is still much to improve, but for start this is cleaner and safer.
I'm going to propose a different solution. Instead of setting different parameters in $_GET based on the message to be sent, set one parameter and parse its value.
// Start by setting integer constants:
define(CNF_UPD, 1);
define(ERR_UPD, 2);
define(CNF_DEL, 3);
define(ERR_DEL, 4);
Then when you set the value un $_GET, use the constant:
// Build the URL with a deletion error...
header("Location: http://example.com/script.php?msg=" . ERR_DEL);
Finally, use a switch to parse them
if (isset($_GET['msg'])) {
switch ($_GET['msg']) {
case CNF_UPD:
// Updated...
break;
case ERR_UPD:
// failed...
break;
// etc...
default:
// invalid code.
}
}
If you use a pattern of confirm/error/confirm/error for your integer constants, you can determine which it is by taking $_GET['msg'] % 2. Odd numbers are confirmations, evens are errors. There are of course many other ways you could lay this out, I just happen to have typed them in the alternating order you used. You could also do positive integers for confirmations and negatives for errors, for example.
$type = $_GET['msg'] % 2 == 1 ? $confirm : $error;
This is easily expanded to use multiple messages as well. Since they are integer values, you can safely construct a comma-separated list and explode() them when received.
$messages = implode(array(ERR_DEL,CNF_UPD));
header("Location: http://example.com/script.php?msg=$messages");
Unless you can somehow generate $value and $type based on the $_GET parameter (which I can't see how you would do), you could do something like:
$messages = array();
$messages[] = array('id' => 'cnf_upd', 'value' => 'The update was successful!', 'type' => 'Confirm');
$messages[] = array('id' => 'err_upd', 'value' => 'The Update failed.', 'type' => 'error');
...
foreach ($messages as $message) {
if(isset($_GET[$message['id']]) && $_GET[$message['id']] == '1'){
construct_the_div($message['value'], $message['type']);
}
}
I have a rather big if statement:
if (!$result_spam)
{
$confrim_spam = "FAILED";
}
else if ($result_spam)
{
$confrim_spam = "PASSED";
}
if (!$result_email_manage)
{
$confrim_email_manage = "FAILED";
}
else if ($result_email_manage)
{
$confrim_email_manage = "PASSED";
}
if (!$result_analyt)
{
$confrim_analytics = "FAILED";
}
else if ($result_analyt)
{
$confrim_analytics = "PASSED";
}
Now I want to do another if statement to check if all have PASSED or if all have FAILED or is some have PASSED and some have FAILED and then echo (do something with) the failed ones.
I know how to check if all have passed or failed:
if ($confirm_spam == "PASSED" AND $confirm_analytics == "PASSED"
but to check if some have passed and some haven't and then find the ones that failed will take too long, right?
I was just wondering, would there be an easier/quicker way to do this?
Since they are all bools anyway:
if($result_spam && $result_email_manage && $result_analyt){
//do all passed
}
elseif($result_spam || $result_email_manage || $result_analyt){
//at least one passed
if(!$result_spam){ echo '$result_spam failed';}
if(!$result_email_manage){ echo '$result_email_manage failed';}
if(!$result_analyt){ echo '$result_analyt failed';}
}
else {
//do all failed
}
You can change validation logic to something like
$passed = array();
$failed = array();
if (!$result_spam)
{
array_push($failed, "confirm_spam");
}
else
{
array_push($passed, "confirm_spam");
}
...
Then you have an easy and clear way to check whether all passed/failed and which tests are failed.
What if you try this way:
$passed = $failed = "";
$all = array("confrim_spam" => $result_spam,
"confrim_email_manage" => $result_email_manage,
"confrim_analytics" => $result_analyt);
foreach($all as $a => $b)
{
if (!$b)
$failed.= $a . ", ";
else
$passed.= $a . ", ";
}
Then if var $passed is empty, none passed else if $failed is not empty, at last one have not passed.. so do you got what passed and what failed and do something with them. And you can store results both in a string or an array whatever you want...