Slim query parameter - php

I want to add a query parameter in my GET Route, which is this one:
$app->get('/rooms', function (ServerRequestInterface $request, ResponseInterface $response, $args) {
try {
$room = new \Riecken\PBS\controller\RoomController();
$result = $room->getRoomsWithDetails();
$response = $response->withJson($result);
$response = $response->withStatus(200);
return $response;
}catch(Exception $e) {
$response->getBody()->write($e->getMessage());
return $response->withStatus($e->getCode());
}
});
What I want to do is that I only want to execute this function when I type "expandAll".
I googled it and I could find something in the Slim documentation:
https://www.slimframework.com/docs/v3/objects/request.html
But I dont know how to implement it.
So in my case:
If "expandAll" I want to execute the function you see above (getRoomWithDetails(), else I want to execute another function.
Is that possible?
Thanky you very much!

You could just pass the required query parameters to getRoomsWithDetails or you just add a if condition.
Example
$app->get('/rooms', function (ServerRequestInterface $request, ResponseInterface $response, $args) {
try {
$expandAll = $request->getParam('expandAll');
$room = new \Riecken\PBS\controller\RoomController();
if ($expandAll) {
$result = $room->getRoomsWithDetails();
} else {
$result = $room->anotherMethod();
}
$response = $response->withJson($result);
$response = $response->withStatus(200);
return $response;
} catch(Exception $e) {
$response = $response->withJson(['error' => ['message' => $e->getMessage()]]);
return $response->withStatus(500);
}
});

Related

"start_batch was called incorrectly" on gRPC unary call

I make an unary call from PHP code like that:
public function getByIDs(array $ids): array
{
$request = new GetByIDsRequest();
$request->setIDs($ids);
$grpcRequest = $this->client->GetByIDs($request, [], ['timeout' => $this->waitTimeout]);
$response = $this->callWithRetries($grpcRequest);
if (!$response->isOk()) {
$status = $response->getStatus();
throw new GrpcServerException(__FUNCTION__, $status->getDetails(), (int)$status->getCode());
}
... // business logic here
}
private function callWithRetries(\Grpc\UnaryCall $grpcRequest): GrpcUnaryCallResponse
{
$response = null;
for ($attempt = 0; $attempt <= self::$maxRetries; $attempt++) {
if ($attempt > 0) {
usleep(mt_rand(1, 5) * self::$waitBeforeRetry);
}
$response = $this->unaryCall($grpcRequest);
$status = $response->getStatus()->getCode();
if ($response->isOk() || !self::isRetryable($status)) {
return $response;
}
}
return $response;
}
protected function unaryCall(UnaryCall $call): GrpcUnaryCallResponse
{
[$response, $status] = $call->wait();
return new GrpcUnaryCallResponse(
$response,
new GrpcStatus($status)
);
}
Sometimes I get the LogicException with message "start_batch was called incorrectly". Any thoughts how to deal with that exception and what is the root cause?
After some investigation I found out that the problem occurs because of reusing the instance of \Grpc\UnaryCall in retries. You must not do that otherwise you get a core dump.
The reason we got the LogicException but not a core dump is using a patched gRPC extension.
Some more technical details you can find in this issue

How do I convert an object to an array in php

Hi I have been trying to figure out how to convert an object to an array I have tried using json_decode but that doesn't turn it into a nested array but it looks like the picture below becuase I am using angular I need everything to be in an array can someone tell me what I am doing wrong
What the data currently looks like when I use json_decode
The PHP function:
public function getForm(Request $request)
{
try
{
$id = $request->input('id');
$form = admin_form::find($id);
if($form) {
$form = admin_form::where('id',$id)->with('fields')->first();
$res['Message'] = "Success";
$res['Status'] = true;
$res['results'] = json_decode($form, true);
return response($res, 200);
} else {
$res['status'] = false;
$res['message'] = "Form not found";
return response($res, 404);
}
} catch(\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
create a variable and store json init and pass response as parameter
var test = json.parse(response);
As I know you don't need to convert object to array, cause you can iterate over it in ng-repeat. Try to use the following syntax:
<div ng-repeat="(key, val) in results">{{key}} => {{val}}</div>
According to ng-repeat documentation
Just for anyone having the problem I had this is how I sloved it
public function getForm(Request $request)
{
try
{
$id = $request->input('id');
$form = admin_form::find($id);
if($form) {
$form = admin_form::where('id',$id)->with('fields')->first();
$res['Message'] = "Success";
$res['Status'] = true;
$res['results'] = [$form->getAttributes()];
return response($res, 200);
} else {
$res['status'] = false;
$res['message'] = "Form not found";
return response($res, 404);
}
} catch(\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
The reason this worked for me was because the $form is an object with all of the information about what I am trying to get and when you do a dd($form) all of the information that it gets from the DB is stored in the attributes array and lumen has a getAttributes() function and from there I put them into [] to get an array
But if you have a relationship with another table then don't use getAttributes just use the [] braces

Too Many redirects in Facebook Login with Phalcon

We have a problem with facebook authentication. We use phalcon and we have the authentication process with the php-sdk-v4 plugin. When we try to login, we have the error of too many redirects. Our website is https://app.wowego.com/register. some help?
CODE:
FILE: AUTH.PHP
public function loginWithFacebook()
{
$di = $this->getDI();
$facebook = new FacebookConnector($di);
$facebookUser = $facebook->getUser();
if (!$facebookUser) {
$scope = [
'scope' => 'email,user_birthday,user_location',
];
return $this->response->redirect($facebook->getLoginUrl($scope), true);
}
try {
return $this->authenticateOrCreateFacebookUser($facebookUser);
} catch (\FacebookApiException $e) {
$di->logger->begin();
$di->logger->error($e->getMessage());
$di->logger->commit();
$facebookUser = null;
}
}
FACEBOOKCONNECTOR.PHP
public function __construct($di)
{
$this->di = $di;
$fbConfig = $di->get('config')->pup->connectors->facebook;
$protocol = strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))).'://';
$protocol="https://";
if (isset($fbConfig['route'])) {
$this->url = $protocol.$_SERVER['HTTP_HOST'].$fbConfig['route'];
} else {
$this->url = $protocol.$_SERVER['HTTP_HOST'].'/usercontrol/loginwithfacebook';
}
//echo $this->url;die();
FacebookSession::setDefaultApplication($fbConfig->appId, $fbConfig->secret);
}
public function getLoginUrl($scope = [])
{
$this->helper = new FacebookRedirectLoginHelper($this->url);
return $this->helper->getLoginUrl($scope);
}
/**
* Get facebook user details.
*
* #return unknown|bool
*/
public function getUser()
{
try {
$this->helper = new FacebookRedirectLoginHelper($this->url);
$this->fb_session = $this->helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
$this->di->get('flashSession')->error($ex->getMessage());
} catch (\Exception $ex) {
$this->di->get('flashSession')->error($ex->getMessage());
}
if ($this->fb_session) {
$request = new FacebookRequest($this->fb_session, 'GET', '/me?fields=id,first_name,last_name,email');
$response = $request->execute();
$fb_user = $response->getGraphObject()->asArray();
return $fb_user;
}
return false;
}
USERCONTROLLER.PHP
public function loginwithfacebookAction()
{
try {
//echo "dentro del try";
$this->view->disable();
$fopen = fopen('../logs/loginWithFacebook.log');
fwrite( $this->auth->loginWithFacebook() , $fopen );
fclose( $fopen );
return $this->auth->loginWithFacebook();
} catch(AuthException $e) {
$this->flash->error('There was an error connectiong to Facebook.');
}
}
I couldn't test it, but it seems to be circular: in facebookconnector.php the if leads to the same call to the static function FacebookSession::setDefaultApplication. You may try:
if (isset($fbConfig['route'])) {
$this->url = $protocol.$_SERVER['HTTP_HOST'].$fbConfig['route'];
FacebookSession::setDefaultApplication($fbConfig->appId, $fbConfig->secret);
} else {
$this->url = $protocol.$_SERVER['HTTP_HOST'].'/usercontrol/loginwithfacebook';
return $this->response->redirect($this->url);
}

Slim 2 to Slim 3 method error

I am trying to convert a slim 2 project to slim 3.
I am stucking with a problem.
When I call my method:
http://localhost:8000/task_manager/v1/tasks
I get the next error:
Catchable fatal error: Argument 1 passed to authenticate() must
be an instance of Slim\Route, instance of
Slim\Http\Request given in
C:\wamp64\www\task_manager\v1\index.php on line 42.
How could I fix it? Some help will be appreciated.
Here is my php code:
$app = new \Slim\App();
...
...
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$data = array();
$app = AppContainer::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization'])) {
$db = new DbHandler();
// get the api key
$api_key = $headers['Authorization'];
// validating api key
if (!$db->isValidApiKey($api_key)) {
// api key is not present in users table
$data["error"] = true;
$data["message"] = "Access Denied. Invalid Api key";
return echoRespnse(401, $data, $response);
//$app->stop();
return $response->withStatus(401)->withBody("Bad Request");
} else {
global $user_id;
// get user primary key id
$user_id = $db->getUserId($api_key);
}
} else {
// api key is missing in header
$data["error"] = true;
$data["message"] = "Api key is misssing";
return echoRespnse(400, $data, $response);
}
}
$app->get('/tasks', function (Request $request, Response $response) {
global $user_id;
$data = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllUserTasks($user_id);
$data["error"] = false;
$data["tasks"] = array();
// looping through result and preparing tasks array
while ($task = $result->fetch_assoc()) {
$tmp = array();
$tmp["id"] = $task["id"];
$tmp["task"] = $task["task"];
$tmp["status"] = $task["status"];
$tmp["createdAt"] = $task["created_at"];
array_push($data["tasks"], $tmp);
}
return echoRespnse(200, $data, $response);
})->add('authenticate');
In Slim2 you could add middleware like this:
<?php
$aBitOfInfo = function (\Slim\Route $route) {
echo "Current route is " . $route->getName();
};
$app->get('/foo', $aBitOfInfo, function () {
echo "foo";
});
This is not possible in slim3: first the middleware must be added with the add method like this:
$app->get('/foo', function () {
echo "foo";
})->add($aBitOfInfo);
Secondly middleware doesn't have the \Slim\Route-Object as first parameter.
These are not the Request, Response and the callable of the next middleware. So this should be like this:
/**
* Example middleware closure
*
* #param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* #param \Psr\Http\Message\ResponseInterface $response PSR7 response
* #param callable $next Next middleware
*
* #return \Psr\Http\Message\ResponseInterface
*/
$aBitOfInfo = function ($request, $response, $next) {
$response->getBody()->write('BEFORE');
$response = $next($request, $response);
$response->getBody()->write('AFTER');
return $response;
};
(Source https://www.slimframework.com/docs/concepts/middleware.html)

How to handle query errors in Zend?

I have a simple question.
I am working on Zend framework 2.
I am trying to make an AJAX call to fetch all booking data from table booking by passing the booking_id. Trouble is, the query is failing for reasons unknown. The actual query is complex and its working when I replace $booking_id with an actual booking_id like '22432'. Hence, I believe that the query is fine, there is some other issue.
But I don't know how to fetch the query errors/exceptions in an Ajax call. Can someone help me with this?
Javascript:
$.post("dashboard/getBookingDataByBookingId", {
booking_id: bookingId,
},
function(data){
if(data.response == true) {
alert(data);
} else {
alert('failed');
}
}, 'json');
Controller
public function getBookingDataByBookingIdAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost())
{
$post_data = $request->getPost();
$booking_id = $post_data['booking_id'];
$booking_data = array();
$booking_data = $this->getBookingTable()->getBookingByUserIdAndBookingId($booking_id);
if (!$booking_data)
$response->setContent(\Zend\Json\Json::encode(array('response' => false, 'booking_data' => $booking_data)));
else {
$response->setContent(\Zend\Json\Json::encode(array('response' => true, 'booking_data' => $booking_data)));
}
}
return $response;
}
The bookingTable model has a public function:
public function getBookingByUserIdAndBookingId($booking_id)
{
$sql = "Select * from booking where id='".$booking_id."';
try {
$statement = $this->adapter->query($sql);
$res = $statement->execute();
return $res->current();
} catch (Exception $ex) {
return $ex;
}
}
You are posting a variable named 'id':
{
id: bookingId,
}
So you should access it as:
$post_data = $request->getPost();
$booking_id = $post_data['id'];
or more concisely:
$booking_id = $request->getPost('id');
You should also be using parameterised queries to avoid SQL injection.
For Getting errors/exceptions in an Ajax call use:
In Google Chrome use: POSTMAN Extension
In FireFox user: FIREBUG Plugin

Categories