How to optimize api call PHP - php

I'm working (for fun), with an API (Riot API), and I made something to retrieve match histories (it's in the game). And I've a problem, everything works really fine, but I don't know how to optimize it, what I mean is : I do the call every time the user refresh the page, and it takes loooong looong time. I tried to call it with AJAX, but didn't find a good way, AJAX dont find my objects.
Here is the code :
$match_history = [];
$api = "";
if (!empty($region)) {
try {
$api = new App\Library\RiotAPI\RiotAPI([
App\Library\RiotAPI\RiotAPI::SET_KEY =>
App\Config::API_KEY,
App\Library\RiotAPI\RiotAPI::SET_CACHE_RATELIMIT => true,
App\Library\RiotAPI\RiotAPI::SET_CACHE_CALLS => true,
App\Library\RiotAPI\RiotAPI::SET_REGION =>
App\Library\RiotAPI\Definitions\Region::getRegion($region),
]);
} catch (\Exception $e) {
// die($e->getMessage());
}
}
if ($api) {
// Insert current rank etc...
try {
$summoner = $api-
>getSummonerByName(App\Repository\UserRepository::getInstance()-
>getUserDetail($_SESSION['user']['id'], 'summoner_name'));
} catch (\Exception $e) {
$summoner = null;
}
// Match history
if (!empty($summoner)) {
try {
$matches = $api->getRecentMatchlistByAccount($summoner->accountId);
// For every matches
foreach ($matches as $match) {
$a_match = $api->getMatch($match->gameId);
if ($a_match->gameType === "MATCHED_GAME") {
$gameCreation = date("d-M-Y H:i:s", substr($a_match-
>gameCreation, 0, 10));
if ($gameCreation >= date("d-M-Y",
strtotime($user['created_at']))) {
// Get the participant ID of the customer
foreach ($a_match->participantIdentities as
$participantIdentity) {
if ($participantIdentity->player->currentAccountId
=== $summoner->accountId) {
$participantId = $participantIdentity-
>participantId;
}
}
// Get stats of the participant
foreach ($a_match->participants as $participant) {
if ($participant->participantId === $participantId)
{
$match_history[$match->gameId]['gameCreation'] =
$gameCreation;
$match_history[$match->gameId]['championId'] =
$participant->championId;
$match_history[$match->gameId]['spells']
['spell1'] = $participant->spell1Id;
$match_history[$match->gameId]['spells']
['spell2'] = $participant->spell2Id;
$match_history[$match->gameId]['win'] =
$participant->stats->win;
$match_history[$match->gameId]['kills'] =
$participant->stats->kills;
$match_history[$match->gameId]['deaths'] =
$participant->stats->deaths;
$match_history[$match->gameId]['assists'] =
$participant->stats->assists;
$match_history[$match->gameId]['goldEarned'] =
$participant->stats->goldEarned;
$match_history[$match->gameId]
['totalMinionsKilled'] = $participant->stats->totalMinionsKilled;
$match_history[$match->gameId]['items']['item0']
= $participant->stats->item0;
$match_history[$match->gameId]['items']['item1']
= $participant->stats->item1;
$match_history[$match->gameId]['items']['item2']
= $participant->stats->item2;
$match_history[$match->gameId]['items']['item3']
= $participant->stats->item3;
$match_history[$match->gameId]['items']['item4']
= $participant->stats->item4;
$match_history[$match->gameId]['items']['item5']
= $participant->stats->item5;
$match_history[$match->gameId]['items']['item6']
= $participant->stats->item6;
}
}
}
}
}
} catch (\Exception $e) {
// die($e->getMessage());
}
}
}
I would like to know if there's a way to : - Run it in background, without AJAX or something like : Keep in mind the match_history for X time, and then after X time, do the call again when the user refresh the page.
Thanks for your help!
Best Regards.

Related

Laravel Session works on Chrome, Not on Iphone

