Symfony redirect response error - php

I got this error when trying to redirect to another method
Type error: Argument 1 passed to
Symfony\Component\HttpFoundation\ResponseHeaderBag::__construct() must
be of the type array, integer given, called in
/proyect/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Response.php
on line 199
But I'm sending an empty array
return new RedirectResponse('persons', array(), UrlGeneratorInterface::RELATIVE_PATH);
Any help?

Is this the HttpFoundation\RedirectResponse class ? Your instanciation looks wrong.
// Symfony\Component\HttpFoundation\RedirectResponse
public function __construct($url, $status = 302, $headers = array())
{
...
}
Your third parameter is an integer, when an array is expected. The RedirectResponse constructor calls its parent, the Response constructor, and this code is executed:
// Symfony\Component\HttpFoundation\Response
public function __construct($content = '', $status = 200, $headers = array())
{
$this->headers = new ResponseHeaderBag($headers);
...
}
This is your error, you're using an integer (UrlGeneratorInterface::RELATIVE_PATH, equals to 2) when the expected value is an array of response headers.
As answered by #Cerad the correct solution is to use the redirectToRoute method, but it'll redirect you to an absolute path:
return $this->redirectToRoute('persons', array());
Or, if you still want to use the RedirectResponse with a relative path:
$url = $this->generateUrl('persons', array(), UrlGeneratorInterface::RELATIVE_PATH);
return new RedirectResponse($url);

Related

Set a referenced variable to a newly initialized class

