Using a switch statement to append URL structure - php

So I have the following switch statement inside a method inside my class:
public function getSASURL(string $blobName, string $size = '') : string
{
if ($this->containerName === 'userpictures-resized') {
switch ($size) {
case 'small':
return '_SThumb';
break;
case 'medium':
return '_MThumb';
break;
case 'large':
return '_LThumb';
break;
case 'original':
return '_Original';
break;
case 'big':
return '_Big';
break;
}
return $this->generateSASURL($blobName . $size . '.jpg');
}
return $this->generateSASURL($blobName);
}
Here is what it's doing:
When I call:
$sasURL = $azure->getSASURL('AHahn_com');
I get the following thing back - this works as expected.
https://storageaccount.blob.core.windows.net/userpictures-resized/AHahn_com.jpg?sv=2017-11-09&sr=b&st=2020-10-08T13:04:47Z
Now when I call:
$sasURL = $azure->getSASURL('AHahn_com', 'small');
I get the following back:
'_SThumb'
Instead, this is the result that I want to receive back (with _SThumb after the filename, before the extension):
https://storageaccount.blob.core.windows.net/userpictures-resized/AHahn_com_SThumb.jpg?sv=2017-11-09&sr=b&st=2020-10-08T13:04:47Z
Does anyone know what I might be doing wrong?

Your problem is that you return from the switch statement rather than use the value for each case. You can either overwrite $size inside each case, so for example $size = '_SThumb'; instead of return '_SThumb';, or create another variable which you substitute for $size to your generateSASURL() method.
However, another approach could be to create a map of the sizes and their corresponding value. Then just access the array with $size as a key. To make it case-insensitve, you can do $map[strtolower($size)]. The default value (when no match was found) is the value after the null-coalescing operator ??, which could be anything - here it's $size, but it could be an empty string if that's more applicable.
public function getSASURL(string $blobName, string $size = '') : string
{
if ($this->containerName === 'userpictures-resized') {
$map = [
'size' => '_SThumb',
'medium' => '_SThumb',
'large' => '_MThumb',
'original' => '_Original',
'big' => '_Big',
];
return $this->generateSASURL($blobName . ($map[$size] ?? $size) . '.jpg');
}
return $this->generateSASURL($blobName);
}

Related

switch loop doesnt recognize zero "0" php

I have this simple function to convert the number of comments of an user to types of members.
function checkMemberN($numMessages){
$n= $numMessages;
switch ($n) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
return $type;
}
echo checkMemberN(0);
It looks like it doesn't recognize zero (0), because when I put 1 or a higher number it retrieves the correct user type. What am I doing wrong?
When you use switch, the first case which returns a value equal to the given one is selected. In this case, your argument (zero) is a false-y value. That's why the first case that returns false is chosen: "Frequent".
To fix it, you can do this:
if ($n<50) {
$type = "New";
} else if ($n>=50 && $n<250) {
$type = "Frequent";
} else if ($n>=250 && $n<1000) {
$type = "Master";
} else {
$type = "undefined";
}
If you still want to use switch, you can change the argument to true:
switch (true) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
Here, the first case which returns true will be used.

Is it possible to use a Switch Case to set a different output?

I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.
If in your $data array there is one car and one location then you can do the following to save the variables and use them later:
$loc_name = '';
$car_name = '';
foreach ($data as $key => $value) {
if ( is_special_car($value['name']) )
continue;
switch ($type) {
case 'car':
$car_name = $name;
break;
case 'location':
$loc_name = $name;
break;
default:
break;
}
if($loc_name && $car_name){
//You have a car and loc name now
}
}
If your $data array is different you will have to modify the code of course, maybe resetting the $loc_name and $car_name when you've done whatever you needed to after getting them.
I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.

How can I get this PHP variable to be determined by the value of another user selected radio button

