Solved

How can I convert this switch / case dynamic into a regular if / else

Posted on 2016-08-29
8
68 Views
Last Modified: 2016-09-14
I need to reconfigure this code and I want to replace the switch / case to a if / else. If all goes well, there will probably be some more questions forthcoming and you'll see why.

Thing is, I'm missing something and I need some other eyes on it. Here's the code and the corresponding page:

<li class='event <?=$left?'left':'right'?> <?=$eventtype?>' data-type='<?=$eventtype=='transactions'?'transaction':$eventtype?>'>
<div class='ev_container'>
    <div class='event_header'><span class='event_icon'><span class='appicons <?=strtolower($eventtype)?>'></span></span><?=ucfirst($eventtype)?></div>
    <div class='event_body'>
      <div class='content'>
        <span class='arrow'><span class="point"><span class="timeline_stopper top"><span></span></span><span class="circle"></span><span class="timeline_stopper bottom"><span></span></span></span></span></span>
      <?
      switch($eventtype){
        case "comment":
        case "text":
        case "note":
        ?>
          <?=$content?>
        <?
          break;
        case "statement":
            $dir_exists = $demo ? true : is_dir($dir);
            $file_exists = $demo ? true : file_exists($dir . $file);

            if($file_exists && $dir_exists) {
        ?>
            <a href='<?=$demo?'/admin/statement/?accountid='.$demo:'/admin/statement/load/'.$content?>' target='_statement'><img src='/assets/images/pdf_hover.png'/>View Statement</a>
        <?
            } else if($dir_exists) {
        ?>  
            <span class="error">Failed to send.</span>
        <? 
            } else {
        ?> 
            <span class="pending">Attempted to send... Pending feedback.</span>
        <?
            }
          break;
        case "transaction":
        ?>
        <div class='amount'><?=GlobalFunctions::formatMoney($amount)?><span class='float'>
          <span class='payer <?=$payer?>'><?=$payer?></span><span class='transtype <?=$transactiontype?>'><?=$transactiontype?></span>
        </div>
        <?if($dos !== null && $dos !=='1900-01-01'){?><div class="dos"><?='DOS : ' . date('M d, Y',strtotime($dos))?></div><?}?>
        <div class='encounter'><?if($encountercode != null){?>Encounter Code <?=$encountercode?><?}else{?>No encounter<?}?></div>
        <div class='description'>
          <?=$content?>
        </div>
        <?
          break;
        case "transactions":
        ?>
        <ul>
        <?foreach($transactions as $txn){
        ?>
        <li>
          <div class='amount'><?=GlobalFunctions::formatMoney($txn['amount'])?><span class='float'>
            <span class='payer <?=$txn['payer']?>'><?=$txn['payer']?></span><span class='transtype <?=$txn['transactiontype']?>'><?=$txn['transactiontype']?></span>
          </div>
          <?if($txn['dos'] !== null && $txn['dos'] !=='1900-01-01'){?><div class="dos"><?='DOS : ' . date('M d, Y',strtotime($txn['dos']))?></div><?}?>
          <div class='encounter'><?if($txn['encountercode'] != null){?>Encounter Code <?=$txn['encountercode']?><?}else{?>No encounter<?}?></div>
          <div class='description'>
            <?=$txn['content']?>
          </div>
          <div class='txntime'><?=Date('h:i A',strtotime($txn['eventdate']))?></div>
          <?/*if(isset($txn['runningbal'])){?>
           <div class='runningbal'>Running balance : <span><?=$txn['runningbal']?></span></div>
          <?}*/?>
        </li>
        <?}?>
        </ul><?
      }
  ?></div>
    <?if(isset($runningbal) && ($new_eventtype == 'transaction' || $eventtype == 'transactions')){?>
    <div class='runningbal'>Running balance : <span><?=$runningbal?></span></div>
    <?}?>
    <div class='datefoot'>
      <span class='appicons clock'></span><?=date('M d, Y'.($eventtype!='transactions'?' / h:i A':''),strtotime($eventdate))?>
    </div>
  </div>
</div></li>

Open in new window


current page
Here's my attempt to replace the switch / case with a regular if /else and the epic fail that results:

