What's the best way to write this in PHP, so I know which condition fails and is easy to maintain? Without resorting to multiple if else statements...
if ((!$titleBlockPresent || !$leadBlock || ($allDoubleBlockCount !=2 || $allDoubleBlockCount!=1) ||$countFirstSmallShowBlocks !=2 ||$countSecondSmallShowBlocks !=2 ) && !$contentNotAvailableMessage)
{
$this->fail("Block missing in the horizontal list of blocks on the non live carousel");
}
try this
$shouldFail = FALSE;
switch(TRUE){
case !titleBlockPresent:
echo "No title block present<br/>";
$shouldFail = TRUE;
case !$leadBlock:
echo "No lead block<br/>";
// the rest of the code
}
If you move that check into the function, it'll be clear for you and anyone else looking at your code, and very easy to maintain, for example:
function tester($var1, $var2, $var3)
{
if (!$var1)
{
$this->fail("error1");
return FALSE;
}
if (!$var2)
{
$this->fail("error2");
return FALSE;
}
if (!$var3)
{
$this->fail("error3");
return FALSE;
}
return TRUE;
}
You could also add a comment to each if that needs further clarification.
I just come up with this, but noticed that it is very similar to GeoPhoenix's answer, just the other way around, may be worth checking this out, as well:
$bFail = false;
if(!$bFail && $contentNotAvailableMessage) $bFail = true;
if(!$bFail && !$titleBlockPresent ) $bFail = true;
if(!$bFail && !$leadBlock ) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 2) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 1) $bFail = true;
if(!$bFail && $countFirstSmallShowBlocks != 2) $bFail = true;
if(!$bFail && $countSecondSmallShowBlocks != 2) $bFail = true;
if($bFail) $this->fail("Block missing in the horizontal list of blocks on the non live carousel");
Related
I have this php code associated with a database and I need here to make a complete email and name validation
based on this code how can I do that because my code has some issues here
1)name key doesn't have (//) or any symbols to be a correct name
2)email key is valid email because what we did here just make ensure that there is # symbol and if I type the email hhhh#hhh.com or even without( .com ) it will be valid also ?!!
if(array_key_exists("submit",$_POST)){
$link = mysqli_connect("localhost","root","123456789","users");
if(mysqli_connect_error()){
die("There is a problem in connecting to database");
}
if(!$_POST['name']){
$error .="<p>Your Full name is required</p><br>";
}
if(!$_POST['email']){
$error .="<p>Your email address is required</p><br>";
}
if(!$_POST['password']){
$error .="<p>Your password is required</p><br>";
}
if($error !=""){
$error = "<p>There were errors in your form</p><br>".$error;
}
}
You can use this function for the validation:
function filtervariable($string,$type,$method) {
//function for sanitizing variables using PHPs built-in filter methods
$validEmail = false;
if ($method == 'sanitize') {
$filtermethod = 'FILTER_SANITIZE_';
} elseif ($method == 'validate') {
$filtermethod = 'FILTER_VALIDATE_';
} else {
return;
}
switch ($type) {
case 'email':
case 'string':
case 'number_int':
case 'int':
case 'special_chars':
case 'url':
$filtertype = $filtermethod.strtoupper($type);
break;
}
if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
list($local,$domain) = explode('#',$string);
$localLength = strlen($local);
$domainLength = strlen($domain);
$checkLocal = explode('.',$domain);
if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
$validEmail = true;
} else {
$validEmail = false;
}
}
if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
return filter_var($string, constant($filtertype));
} else {
return false;
}
}
And use it like this:
$email = filtervariable($registeremail,'email','validate');
It will return "true" on success and "false" on failure.
I'm new to prestashop and I'm having major trouble removing the address(I want to have only Summary=Shrnutí, Login/Guest Checkout=Přihlásit se, Delivery=Doručení and Payment=Platba here https://www.enakupak.cz/objednavka?step=1) step,. I am using prestashop 1.6.1.5
I know I have to modify order-carrier.tpl file and have followed several posts here and there but couldn't get it done right.
Does any of you have any actual idea on how to do this ?
I think that it will be change in this part of OrderController.php but dont know how to concretly change it
switch ((int)$this->step) {
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
case OrderController::STEP_DELIVERY:
if (Tools::isSubmit('processAddress')) {
$this->processAddress();
}
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
break;
case OrderController::STEP_PAYMENT:
// Check that the conditions (so active) were accepted by the customer
$cgv = Tools::getValue('cgv') || $this->context->cookie->check_cgv;
if ($is_advanced_payment_api === false && Configuration::get('PS_CONDITIONS')
&& (!Validate::isBool($cgv) || $cgv == false)) {
Tools::redirect('index.php?controller=order&step=2');
}
if ($is_advanced_payment_api === false) {
Context::getContext()->cookie->check_cgv = true;
}
// Check the delivery option is set
if ($this->context->cart->isVirtualCart() === false) {
if (!Tools::getValue('delivery_option') && !Tools::getValue('id_carrier') && !$this->context->cart->delivery_option && !$this->context->cart->id_carrier) {
Tools::redirect('index.php?controller=order&step=2');
} elseif (!Tools::getValue('id_carrier') && !$this->context->cart->id_carrier) {
$deliveries_options = Tools::getValue('delivery_option');
if (!$deliveries_options) {
$deliveries_options = $this->context->cart->delivery_option;
}
foreach ($deliveries_options as $delivery_option) {
if (empty($delivery_option)) {
Tools::redirect('index.php?controller=order&step=2');
}
}
}
}
$this->autoStep();
// Bypass payment step if total is 0
if (($id_order = $this->_checkFreeOrder()) && $id_order) {
if ($this->context->customer->is_guest) {
$order = new Order((int)$id_order);
$email = $this->context->customer->email;
$this->context->customer->mylogout(); // If guest we clear the cookie for security reason
Tools::redirect('index.php?controller=guest-tracking&id_order='.urlencode($order->reference).'&email='.urlencode($email));
} else {
Tools::redirect('index.php?controller=history');
}
}
$this->_assignPayment();
if ($is_advanced_payment_api === true) {
$this->_assignAddress();
}
// assign some informations to display cart
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'order-payment.tpl');
break;
default:
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
}
What if you cann this code after first case - break:
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
After this case add this case:
case OrderController::STEP_ADDRESSES:
$this->_assignAddress();
$this->processAddressFormat();
if (Tools::getValue('multi-shipping') == 1) {
$this->_assignSummaryInformations();
$this->context->smarty->assign('product_list', $this->context->cart->getProducts());
$this->setTemplate(_PS_THEME_DIR_.'order-address-multishipping.tpl');
} else {
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
}
break;
Check, is it work.
I have written a ternary function in PHP and it seems to work, although I am not sure if it is correct, can someone take a look and tell me if it is right?
I have added the ternary and the if of what should be happening.
//Foreach Loop
foreach ($post as $item) {
//If of what should occur
if ($passed == true) {
if (is_numeric($item)) {
if ($item > 0) {
$passed = true;
}
else {
$passed = false;
}
}
else {
if ($item != "") {
$passed = true;
}
else {
$passed = false;
}
}
//Ternary operator.
$passed = (is_numeric($item) ? ($item > 0 ? true : false) : ($item != "" ? true : false));
}
else {
return $passed;
}
}
please have a look on corrected code
$passed = (is_numeric($item))?($item>0?true:false):($item !="" ? true:false);
Honestly I do not really understand why you do not use a
if (!empty($item)) {
$passed = true;
} else {
return false;
}
In any case, ternaries are less readable than if /elseif / else, they are also slower (note that it is not an universal truth but a more general use case thing http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html).
I would recommend, if you really need all these if and elses to keep them rather than using ternaries (for readability's purpose).
I'm trying to convert some old code by converting to mysqli. Unfortunately I can't figure out what part of the code is trying to do, so I don't know how to change it. It seems to be a standard safety check that everyone who uses the original mysql extension used, but I can't find anyone who explains why. Here is the original code:
function query($query = "", $transaction = FALSE)
{
//
// Remove any pre-existing queries
//
unset($this->query_result);
if( $query != "" )
{
$this->num_queries++;
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
{
$result = mysql_query("BEGIN", $this->db_connect_id);
if(!$result)
{
return false;
}
$this->in_transaction = TRUE;
}
$this->query_result = mysql_query($query, $this->db_connect_id);
}
else
{
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$result = mysql_query("COMMIT", $this->db_connect_id);
}
}
if( $this->query_result )
{
unset($this->row[$this->query_result]);
unset($this->rowset[$this->query_result]);
if( $transaction == END_TRANSACTION && $this->in_transaction )
{
$this->in_transaction = FALSE;
if ( !mysql_query("COMMIT", $this->db_connect_id) )
{
mysql_query("ROLLBACK", $this->db_connect_id);
return false;
}
}
return $this->query_result;
}
else
{
if( $this->in_transaction )
{
mysql_query("ROLLBACK", $this->db_connect_id);
$this->in_transaction = FALSE;
}
return false;
}
}
I can't figure out what they're doing with
if( $transaction == BEGIN_TRANSACTION && !$this->in_transaction )
Can anybody explain this to me?
The tokens BEGIN_TRANSACTION and END_TRANSACTION are arbitrary constants defined eslewhere to make the code more readable. Basically, this entire function is an implementation of MySQL Transactions in mysql, which doesn't directly support them. Much of the code is there just to work out whether or not a transaction has been started, and whether to commit it, or roll it back.
You can supprt the same functionality by using mysqli::begin_transaction(), mysqli::commit(), and mysqli::rollback()
The PHP reference ishere
I've got a small snippet of code below and I was curious what types of things you would change with regards to best practices/code maintainablity and so on.
function _setAccountStatus($Username, $AccountStatus)
{
if ($Username == '' || ($AccountStatus != 'Active' || $AccountStatus != 'Banned' || $AccountStatus != 'Suspended')) {
// TODO: throw error here.
}
$c1 = new Criteria();
$c1->add(UsersPeer::USERNAME,$Username);
$rs = UsersPeer::doSelect($c1);
if (count($rs) > 0) {
$UserRow = array_pop($rs);
$UserRow->setAccountStatus($AccountStatus);
try {
$UserRow->save();
} catch ( PropelException $e ) {
return false;
}
return true;
}
return false;
}
I would use the empty() instead of $Username == '' in your if statement. I haven't used propel before, but I would prefer to have this method be on my User object itself with the fetching and saving of the user object performed by a seperate object. Pseudo code would be something like this.
$user = userManager->getUser($username);
$user->setAccountStatus($accountStatus);
$userManager->saveUser($user);
An else clause before the last return false would be prefererred, just to make the code more readable.