I have controller:
class MyController extends AbstractRestfulController{
protected $myTable;
public function getList(){
$results = $this->getMyTable()->fetchAll();
$data = array();
foreach($results as $result) {
$data[] = $result;
}
return new JsonModel(array(
'data' => $data
));
}
[...]
and I check:
curl -i -H "Accept: application/json" http://localhost/myapp/restroute -X GET
and it's fine. But I want to send to this method extra data, for example:
curl -i -H "Accept: application/json" http://localhost/myapp/restroute -X GET -d "name=john"
How to read this data in getList() method?
I could use create($data) method but somehow it does not fit me (create method is for creation, etc). I want, for example get list of some type of objects limited by variable in $_GET.
Within AbstractRestfulController, there's a helper method called processBodyContent which is ideal for what you're trying to do:
public function getList()
{
$content = $this->processBodyContent($this->getRequest());
$name = array_key_exists('name', $content) ? $content['name'] : '';
// ...
}
As you're using GET thought, you should consider doing:
curl -i -H "Accept: application/json" http://localhost/myapp/restroute?name=john -X GET
You can then retrieve within getList() like this:
public function getList()
{
$name = $this->params()->fromQuery('name');
// ...
}
Related
I've been trying to generate a public downloadable URL for OneDrive
for Business and SharePoint DriveItem object using /createLink api.
curl \
-X POST \
-d '{"type":"view","scope":"anonymous"}' \
-H 'Authorization: bearer xxx_Access_Token_xxx' \
-H 'Content-Type: application/json' \
"https://graph.microsoft.com/v1.0/drive/items/<item-id>/createLink"
Above call returns JSON result with body.link.webUrl (https://my.sharepoint.com/:u:/g/XXXXrKmGKlXXXXXXXXXXsq0Bh3x4TTXXXXXXXXXXXXXXXXX) being the sharable URL. However, this link doesn't contain the reference to file directly.
As per this comment, appending download=1 as query string parameter to generated shared URL will allow the user to open the original file directly. But I could not find any documentation supporting this behavior.
Is it possible to
Download the file directly.
To use public URL as src attribute of img tag.
You may follow official document of OneDrive
You will have to put below line of code in success field of IProgressCallback. Here ItemId is "id of uploaded item".
String itemId = result.id;
TestBase testBase = new TestBase(xdata.getinstance().getSetting(config.onedriveaccesstoken));
AsyncTask<Void, Void, Void> downloadfileonedrive = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(final Void... params) {
com.microsoft.graph.models.extensions.Permission response = testBase.graphClient
.me()
.drive()
.items(itemId)
.createLink("edit", "anonymous")
.buildRequest().post();
Log.e("Sharable link : ", ""+response);
try {
String sharabalelink = new JSONObject(response.getRawObject().getAsJsonObject("link").toString()).getString("webUrl");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}};
downloadfileonedrive.execute();
I'm new at phpspec (coming from phpunit) and I have problems setting the behavior of a mock returned by another mock.
I'm creating a wrapper class around the Guzzle client and I want to check the output of the response.
Here's the spec:
function it_gets_response_status_code(Client $client, Url $url, Response $response)
{
$this->beConstructedWith($client);
$url->__toString()->willReturn('http://example.com');
$data = ['foo' => 'bar'];
$response->getStatusCode()->willReturn(200);
$client->request('POST', $url, ['form_params' => $data])->willReturn($response);
$this->post($url, $data);
assert($this->getResponseStatusCode() === 200); // Failing! :(
}
and the corresponding functions in my class:
public function post(Url $url, array $data)
{
$this->response = $this->client->request('POST', (string) $url, ['form_params' => $data]);
}
public function getResponseStatusCode()
{
return $this->response->getStatusCode();
}
The assertion is failing and when I check what is this status code, I see that instead of the integer 200, it's an instance of PhpSpec\Wrapper\Subject. What am I missing here?
I've searched and googled but cannot find resources about using the mock returned by another mock in phpspec. I'm wondering if the reason for this is that it's a code smell? If so I'd be glad to see how I could do this differently (currently I cannot see how I could keep the code simple and doing differently).
try:
assert($this->getResponseStatusCode()->getWrappedObject() === 200);
this:
$response->getStatusCode()->willReturn(200)
returns a '200' string wrapped in an Subject object, on which you can then make mock/stub calls if needed. To get the real value of the subject you need to call getWrappedObject
i'm trying to queue an email sending invoice emails in laravel 5.1, i pass in a variable called invoice, when i dd($invoice->dateString()) in the Job class it's return the correct value but when i pass it in to the view the $invoice variable return empty array (so i get an error about trying to get property from non-object...).
the second problem i have is when i try to add attachment to the job it returns an error : "Serialization of closure failed: Serialization of 'SplFileInfo' is not allowed".
the job class looks like that:
namespace LM2\Jobs;
use Guzzle\Service\Client;
use LM2\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use LM2\Models\User as User;
use LM2\Models\Client as LMClient;
class SendInvoiceEmail extends Job implements SelfHandling, ShouldQueue
{
protected $user;
protected $invoice;
protected $attachment;
protected $update;
public function __construct(User $user, LMClient $client, $invoice,$update)
{
$this->user = $user;
$this->client = $client;
$this->invoice = $invoice;
$this->update = $update;
}
public function handle()
{
$attachment = $this->client->invoiceFile($this->invoice->id,['vendor' => 'Test','product' => 'Your Product']);
$invoice = $this->invoice;
$data = [
'invoice' => $this->invoice,
'update'=> $this->update,
];
$user = $this->user;
\Mail::queue('emails.invoices', $data , function($m) use ($user,$invoice,$attachment){
$m->to($user->email)->subject('New payment received')->attach($attachment);
});
}
}
and my controller function looks like that:
public function sendEmailInvoice($update = false){
$client = \Auth::client();
$user = \Auth::user();
$invoices = $client->invoices();
$this->dispatch(new SendInvoiceEmail($user,$client,$invoices[0],$update));
$activity = $data['update'] ? 'updated': 'added';
return ['success', $activity];
}
can someone please tell me what am i doing wrong?
thanks a lot you all :)
Just a guess... but when using Mail::queue() the $data get's converted/cast to an array/you lose your objects inside of the view - hence why you're receiving errors when trying to call methods(), because they don't exist.
Rather than passing invoice + update objects, get what you need from them in the handle method and construct the $data array.
$data = [
'invoice_foo' => $invoice->getFoo(),
'invoice_bar' => $invoice->getBar(),
];
*** Apologies if this doesn't help at all!
so i found the answer thanks to #Michael, i have changed my handle so it's look like this now:
public function handle(Mailer $mailer)
{
$client = $this->client;
$invoice = $this->invoice;
$data = [
'date' => $invoice->dateString(),
'amount' => $invoice->dollars(),
'update'=> $this->update,
];
$user = $this->user;
return $mailer->queue('emails.invoices', $data , function($m) use ($user,$client,$invoice){
$attachment = $client->invoiceFile($invoice->id,['vendor' => 'Infogamy','product' => 'Your Product']);
$m->to($user->email)->subject('New payment received')->attach($attachment);
});
}
The attachment should be processed inside the mailer callback function, and the function called from the $invoice variable (object) should be called inside the handle function and not in the blade view template.
Hi I am writing custom plugin for elastic search,
but I unable to get the parameter from the post request.
#Inject
public HelloRestHandler(Settings settings, RestController restController, Client esClient) {
super(settings, restController, esClient);
restController.registerHandler(RestRequest.Method.GET, "/_hello", this);
restController.registerHandler(RestRequest.Method.POST, "/_hello", this);
restController.registerHandler(RestRequest.Method.PUT, "/_hello", this);
}
#Override
public void handleRequest(final RestRequest request, final RestChannel channel, Client esClient) {
ObjectMapper mapper = new ObjectMapper();
String json;
try{json= mapper.writeValueAsString(request.params());}catch (Exception exp){ json ="not found";}
channel.sendResponse(new BytesRestResponse(OK,json));}
The curl:
curl -XPOST "http://localhost:9200/_hello/" -d '{"first":"1"}'
response :
"{}" (empty JSON)
Please help me out to fix my issue. Thanks.
request.params() returns the HTTP parameters passed in the query string. In your case, there are none. Try with request.content() instead.
String json;
try{
json = mapper.writeValueAsString(request.content());
} catch (Exception exp){
json ="not found";
}
channel.sendResponse(new BytesRestResponse(OK,json));
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
Here is my code of SessionManager.php:
private function generateAuthToken($user)
{
$bits = '';
$fp = #fopen('/dev/urandom', 'rb');
if ($fp !== false) {
$bits .= #fread($fp, 128);
#fclose($fp);
}
return sha1($bits . time() . microtime() . $user->getUsername());
}
I'm getting this error:
Fatal error: Call to a member function getUsername() on a non-object
in
/home/shwetanka/src/Practo/PvrBundle/Manager/SessionManager.php
on line 49
When I'm doing var_dump($user); right before the problem line I'm getting the full user object printed. I'm unable to understand the reason of this error. The function is present in the class User. Even if I try to call any other function of the class even then I get the same error for that function. I'm new to php and having hard time debugging this problem.
Also $user is object of User entity. I'm using symfony2 and this object is returned to me by using this:
$ur = $this->getDoctrine()->getRepository('PractoPvrBundle:User');
$user = $ur->findBy(array('email' => $email));
Sometimes in the implicitly-convert-to-string context, PHP does not do well with method calls... I'm not sure why. Try this:
$username = $user->getUsername();
return sha1($bits . time() . microtime() . $username);
edit:
Also, I suspect that you are actually dealing with an array instead of an object. the line:
$user = $ur->findBy(array('email' => $email));
is probably intended to return many results. Use current() to get the first one:
$user = current($ur->findBy(array('email' => $email)));
Take the user out of the return like:
$username = $user->getUsername();
return sha1($bits . time() . microtime() . $username);
If this doesn't fix it, for debugging purpose you can try:
$username = 'N/A';
if(is_object($user) && method_exists($user, 'getUsername'))
{
$username = $user->getUsername();
}
Also you can cast your parameter $user like:
private function generateAuthToken(User $user) {...
This will throw an error if you get different class instance or non object
$ur = $this->getDoctrine()->getRepository('PractoPvrBundle:User');
$user = $ur->findBy(array('email' => $email));
-> findBy returns array of objects, use -> findOneBy