I have created a system where users can search for payment solutions for their business here: http://104.236.45.72/
When you click an answer for a question, you'll notice that as you click through on chrome, you get a list at the top of previously answered questions.
When you view this same thing on your mobile device, you'll notice that the questions as the top only show ONE. It's like the session is not persisting on mobile. I have no idea why and I've tried changing the session driver from database to file and tried replacing all of the "$request->session->" references with "Session::", which leads to the same thing, it working on desktop and only showing one previous answer on mobile.
Here is the function being called when you answer a question on the fontend.
public function questions(Request $request, $id, $parentId, $question)
{
//Get the industry...
$data['industry'] = Industries::find($id);
//Get the parent level question and one child...
$data['parentQuestion'] = Questions::where('parentId', $parentId)->where('industryId', $id)->get();
if(count($data['parentQuestion']) > 0) {
foreach($data['parentQuestion'] as $pq) {
if($pq->parentId != 0) {
//How many steps are currently in the array?
if ($request->session()->has('lastSteps')) {
$hasLastSteps = TRUE;
}else {
$hasLastSteps = FALSE;
}
$stepCount = 1;
if($hasLastSteps == TRUE) {
$stepCount += count(Session('lastSteps'));
}
//Get the last steps ready...
$lsQuestion = Questions::find($question);
$lsAnswer = Questions::find($parentId);
$lsQ = array(
'unique' => uniqid(),
'questionId' => $question,
'question' => $lsQuestion->question,
'answer' => $lsAnswer->question,
'url' => '/'.$request->path(),
'stepCount' => $stepCount
);
$dup = 0;
//see if the session has a lastSteps array...
if ($hasLastSteps == TRUE) {
$temp = Session('lastSteps');
foreach($temp as $t) {
if($t['questionId'] == $question) {
$dup = 1;
}
}
}
//No duplicates exist, go ahead and add it to the session!
if($dup === 0) {
$request->session()->push('lastSteps', $lsQ);
}
}
//Grab its children...
if($pq->type === 'question') {
$data['children'] = Questions::where('industryId', $id)->where('parentId', $pq->id)->get();
}else {
//its an endpoint / answer!
}
}
}
//see if the session has a follow up array...
if ($request->session()->has('followUp')) {
$data['followUp'] = Session('followUp');
}else {
$data['followUp'] = array();
}
//see if the session has a lastSteps array...
if ($request->session()->has('lastSteps')) {
$data['lastSteps'] = Session('lastSteps');
}else {
$data['lastSteps'] = array();
}
return view('frontend.questions', $data);
}

PDO There is no active transaction

One of my class files has been spitting out the "There is no active transaction" warning when creating some records. It is the only one doing it and I can't figure out why because all my queries are executing successfully.
My php_errors log has given me zero insight to the issue, nor have any of the other related questions provided any solutions.
try {
App::$DB->beginTransaction();
$rQuery = App::$DB->prepare("INSERT INTO `Cervidae` (`".implode('`, `',array_keys($aSQL)) ."`) VALUES (".implode(",",$aPlaceholders).")");
$rQuery->execute(array_values($aSQL));
$this->_Cervid_ID = App::$DB->lastInsertId();
if (is_array($aData["Treatments"])) {
foreach ($aData["Treatments"] as $sTreatmentName => $sTreatmentData) {
$oTreatmentToCervid = new TreatmentToCervid(array("Treatment_ID" => $sTreatmentData["Treatment_ID"], "Cervid_ID" => $this->_Cervid_ID, "CreatedBy" => $aSQL["CreatedBy"], "UpdatedBy" => $aSQL["UpdatedBy"], "Dose" => $sTreatmentData["TreatmentDose"]), "NEW");
}
}
$oHerdSize = App::getFlat(self::get(array("COUNT(Cervidae.Cervid_ID) AS HerdSize"),array("Cervidae.Herd_ID = $nHerdID","Cervidae.IsActive = 1")));
$rQuery = App::$DB->prepare("UPDATE `Herds` SET `HerdSize` = ".$oHerdSize->HerdSize." WHERE `Herd_ID` = ".$nHerdID);
$rQuery->execute();
App::$DB->commit();
$this->__construct($this->_Cervid_ID, 'ID');
}
catch (Exception $e) {
App::$DB->rollBack();
throw new Exception($e->getMessage());
}

