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 created 12 different functions and 12 different ctp files for showing the value from the database into my webpage using 12 months 12 Tabs LIKE January ... December . I want to show three top values from each month. As per cakephp we created different function for different CTP files. Like for January i created one function name January and created one CTP file name january.ctp and like for rest of 11 months i created different different functions using months name with same month wise CTP files.Just the value of the month($month) is different in each function , Is there is any way to write one function and sending variable into the 12 ctp files. How can i make my code more efficient, i added my code below
<?php
namespace App\Controller;
use Cake\Core\Configure;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
public function january()
{
$userDetails=Configure::read('userdetails');
$profile=Configure::read('profile');
$this->loadModel('Users');
$usersID = $this->Auth->user('id');
$profileImageShow=$this->Users->getUploadPath($usersID);
$categoryTable=TableRegistry::getTableLocator()->get('categories');
$results=$categoryTable->find("all")->toList();
$votes;
$month = 01;
$year=date("Y");
$categoriesArray;
foreach($results as $result)
{
$votesCount=$this->Sjvotes->find("all",[
'conditions'=>['month'=> $month,'year'=>$year,'category_id'=>$result->id]])->select(['count' => $this->Sjvotes->find()->func()->count('*')])->group(['user_id','category_id'])->order(['count'=>'desc'])->limit(2)->toList();
$categoriesArray[]=$result->id;
$temp=0;
foreach($votesCount as $key => $count)
{
if($temp!=$count->count)
{
$userVotes=$this->Sjvotes->find("all", ['conditions'=>['year'=>$year,'category_id'=>$result->id]])->
select(['count' => $this->Sjvotes->find()->func()->count('*'), 'category_id','user_id','fname'=>'Users.firstname','lname'=>'Users.lastname', 'profile_image'=>'Users.profile_image'])
->contain(['Users'])
->group(['user_id','category_id'])
->having(['count'=>$count->count])
->order(['count'=>'desc'])
->toList();
$temp=$count->count;
if($key==0)
{
$class="gold";
}else
if($key==1)
{
$class="silver";
}else
{
$class="bronz";
}
$votes[$result->id][$class]=$userVotes;
}
}
}
$voteToppers=$this->Sjvotes->find("all", ['conditions'=>['year'=>$year,'category_id in ' =>$categoriesArray]])->
select(['count' => $this->Sjvotes->find()->func()->count('*'), 'category_id','user_id','fname'=>'Users.firstname','lname'=>'Users.lastname', 'profile_image'=>'Users.profile_image'])
->contain(['Users'])
->group(['user_id'])
->order(['count'=>'desc'])
->toList();
$temp=0;
$changes=0;
foreach($voteToppers as $key => $topper)
{
if($temp!=$topper->count)
{
if($changes==0)
{
$class="gold";
}else
if($changes==1)
{
$class="silver";
}else
{
$class="bronz";
}
$temp=$topper->count;
$changes++;
}
if($changes>3)
{
break;
}
$topUsers[$class][]=$topper;
}
$this->set(compact("results"));
$this->set(compact("votes"));
$this->set(compact(["topUsers", "userDetails", "profile"]));
}
//For February
public function february()
{
$userDetails=Configure::read('userdetails');
$profile=Configure::read('profile');
$this->loadModel('Users');
$usersID = $this->Auth->user('id');
$profileImageShow=$this->Users->getUploadPath($usersID);
$categoryTable=TableRegistry::getTableLocator()->get('categories');
$results=$categoryTable->find("all")->toList();
$votes;
$month = 02;
$year=date("Y");
$categoriesArray;
foreach($results as $result)
{
$votesCount=$this->Sjvotes->find("all",[
'conditions'=>['month'=> $month,'year'=>$year,'category_id'=>$result->id]])->select(['count' => $this->Sjvotes->find()->func()->count('*')])->group(['user_id','category_id'])->order(['count'=>'desc'])->limit(2)->toList();
$categoriesArray[]=$result->id;
$temp=0;
foreach($votesCount as $key => $count)
{
if($temp!=$count->count)
{
$userVotes=$this->Sjvotes->find("all", ['conditions'=>['month'=>$month,'year'=>$year,'category_id'=>$result->id]])->
select(['count' => $this->Sjvotes->find()->func()->count('*'), 'category_id','user_id','fname'=>'Users.firstname','lname'=>'Users.lastname', 'profile_image'=>'Users.profile_image'])
->contain(['Users'])
->group(['user_id','category_id'])
->having(['count'=>$count->count])
->order(['count'=>'desc'])
->toList();
$temp=$count->count;
if($key==0)
{
$class="gold";
}else
if($key==1)
{
$class="silver";
}else
{
$class="bronz";
}
$votes[$result->id][$class]=$userVotes;
}
}
}
$voteToppers=$this->Sjvotes->find("all", ['conditions'=>['month'=>$month,'year'=>$year,'category_id in ' =>$categoriesArray]])->
select(['count' => $this->Sjvotes->find()->func()->count('*'), 'category_id','user_id','fname'=>'Users.firstname','lname'=>'Users.lastname', 'profile_image'=>'Users.profile_image'])
->contain(['Users'])
->group(['user_id'])
->order(['count'=>'desc'])
->toList();
$temp=0;
$changes=0;
foreach($voteToppers as $key => $topper)
{
if($temp!=$topper->count)
{
if($changes==0)
{
$class="gold";
}else
if($changes==1)
{
$class="silver";
}else
{
$class="bronz";
}
$temp=$topper->count;
$changes++;
}
if($changes>3)
{
break;
}
$topUsers[$class][]=$topper;
}
$this->set(compact("results"));
$this->set(compact("votes"));
$this->set(compact(["topUsers", "userDetails", "profile"]));
}
//March
public function march()
{
$userDetails=Configure::read('userdetails');
$profile=Configure::read('profile');
$this->loadModel('Users');
$usersID = $this->Auth->user('id');
$profileImageShow=$this->Users->getUploadPath($usersID);
$categoryTable=TableRegistry::getTableLocator()->get('categories');
$results=$categoryTable->find("all")->toList();
$votes;
$month = 03;
$year=date("Y");
$categoriesArray;
foreach($results as $result)
{
$votesCount=$this->Sjvotes->find("all",[
'conditions'=>['month'=> $month,'year'=>$year,'category_id'=>$result->id]])->select(['count' => $this->Sjvotes->find()->func()->count('*')])->group(['user_id','category_id'])->order(['count'=>'desc'])->limit(2)->toList();
$categoriesArray[]=$result->id;
$temp=0;
foreach($votesCount as $key => $count)
{
if($temp!=$count->count)
{
$userVotes=$this->Sjvotes->find("all", ['conditions'=>['month'=>$month,'year'=>$year,'category_id'=>$result->id]])->
select(['count' => $this->Sjvotes->find()->func()->count('*'), 'category_id','user_id','fname'=>'Users.firstname','lname'=>'Users.lastname', 'profile_image'=>'Users.profile_image'])
->contain(['Users'])
->group(['user_id','category_id'])
->having(['count'=>$count->count])
->order(['count'=>'desc'])
->toList();
$temp=$count->count;
if($key==0)
{
$class="gold";
}else
if($key==1)
{
$class="silver";
}else
{
$class="bronz";
}
$votes[$result->id][$class]=$userVotes;
}
}
}
$voteToppers=$this->Sjvotes->find("all", ['conditions'=>['month'=>$month,'year'=>$year,'category_id in ' =>$categoriesArray]])->
select(['count' => $this->Sjvotes->find()->func()->count('*'), 'category_id','user_id','fname'=>'Users.firstname','lname'=>'Users.lastname','profile_image'=>'Users.profile_image'])
->contain(['Users'])
->group(['user_id'])
->order(['count'=>'desc'])
->toList();
$temp=0;
$changes=0;
foreach($voteToppers as $key => $topper)
{
if($temp!=$topper->count)
{
if($changes==0)
{
$class="gold";
}else
if($changes==1)
{
$class="silver";
}else
{
$class="bronz";
}
$temp=$topper->count;
$changes++;
}
if($changes>3)
{
break;
}
$topUsers[$class][]=$topper;
}
$this->set(compact("results"));
$this->set(compact("votes"));
$this->set(compact(["topUsers", "userDetails", "profile"]));
}
//april
One thing you can do is. Get the current month and then check the current month, then send to that month ctp file according to the current month. Like this -
$month = date('M');
if ($month == 'Mar') {
$this->render('/march');
}
if ($month == 'Jan'){
$this->render('/jan');
}
The only difference is the value of the $month variable?
public function january() {
return $this->_month(1, 'January');
}
public function february() {
return $this->_month(2, 'February');
}
// etc...
protected function _month($month, $monthName) {
// Existing implementation of each month's function here,
// except without initializing the $month variable
$this->set(compact('results', 'votes', 'topUsers', 'userDetails', 'profile', 'month', 'monthName'));
$this->render('month');
}
And rename january.ctp to month.ctp, and you'll have the $month and $monthName variables available there now to tell you what month it's for.
In this example, the function validateJsonNotEmptyImage does not work as expected?
Just to clarify.
'src' => $image->src, // WORKS
'height' => $this->validateJsonNotEmptyImage('type', 'width'), // DOES NOT WORK
public function validateJsonNotEmptyImage($type, $array1) {
if ($type, $array1) {
if (isset($type->$array1)) {
return $type . '->' . $array1;
} else {
return null;
}
}
}
$productsImagesToSiteArray = array();
foreach ($this->resource->images as $image) {
$productsImagesToSiteArray[] = array(
'height' => $this->validateJsonNotEmptyImage('$image', 'width'),
'src' => $image->src,
);
}
I see two mistakes
1) your method validateJsonNotEmptyImage, in body you have wrong IF it should be check with null[here1] and you should return value not string[here2].
And also you should return everytime any value or null[here3].
public function validateJsonNotEmptyImage($type, $array1) {
if ($type != null && $array1 != null) { <----------- here1
if (isset($type->$array1)) {
return $type->$array1; <----------- here2
} else {
return null;
}
}
return null; <----------- here3
}
2) you should pass variable not string in your call (remove quotes from $image)
$this->validateJsonNotEmptyImage($image, 'width')
I am trying to port my web app from laravel 4 to 5 but I am having issues in that one of my model classes is not found.
I have tried to utilize namespacing and have the following my Models which are located locally C:\xampp\htdocs\awsconfig\app\Models
the file which the error appears in looks like
<?php
use App\Models\SecurityGroup;
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../resources/sns messages/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
/*if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
} */
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'ResourceDeleted':
// echo"found Resource Deleted<br>";
//ITEM DELETED
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
$resource->delete();
if( isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
if ($tag->checkExists($cfi->configuration->tags))
{
$tag->delete();
}
}
}
}
}
else
{
echo "Deleting ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'OK':
//echo"found Resource OK<br>";
//ITEM UPDATED
if (array_key_exists($cfi->resourceType, $resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$update_array[from_camel_case($key)] = $value;
}
}
$resource->populate($update_array);
$resource->save();
}
}
else
{
echo "Updating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
default:
echo "Status ".$cfi['configurationItemStatus']." not yet supported<br>";
break;
}
}
}
}
}
and the corresponding model whose class cannot be found looks like :
<?php namespace App\Models;
use Eloquent;
class SecurityGroup extends Eloquent
{
protected $table = 'security_group';
public $timestamps = false;
protected $guarded = array('id');
public $fields = array('groupId',
'groupName',
'description',
'ownerId'
);
public function checkExists()
{
return self::where('group_id', $this->group_id)->first();
}
public function populate($array)
{
foreach ($array as $k => $v)
{
$this->$k = $v;
}
}
}
I am lost as to what is causing the problem I don't see any typos but then again who knows as always thanks for any help given.
to solve the resource type needs the full namespace declaration
Hello I have a four computers that I would like to ping before using. The pinging is done via a PHP page with the following function.
if (isset($_POST['playgroundcheck'])) {
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping))
echo $ping -> getMessage();
else {
/* Number of packets to send */
$ping -> setArgs(array('count' => 2));
$pgData = $ping -> ping($PGIP);
// print_r($pgData);
if ($pgData -> _received > 0) {
return true;
//echo "<h1><font color=\"green\">ON</font></h1>";
} else {
//echo "<h1><font color=\"red\">OFF</font></h1>";
return false;
}
}
}
$IP2sping = array("pc1" => "192.168.1.121", "pc2" => "192.168.1.122", "pc3" => "192.168.1.123", "pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value) {
if (ping($value) == true) {
echo $key . " alive<br>";
} else {
echo $key . " off<br>";
}
}
}
I created a form to call the function with a submit button. All of this works but my problems is trying to display the output outside the function. For example currently all output is displayed like the following.
pc1 alive
pc2 alive
pc3 alive
pc4 alive
I want to know how the results of pc1, pc2, pc3 and pc4 can be displayed separately outside the function.
Thanks for answers, but I found a solution that works great for what I want to do using variables variables.
By changing $key to $$key pc1 pc2 pc3 and pc4 become variables and then I can use it anywhere I want.
$IP2sping = array("pc1" => "192.168.1.121",
"pc2" => "192.168.1.122",
"pc3" => "192.168.1.123",
"pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
$key." alive<br>";
} else {
$key." off<br>"; }
}
}
In fact, it's shown outside the function. Here is where you show the results.
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
I would do something like that for what you want:
$available = null;
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
}
Or
$available = null;
foreach ($IP2sping as $key => $value)
$available[$key] = ping($value) ? true : false;
Then, you'll be able to use the $available array for whatever you want :)
Does this help?
if (isset($_POST['playgroundcheck'])) {
// Define the function
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
return FALSE;
} else {
/* Number of packets to send */
$ping->setArgs(array('count' => 2));
$pgData = $ping->ping($PGIP);
// print_r($pgData);
return ($pgData->_received > 0);
}
}
// Define array of items to ping
$IP2sping = array("pc1" => array('ip' => "192.168.1.121"),
"pc2" => array('ip' => "192.168.1.122"),
"pc3" => array('ip' => "192.168.1.123"),
"pc4" => array('ip' => "192.168.1.124")
);
// Get the results of whether the machines are alive
foreach ($IP2sping as $key => $value){
$IP2sping[$key]['alive'] = ping($value);
}
/*
Do a load more stuff
*/
foreach ($IP2sping as $name => $data) {
echo "$name ({$data['ip']}) is ".(($data['alive']) ? 'alive' : 'dead')."<br />\n";
}
}