guzzlehttp and symfony with rest api problem - symfony

I want to make a post call with rest api using guzzlehttp in symfony ... I wrote this code but the response
/**
* #Route("/post/")
*/
public function postAction()
{
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $url, [
'form_params' => [
'username' => 'test',
'password' => 'test',
]
]);
return $this->render('esterne/post.html.twig', array(
'response'=>$response,
));
}
this is the twig file post.html.twig
{{response}}
the result is this:
{"status":"200","data":{"is_auth":true,"userToken":"194b873c004716acb3e0a5fba09fe405"}}
but if I put in html:
return $this->render('esterne/post.html.twig', array(
'response'=>$response->getBody(),
));
it results in error 500 internal server error
[2018-11-14 09:56:35] request.CRITICAL: Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string")." at /app/app/Resources/views/esterne/post.html.twig line 1 {"exception":"[object] (Twig_Error_Runtime(code: 0): An exception has been thrown during the rendering of a template (\"Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string\"). at /app/app/Resources/views/esterne/post.html.twig:1, ErrorException(code: 0): Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string at /app/var/cache/prod/twig/47/478ca9f9b0a5c69caa7b0fed874bf831466230764635f396f057dc2c33868549.php:23)"} []
SOLUTION
use file
{{ response|json_encode()|raw }}
in twig and
return $this->render('esterne/post.html.twig', array(
'response'=>json_decode($response->getBody()->getContents(), FALSE),
));

You could try following response.
return $this->render('esterne/post.html.twig', array(
'response'=>$response->getBody()->getContent(),
));

Related

WordPress endpoint plugin shows SyntaxError: JSON.parse

i have read many pages to find out howto create a simple endpoint into my simple WP-Plugin.
links of good articles i have read for that:
https://developers.shopware.com/developers-guide/rest-api/plugin-api-extension/ , https://wptips.dev/custom-rest-api/ , https://torquemag.io/2016/07/adding-custom-endpoints-extra-touches/ , https://www.cloudways.com/blog/wordpress-rest-api-to-fetch-posts/#get-wp-v2-posts , https://www.cloudways.com/blog/wordpress-rest-api-to-fetch-posts/#wordpress-rest-api-using-json , https://developer.wordpress.org/rest-api/
this gives me most hope to get success with it and i used the source from here:
https://stackoverflow.com/a/64331655/2891692
My URL i using in Web-Browser:
http://localhost/wordpress/wp-json/a0plugin/v1/testing
excerpt of my complete source from gist
htdocs/wp-content/plugins/a0plugin/a0plugin.php
<?php
/**
* Plugin Name: a0plugin
*/
function at_rest_testing_endpoint(){
return new WP_REST_Response('Howdy!!');
}
function at_rest_init(){
$namespace = 'a0plugin/v1';
$route = 'testing';
register_rest_route($namespace, $route, array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'at_rest_testing_endpoint'
));
}
add_action('rest_api_init', 'at_rest_init');
?>
complete source:
https://gist.github.com/sl5net/10d21e8bd358b9149968885a93862424
SyntaxError: JSON.parse
Error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
if the comments are left out, the error disappears. these are not listed in the so-called relevant source text excerpt. the cause is unknown to me.

Doctrine DBAL and sqlite problems

I am trying to connect to sqlite database file with Doctrine DBAL.
<?php
use Doctrine\DBAL\DriverManager;
require_once 'bootstrap.php';
$connectionParams = [
'url' => 'sqlite:///crawls.db',
];
$conn = DriverManager::getConnection($connectionParams);
But when I try to execute sql code it says that table is not exist (of course I checked manually and it is there).
$conn->exec('SELECT * FROM crawl_item');
outputs
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1 no such table: crawl_item' in /home/px/Documents/phpcrawler/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:57
Stack trace:...
May be this output can be helpful
var_dump($conn->connect());
var_dump($conn->getDatabase());
bool(true)
NULL
If you look at the AbstractSQLiteDriver::_constructPdoDsn() method you will see that the parameter is 'path':
$connectionParams = [
[
'driver' => 'pdo_sqlite',
'path' => '../products.db'
]
);
$conn = DriverManager::getConnection($connectionParams);
greetings,
thomas

