l am writing an application that makes a call to an api then returns some data. However l am stuck on populating the database with the data from the API. l tried looking through the decoded json array of object but that for some reason throws an error. my code is as below:
class DefaultController extends Controller
{
public function indexAction()
{
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', API);
$data = json_decode($response->getBody()->getContents(), true);
$request = new Request();
foreach ($data as $data) {
$request->setName($data['name']);
}
$em = $this->getDoctrine()->getManager();
$em->persist($request);
$em->flush();
return new Response('Saved new product with id '.$request->getId());
return $this->render('ApiBundle:Default:index.html.twig');
}
For some reason the loop is not working. Is there a reason why this loop wont work and any work around?
Not certain, but in your for loop you are using '$data' twice. Instead should be (used $d instead):
foreach ($data as $d) {
$request->setName($d['name']);
}
Also, you could try dumping $data to see what it contains.
Related
I'm working on cakephp, make an http client where the driver is like this
public function index()
{
$http = new Client();
$response = $http->get('http://localhost/paginaws/articles/index.json');
$json = $response->json;
$valor = $response->body;
$this->set(compact(['valor']));
}
and what I want is to pass it to a view that is going to be a table. I know I have to use a foreach but it does not show me anything. When doing a var_dump shows me that it is an object type.
public function searchStudent($student)
{
$db = Di::getDefault()->get('db');
$sql = 'SELECT * FROM students WHERE insurance_number = "'.$student['searchInsurenceNum'].'"';
$sth = $db->prepare($sql);
$sth->execute();
When i check here die(var_dump($sth->fetchAll())), i am getting array with data from database.
return $sth->fetchAll();
}
public function searchAction()
{
$request = new Request();
$response = new Response();
if ($request->isPost()) {
(new ContactsStorage())->searchStudent($request->getPost());
}
But in controller when i call fuction die(var_dump((new ContactsStorage())->searchStudent())), i am getting empty array .
$this->view->setVar('findData', (new ContactsStorage())->searchStudent());
}
Maybe your request is not a POST ? ($request->isPost())
by using this method you're allow to find your students only on POST request. Remove condition and try again.
If you have model Student which extends \Phalcon\Mvc\Model you can use magic static methods findBy{$FeildCamelCasedName} so there is no need to create extra repositories and even methods if you want to ge tsome entity by simple criteria:
$findData = Student::findByInsuranceNumber($in);
also you can find one element by such criteria by simply using magic method findFirstBy{$Field}
I am working with Yii2 REST api and using Authorisation : Bearer for authentication.
I have a model Event and only 2 actions Create and Update but my Updateaction is not working fine and throws Object Class conversion error.
I am using following code for finding Event model with mixed condition.
public function actionUpdate($id)
{
$params=$_REQUEST;
/*Following line throws error */
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id'=> Yii::$app->user->identity]);
if($model !== null){
$model->attributes=$params;
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
}
}
}
The error is something like this
Object of class api\modules\v1\models\User could not be converted to string
I cant figure out why it says i have created object of User class.
Yii::$app->user->identity
is object you should use
Yii::$app->user->identity->id
so final line will be:
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id'=> Yii::$app->user->identity->id]);
The problem is with your andWhere(), you are trying to assign partner_id an object viz. Yii::$app->user->identity, so this is where your code is breaking. And do not use json_encode when you can use Yii's response format Response::FORMAT_JSON, so your code would be like:
public function actionUpdate($id)
{
\Yii::$app->response->format = yii\web\Response::FORMAT_JSON; // formatting response in json format
$params= json_decode(\Yii::$app->request->rawBody, 1);
/*Following line throws error */
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id'=> Yii::$app->user->identity->id]);
if($model !== null){
$model->attributes=$params;
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
$this->setHeader(200);
return array('status'=>1,'data'=> $model); // you can simply use $model
}
}
}
The issue is here:
andWhere(['partner_id'=> Yii::$app->user->identity])
You ARE attempting to convert a user object (Yii::$app->user->identity) to a string. Instead, you need to use the user's id (Yii::$app->user->identity->id) which is a string.
I am currently working with the Amazon MWS to integrate some features into wordpress via a plugin. I am using the client libraries provided by amazon found here:
https://developer.amazonservices.com/api.html?group=bde§ion=reports&version=latest
Using these client libraries and the sample php files included I have set up my plugin to make two API calls. The first is requestReport
public function requestInventoryReport() {
AWI_Amazon_Config::defineCredentials(); // Defines data for API Call
$serviceUrl = "https://mws.amazonservices.com";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebService_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
$config,
APPLICATION_NAME,
APPLICATION_VERSION);
$request = new MarketplaceWebService_Model_RequestReportRequest();
$request->setMerchant(MERCHANT_ID);
$request->setReportType('_GET_MERCHANT_LISTINGS_DATA_');
self::invokeRequestReport($service, $request);
}
private function invokeRequestReport(MarketplaceWebService_Interface $service, $request) {
try {
$response = $service->requestReport($request);
if ($response->isSetRequestReportResult()) {
// Print Out Data
}
} catch (MarketplaceWebService_Exception $ex) {
// Print Out Error
}
}
and the second is getReportRequestList which has code similar to the first function. I am able to run these functions without any errors. The issue that I am having is that $response->isSetRequestReportResult() returns false. From my understanding and looking into the response object, this would suggest that the response object does not have the result. (Upon printing out the response object I can see that the FieldValue of the result array is NULL.) The call, however, does not throw an error but neither does it have the result.
I did some digging through the code and found that the result does actually get returned from the api call but never gets set to the return object when the library attempts to parse it from XML. I've tracked the error down to this block of code (This code is untouched by me and directly from the amazon mws reports library).
private function fromDOMElement(DOMElement $dom)
{
$xpath = new DOMXPath($dom->ownerDocument);
$xpath->registerNamespace('a', 'http://mws.amazonaws.com/doc/2009-01-01/');
foreach ($this->fields as $fieldName => $field) {
$fieldType = $field['FieldType'];
if (is_array($fieldType)) {
if ($this->isComplexType($fieldType[0])) {
// Handle Data
} else {
// Handle Data
}
} else {
if ($this->isComplexType($fieldType)) {
// Handle Data
} else {
$element = $xpath->query("./a:$fieldName/text()", $dom);
$data = null;
if ($element->length == 1) {
switch($this->fields[$fieldName]['FieldType']) {
case 'DateTime':
$data = new DateTime($element->item(0)->data,
new DateTimeZone('UTC'));
break;
case 'bool':
$value = $element->item(0)->data;
$data = $value === 'true' ? true : false;
break;
default:
$data = $element->item(0)->data;
break;
}
$this->fields[$fieldName]['FieldValue'] = $data;
}
}
}
}
}
The data that should go into the RequestReportResult exists at the beginning of this function as a node in the dom element. The flow of logic takes it into the last else statement inside the foreach. The code runs its query and returns $element however $element->length = 13 in my case which causes it to fail the if statement and never set the data to the object. I have also looked into $element->item(0) to see what was in it and it appears to be a dom object itself matching the original dom object but with a bunch of empty strings.
Now, I'm new to working with the MWS and my gut feeling is that I am missing a parameter somewhere in my api call that is messing up how the data is returned and is causing this weird error, but I'm out of ideas at this point. If anyone has any ideas or could point me in the right direction, I would greatly appreciate it.
Thanks for your time!
** Also as a side note, Amazon Scratchpad does return everything properly using the same parameters that I am using in my code **
These works for me, check if you are missing anything.
For RequestReportRequest i am doing this:
$request = new MarketplaceWebService_Model_RequestReportRequest();
$marketplaceIdArray = array("Id" => array($pos_data['marketplace_id']));
$request->setMarketplaceIdList($marketplaceIdArray);
$request->setMerchant($pos_data['merchant_id']);
$request->setReportType($this->report_type);
For GetReportRequestList i am doing this:
$service = new MarketplaceWebService_Client($pos_data['aws_access_key'], $pos_data['aws_secret_access_key'], $pos_data['config'], $pos_data['application_name'], $pos_data['application_version']);
$report_request = new MarketplaceWebService_Model_GetReportRequestListRequest();
$report_request->setMerchant($pos_data["merchant_id"]);
$report_type_request = new MarketplaceWebService_Model_TypeList();
$report_type_request->setType($this->report_type);
$report_request->setReportTypeList($report_type_request);
$report_request_status = $this->invokeGetReportRequestList($service, $report_request, $report_requestID);
In Symfony2, I want to test a controller action with 2 subsequent requests if it behaves properly.
The first request will analyze the database and take appropriate action, the second request will also analyze the database and take a different action.
My code goes as follows:
protected function setUp() {
$this->_client = static::createClient();
$kernel = static::$kernel;
$kernel->boot();
$this->_em = $kernel->getContainer()->get('doctrine.orm.default_entity_manager');
$this->_em->beginTransaction();
}
public function testAddToCartWith2Posts() {
$this->addObjects(); // Initialize the database
$object = static::$kernel->getContainer()->get('doctrine')->getRepository('BaseBundle:Object')->findAll()[0];
$id = $object->getId();
$crawler = $this->_client->request('POST', '/cart/add/' . $id);
$crawler = $this->_client->request('POST', '/cart/add/' . $id);
$session = static::$kernel->getContainer()->get('session');
$cart = $session->get('cart');
$this->assertEquals($session->getId(), $cart->getSession());
$this->assertEquals(2, count($cart->getCartItems()));
}
The first request is able to read the list of objects. The second request is not.
The database becomes empty between requests. How could I fix this problem?