Symfony3 render CSS file from Controller - php

I would like to do this in Symfony 3 :
public function styleAction()
{
// Fetch it from service or whatever strategy you have
$backgroundColor = '#ff0000';
return $this->render(
'AcmeMyBundle::somefile.css.twig',
['backgroundColor' => $backgroundColor],
['Content-Type' => 'text/css']
);
}
But infortunately I still get a problem with the third argument of the render method.
Here is my error message :
Catchable Fatal Error: Argument 3 passed to Symfony\Bundle\FrameworkBundle\Controller\Controller::render() must be an instance of Symfony\Component\HttpFoundation\Response, array given
EDIT :
This is how to solve it :
public function styleAction()
{
$response = new Response();
$response->headers->set('Content-Type', 'text/css');
// replace this example code with whatever you need
return $this->render('main.css.twig', [
'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
],
$response
);
}

Related

Too few arguments to function when downloading a PDF

I am trying to generate a PDF with some details of an individual user using the Barryvdh DomPDF library but having some problems trying to generate it.
Controller method:
public function downloadPDF(Card $card)
{
$user = User::find($card->user_id);
$pdf = (new \Barryvdh\DomPDF\PDF)->loadView('pdf/cardsReport', $user);
return $pdf->download('cards.pdf');
}
Here is how I am referencing the route.
Download PDF
Route:
$router->get(
'/downloadPDF/{card}',
[
'as' => 'get::admin.download-pdf',
'uses' => 'EditCardController#downloadPDF',
]
);
I get this error:
Type error: Too few arguments to function
Barryvdh\DomPDF\PDF::__construct(), 0 passed in EditCardController.php
and exactly 4 expected.
I'm confused by this as I've seen many samples of using pdf and laravel where you don't need to pass four arguments so was wondering why this would be?
According to documentation, you should use facade instead of constructor:
public function downloadPDF(Card $card)
{
$user = User::find($card->user_id);
$pdf = PDF::loadView('pdf/cardsReport', $user);
return $pdf->download('cards.pdf');
}
Kindly use below format
$data = [
'title' => 'Welcome to ItSolutionStuff.com',
'date' => date('m/d/Y'),
];
$pdf = App::make('dompdf.wrapper');
$pdf->loadView('bill',$data);
return $pdf->stream();

Undefined property: Mockery_3_App_Repositories_ArticleRepositoryInterface::$id in laravel unit test

I'm trying to test the "store" method of ArticleController. When I run the phpunit, I'm getting -
ErrorException: Undefined property: Mockery_3_App_Repositories_ArticleRepositoryInterface::$id
ArticleController.php
public function store(StoreArticle $request)
{
$article = $this->article->create([
'id' => Str::uuid(),
'user_id' => $request->user()->id,
'category_id' => request('category'),
'title' => request('title'),
'description' => request('description')
]);
return Redirect::route('frontend.articles.show', $article->id);
}
ArticleControllerTest.php
public function testStoreSuccess()
{
$this->withoutMiddleware();
$this->mock(StoreArticle::class, function ($mock)
{
$mock->shouldReceive('user')
->once()
->andReturn((object) ['id' => Str::uuid()]);
});
$this->mock(ArticleRepositoryInterface::class, function ($mock)
{
$mock->shouldReceive('create')
->once();
Redirect::shouldReceive('route')
->with('frontend.articles.show', $mock->id) // error occurs on the $mock->id portion
->once()
->andReturn('frontend.articles.show');
});
$response = $this->post(route('frontend.articles.store'));
$this->assertEquals('frontend.articles.show', $response->getContent());
}
I'm using repository pattern. ArticleRepositoryInterface and eloquent ArticleRepository are binded with a service provider.
You need to return an object representing an Article instance:
// Assuming you have an Article model, otherwise stdClass could be instead.
$instance = new Article();
$instance->id = 123;
$mock->shouldReceive('create')
->once()
->andReturn($instance);
Then the line causing the error becomes:
->with('frontend.articles.show', $instance->id)
Another problem is this line:
->andReturn('frontend.articles.show');
The controller method returns an instance of a redirect response object, not a string.