Firebase - Invalid path: Invalid token in path

I'm using this PHP package, firebase-php, to communicate with the REST API.
I want to do very basic data push:
require_once ('utilities/firebase/firebaseLib.php');
$firebase = new Firebase(<my firebase url>, <my firebase token>);
$data = [
'ip' => "123456789",
'session' => "1234",
'sequence' => "12",
'time' => "159159159",
'event' => "Pause",
'data' => "1"
];
$res = $firebase->push(<my firbase path.json>, $data);
After execution I get this error: { "error" : "Invalid path: Invalid token in path" }
Not sure what this error means, no explanation at the docs...
Will be thankful for any help!
The firebase path in the push method ($res = $firebase->push(my-firebase.firebaseio.com/structure/of/json, $data); should be the relative path to the main firebase url.
So instead of 'my-firebase.firebaseio.com/structure/of/json' it should be just 'structure/of/json'.

Symfony 2. How to catch Exception parameter in Twig template?

I'm throwing some exception in my controller.
For example:
throw new AccessDeniedHttpException('some_text');
How can i catch it's 'some_text' parameter in my Twig template?
I found the {{ status_code }} and {{ status_text }} variables, but can't find something similar that solve my problem.
P.S. I'm already use custom error page. I just want give users specific error explanations.
Thnx.
By default Symfony uses the showAction of Symfony\Bundle\TwigBundle\Controller\ExceptionController to render your error page. The Implementation in Symfony 2.3 is like:
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $_format = 'html')
{
$currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
$code = $exception->getStatusCode();
return new Response($this->twig->render(
$this->findTemplate($request, $_format, $code, $this->debug),
array(
'status_code' => $code,
'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
'exception' => $exception,
'logger' => $logger,
'currentContent' => $currentContent,
)
));
}
From there you can see that there is 'exception' => $exception passed to your twig template. $exception is of type Symfony\Component\HttpKernel\Exception\FlattenException which is a wrapper for the original PHP Exception.
FlattenException::getMessage is probably what you want to access your error message. See FlattenException API for more Information.
Ok. The TWIG code is
{{ exception.message|nl2br }}

Symfony2 - ExceptionController - NotFoundHttpException

I am trying to create a custom exception error page and I have been following Mike's tutorial. I have inserted the following code into config.yml, and created an ExceptionController in StoreBundle\Controller\ExceptionController.php. When I try to test my 404 error page by going local.store.com/fake-page, I get a NotFoundHttpException: No route found for "GET /fake-page" error. I thought my ExceptionController is suppose to redirect all users if a page is not found so I added a var_dump('testing') in it but it never dumped. I tried to remove the code I injected into config.yml and I get the default Symfony error page instead. Am I doing something wrong in config.yml?
Inserted into app/config/config.yml:
twig:
exception_controller: StoreBundle\Controller\ExceptionController::showAction
EDIT
I now think my problem is in my controller. This is what I have in StoreBundle\ControlleExceptionController.php. My error pages are in StoreBundle\Resources\views\Pages\Errors\404.html.twig and StoreBundle\Resources\views\Pages\Errors\500.html.twig
<?php
namespace StoreBundle\Controller;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController;
class ExceptionController extends BaseExceptionController
{
public function showAction(FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
{
$template = $this->container->get('kernel')->isDebug() ? 'exception' : 'error';
$code = $exception->getStatusCode();
return $this->container->get('templating')->renderResponse(
'StoreBundle:Exception:Pages/Errors:' . $code . '.html.twig', array(
'status_code' => $code,
'status_text' => Response::$statusTexts[$code],
'exception' => $exception,
'logger' => null,
'currentContent' => '',
));
}
}
}

Resources