how to simplify the same code in two else condition PHP - php

There are two 'else' condition with the same code, so how to simplify this code?
if(!empty($data))
{
$getData = $this->getData($data);
if(!empty($getData))
{
$response = $getData->name;
}
else
{
$response = $this->getRequest($value);
}
}
else
{
$response = $this->getRequest($value);
}
return $response;

Get the response from getData(), and in a second step, check if $response is set, and if not, get the value from getRequest():
if (!empty($data)) {
$getData = $this->getData($data);
if (!empty($getData)) {
$response = $getData->name;
}
}
$response = $response ?? $this->getRequest($value);

You could do this:
if(!empty($data)) {
$getData = $this->getData($data);
if(!empty($getData)) {
$response = $getData->name;
}
}
if ($response == null) { // Or check if the $response is not filled yet
$response = $this->getRequest($value);
}
return $response;

This should help
$response = $this->getRequest($value);
if(!empty($data)){
$getData = $this->getData($data);
if(!empty($getData))
{
$response = $getData->name;
}
}
return $response;

if(!empty($data) && ($getData = $this->getData($data)) && !empty($getData))
{
$response = $getData->name;
}
else
{
$response = $this->getRequest($value);
}
return $response;

Related

Is it possible to update inventory_policy for all products using API in Shopify?

From my PHP application, I want to update the inventory_policy (continue/deny) of all products using API. Is there any way to do so without a loop?
I did not find any way to update it at once. Hence, I have updated it one by one. Please have the code below.
public function update_inventory_policy_for_all_item($inventory_policy, $page_info=null){
$response = $this->do_get("/admin/api/2021-04/products.json?limit=250".$page_info);
if ($response === FALSE)
{
return false;
}
$result_products = $response['body']['products'];
$headers = $response['headers'];
foreach($result_products as $shopify_product){
foreach($shopify_product['variants'] as $variant){
$variant_id = $variant['id'];
$data['variant'] = array(
'id' => $variant['id'],
'inventory_policy' => $inventory_policy,
);
$this->do_put("/admin/api/2021-04/variants/$variant_id.json", $data);
}
}
if(isset($headers['link'])) {
$links = explode(',', $headers['link']);
foreach($links as $link) {
$next_page = false;
if(strpos($link, 'rel="next"')) {
$next_page = $link;
}
}
if($next_page) {
preg_match('~<(.*?)>~', $next_page, $next);
$url_components = parse_url($next[1]);
parse_str($url_components['query'], $params);
$page_info = '&page_info=' . $params['page_info'];
$this->update_inventory_policy_for_all_item($inventory_policy, $page_info);
}
}
return true;
}

php always returns error for empty params in postman?

I'm trying to make php get, but it always seems to call haveEmptyParameters.
The call is to getInformation() and that works fine. Just the parameters never seem to go through? Or maybe there is another error?
$app->get('/getinformation', function(Request $request, Response $response){
if(!haveEmptyParameters(array('field', 'username'), $request, $response)){
$request_data = $request->getParsedBody();
$field = $request_data['field'];
$username = $request_data['username'];
$db = new DbOperations;
$result = $db->getInformation($field,$username);
$response_data = array();
$response_data['error'] = false;
$response_data['users'] = $result;
$response->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
}
});
function haveEmptyParameters($required_params, $request, $response){
$error = false;
$error_params = '';
$request_params = $request->getParsedBody();
foreach($required_params as $param){
if(!isset($request_params[$param]) || strlen($request_params[$param])<=0){
$error = true;
$error_params .= $param . ', ';
}
}
if($error){
$error_detail = array();
$error_detail['error'] = true;
$error_detail['message'] = 'Required parameters ' . substr($error_params, 0, -2) . ' are missing or empty';
$response->write(json_encode($error_detail));
}
return $error;
}
$app->run();
-----Postman Output of error-------
{"error":true,"message":"Required parameters field, username are missing or empty"}

Symfony- passing post params returns the same