Google Calendar API - Updating an Events start & end date/time

The sample/demo code for Google's API is pretty clear about updating an event title, and it seems like everyone loves copying it into their own tutorials... I can use that example to easily update the title, description, and location of an event, but I cannot use it to update the "when" attribute, which is made up of an array with start and end date/time.
The following code does not return an error but it does not update the date and time as well:
if ($eventOld = getEvent($client, $eventId)) {
//echo "Old title: " . $eventOld->title->text . "<br />\n";
$eventOld->title = $gdataCal->newTitle($title);
$eventOld->where = array($gdataCal->newWhere($where));
$eventOld->content = $gdataCal->newContent("$description");
$eventOld->when[startTime] = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$eventOld->when[endTime] = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
print $startDate;
try
{
$eventOld->save();
}
catch (Zend_Gdata_App_Exception $e)
{
var_dump($e);
return null;
}
//return $eventNew;
}
else
{
return null;
}
You're submitting to the wrong var. $eventOld is previous to make changes
create a new var. Then submit your data for ex.
$eventNew = getEvent($client, $eventId)
$eventNew->when[startTime] = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$eventNew->when[endTime] = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
when is an array of startTime/endTime pairs.

Create order programmatically in Magento

I'm using these two methods to create orders programmatically in Magento.
The first one creates a Quote:
public function prepareCustomerOrder($customerId, array $shoppingCart, array $shippingAddress, array $billingAddress,
$shippingMethod, $couponCode = null)
{
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$storeId = $customerObj->getStoreId();
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeObj = $quoteObj->getStore()->load($storeId);
$quoteObj->setStore($storeObj);
// add products to quote
foreach($shoppingCart as $part) {
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->setStore($storeId)->setStoreId($storeId)->load($part['PartId']);
$productObj->setSkipCheckRequiredOption(true);
try{
$quoteItem = $quoteObj->addProduct($productObj);
$quoteItem->setPrice(20);
$quoteItem->setQty(3);
$quoteItem->setQuote($quoteObj);
$quoteObj->addItem($quoteItem);
} catch (exception $e) {
return false;
}
$productObj->unsSkipCheckRequiredOption();
$quoteItem->checkData();
}
// addresses
$quoteShippingAddress = new Mage_Sales_Model_Quote_Address();
$quoteShippingAddress->setData($shippingAddress);
$quoteBillingAddress = new Mage_Sales_Model_Quote_Address();
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setShippingAddress($quoteShippingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);
// coupon code
if(!empty($couponCode)) $quoteObj->setCouponCode($couponCode);
// shipping method an collect
$quoteObj->getShippingAddress()->setShippingMethod($shippingMethod);
$quoteObj->getShippingAddress()->setCollectShippingRates(true);
$quoteObj->getShippingAddress()->collectShippingRates();
$quoteObj->collectTotals(); // calls $address->collectTotals();
$quoteObj->setIsActive(0);
$quoteObj->save();
return $quoteObj->getId();
}
And the second one uses that Quote to create Order:
public function createOrder($quoteId, $paymentMethod, $paymentData)
{
$quoteObj = Mage::getModel('sales/quote')->load($quoteId); // Mage_Sales_Model_Quote
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
// set payment method
$quotePaymentObj = $quoteObj->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
// convert quote to order
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
// convert quote addresses
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
// set payment options
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if ($paymentData) {
$orderObj->getPayment()->setCcNumber($paymentData->ccNumber);
$orderObj->getPayment()->setCcType($paymentData->ccType);
$orderObj->getPayment()->setCcExpMonth($paymentData->ccExpMonth);
$orderObj->getPayment()->setCcExpYear($paymentData->ccExpYear);
$orderObj->getPayment()->setCcLast4(substr($paymentData->ccNumber,-4));
}
// convert quote items
foreach ($items as $item) {
// #var $item Mage_Sales_Model_Quote_Item
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options) {
$orderItem->setProductOptions($options);
}
if ($item->getParentItem()) {
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$orderObj->setCanShipPartiallyItem(false);
try {
$orderObj->place();
} catch (Exception $e){
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
}
$orderObj->save();
//$orderObj->sendNewOrderEmail();
return $orderObj->getId();
}
The process works fine, no errors, and the order is created. But the total is 0 and there are no products in it no matter what I put.
I've traced it and I can confirm that the rows are added to the sales_flat_quote and sales_flat_quote_item tables, so that is ok. But when running the createOrder and calling
$items = $quoteObj->getAllItems();
an empty array is always returned, and I have no idea why. I have configurable and simple products in my shop. This happens when I add simple, when I add configurable the error appears as the method
$quoteItem = $quoteObj->addProduct($productObj);
returns null.
It seems to me, you didn't load product collection, therefore, the cart always return empty. Try this link, it will give you more clear help. Create order programmatically
// this is get only one product, you can refactor the code
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'Some value here...')
->addAttributeToSelect('*')
->getFirstItem();
// load product data
$this->_product->load($this->_product->getId());
This code worked for me,
public function createorder(array $orderdata)
{
$quoteId = $orderdata['quoteId'];
$paymentMethod = $orderdata['paymentMethod'];
$paymentData = $orderdata['paymentData'];
$quoteObj = Mage::getModel('sales/quote')->load($quoteId);
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
$quotePaymentObj = $quoteObj->getPayment();
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
foreach ($items as $item)
{
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()))
{
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options'))
{
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options)
{
$orderItem->setProductOptions($options);
}
if ($item->getParentItem())
{
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$quoteObj->collectTotals();
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
$orderObj->setCanShipPartiallyItem(false);
try
{
$last_order_increment_id = Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId();
return $last_order_increment_id;
}
catch (Exception $e)
{
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
return "Exception:".$e;
} }
I had the same problem and delved into the API to find a solution. I changed the way that I loaded a product by using :
$productEntityId = '123456';
$store_code = 'my_store_code';
$product = Mage::helper('catalog/product')->getProduct($productEntityId,Mage::app()->getStore($store_code)->getId());
I found this tutorial to be very useful too :
http://www.classyllama.com/content/unravelling-magentos-collecttotals
If you are looking for a script on order creation this is a very good start :
http://pastebin.com/8cft4d8v
Hope that this helps someone ;)

