Symfony Controller return array - symfony

I am trying to create a listener that configures the Response using annotations and sets the response content as the controller return.
The Controller code:
use PmtVct\PhotoBookBundle\Annotations\ResponseType;
use Symfony\Component\HttpFoundation\Request;
/**
* #ResponseType("JSON")
*/
public function home(Request $request) {
return ['asdf' => 123];
}
But I receive the 'The controller must return a response' error.
There is a way to return an array on Controller instead a Response?

You are trying to do a similar thing to FOSRestBundle. Maybe consider using this bundle? It will allow:
Return arrays in controller, exactly in a way you want
Serialise response into Json, or other format you wish, also it can detect format automatically from Request.
In case you still want to build such listener yourself - look how it's done in FOSRestBundle - https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/EventListener/ViewResponseListener.php - they are using "kernel.view" event.

According to the documentation you can return a JsonResponse like this:
return new JsonResponse(['asdf' => 123]);

Related

How I can mock `Dingo\Api\Auth\Provider\JWT` so I can bypass the Authentication overhwad whilst I am unit testing my endpoints?

I am using dingo/api in my api and I want to unit test the endpoint:
class MyApiTest extends TestCase
{
public function testEndpoint()
{
$dispatcher = app('Dingo\Api\Dispatcher');
$fake_token = 'cndksjonsdcnsod';
$dispatcher->header('Authorization', 'Bearer: '.$fake_token);
$dispatcher->version($version)->get('/my-endpoint');
}
}
In my app.php I have the following configuration:
'auth' => [
'jwt' => Dingo\Api\Auth\Provider\JWT::class,
],
Is there a way to mock/fake/set default values to the Dingo\Api\Auth\Provider\JWT provider of jwt authentication?
An approach that worked for me, is via testing the controller itself and mock JWT authentication service by bypassing the Dingo and any middleware used by routing itself.
Example:
Let us suppose we have the following controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Tymon\JWTAuth\Facades\JWTAuth;
class ProfileController extends Controller
{
public function getProfile(Request $request,$profile_id)
{
$user = JWTAuth::parseToken()->authenticate();
$language = App::getLocale();
// Do stuff Here
}
}
You can write a simple test:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Tymon\JWTAuth\Facades\JWTAuth;
// Set a test class for speed is ommited
public function testMyApiCall()
{
/**
* $user is an instance of a User
*/
JWTAuth::shouldReceive('parseToken->authenticate')->andReturn($user);
App::setlocale('el');
$request = new Request();
$request->initialize([],['token' => 'AAABBBCCC' ],[],[],[],[],[]);
$controller = new ProfileController();
// I ommit the profile_id value it is just a demonstration
$response = $controller->getProfile($request,$profile_id)
$response_dody = $response->getData(false);
// Perform assertions upon $response_dody
}
In our case we do not care about what routing is used and how it is set up. Therefore, are no mentioning any routing and anything regarding Dingo in this example, we just forget it.
Cons and pros
Though it is not a silver bullet, it is an approach that will give a reliable result focusing on the actual code. Keep in mind though that you bypass many middlewares that may you also want to test as well eg. Authentication ones.
On the other hand you are able to test the logic inside the controller, in cases where the logic is rather small to create a seperate class/method for it eg. selecting data from DB.

What is the best way to create a singleton entity in Symfony 4?