I defined my postParams where I want to pass "hash" value from db.
What I am trying to accomplish is that if hash exists in my Session table to return TRUE and if not to return FLASE.
Problem is my code always returns TRUE.
What I am missing?
$postData = $this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($postData['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}
And my requirePostParams works fine! (tested on other functions)
protected function requirePostParams($params) {
$currentRequest = $this->get('request_stack')->getCurrentRequest();
$postData = $currentRequest->request->all();
$postContent = json_decode($currentRequest->getContent(), true);
if(!empty($postContent)) $postData = $postContent;
$this->data = $postData;
$missingParams = [];
foreach ($params as $param) {
if (!array_key_exists($param, $postData)) {
$missingParams[] = $param;
}
}
}
And my service:
$findHash = $this->getSessionRepository()->findOneBy([
'hash' => $hash
]);
As xmike mentioned in comments, function requirePostParams returns nothing. That's why $postData['hash'] is never set.
Try to replace $postData['hash'] with $this->data['hash']:
$this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($this->data['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}

Use PHP function to override default JSON target with Array

We built an API to directly access other social networks APIs using our keys.
I'm trying to build a fuction to access that API.
The default function has been written and is working.
Question
How can I specify a new array to target the json data?
This will override the default setting.
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if($api !== false) {
$data = json_decode($api, true);
if($data !== null) {
if($service === "twitter") {
return $data['0']['followers_count'];
}
if($service === "instagram") {
if(!empty($path)) {
while($id = array_shift($path)) {
echo $data[$id];
}
return $data;
} else {
return $data['user']['followed_by']['count'];
}
}
} else {
return false;
}
} else {
return "API call failed.";
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", "['user']['full_name']");
exit();
function array_deref($data, $keys) {
return empty($keys) ? $data
: array_deref($data[$keys[0]], array_slice($data, 1))
}
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if ($api === false) {
return "API call failed.";
}
$data = json_decode($api, true);
if($data !== null) {
return false;
}
if ($service === "twitter") {
if (empty($path)) $path = ['0','followers_count'];
return array_deref($data, $path);
} elseif ($service === "instagram") {
if (empty($path)) $path = ['user','followed_by'];
return array_deref($data, $path);
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", ['user', 'full_name']);
echo SocialAPI("JohnDoe", "Instagram");
exit();
I added a utility function, array_deref, to walk the arrays recursively (calls itself to handle each level down).

REST Webservice HTTP_PUT parameter

I make with tonic (php library for rest ) a rest webservice.
I use according to CRUD and REST put for editing a element.
So i call my method with a picture and filetype and parse the paramters and save the base64 encoded file on my server.
Code:
function put($request) {
$response = new Response($request);
$msg = new ErrorMessage();
$dbmodel = new DBModel();
$arr = array('Data' => null,'Message' =>null,'Code' => null);
try{
$split = explode ('&',$request->data);
$para = array();
foreach($split as $i) {
$names = explode('=',$i);
if(!isset($names[0]) or !isset($names[1]))
{
throw new Exception();
}
$para[$names[0]] = $names[1];
}
}
catch(Exception $e)
{
$arr['Code'] = 400;
$arr['Message'] = $msg->getMessage(400);
$response->body = json_encode($arr);
return $response;
}
if (isset($para['picture']) or isset($para['filetype']) )
{
if (isset($para['picture']) and isset($para['filetype']))
{
if (!($para['filetype'] == 'jpg' || $para['filetype'] == 'png'))
{
$arr['Code'] = 688;
$arr['Message'] = $msg->getMessage(617);
$response->body = json_encode($arr);
return $response;
}
$bin = base64_decode($para['picture']);
if (strlen($bin) >524288)
{
$arr['Code'] = 617;
$arr['Message'] = $msg->getMessage(617);
$response->body = json_encode($arr);
return $response;
}
$uid = $dbmodel->getUid($sid);
if($uid<1)
{
$arr['Code'] = 699;
$arr['Message'] = $msg->getMessage(699);
$response->body = json_encode($arr);
return $response;
}
$file = fopen($_SERVER['DOCUMENT_ROOT']."/img/".$uid.".".$para['filetype'], 'wb');
fwrite($file, $bin);
fclose($file);
}
else
{
$arr['Code'] = 616;
$arr['Message'] = $msg->getMessage(616);
$response->body = json_encode($arr);
return $response;
}
}
$arr['Code'] = 200;
$arr['Message'] = $msg->getMessage(200);
$response->body = json_encode($arr);
return $response;
}
Problem: The saved picture isn't like the original one it can't be displayed as image
I use http://www.redio.info/werkzeuge/file2base64.html to convert my picture into base64. I think that the problem could be in the parsing at the beginning of my code.
Original: 13.872 Bytes
New Image: 14.313 Bytes
Your picture parameter gets probably urlencoded, that would explain the bigger filesize. (e.g. '/' to %2F)
Try to put a urldecode around the parameter before you decode it.
$bin = base64_decode(urldecode($para['picture']));

Categories