Laravel test response with The given data was invalid

I'm doing unit test with laravel, so I called controller function and I get like a respnse an array
I have been response with this
return back()->with('success', 'Lots was generated')
and
return $this->lots_available;
The test give me as response this:
There was 1 error:
Tests\Feature\LotTest::test_lots
Illuminate\Validation\ValidationException: The given data was invalid.
I don't understand the reazon to this response, I'm beginning with the test
This is my function test
public function test_lots()
{
$this->withoutExceptionHandling();
$product = factory(Product::class)->create([
'size' => 20
]);
$lots = factory(Lot::class, 10)->create([
'product_id' => $product->id,
]);
$admin = factory(User::class)->create([
'role_id' => 3
]);
$client_request = 500;
$this->actingAs($admin)
->post(route('lots.distribution'), [$product, $client_request])
->assertStatus(200);
}
And this my called method
public function distribute(ProductRequest $product, $client_order)
{
$this->lots = $product->lots;
$this->client_order = $client_order;
$this->getLotAvailable();
return $this->lots_available;
}
Assuming your route is something like Route::post('/distribute/{product}/{client_order}')
route('lots.distribution') needs the parameters inside the function call
route('lots.distribution', [$product, $client_request])
Then you need to send the data that passes your rules in ProductRequest otherwise you will get a validation error. If you try a dd(session('errors')) after the post, you will probably see errors about missing fields.
->post(
route('lots.distribution', [$product, $client_request]),
['title => 'unique_title', 'sap_id' => 'unique_id']
)
Finally in your method, I'm assuming that the request ProductRequest is different than the Model Product:
public function distribute(ProductRequest $request, Product $product, $client_order)
Put the response in a variable and use dd() to print it.
You will find it on the messages method.
Worked for me.
dd($response);

Yii2. Can't get models image path from another table

In Product model I have:
public function getImage()
{
return $this->hasMany(Image::className(), ['product_id' => 'id']);
}
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image->path;
}
In view file I have ListView with _item file:
<img src="<?=$model->getMainImage()?>"></img>
Controller:
$dataProvider = new ActiveDataProvider([
'query' => Product::find()->with(['image']),
]);
Error is:
Trying to get property 'path' of non-object.
The code you have submitted may cause this error if the image was not found.
You should include a null check.
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image ? $image->path : false;
}
You may also want to look at implementing this with an AR relation via hasOne, which would be more concise. It is documented here:
https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#hasOne()-detail
Have you write full code:
return is_null($image) ? false : $image->path;
if not working, check your condition!

Zend Form : Call to undefined method Zend\InputFilter\InputFilter::getFilterChain()

I'm trying to upload an image with Zend Form. As we need it to move the image, I want to add a filter to do the job. But I can't use the getInputFilterChain(), I keep having this fatal error : Call to undefined method Zend\InputFilter\InputFilter::getFilterChain(). What am I missing here ?
I'm able to get the file information in $prg array. And as I looked on https://framework.zend.com/manual/2.4/en/modules/zend.mvc.plugins.html, this method is supposed to exist here, no ?
And I get the same error if I use this in my Form.php file.
Thank you in advance for your time!
My controller action :
public function signinAction()
{
$this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$form = new SignupForm($this->em);
$form->getInputFilter()->getFilterChain()->attach(
new Zend\Filter\File\RenameUpload(array(
'target' => './data/tmpuploads/file',
'randomize' => true,
))
);
$model = new ViewModel(array("form" => $form));
$url = $this->url()->fromRoute("signin");
$prg = $this->fileprg($form, $url, true);
if($prg instanceof \Zend\Http\PhpEnvironment\Response){
return $prg;
}
else if($prg === false){
return $model;
}
//other stuff
...
}
You need to get the Input instance from the InputFilter first and then you can get the filter-chain from the input:
$inputName = 'file'; // name of the input you want to work with
$input = $form->getInputFilter()->get($inputName);
$filterChain = $input->getFilterChain();

Categories