change param in request of Slim Framework 3 - slim-3

Using Slim 3 Framework I try to change a param of a post/put-request in one function and pass the manipulated request to another function like this:
public function myFunction(Request $request, Response $response, $args)
{
$markdown = $request->getParams("markdown");
$markdown = strg_replace('needle', 'replace', $markdown);
$request->setParams("markdown", $markdown);
$this->anotherFunction($request, $response, $args);
}
Of course, setParams does not exist in slim, so I tried with getAttribute / withAttribute, but it seems that you do not have access to the post/put-params like this:
$markdown = $request->getAttribute('markdown'); // is empty
$markdown = strg_replace('needle', 'replace', $markdown);
$request = $request->withAttribute('markdown', $markdown);
$this->anotherFunction($request, $response, $args);
I found another function withParsedBody() but I don't see a way to manipulate the params and put it back into the request and pass the request. Has anybody an idea or an workaround?

Oh sorry, I just found it in the documentation of PSR-7:
$params = $request->getParsedBody();
$params['markdown'] = 'manipulate me'
$request = $request->withParsedBody($params);
and that works. Maybe it helps someone...

Related

Change the request of cakephp 3 using middleware

I am trying to implement a middleware who will read data from an API and will use it later on the controller. How can do this ?
I have made a simple middleware where i have
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$dataFromApi = curl_action....
$request->dataFromApi = $dataFromApi;
return next($request, $response);
}
Later on the controller i want to have access to these data by using
public function display(...$path)
{
$this->set('dataFromApi', $this->request->dataFromAPI);
}
Look at the \Psr\Http\Message\ServerRequestInterface API, you can store your custom data in an attribute using ServerRequestInterface::withAttribute():
// ...
// request objects are immutable
$request = $request->withAttribute('dataFromApi', $dataFromApi);
// ...
return next($request, $response);
and read in your controller accordingly via ServerRequestInterface::getAttribute():
$this->set('dataFromApi', $this->request->getAttribute('dataFromApi'));
See also
PHP-FIG > PSR-7 > Psr\Http\Message\ServerRequestInterface

Creating Rest API without views using cakePHP 3.5

I'm trying to create Rest API without view and planning to use these api's in angular 2 application. does have any idea about it?
Cake makes this incredibly easy. A few things I have learned building without views.
Set the _serialize variable
$data = ['cheeses' => ['gouda', 'pepper jack', 'cheddar']];
$this->set('responseData', $data);
$this->set('_serialize', 'responseData');
Throw bad request exceptions and other network related exceptions
Cake will render nice json views for you.
Set your accept header when issuing and ajax request to be application/json
You can use cake prefixes for api versions
Look at Stateless Authentication for your api
In your AppController.php, with these parameters, all of your controllers will be render in json
public function beforeRender(Event $event)
{
$this->RequestHandler->renderAs($this, 'json');
$this->response->type('application/json');
$this->set('_serialize', true);
}
CakePHP will render json easily.
In your Controller,look like something.
protected $responseBody = [];
public function beforeRender(Event $event){
foreach($this->responseBody as $responseKey=>$response){
$this->set($responseKey, $response);
}
$this->set('_serialize', array_keys($this->responseBody));
}
public function initialize()
{
parent::initialize();
$this->RequestHandler->renderAs($this, 'json');
}
public function index(){
$this->request->allowMethod(['get']); // Method like post,get..
$this->responseBody["statusCode"] = 200;
$this->responseBody["statusDescription"] = ''; //You send any text in json.
$this->responseBody["data"] = []; // All data that you can send.
}
For further informations , You can see CakePHP Cookbook REST API to click here

CakePHP3 Render View to a Variable

