How to beautify code in PhpStorm and other Intellij editors?

Choose Code | Reformat Code, or press Ctrl + Alt + L.

EDIT: The keyboard shortcode has changed since PHPStorm 10 for windows to Ctrl + Alt + F


Sometimes Code | Reformat isn't enough.

As an example, after reformating a very ugly code I got this result

 public function createAction(Request $request)

{

    $news = new News();

    $em = $this->getDoctrine()->getManager();


    $form = $this->get('form.factory')
        ->createNamed(

            'backend_news',

            'backend_news',

            $news,

            array(

                'action' => '',

                'method' => 'POST',

                'attr' => array(

                    'class' => 'form-horizontal',

                    'role' => 'form'

                )

            )

        )->add('submit', 'submit', array('label' => 'Valider'));;


    $form->handleRequest($request);


   [...]

    return $this->render('BackendNewsBundle:List:form.html.twig', array(

        'form' => $form->createView()

    ));

}

In this case you need to go to

Preferences | Editor | Code Style | PHP

and from here fine tune. Then reformat again. Example for this file it was a lot of blank line, so I put to 0 the 'In Code' section of the Blank Lines tab. Once I reformated the code I put it back to 2. Anyway a lot of tuning is possible in this section.


Select code to reformat and press Ctrl + Alt + Shift + L

This is tested and working (Ubuntu), cheers!

For Mac:

Select code to reformat and press Command + Alt + Shift + L

For full page code reformat Alt + Command + L

Tested in phpStorm 2018.1.1


Under the 'Code' menu there is an option to Reformat Code. In the project settings there is an option to set code style for each file type.

Tags:

Phpstorm