I'm wondering if there is another way to refactor my conditionals if/else statements. I feel I'm repeating the same thing over and over,
Here is a snippet (Keep in mind is wayyyy longer than that, but it follows the same principle) I could do a switch statement but it does not reduce the total code quantity.
I just want to get a second opinion of the best approach for this code to go into production. Also important to mention that the statements that I'm comparing $screen->id; are most likely to be dynamically generated if the user selects the checkbox, but that is outside of the scope of the question.
//check admin screen
$screen = get_current_screen();
if ( $screen->id === 'topic') {
$in['content_css'] = get_template_directory_uri() . "/build/styles/tiny-mce-editor.css";
$in['block_formats'] = $topics_blocks;
return $in;
}
elseif ( $screen->id === 'provider-jobs') {
$in['content_css'] = get_template_directory_uri() . "/build/styles/tiny-mce-editor.css";
$in['block_formats'] = $providers_blocks;
return $in;
}
//for all the page options
else {
$in['block_formats'] = $global_blocks;
return $in;
}
}
Thanks! Any guidance is appreciated.
UPDATE! Here is the refactored code, a little bit more cleaner! And complete so the whole context shows.
//check admin screen
$screen = get_current_screen();
//global ones
$in['block_formats'] = $global_blocks;
$in['toolbar1'] = $global_toolbar;
if ( $screen->id === 'topic') {
$in['block_formats'] = $topics_blocks;
$in['toolbar1'] = $topics_toolbar;
} elseif ( $screen->id === 'forum') {
$in['block_formats'] = $forums_blocks;
$in['toolbar1'] = $forums_toolbar;
} elseif ( $screen->id === 'post') {
$in['block_formats'] = $blogs_blocks;
$in['toolbar1'] = $blogs_toolbar;
} elseif ( $screen->id === 'jobs') {
$in['block_formats'] = $jobs_blocks;
$in['toolbar1'] = $jobs_toolbar;
}
elseif ( $screen->id === 'provider-jobs') {
$in['block_formats'] = $providers_blocks;
$in['toolbar1'] = $providers_toolbar;
}
return $in;
You might register key/value pairs all known options/blocks. So your code becomes straight reduced, like this:
$options = [
'topic' => $topics_blocks,
'provider_jobs' => $providers_blocks,
// ...
];
//check admin screen
$screen = get_current_screen();
if (array_key_exists($screen->id, $options) {
$in['content_css'] = get_template_directory_uri() . "/build/styles/tiny-mce-editor.css";
$in['block_formats'] = $options[$screen->id];
} else {
$in['block_formats'] = $global_blocks;
}
return $in;
Edit, applies to the 2nd version of the OP
Here the problem appears a bit different, so here is another solution:
$options = [
'topic' => 'topics',
'forum' => 'forums',
'post' => 'blogs',
'jobs' => 'jobs',
'provider_jobs' => 'providers',
];
//check admin screen
$screen = get_current_screen();
//global ones
$in['block_formats'] = $global_blocks;
$in['toolbar1'] = $global_toolbar;
// variable ones
if (array_key_exists($screen->id, $options) {
$in['block_formats'] = ${$options[$screen->id] . '_blocks'};
$in['toolbar1'] = $options[$screen->id] . '_toolbar'};
}
return $in;
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
I'm trying to get the shipping available methods by country code that giving in the request, in the above code I'm facing an issue/conflict
That the available locations can be both a country or a continent so I need to check if this country code is a part of some continent.
the problem is with the first zone I get all methods in all zones not just within the first ( the callback return ).
The second zone which has the continents/countries ( rest of the world ) I get no issues with it but as far I guess that's because its the end of the loop. ( as I have two zones for now )
add_action("rest_api_init", function () {
register_rest_route(
"test-api/v1",
"shipping-cost",
array(
'callback' => function ($req) {
$country_code = $req->get_param('country_code');
$quantity = $req->get_param('quantity');
$shipping_cost = 0;
$methodes = [];
if (class_exists('WC_Shipping_Zones')) {
$all_zones = WC_Shipping_Zones::get_zones();
if (!empty($all_zones)) {
foreach ($all_zones as $zone) {
if (!empty($zone['zone_locations'])) {
foreach ($zone['zone_locations'] as $location) {
$wc_contries = new WC_Countries();
$continent_code = $wc_contries->get_continent_code_for_country($country_code);
if ($country_code === $location->code || $continent_code === $location->code) {
if (!empty($zone['shipping_methods'])) {
$shipping_method_ctrl = new WC_REST_Shipping_Zone_Methods_Controller();
foreach ($zone['shipping_methods'] as $flat_rate) {
$shipping_method = $shipping_method_ctrl->prepare_item_for_response($flat_rate, $req);
$methodes[] = (object) $shipping_method;
}
}
}
}
}
}
}
}
return $methodes;
}
)
);
});
Here's the answer: ( adding break with the number of the array want it to be stop )
Register_rest_route(
"kefan-api/v1",
"shipping-cost",
array(
'callback' => function ($req) {
$country_code = $req->get_param('country_code');
$methodes = [];
if (class_exists('WC_Shipping_Zones')) {
$all_zones = WC_Shipping_Zones::get_zones();
if (!empty($all_zones)) {
foreach ($all_zones as $zone) {
if (!empty($zone['zone_locations'])) {
foreach ($zone['zone_locations'] as $location) {
$wc_contries = new WC_Countries();
$continent_code = $wc_contries->get_continent_code_for_country($country_code);
if ($country_code === $location->code || $continent_code === $location->code) {
if (!empty($zone['shipping_methods'])) {
$shipping_method_ctrl = new WC_REST_Shipping_Zone_Methods_Controller();
foreach ($zone['shipping_methods'] as $flat_rate) {
$shipping_method = $shipping_method_ctrl->prepare_item_for_response($flat_rate, $req);
$methodes[] = (object) $shipping_method;
}
break 2;
}
}
}
}
}
}
}
return $methodes;
}
)
);
I'm using pods admin plugin and I want to change the value in array. raspored.meta_value are days from 0-6 or from Sunday to Monday.
I want that the value in raspored.meta_value = "dynamic" is changing how the days are going.
Btw: I'm new and not so good in English.Hope you understand :)
$params = array( 'limit' => -1, 'where' => 'raspored.meta_value = "4"' );
$pods = pods( 'raspored', $params );
if ( $pods->total() > 0 ) {
while( $pods->fetch() ) {
//reset id
$pods->id = $pods->id();
//get the template
$temp = $pods->template( 'Probni' );
//output template if it exists
if ( isset( $temp ) ) {
echo $pods->display( 'some_other_field' );
echo $temp;
}
}
//pagination
echo $pods->pagination();
}
else {
echo 'No content found.';
}
I found the solution.
I added if statement and change the array value for "where clause".
Example:
$params = array( 'limit' => -1, 'where' => 'raspored.meta_value = "1"', 'orderby' => 'vrijeme_start ASC' );
if (date("l") === "Monday") {
$params["where"] = array ('1');
}
elseif (date("l") === "Tuesday") {
$params["where"] = array ('2');
}
elseif (date("l") === "Wednesday") {
$params["where"] = array ('3');
}
elseif (date("l") === "Thursday") {
$params["where"] = array ('4');
}
elseif (date("l") === "Friday") {
$params["where"] = array ('5');
}
elseif (date("l") === "Saturday") {
$params["where"] = array ('6');
}
elseif (date("l") === "Sunday") {
$params["where"] = array ('0');
}
else {
echo 'Nema sadržaja';
}
Hope somebody will need this :)
i using a wordpress plugin, i notice that returns a error on
$alias = (string)end(array_keys($settings));
above line .the error is
PHP Strict Standards: Only variables should be passed by reference in on wordpress function
i added that function below. anyone know how to solve that error please, becoz admin dashboard of the plugin not loading because of this error.
/*
* GET modules lists
*/
function load_modules ()
{
$folder_path = $this->cfg['paths']['plugin_dir_path'] . 'modules/';
$cfgFileName = 'config.php';
// static usage, modules menu order
$menu_order = array();
foreach(glob($folder_path . '*/' . $cfgFileName) as $module_config ){
$module_folder = str_replace($cfgFileName, '', $module_config);
// Turn on output buffering
ob_start();
if( is_file( $module_config ) ) {
require_once( $module_config );
}
$settings = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer
if(trim($settings) != "") {
$settings = json_decode($settings, true);
$alias = (string) end(array_keys($settings));
// create the module folder URI
// fix for windows server
$module_folder = str_replace( DIRECTORY_SEPARATOR, '/', $module_folder );
$__tmpUrlSplit = explode("/", $module_folder);
$__tmpUrl = '';
$nrChunk = count($__tmpUrlSplit);
if($nrChunk > 0) {
foreach ($__tmpUrlSplit as $key => $value){
if( $key > ( $nrChunk - 4) && trim($value) != ""){
$__tmpUrl .= $value . "/";
}
}
}
// get the module status. Check if it's activate or not
$status = false;
// default activate all core modules
if(in_array( $alias, $this->cfg['core-modules'] )) {
$status = true;
}else{
// activate the modules from DB status
$db_alias = $this->alias . '_module_' . $alias;
if(get_option($db_alias) == 'true'){
$status = true;
}
}
// push to modules array
$this->cfg['modules'][$alias] = array_merge(array(
'folder_path' => $module_folder,
'folder_uri' => $this->cfg['paths']['plugin_dir_url'] . $__tmpUrl,
'db_alias' => $this->alias . '_' . $alias,
'status' => $status
), $settings );
// add to menu order arrayhttp://cc.aa-team.com/wp-plugins/smart-seo-v2/wp-admin/admin-ajax.php?action=pspLoadSection§ion=Social_Stats
if(!isset($this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']])){
$this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']] = $alias;
}else{
// add the menu to next free key
$this->cfg['menu_order'][] = $alias;
}
// add module to activate modules array
if($status == true){
$this->cfg['activate_modules'][$alias] = true;
}
// load the init of current loop module
if( $status == true && isset( $settings[$alias]['module_init'] ) ){
if( is_file($module_folder . $settings[$alias]['module_init']) ){
//if( is_admin() ) {
$current_module = array($alias => $this->cfg['modules'][$alias]);
require_once( $module_folder . $settings[$alias]['module_init'] );
//}
}
}
}
}
// order menu_order ascendent
ksort($this->cfg['menu_order']);
}
End rereceives value by reference, but result of function is not variable.
You could rewrite your code.
$array_keys = array_keys($settings);
$alias = (string)end($array_keys);
unset($array_keys);
I would like to be able to set a global username like <anythinghere>#domain3.com as a username value in the $usernames array (in code below). This is so that I can then go and redirect users based on domain, having already been "authenticated".
I will put example in code below.
Can i do something like $usernames = array("username#domain1.com", $X) where $X = <anything-so-long-as-not-blank>#domain3.com?
Full Code Below:
<?php
//VALIDATE USERS
$usernames = array("username#domain1.com", "username2#domain1.com", "username3#domain1.com", "username1#domain2.com", "username2#domain2.com", "username1#domain3.com");
$passwords = array("password1", "password2", "password3", "password4", "password5", "password6");
//REDIRECT SPECIFIC VALID USERS OR DOMAIN
function get_page($username) {
$username = strtolower($username);
switch ($username) {
case "username#domain1.com" : return "http://www.google.com";
case "username2#domain1.com" : return "http://www.yahoo.com";
case "username3#domain1.com" : return "http://www.stackoverflow.com";
case "username1#domain2.com" : return "http://www.serverfault.com";
}
return preg_match('/#domain3\.com$/',$username) ?
"http://www.backblaze.com" : "DefaultBackupPage.php";
}
$page = get_page($_POST['username']);
for($i=0;$i<count($usernames);$i++)
{
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++)
{
if ($usernames[$i] == $_POST["username"])
{
$found = 1;
}
}
if ($found == 0)
{
header('Location: login.php?login_error=1');
exit;
}
if($logindata[$_POST["username"]]==$_POST["password"])
{
session_start();
$_SESSION["username"]=$_POST["username"];
header('Location: '.$page);
exit;
}
else
{
header('Location: login.php?login_error=1');
exit;
}
?>
#inhan Has already helped me like a champ. I am wondering if any one can get me over the line? Cheers!
Your code needed a clean-up first. There's a bunch of errors in it if you do a test run. It's also a bit hard to read IMO.
I've attached a working code sample below.
// Get users
$input_pwd = ( isset( $_POST["password"] ) ? $_POST["password"] : '' );
$input_user = ( isset( $_POST["username"] ) ? $_POST["username"] : '' );
// Your pseudo database here ;)
$usernames = array(
"username#domain1.com",
"username2#domain1.com",
"username3#domain1.com",
"username1#domain2.com",
"/[a-z][A-Z][0-9]#domain2\.com/", // use an emtpy password string for each of these
"/[^#]+#domain3\.com/" // entries if they don't need to authenticate
);
$passwords = array( "password1", "password2", "password3", "password4", "", "" );
// Create an array of username literals or patterns and corresponding redirection targets
$targets = array(
"username#domain1.com" => "http://www.google.com",
"username2#domain1.com" => "http://www.yahoo.com",
"username3#domain1.com" => "http://www.stackoverflow.com",
"username1#domain2.com" => "http://www.serverfault.com",
"/[a-z][A-Z][0-9]#domain2\.com/" => "http://target-for-aA1-usertypes.com",
"/[^#]+#domain3\.com/" => "http://target-for-all-domain3-users.com",
"/.+/" => "http://default-target-if-all-else-fails.com",
);
$logindata = array_combine( $usernames, $passwords );
if ( get_user_data( $input_user, $logindata ) === $input_pwd ) {
session_start();
$_SESSION["username"] = $input_user;
header('Location: ' . get_user_data( $input_user, $targets ) );
exit;
} else {
// Supplied username is invalid, or the corresponding password doesn't match
header('Location: login.php?login_error=1');
exit;
}
function get_user_data ( $user, array $data ) {
$retrieved = null;
foreach ( $data as $user_pattern => $value ) {
if (
( $user_pattern[0] == '/' and preg_match( $user_pattern, $user ) )
or ( $user_pattern[0] != '/' and $user_pattern === $user)
) {
$retrieved = $value;
break;
}
}
return $retrieved;
}