$door = $_POST["doorType"];
$doorWidth;
if ($door=="Single")
{
$doorWidth = $width;
}
else if ($door=="Double")
{
$doorWidth = $dOneWidth;
}
When I run the page it doesn't recognize the variable $doorWidth?
$doorWidth;
doesn't assign anything. It only returns the variable ... to anything. Doing this PHP is accessing the variable, causing a notice. Write for example:
$doorWidth = NULL; // assigns something (some default value if $door isn't "Signle" nor "Double")
I guess that $door has a value far from Single|Double. This may be caused by another error in your application. You should learn, that you should in any case set a proper default value for a variable if you are about to assign to it from into a conditional statement (like if):
$doorWidth = 'not set!';
if ($door=="Single")
{
$doorWidth = $width;
}
else if ($door=="Double")
{
$doorWidth = $dOneWidth;
}
Further note about the switch statement which has a default: branch:
switch($door) {
case 'Single' :
// do something
break;
case 'Double' :
// do something else
break;
default:
die('$door has a value far from 'Single|Double'. Currently: ' . $door);
}

Dynamic functions, variable inputs

Right now, lets say I have code much like this...
$some_var=returnsUserInput();
function funcA($a) {...}
function funcB($a,$b) {...}
function funcC($a,$b,$c) {...}
$list[functionA] = "funcA";
$list[functionB] = "funcB";
$list[functionC] = "funcC";
$temp_call = list[$some_var];
//Not sure how to do this below, just an example to show the idea of what I want.
$temp_call($varC1,varC2,$varC3);
$temp_call($varB1,varB2);
$temp_call($varA1);
My problem starts here, how can I specify the proper variables into the arguments depending on these? I have a few thoughts such as creating a list for each function that specifies these, but I would really like to see an elegant solution to this.
You need to use call_user_func or call_user_func_array.
<?php
// if you know the parameters in advance.
call_user_func($temp_call, $varC1, $varC2);
// If you have an array of params.
call_user_func_array($temp_call, array($varB1, $varB2));
?>
You want something like the following?
function test()
{
$num_args = func_num_args();
$args = func_get_args();
switch ($num_args) {
case 0:
return 'none';
break;
case 1:
return $args[0];
break;
case 2:
return $args[0] . ' - ' . $args[1];
break;
default:
return implode($args, ' - ');
break;
}
}
echo test(); // 'none'
echo test(1); // 1
echo test(1, 2); // 1 - 2
echo test(1, 2, 3); // 1 - 2 - 3
It'd act as some sort of delegation method.
Or what about just accepting an array rather than paramaters?
function funcA($params)
{
extract($params);
echo $a;
}
function funcB($params)
{
extract($params);
echo $a, $b;
}
function funcC($params)
{
extract($params);
echo $a, $b, $c;
}
$funcs = array('funcA', 'funcB', 'funcC');
$selected = $funcs[0];
$selected(array('a' => 'test', 'b' => 'test2'));
// or something like (beware of security issues)
$selected($_GET);
You can't and maybe that's good to. You can find the amount of arguments with if/else.
if($temp_call == "funcA") { .....} elseif(...)...

PHP Function parameters - problem with var not being set

So I am obviously not a very good programmer. I have written this small function:
function dispAdjuggler($atts) {
extract(shortcode_atts(array(
'slot' => ''
), $atts));
$adspot = '';
$adtype = '';
// Get blog # we're on
global $blog_id;
switch ($blog_id) {
case 1:
// root blog HOME page
if (is_home()) {
switch ($slot) {
case 'top_leaderboard':
$adspot = '855525';
$adtype = '608934';
break;
case 'right_halfpage':
$adspot = '855216';
$adtype = '855220';
break;
case 'right_med-rectangle':
$adspot = '858222';
$adtype = '613526';
break;
default:
throw new Exception("Ad slot is not defined");
break;
}
When I reference the function on a page like so:
<?php dispAdjuggler("top_leaderboard"); ?>
The switch is throwing the default exception. What am I doing wrong here?
Thanks!!
Without know what the shortcode_atts() function does, it looks like you're passing in array to set default values ('slot' = empty string), which extract() then converts into $short = ''
extract(shortcode_atts(array(
'slot' => ''
), $atts));
right? Now that $slot is the empty string, it won't match any of the cases in your switch, and therefore the default case gets triggered, which throws the "Ad slot is not defined" exception.
Aren't you missing the extract type parameter?
http://us.php.net/manual/en/function.extract.php

Categories