<li class='event <?=$left?'left':'right'?> <?=$new_eventtype?>' data-type='<?=$new_eventtype=='transactions'?'transaction':$new_eventtype?>'>
<div class='ev_container'>
    <div class='event_header'><span class='event_icon'><span class='appicons <?=strtolower($eventtype)?>'></span></span><?=ucfirst($eventtype)?></div>
    <div class='event_body'>
      <div class='content'>
        <span class='arrow'><span class="point"><span class="timeline_stopper top"><span></span></span><span class="circle"></span><span class="timeline_stopper bottom"><span></span></span></span></span></span>
      <?
	  if($eventtype=="comment" OR $eventtype=="text" OR $eventtype=="note")
	  {
		echo $content;
	  }
		if($eventtype=="statement")
		{
            $dir_exists = $demo ? true : is_dir($dir);
            $file_exists = $demo ? true : file_exists($dir . $file);

            if($file_exists && $dir_exists) {
        ?>
            <a href='<?=$demo?'/admin/statement/?accountid='.$demo:'/admin/statement/load/'.$content?>' target='_statement'><img src='/assets/images/pdf_hover.png'/>View Statement</a>
        <?
            } else if($dir_exists) {
        ?>  
            <span class="error">Failed to send.</span>
        <? 
            } else {
        ?> 
            <span class="pending">Attempted to send... Pending feedback.</span>
        <?
            }
		}
		if($eventtype=="transaction")
		{
        ?>
        <div class='amount'><?=GlobalFunctions::formatMoney($amount)?><span class='float'>
          <span class='payer <?=$payer?>'><?=$payer?></span><span class='transtype <?=$transactiontype?>'><?=$transactiontype?></span>
        </div>
        <?if($dos !== null && $dos !=='1900-01-01'){?><div class="dos"><?='DOS : ' . date('M d, Y',strtotime($dos))?></div><?}?>
        <div class='encounter'><?if($encountercode != null){?>Encounter Code <?=$encountercode?><?}else{?>No encounter<?}?></div>
        <div class='description'>
          <?=$content?>
        </div>
		<?php
		}
		?>
			<?
			if($eventtype=="transactions")
			{
			?>
			<ul>
			<?foreach($transactions as $txn){
			?>
			<li>
			  <div class='amount'><?=GlobalFunctions::formatMoney($txn['amount'])?><span class='float'>
				<span class='payer <?=$txn['payer']?>'><?=$txn['payer']?></span><span class='transtype <?=$txn['transactiontype']?>'><?=$txn['transactiontype']?></span>
			  </div>
			  <?if($txn['dos'] !== null && $txn['dos'] !=='1900-01-01'){?><div class="dos"><?='DOS : ' . date('M d, Y',strtotime($txn['dos']))?></div><?}?>
			  <div class='encounter'><?if($txn['encountercode'] != null){?>Encounter Code <?=$txn['encountercode']?><?}else{?>No encounter<?}?></div>
			  <div class='description'>
				<?=$txn['content']?>
			  </div>
			  <div class='txntime'><?=Date('h:i A',strtotime($txn['eventdate']))?></div>
			  <?/*if(isset($txn['runningbal'])){?>
			   <div class='runningbal'>Running balance : <span><?=$txn['runningbal']?></span></div>
			  <?}*/?>
			</li>
			<?}?>
			</ul><?
			}
  ?></div>
    <?if(isset($runningbal) && ($eventtype == 'transaction' || $eventtype == 'transactions')){?>
    <div class='runningbal'>Running balance : <span><?=$runningbal?></span></div>
    <?}?>
    <div class='datefoot'>
      <span class='appicons clock'></span><?=date('M d, Y'.($eventtype!='transactions'?' / h:i A':''),strtotime($eventdate))?>
    </div>
  </div>
</div></li>

Open in new window


Here's the page:

my page
You'll notice with my page, there are no icons. It's just a running list and I need to duplicate the look of the original page.

What am I missing?
0
Comment
Question by:brucegust
8 Comments
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 50 total points
ID: 41775354
Compare the HTML output between the two versions. Chances are that you're missing some closing </div> or </span> or something, resulting in incorrect styling.
1
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points
ID: 41775370
In addition to gr8gonzo's excellent advice, I recommend you stop using the short-open tags forever.  This is a settable configuration option that you cannot always depend on.  This can only lead to sadness and tears, and is regrettable since the full start-php tag is always available.

There's almost never any value in making switch / case into the more verbose if / else.  But that aside, please have a look at this awkward piece of code:
      switch($eventtype){
        case "comment":
        case "text":
        case "note":
        ?>
          <?=$content?>
        <?
          break;

Open in new window

Here is how a professional might express it:
      switch($eventtype){
        case "comment":
        case "text":
        case "note":
          echo $content;
          break;

Open in new window

I would recommend refactoring this code.  It's a spaghetti-mess and will prove (as you are now seeing) very difficult to maintain.
1
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 41775458
The only real difference between the files is line 69 / 70 respectively
    <?if(isset($runningbal) && ($new_eventtype == 'transaction' || $eventtype == 'transactions')){?>

Open in new window

    <?if(isset($runningbal) && ($eventtype == 'transaction' || $eventtype == 'transactions')){?>

Open in new window


$new_eventtype vs $eventtype - can't find the definition of $new_eventtype.
1
 
LVL 52

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 41775462
Note: converting switch to if you should use else on the subsequent if statements. The breaks in the case statement effectively terminate processing of the case so no need to test the other cases.

As a matter of interest - why are you converting from one to the other.

If the above don't help - can you post the rendered output of both pages.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 9

Assisted Solution

by:Brian Tao
Brian Tao earned 50 total points
ID: 41776072
One other thing, at line #8 of your new page:
if($eventtype=="comment" OR $eventtype=="text" OR $eventtype=="note")

Open in new window

should be
if($eventtype=="comment" || $eventtype=="text" || $eventtype=="note")

Open in new window

0
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 41776124
@Brian
PHP supports both the double pipe (||) and the OR operator - however they operate at different precedence. The Word version (OR) has a lower operator precedence than ||

In this case it makes no difference as there are no other operators in the expression.
3
 

Author Closing Comment

by:brucegust
ID: 41798836
Gentlemen! Forgive me for not being more timely in closing / resolving this question. The good news is that today I turned the completed project, as far as adding an additional feature to the code that you see. Rather than trying to revamp the "switch" dynamic, I just chose to fix something that wasn't broke and kept the format the same. Initially I hesitated only because I'm not as familiar with the swtich / break approach and I was looking for ways to break things down into what was most familiar. Once I got my head around the real heavy lifting, however, I was able to move forward even with being a little guarded about the switch syntax. As always, thanks for your time and your help!
0
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 41798879
Welcome as always Bruce,
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now