if null assign value 0, if statement code reuse - php

If my value is equal to null then I want to assign the value of 0 instead of having null. I've achieved that using my if statement however, its a lot of code production and I plan on adding more social networks is there a better way of achieving this.
$google = $request->input('google');
$facebook = $request->input('facebook');
if ($request->input('google') == null){
$google = 0;
} else {
$google = 1;
}
if ($request->input('facebook') == null){
$facebook = 0;
} else {
$facebook = 1;
}

You can use trenary operator
$google = ($request->input('google') == null) ? 0 : 1;

In order to prevent repeating the same code for each social networks you can do this.
$providers = array(
'google',
'facebook',
);
foreach ($providers as $provider) {
if ($request->input($provider) == null) {
$$provider = 0;
} else {
$$provider = 1;
}
}
IMO the drawback is creating a dynamic variable name, to prevent this, you need to some modifications :
$providers = array(
'google' => 0,
'facebook' => 0,
);
foreach ($providers as $providerKey => $providerValue) {
if ($request->input($providerKey) != null) {
$providers[$providerKey] = 1;
}
}
Hope this helps

Related

Problem of Curly Brackets in my controller Php Symfony

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.

How to insert multiple dynamic data using CodeIgniter?

I am using CodeIgniter, I am displaying the fields dynamically. Now I have to insert the data in the database. So I tried below code.
$order = $this->input->post('order[]');
$partner = $this->input->post('parner[]');
$bankname = $this->input->post('newpartner[]');
$status = $this->input->post('filestatus[]');
$user_id = $this->input->post('user_id');
$order_length = sizeof($order);
for ($j = 0; $j < $order_length; $j++) {
if (($status = 1) || ($status = 3)) {
$remark = $this->input->post('remark[]');
} else {
$remark = "";
}
if (($status = 2) || ($status = 4))) {
$reasonDate = $this->input-> post('reasonDate[]');
$remark = $this->input-> post('remark[]');
} else {
$reasonDate = "";
$remark = "";
}
if ($status = 7) {
$reasonAmt = $this->input->post('reasonAmt[]');
$reason = $this->input->post('reason[]');
} else {
$reasonAmt = "";
$reason = "";
}
$data['row'] = array(
'order' => $order[$j],
'bankname' => $bankname[$j],
'status' => $status[$j],
'lead_id' => $user_id,
'remark' => $remark[$j],
'reasonDate' => $reasonDate[$j],
'reasonAmt' => $reasonAmt[$j],
'reason' => $reason[$j]
);
$save = array(
'b_orderno' => $data['row']['order'],
'b_bankname' => $data['row']['bankname'],
'b_filestatus' => $data['row']['status'],
'p_id' => $data['row']['pid'],
'lead_id' => $data['row']['lead_id'],
'b_remark' => $data['row']['remark'],
'b_date' => $data['row']['reasonDate'],
'b_amt' => $data['row']['reasonAmt'],
'b_reason' => $data['row']['reason']
);
$afterxss = $this->security-> xss_clean($save);
if ($afterxss) {
$this - > db - > insert('tbl_bankdata', $afterxss);
$response['error'] = "true";
$response['msg'] = "added successfully";
} else {
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
}
echo json_encode($response);
I am getting the issue on the status field because depending upon the status value input field will display. Also, I used If the condition in logic for the status field. Each row has a unique status field.
You will find my HTML and script in below link.
https://jsfiddle.net/08phzue3/
This is my UI screenshot. Ignore the value that is only for testing purpose.
1)Onload this will display
2) If user select the status
3) If multiple row
Would you help me out with this?
Actually you are not comparing here:
if (($status = 1) || ($status = 3)) {
You are assigning the values to your $status variable
this should be:
if (($status == 1) || ($status == 3)) {
Side note: same for other conditions as well.
Edit:
As you mentioned you are getting array in $status so using comparison is not a correct logic here, there are multiple solution available,
You can use in_array() like:
if(in_array(1, $status) || in_array(3, $status)){
$remark = $this->input->post('remark[]');
}
else{
$remark = "";
}
Final Solutions (04-07-2019):
After changing the $save and $data arrays, issue has been resolved for OP:
$save['b_orderno'] = $order[$j];
$save['b_bankname'] = $bankname[$j];
$save['b_filestatus'] = $status[$j];
$save['p_id'] = $partner[$j];
$save['lead_id'] = $user_id;
if(!empty($remark[$j])){
$save['b_remark'] = $remark[$j];
}
if(!empty($reasonDate[$j])){
$save['b_date'] = $reasonDate[$j];
}
if(!empty($message[$j])){
$save['b_message'] = $message[$j];
}
if(!empty($reasonAmt[$j])){
$save['b_amt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$save['b_reason'] = $reason[$j];
}
$data['row']['order'] = $order[$j];
$data['row']['bankname'] = $bankname[$j];
$data['row']['status'] = $status[$j];
$data['row']['lead_id'] = $user_id;
$data['row']['remark'] = $remark[$j];
$data['row']['reasonDate'] = $reasonDate[$j];
if(!empty($reasonAmt[$j])){
$data['row']['reasonAmt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$data['row']['reason'] = $reason[$j];
}

How to use eager loading here, i mean just by using one variable instead of two. So i don't need to run two separate queries

1) How can use eager loading here, i mean just by using $SponceringUser instead of $ProfileUser. so i don't need to run two separate queries.
if i exchange my $profileUser variable with $SponceringUser where in the code i should save it to get the right output
here is the Post_edit method for more details please refer gist here : https://gist.github.com/gupta2205/b33dcf762876e5df34d9
public function post_edit($id = null)
{
if ($id)
{
$Petition = Petition::find($id);
if (!$Petition)
{
//oh noes! invalid petition specified!
Alert::error("That petition no longer exists");
return Redirect::action('AdminPetitionsController#index');
}
}
else
{
$Petition = new Petition;
}
$PetitionCreationForm = new AdminPetitionCreationForm;
$errors = array();
if ($PetitionCreationForm->passes())
{
$Petition->call_to_action = Input::get('call_to_action');
if (empty($Petition->id))
{
$Petition->slug = Str::slug($Petition->call_to_action);
}
$Petition->recipient = Input::get('recipient');
if (Input::get('feature_type') == '1')
{
$Petition->featured_sort_order = Input::get('featured_sort_order') + 1;
$Petition->flag_featured = 1;
}
else if(Input::get('feature_type') == '0')
{
$Petition->featured_sort_order=null;
$Petition->flag_featured = 0;
}
//$selected_position = Input::get('dropdown_menu_list');
$Petition->description_md = Input::get('description_md');
$Petition->description = Petition::parseMD($Petition->description_md);
$Petition->letter_md = Input::get('letter_md');
$Petition->letter = Petition::parseMD($Petition->letter_md);
$Petition->target_signatures = Input::get('target_signatures', 50000);
$Petition->flag_published = Input::get('flag_published');
$Petition->media_type = Input::get('media_type', null);
if (Input::get('media_type') == 'img' && Input::hasFile('petition_image'))
{
$Petition->media_url = Petition::uploadFile(Input::file('petition_image'));
}
else if (Input::get('media_type') == 'youtube' && Input::get('media_url_youtube'))
{
$Petition->media_url = Input::get('media_url_youtube');
}
// how to fix this part .... gurrrrrrrrrrrr=======================
$ProfileUser= $Petition->User;
if (Input::get('profile_type') == 'image' && Input::hasFile('profile_image'))
{
$ProfileUser->profile_img_url = Petition::uploadFile(Input::file('profile_image'));
}
else if (Input::get('profile_type') == 'url' && Input::get('profile_url'))
{
$ProfileUser->profile_img_url = Input::get('profile_url');
}
//$Petition->sponsor_user_id = $SponsoringUser->id;
$ProfileUser->save();
//====================================================
try {
try {
$SponsoringUser = User::where('email', Input::get('user.email'))->firstOrFail();
}
catch (Exception $e)
{
$PetitionSponsorForm = new AdminPetitionSponsorForm(Input::get('user'));
if ($PetitionSponsorForm->passes())
{
$SponsoringUser = new User;
$SponsoringUser->email = Input::get('user.email');
$SponsoringUser->first_name = Input::get('user.first_name');
$SponsoringUser->last_name = Input::get('user.last_name');
$SponsoringUser->populateLocation(Input::get('user.zip'));
$SponsoringUser->save();
}
else
{
throw new Exception();
}
}
$Petition->save();
1) How can use eager loading here, i mean just by using $SponceringUser instead of $ProfileUser. so i don't need to run two separate queries.
i got it :)
if (Input::get('profile_type') == 'image' && Input::hasFile('profile_image'))
{
$SponsoringUser->profile_img_url = Petition::uploadFile(Input::file('profile_image'));
}
else if (Input::get('profile_type') == 'url' && Input::get('profile_url'))
{
$$SponsoringUser->profile_img_url = Input::get('profile_url');
}
$SponsoringUser->save();

Pulling articles from specific category through Joomla! 3.0 Module

Here is the scenario, and let me start off saying any help would be a god-send, I have cloned the Article Category module inside Joomla! Basically changed all the articles_category to breed_articles (for my purpose). This worked fine, where I am stuck at is where in the module code can I define a specific category to pull articles from.
I know I can do this in the backend but I am working on a dynamic way to pull articles by categories and need to define the category in the module code. That being said, I will also need to pull the categoies by the slug not id.
Where I have been looking is the helper.php file in the module and I believe that I am on the right path there. I have tried replacing a few things and tracing the code but I am not very familiar with Joomla!
helper.php
$com_path = JPATH_SITE.'/components/com_content/';
require_once $com_path.'router.php';
require_once $com_path.'helpers/route.php';
JModelLegacy::addIncludePath($com_path . '/models', 'ContentModel');
abstract class modBreedArticlesHelper
{
public static function getList(&$params)
{
// Get an instance of the generic articles model
$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$articles->setState('params', $appParams);
// Set the filters based on the module params
$articles->setState('list.start', 0);
$articles->setState('list.limit', (int) $params->get('count', 0));
$articles->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$articles->setState('filter.access', $access);
// Prep for Normal or Dynamic Modes
$mode = $params->get('mode', 'normal');
switch ($mode)
{
case 'dynamic':
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content') {
switch($view)
{
case 'category':
$catids = array($app->input->getInt('id'));
break;
case 'categories':
$catids = array($app->input->getInt('id'));
break;
case 'article':
if ($params->get('show_on_article_page', 1)) {
$article_id = $app->input->getInt('id');
$catid = $app->input->getInt('catid');
if (!$catid) {
// Get an instance of the generic article model
$article = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article->setState('params', $appParams);
$article->setState('filter.published', 1);
$article->setState('article.id', (int) $article_id);
$item = $article->getItem();
$catids = array($item->catid);
}
else {
$catids = array($catid);
}
}
else {
// Return right away if show_on_article_page option is off
return;
}
break;
case 'featured':
default:
// Return right away if not on the category or article views
return;
}
}
else {
// Return right away if not on a com_content page
return;
}
break;
case 'normal':
default:
$catids = $params->get('catid');
$articles->setState('filter.category_id.include', (bool) $params->get('category_filtering_type', 1));
break;
}
// Category filter
if ($catids) {
if ($params->get('show_child_category_articles', 0) && (int) $params->get('levels', 0) > 0) {
// Get an instance of the generic categories model
$categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true));
$categories->setState('params', $appParams);
$levels = $params->get('levels', 1) ? $params->get('levels', 1) : 9999;
$categories->setState('filter.get_children', $levels);
$categories->setState('filter.published', 1);
$categories->setState('filter.access', $access);
$additional_catids = array();
foreach($catids as $catid)
{
$categories->setState('filter.parentId', $catid);
$recursive = true;
$items = $categories->getItems($recursive);
if ($items)
{
foreach($items as $category)
{
$condition = (($category->level - $categories->getParent()->level) <= $levels);
if ($condition) {
$additional_catids[] = $category->id;
}
}
}
}
$catids = array_unique(array_merge($catids, $additional_catids));
}
$articles->setState('filter.category_id', $catids);
}
// Ordering
$articles->setState('list.ordering', $params->get('article_ordering', 'a.ordering'));
$articles->setState('list.direction', $params->get('article_ordering_direction', 'ASC'));
// New Parameters
$articles->setState('filter.featured', $params->get('show_front', 'show'));
$articles->setState('filter.author_id', $params->get('created_by', ""));
$articles->setState('filter.author_id.include', $params->get('author_filtering_type', 1));
$articles->setState('filter.author_alias', $params->get('created_by_alias', ""));
$articles->setState('filter.author_alias.include', $params->get('author_alias_filtering_type', 1));
$excluded_articles = $params->get('excluded_articles', '');
if ($excluded_articles) {
$excluded_articles = explode("\r\n", $excluded_articles);
$articles->setState('filter.article_id', $excluded_articles);
$articles->setState('filter.article_id.include', false); // Exclude
}
$date_filtering = $params->get('date_filtering', 'off');
if ($date_filtering !== 'off') {
$articles->setState('filter.date_filtering', $date_filtering);
$articles->setState('filter.date_field', $params->get('date_field', 'a.created'));
$articles->setState('filter.start_date_range', $params->get('start_date_range', '1000-01-01 00:00:00'));
$articles->setState('filter.end_date_range', $params->get('end_date_range', '9999-12-31 23:59:59'));
$articles->setState('filter.relative_date', $params->get('relative_date', 30));
}
// Filter by language
$articles->setState('filter.language', $app->getLanguageFilter());
$items = $articles->getItems();
// Display options
$show_date = $params->get('show_date', 0);
$show_date_field = $params->get('show_date_field', 'created');
$show_date_format = $params->get('show_date_format', 'Y-m-d H:i:s');
$show_category = $params->get('show_category', 0);
$show_hits = $params->get('show_hits', 0);
$show_author = $params->get('show_author', 0);
$show_introtext = $params->get('show_introtext', 0);
$introtext_limit = $params->get('introtext_limit', 100);
// Find current Article ID if on an article page
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content' && $view === 'article') {
$active_article_id = $app->input->getInt('id');
}
else {
$active_article_id = 0;
}
// Prepare data for display using display options
foreach ($items as &$item)
{
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid ? $item->catid .':'.$item->category_alias : $item->catid;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$menuitems = $menu->getItems('link', 'index.php?option=com_users&view=login');
if (isset($menuitems[0]))
{
$Itemid = $menuitems[0]->id;
}
elseif ($app->input->getInt('Itemid') > 0)
{
// Use Itemid from requesting page only if there is no existing menu
$Itemid = $app->input->getInt('Itemid');
}
$item->link = JRoute::_('index.php?option=com_users&view=login&Itemid='.$Itemid);
}
// Used for styling the active article
$item->active = $item->id == $active_article_id ? 'active' : '';
$item->displayDate = '';
if ($show_date) {
$item->displayDate = JHTML::_('date', $item->$show_date_field, $show_date_format);
}
if ($item->catid) {
$item->displayCategoryLink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid));
$item->displayCategoryTitle = $show_category ? ''.$item->category_title.'' : '';
}
else {
$item->displayCategoryTitle = $show_category ? $item->category_title : '';
}
$item->displayHits = $show_hits ? $item->hits : '';
$item->displayAuthorName = $show_author ? $item->author : '';
if ($show_introtext) {
$item->introtext = JHtml::_('content.prepare', $item->introtext, '', 'mod_articles_category.content');
$item->introtext = self::_cleanIntrotext($item->introtext);
}
$item->displayIntrotext = $show_introtext ? self::truncate($item->introtext, $introtext_limit) : '';
$item->displayReadmore = $item->alternative_readmore;
}
return $items;
}
public static function _cleanIntrotext($introtext)
{
$introtext = str_replace('<p>', ' ', $introtext);
$introtext = str_replace('</p>', ' ', $introtext);
$introtext = strip_tags($introtext, '<a><em><strong>');
$introtext = trim($introtext);
return $introtext;
}
/**
* Method to truncate introtext
*
* The goal is to get the proper length plain text string with as much of
* the html intact as possible with all tags properly closed.
*
* #param string $html The content of the introtext to be truncated
* #param integer $maxLength The maximum number of charactes to render
*
* #return string The truncated string
*/
public static function truncate($html, $maxLength = 0)
{
$baseLength = strlen($html);
$diffLength = 0;
// First get the plain text string. This is the rendered text we want to end up with.
$ptString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = false);
for ($maxLength; $maxLength < $baseLength;)
{
// Now get the string if we allow html.
$htmlString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = true);
// Now get the plain text from the html string.
$htmlStringToPtString = JHtml::_('string.truncate', $htmlString, $maxLength, $noSplit = true, $allowHtml = false);
// If the new plain text string matches the original plain text string we are done.
if ($ptString == $htmlStringToPtString)
{
return $htmlString;
}
// Get the number of html tag characters in the first $maxlength characters
$diffLength = strlen($ptString) - strlen($htmlStringToPtString);
// Set new $maxlength that adjusts for the html tags
$maxLength += $diffLength;
if ($baseLength <= $maxLength || $diffLength <= 0)
{
return $htmlString;
}
}
return $html;
}
public static function groupBy($list, $fieldName, $article_grouping_direction, $fieldNameToKeep = null)
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
if (!isset($grouped[$item->$fieldName])) {
$grouped[$item->$fieldName] = array();
}
if (is_null($fieldNameToKeep)) {
$grouped[$item->$fieldName][$key] = $item;
}
else {
$grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
return $grouped;
}
public static function groupByDate($list, $type = 'year', $article_grouping_direction, $month_year_format = 'F Y')
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
switch($type)
{
case 'month_year':
$month_year = JString::substr($item->created, 0, 7);
if (!isset($grouped[$month_year])) {
$grouped[$month_year] = array();
}
$grouped[$month_year][$key] = $item;
break;
case 'year':
default:
$year = JString::substr($item->created, 0, 4);
if (!isset($grouped[$year])) {
$grouped[$year] = array();
}
$grouped[$year][$key] = $item;
break;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
if ($type === 'month_year') {
foreach($grouped as $group => $items)
{
$date = new JDate($group);
$formatted_group = $date->format($month_year_format);
$grouped[$formatted_group] = $items;
unset($grouped[$group]);
}
}
return $grouped;
}
}
It looks like my issue was really specific to the project I am working on. If anyone happens to find this or wants to accomplish something similar, read on.
Decided to accomplish what I was doing using a JDatabase query. To retrieve the articles using the category alias, I queried the DB to match the alias I was giving the query to the category ID. Then joined the content table to get the article information.
All the information you need to make a proper JDatabase query can be found here: http://docs.joomla.org/Accessing_the_database_using_JDatabase