I want to create a settings page, which only has a form in it. If the form is submitted it only updates settings entity but never creates another one. Currently, I achieved this like:
/**
* #param SettingsRepository $settingsRepository
* #return Settings
*/
public function getEntity(SettingsRepository $settingsRepository): Settings
{
$settings = $settingsRepository->find(1);
if($settings == null)
{
$settings = new Settings();
}
return $settings;
}
In SettingsController I call getEntity() method which returns new Settings entity (if the setting were not set yet) or already existing Settings entity (if setting were set at least once).
However my solution is quite ugly and it has hardcoded entity id "1", so I'm looking for a better solution.
Settings controller:
public function index(
Request $request,
SettingsRepository $settingsRepository,
FlashBagInterface $flashBag,
TranslatorInterface $translator,
SettingsService $settingsService
): Response
{
// getEntity() method above
$settings = $settingsService->getEntity($settingsRepository);
$settingsForm = $this->createForm(SettingsType::class, $settings);
$settingsForm->handleRequest($request);
if ($settingsForm->isSubmitted() && $settingsForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($settings);
$em->flush();
return $this->redirectToRoute('app_admin_settings_index');
}
return $this->render(
'admin/settings/index.html.twig',
[
'settings_form' => $settingsForm->createView(),
]
);
}
You could use Doctrine Embeddables here.
Settings, strictly speaking, should not be mapped to entities, since they are not identifiable, nor meant to be. That is, of course, a matter of debate. Really, a Settings object is more of a value object than an entity. Read here for more info.
So, in cases like these better than having a one to one relationship and all that fuzz, you probably will be fine with a simple Value Object called settings, that will be mapped to the database as a Doctrine Embeddable.
You can make this object a singleton by creating instances of it only in factory methods, making the constructor private, preventing cloning and all that. Usually, it is enough only making it immutable, meaning, no behavior can alter it's state. If you need to mutate it, then the method responsible for that should create a new instance of it.
You can have a a method like this Settings::createFromArray() and antoher called Settings::createDefaults() that you will use when you new up an entity: always default config.
Then, the setSettings method on your entity receieves only a settings object as an argument.
If you don't like inmutablity, you can also make setter methods for the Settings object.

Transform GET parameters to clean URL

I use Datatables on fronted to send GET parameters to my Silex application.
Datatables send GET parameters of that type:
champs_societes%5B%5D=naf&zone-geographique=ville&effectif%5B%5D=eff_1a9&effectif%5B%5D=eff_10a19&effectif
%5B%5D=eff_20a49&effectif%5B%5D=eff_plus5000&ca%5B%5D=10k-50k&ca%5B%5D=50k-100k&ca%5B%5D=1kk-2kk&ca%5B
%5D=2kk-5kk&champs_societes%5B%5D=capital_int&fondation%5Bmin%5D=&fondation%5Bmax%5D=&champs_societes
%5B%5D=siren&champs_societes%5B%5D=siret&champs_societes%5B%5D=nature&nature%5B%5D=Etablissement&champs_societes
%5B%5D=formejur&champs_societes%5B%5D=emailg&champs_contacts%5B%5D=emailn&ac_formejur=Artisan-Commer
%C3%A7ant%2CBanque+Populaire%2FLoi+Mars+1917%2CCoop.+%C3%80+Responsabilit%C3%A9+Limit%C3%A9e&ac_naf=0113Z
%2C0121Z%2C0126Z%2C0130Z&ac_departements=14%2C50%2C61%2C68%2C03&ac_villes=77330%2C77680%2C77340&ac_fonction
=Assistant%2CCharg%C3%A9+D'Affaires%2CContr%C3%B4leur+De+Gestion%2CDirecteur+%2F+Responsable
I there a way to genereate a clean URL from this chain ? Ideally by using the Symfony/Silex routing.
Thanks for help
EDIT
I get the GET params above with Request:
$app->post('/ajax/formprocess', function (Request $request) use ($app) {
$df = new Filtres( $request->request->get('dataForm') );
$filtroAdd = $df->getRequest();
I would try with Request class first
Request class from HttpFoundation component (default in Symfony, not sure about Silex as I never used it)
/**
* #param \Symfony\Component\HttpFoundation\Request $request
*/
public function someAction(Request $request)
{
$request->getSchemeAndHttpHost();
$request->getBasePath();
$request->getQueryString(); // this will be the most helpful in your case
// access what you need and build normalized url
}
You should be able to build clean normalized url
Edit, solution for parsing query parameter string to array
$queryParameters = 'query parameters as string to be parsed';
$output = [];
parse_str($queryParameters, $queryParameters);
print_r($queryParameters);
http://php.net/manual/en/function.parse-str.php

handleRequest($request) does not work for "GET" method in Symfony 2

I am a noobie in Symfony2. The handleRequest() function does not work for "GET" method whereas same code works fine for "POST".
public function addAction(Request $request){
$std = new Student();
$form = $this->createForm(new StudentForm, $std,
array( 'method'=>'GET'));
$form->handleRequest($request);
if($form->isSubmitted()){
$std= $form->getData();
$em= $this->getDoctrine()->getManager();
$em->persist($std);
$em->flush();
return $this->render('target.twig');
}
return $this->render('target twig',
array('newStdForm'=> $form->createView(),));
}
The above code is not working but if I change 'method':'GET' to 'method':'POST', then it works fine.
Specify the form's method in the StudentForm class's buildForm method. Therefore, handleRequest will be able to grab the GET parameters.
class StudentForm
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->setMethod('GET');
}
}
I think it is because in POST requests, parameters are passed in the body of the HTTP request. And that handleRequest looks for those values inside the body of the request. But in a GET request, parameters are passed in the url directly. So I think that is why the handling doesn't work.
Usually we use GET to fetch a page or url and a POST to send info to server.
Are you sure your twig template is correct?
I faced this issue today.
Pierre Roland's answer is partially correct for the current version.
I checked the default "HttpFoundationRequestHandler" which is called in "handleRequest".
An explicit GET form will be considered "submitted" if:
the form has no name (if you use a form class for example).
the request query contains a parameter with the form's name.