Google Calendar EventId issues (PHP Api)

I've been working with the PHP api for google Calendar, and have been getting quite frustrated.
I downloaded the zend package with all the libraries from google's page, and have been working off the provided code to make sure it can meet my requirements.
The issue I'm running into involves getting an event back from the system. The provided code includes a demo with function getEvent($clientId, $eventId), which based on the documentation and reading the code, i would expect to return an event that is in my calendar that matches the provided Id.
So in my tests, I create a new event, and then I try to retrieve it. However, whenever I retrieve the event, Zend_data_Gdata_App_HttpException is:
function processPageLoad()
{
global $_SESSION, $_GET;
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
requestUserLogin('Please login to your Google Account.');
} else {
$client = getAuthSubHttpClient();
$id = createEvent ($client, 'Tennis with Beth',
'Meet for a quick lesson', 'On the courts',
'2010-10-20', '10:00',
'2010-10-20', '11:00', '-08');
$newEvent = getEvent($client, $id);
}
}
the code for createEvent( ) is :
function createEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$startDate = '2008-01-20', $startTime = '10:00',
$endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08')
{
$gc = new Zend_Gdata_Calendar($client);
$newEntry = $gc->newEventEntry();
$newEntry->title = $gc->newTitle(trim($title));
$newEntry->where = array($gc->newWhere($where));
$newEntry->content = $gc->newContent($desc);
$newEntry->content->type = 'text';
$when = $gc->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$newEntry->when = array($when);
$createdEntry = $gc->insertEvent($newEntry);
return $createdEntry->id->text;
}
And finally the code for getEvent() is:
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
}
we have the same problem, just share my solution. since you assign $id = createEvent()
$id will have a URL values. then you use $id getEvent($client, $id);
the solution is that getCalendarEventEntry() can have a $query or just a URL.
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($eventId);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
Hope it helps!!

Categories