I have a method, which takes a reference
// CarService.php
public function getCars(&$carCollection = null)
{
$promise = // guzzle request for getting all cars would be here
$promise->then(function (ResponseInterface $response) use (&$carCollection) {
$cars= json_decode($response->getBody(), true);
$carCollection= new CarCollection($cars);
});
}
However, when accessing the collection and trying to reuse it, I'm getting the error
Argument 1 passed to {placeholder} must be an instance of {placeholder}, null given
I know that the reason for this is, that the constructor returns nothing, but how can I still assign my variable to a new instance of the CarCollection (which extends Doctrine's ArrayCollection)
I even tried it with a static method as a work around
// CarCollection.php
public static function create(array $cars): CarCollection
{
$carCollection = new CarCollection($cars);
return $carCollection;
}
// CarService.php
public function getCars(&$carCollection = null)
{
$cars = // curl request for getting all cars would be here
$carCollection = CarCollection::create($cars)
}
but it's still null. Why is that? How can I set a referenced variable to a new class?
I access the method like this
$carService = $this->get('tzfrs.vehicle.services.car');
$carCollection = null;
$promises = [
$carService->getCars($carCollection)
];
\GuzzleHttp\Promise\unwrap($promises);
var_dump($carCollection); // null
When I set the reference directly, eg.
// CarService.php
public function getCars(&$carCollection = null)
{
$carCollection = new CarCollection([]);
}
it works without any problems. Seems like the callback is somehow the problem.
Whoever downvoted this, can you please elaborate why and why you voted to close?
I might be misunderstanding the question, but you should be able to modify an object when passing by reference. See here for an example: https://3v4l.org/KtFvZ
In the later example code that you added, you shouldn't pass $carCollection by reference, the & should only be in the method/function defintion, not provided when you call it. I don't think that is your problem though, that should be throwing an error in php7.

Fracture Transform throws boolean given

I am using a Transformer in my Laravel project. When I don't include an other object in the Transformer there isn't any problem but when I include the Customer object I get the following error:
Argument 1 passed to App\Transformers\CustomerTransformer::transform() must be an instance of App\Models\Customer, boolean given, called in /home/vagrant/Code/project/vendor/league/fractal/src/Scope.php on line 365 and defined
When I printed the object from Scope.php there weren't any booleans in it. What could be the problem? (The code crashes after Review #298.
How I call the code:
$reviews = $this->review->paginate();
$transformer = new ReviewTransformer();
$with = $request->get('with', null);
if($with) {
$with = explode(';', $with);
$transformer->parseIncludes($with);
}
return $this->response->paginator($reviews, $transformer);
Fixed the problem, I'm an idiot..
I had the following include in my Transformer class:
public function includeCustomer(Review $review)
{
$customer = $review->customer;
return $this->collection($customer, new CustomerTransformer);
}
The problem is that $customer is an Item an not a Collection. I had to change this->collection to this->item.

Yii2 rest api update throws object conversion error

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.

Laravel 4 Redirect to Route with Array

I have an issue in my laravel app.
I want to sent an array to another route.
here is the code.
Controller:
$emparray =[
'fname'=>Input::get('efname'),
'lname'=>Input::get('elname'),
'dob'=>Input::get('edob'),
'reg_date'=>date('Y-m-d'),
'email'=>Input::get('eemailaddrs'),
'gender'=>Input::get('gender'),
'mobile'=>Input::get('emobile'),
'p_addrss'=>Input::get('epaddress'),
'c_addrss'=>Input::get('ecaddress'),
'quals'=>Input::get('quali'),
'pdfname'=>$pdfname,
];
return Redirect::to('print-view',$emparray);
Routes.php
Route::get('print-view/{$emparray}', array('as'=>'print-view','uses'=>'EmployeeController#PrintView'));
Final Controller.
public function PrintView($emparray)
{
return $emparray;
}
I Can't get the successful output. Is there any issues with my code.?
Getting error like "The HTTP status code "1" is not valid."
Thanks..
Use Redirect::to('print-view')->with($emparray);
You cant do it like this ,if you would check the to method you would see this -
public function to($path, $status = 302, $headers = [], $secure = null)
{
$path = $this->generator->to($path, [], $secure);
return $this->createRedirect($path, $status, $headers);
}
so basically you send the status parameter an array. to send parameters you will need to use the action/route methods
Why don't you call the PrintView method directly? I mean... why do you need to route all this data?

Validating HTTP Response Codes in PHPUnit

I am writing unit tests for several methods which return HTTP response codes. I cannot find a way to assert an HTTP response code. Perhaps I am missing something obvious, or I am misunderstanding something about PHPUnit.
I am using PHPUnit 4.5 stable.
Relevant part of class Message:
public function validate() {
// Decode JSON to array.
if (!$json = json_decode($this->read(), TRUE)) {
return http_response_code(415);
}
return $json;
}
// Abstracted file_get_contents a bit to facilitate unit testing.
public $_file_input = 'php://input';
public function read() {
return file_get_contents($this->_file_input);
}
Unit test:
// Load invalid JSON file and verify that validate() fails.
public function testValidateWhenInvalid() {
$stub1 = $this->getMockForAbstractClass('Message');
$path = __DIR__ . '/testDataMalformed.json';
$stub1->_file_input = $path;
$result = $stub1->validate();
// At this point, we have decoded the JSON file inside validate() and have expected it to fail.
// Validate that the return value from HTTP 415.
$this->assertEquals('415', $result);
}
PHPUnit returns:
1) MessageTest::testValidateWhenInvalid
Failed asserting that 'true' matches expected '415'.
I'm unsure why $result is returning 'true' . . . especially as a string value. Also unsure what my 'expected' argument ought to be.
According to the docs you can call the http_response_code() method with no parameters to receive the current response code.
<?php
http_response_code(401);
echo http_response_code(); //Output: 401
?>
Therefore your test should look like:
public function testValidateWhenInvalid() {
$stub1 = $this->getMockForAbstractClass('Message');
$path = __DIR__ . '/testDataMalformed.json';
$stub1->_file_input = $path;
$result = $stub1->validate();
// At this point, we have decoded the JSON file inside validate() and have expected it to fail.
// Validate that the return value from HTTP 415.
$this->assertEquals(415, http_response_code()); //Note you will get an int for the return value, not a string
}

Categories