right way to write those checks? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
what is the right way to write those checks. i have a array, some time values are not set or they are empty. right now that code bit hard to read, what can i do to make that look more clear and trust-able. or i'm just going to hard on this . any suggestions?
<?php
private static function filter_yt_data($yt_api_response = null)
{
$data = array();
$api = json_decode($yt_api_response);
$api = $api->data->items[0];
$data = array(
'id' => $api->id,
'author' => e($api->uploader),
'label' => e($api->category),
'title' => e($api->title),
'description' => e($api->description),
'duration' => $api->duration,
'view_count' => $api->viewCount,
'access' => $api->accessControl->embed,
'favorite_count'=> $api->favoriteCount
);
if($api->accessControl->comment == 'allowed')
{
$data['comment_count'] = $api->commentCount;
}
else
{
$data['comment_count'] = 0;
}
if($api->ratingCount)
{
$data['rating_count'] = $api->ratingCount;
}
else
{
$data['rating_count'] = 0;
}
if($api->accessControl->rate == 'allowed')
{
$data['like_count'] = $api->likeCount;
}
else
{
$data['like_count'] = 0;
}
if($api->thumbnail->hqDefault)
{
$data['thumbnail'] = $api->thumbnail->hqDefault;
}
elseif($api->thumbnail->sqDefault)
{
$data['thumbnail'] = $api->thumbnail->sqDefault;
}else
{
$data['thumbnail'] = null;
}
return $data;
}
?>
if($api->accessControl->comment == 'allowed')
{
$data['comment_count'] = $api->commentCount;
}
else
{
$data['comment_count'] = 0;
}
could also be:
$data['comment_count'] = $api->accessControl->comment == 'allowed' ? $api->commentCount : 0;
This is called ternary operator
Syntax:
$variable = (condition) ? if condition true : else;
in that way you could replace all your if-else statements.
One way would be to initialise the default values then do the checks:
$data['comment_count'] = 0;
if($api->accessControl->comment == 'allowed'){
$data['comment_count'] = $api->commentCount;
}
$data['rating_count'] = 0;
if($api->ratingCount){
$data['rating_count'] = $api->ratingCount;
}
$data['like_count'] = 0;
if($api->accessControl->rate == 'allowed'){
$data['like_count'] = $api->likeCount;
}
$data['thumbnail'] = null;
if($api->thumbnail->hqDefault){
$data['thumbnail'] = $api->thumbnail->hqDefault;
}elseif($api->thumbnail->sqDefault){
$data['thumbnail'] = $api->thumbnail->sqDefault;
}
These could also be initialised in the original array.

Categories