$this object not working properly when used in services in Symfony2

I've working for a while with Symfony and I started to use controllers as services. The problem is that I'm not sure if I get how the Dependency Injection works. If I print $this inside an action it works perfectly.
/**
* #Route("/testing/this")
*/
public function thisAction(Request $request)
{
var_dump($this);
return new Response();
}
Response:
object(Linkedip\WizardBundle\Controller\PaymentsController)[153]
protected 'object' => null
protected 'container' =>
object(appDevDebugProjectContainer)[198]
protected 'parameterBag' =>
object(Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag)[48]
protected 'parameters' =>
array
...
But then, I decided to make my controller a service to be used in other controllers (I want to have actions methods and service methods in one controller).
parameters:
linkedip.controller.payments.class: Linkedip\WizardBundle\Controller\PaymentsController
services:
payments.controller:
class: %linkedip.controller.payments.class%
So, I add a new method that I'll plan to use in other controllers but when I try to call $this inside the new method look what I get.
/**
* #Route("/testing/this")
*/
public function thisAction(Request $request)
{
$paymentsController = $this->get('payments.controller');
$paymentsController->service();
return new Response();
}
/**
* [SERVICE]
*/
public function service()
{
var_dump($this);
return null;
}
Response:
object(Linkedip\WizardBundle\Controller\PaymentsController)[937]
protected 'object' => null
protected 'container' => null
To solve this issue I created a setter to inject $this object directly to the controller.
/**
* [DEPENDENCY INJECTION]
*/
protected $object;
public function setObject($object) { $this->object = $object; }
And then, When I try to call one of those services I need to add an extra line setting $this.
$paymentsController = $this->get('payments.controller');
$paymentsController->setObject($this);
And in the service method, I call the object.
$em = $this->object->getDoctrine()->getManager();
This code works for me but I feel is a dirty trick. Am I doing something wrong?
[..]But then, I decided to make my controller a service to be used in other controllers (I want to have actions methods and service methods in one controller).
I don't agree with this architecture choice. You should make your own controller to let the other ones herits from it. Then, if you still need a service, you can create one.
I agree with goto, you should not mix responsibilities within one class. Also, this is mainly the cause for your problem. To answer your question:
By defining your controller as a service, you are not using the default instantiation logic for a controller, so the container will not be injected automatically. If you want this to happen, you should manually inject the container (or better: the specific services you need) from within your dependency injection config. But, again, if you plan on still using the controller in the 'regular' way, by defining routes for example, things will get REALLY messy, so I would suggest, if you are already playing with the DIC, just create a separate service and call that from within your other controller. Hope this helps.

Resources