I want to render the view to a variable without directly sending it to the browser. I used to do it with cakephp2.*. But, I cannot figure out how to do it in CakePHP3. Could you please tell me how to do it?
ViewBuilder was introduced in CakePHP 3.1 and handles the rendering of views. When ever I want to render to a variable I always go look at how send email works.
From a controller:
function index() {
// you can have view variables.
$data = 'A view variable';
// create a builder (hint: new ViewBuilder() constructor works too)
$builder = $this->viewBuilder();
// configure as needed
$builder->layout('default');
$builder->template('index');
$builder->helpers(['Html']);
// create a view instance
$view = $builder->build(compact('data'));
// render to a variable
$output = $view->render();
}
For Ajax request/response, I use this:
public function print(){
if ($this->request->is('ajax')) {
$data = $this->request->getData();
$builder = $this->viewBuilder()
->setTemplatePath('ControllerName')
->setTemplate('print');
->setLayout('ajax');
->enableAutoLayout(false);
$view = $builder->build(compact('data'));
$html = $view->render();
$res = ['html' => $html];
$this->set('response',$res);
$this->set("_serialize",'response');
}
}
And the print.ctp is under Template/ControllerName

Error: Cannot be accessed directly CakePHP

Element file I am calling:
$brand = $this->requestAction('brands/buyer_getnames/');
Action file I am calling:
public function buyer_getnames(){
$newid=$this->Auth->User('brand_id');
$name=$this->Brand->find('first',array('conditions'=>array('Brand.id'=>$newid),'recursive'=>-1));
return $name['Brand']['name'];
}
Getting error below..!!
Private Method in BrandsController
Error: BrandsController::buyer_getnames() cannot be accessed directly.
Please help
Request action respects normal url routing rules
If you're using prefix routing then you can't access function prefix_foo() via a url of the form /controller/prefix_foo - it needs to be the corresponding prefix url: /prefix/controller/foo.
As such your request action call should be:
$brand = $this->requestAction('/prefix/brands/getnames/');
Note that if the only thing that method does is call a model method, you're better off simply doing:
$model = ClassRegistry::init('Brand');
$brand = $model->someMethod();
You can allow unauthorized access to action if your action is requested with requestAction method.
For example:
public function beforeFilter() {
parent::beforeFilter();
if ($this->request->is('requested') && $this->request->params['action'] == 'index') {
$this->Auth->allow(array('index'));
}
}
This may also work (haven't tested):
public function index() {
if ($this->request->is('requested')) {
$this->Auth->allow(array('index'));
}
}
let me know if i can help you more.

import of HttpSocket in Paypal in cakephp

Well, here's what i got. I have a line of code here that imports HttpSocket in my CakePHP-paypal integration.
It is located in my /app/PaypalIpn/Model/DataSource/PaypalIpnSource.php. Here it is:
function __construct(){
if (!class_exists('HttpSocket')) {
if(App::uses('HttpSocket', 'Network/Http')){
$this->log('http socket imported','paypal');
}
}
else{
$this->log('http socket not imported','paypal');
}
$this->Http = new HttpSocket();
}
By the way, my HttpSocket.php is located here:
C:\xampp\htdocs\wifidrivescanportal\lib\Cake\Network\Http\HttpSocket.php
So everytime i try to access this function in my HttpSocket.php:
public function post($uri = null, $data = array(), $request = array()) {
//$this->log('entered post in http socket','paypal');
$request = Set::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
return $this->request($request);
}
via this line of code inside my PaypalIpnSource.php:
function isValid($data){
// .... other codes
$response = $this->Http->post($server, $data);
return $response;
}
nothing happens. It doesn't log anything despite that i indicated it to log something particularly in some portions in /app/PaypalIpn/Model/DataSource/PaypalIpnSource.php
Debug the raw response data in the HttpSocket class. In 1.3 I had a few cases in the past were I had the same issue with this class.
Try http://api13.cakephp.org/view_source/http-socket/#l-292 debug($this->request['raw']) after this line.
The raw data might contain something that the 1.3 class does not pick up.
Well here's what I did these line of codes
function isValid($data){
// .... other codes
$response = $this->Http->post($server, $data);
return $response;
}
I made it this way:
function isValid($data){
// .... other codes
return $this->Http->post($server, $data);
}
Not so certain with the difference but it worked out this way. Once I finished my paypal integration in cakephp, i'll make sure i'll provide a tutorial for beginners like me. Hope I could help that way. My next goal is to do the encryption using ppcrypto.

Resources