Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Setting up PhpStorm: Difference between revisions

From MoodleDocs
(Adding debugging locally with xdebug and docker containers)
(→‎Code formatting: Update settings)
 
(8 intermediate revisions by 3 users not shown)
Line 9: Line 9:
==General settings==
==General settings==


* Disable missing @throws tag warning in "Preferences / Project Settings / Inspections / PHP / PHPDoc"
* Uncheck "Missing @throws tag(s)" setting in "Preferences / Editor / Inspections / PHP / PHPDoc"
* Strip trailing whitespace from "Modified Lines" in "Preferences / IDE Settings / Editor/ General"
* Check "Strip trailing whitespace on Modified Lines" in "Preferences / Editor / General"
* Show line numbers in "Preferences / IDE Settings / Editor / Appearance"
* Check "Show line numbers" in "Preferences / Editor / Appearance"
* Add Moodle database prefix by create file .phpstorm.meta.php in the project root directory, put the code below to enable PhpStorm recognized {table_name} as Database table:
* Add Moodle database prefix by create file .phpstorm.meta.php in the project root directory, put the code below to enable PhpStorm recognized {table_name} as Database table:
<code php>
<syntaxhighlight lang="php">
<?php
<?php


Line 26: Line 26:
         ]));
         ]));
}
}
</code>
</syntaxhighlight>


==Bug tracker integration==
==Bug tracker integration==
Line 35: Line 35:
==Code formatting==
==Code formatting==


* Setup coding style to use all rules from [[Coding style]] in "Preferences / Project Settings / Code Style / PHP" (or simply import from https://github.com/enovation/moodle-utils/blob/master/phpstorm-config/Moodle.xml) - this will allow you to use automatic code formatting and it does nice code formatting on copy/paste.
* Setup coding style to use all rules from [[Coding style]] in "Preferences / Code Style / PHP" (or simply import from https://github.com/enovation/moodle-utils/blob/master/phpstorm-config/Moodle.xml) - this will allow you to use automatic code formatting and it does nice code formatting on copy/paste.
* Set line separator to "Unix and OS X (\n)" in "Preferences / Project Settings / Code Style / General".
* Set line separator to "Unix and OS X (\n)" in "Preferences / Code Style / General".
* Set right margin to 132 or 180 in "Preferences / Project Settings / Code Style / General".
* Set right margin to 132 or 180 in "Preferences / Code Style / General".


==Tips & Tricks==
==Tips & Tricks==


* Use <code php>/** @var admin_root $ADMIN */</code>  to autofill $ADMIN->...
* Use <syntaxhighlight lang="php">/** @var admin_root $ADMIN */</syntaxhighlight>  to autofill $ADMIN->...
* Remove SQL syntax inspection errors for Moodle tables surrounded by curly brackets (like: <code php>SELECT * FROM {user}</code>)  by adding <code php>\{(\w+)\}</code> to Tools > Databases > user parameters  
* Remove SQL syntax inspection errors for Moodle tables surrounded by curly brackets (like: <syntaxhighlight lang="php">SELECT * FROM {user}</syntaxhighlight>)  by adding <syntaxhighlight lang="php">\{(\w+)\}</syntaxhighlight> to Tools > Databases > user parameters  
(more info: https://blog.jetbrains.com/phpstorm/2014/11/database-language-injection-configuration/ , and a "feature request" to improve it: https://youtrack.jetbrains.com/issue/WI-4123 )
(more info: https://blog.jetbrains.com/phpstorm/2014/11/database-language-injection-configuration/ , and a "feature request" to improve it: https://youtrack.jetbrains.com/issue/WI-4123 )
* You can deactivate warnings for specific exceptions (in particular the coding_exception, which is unlikely to be catched in your code) by going to Settings > PHP and add them to 'Unchecked Exceptions' under the 'Analysis' tab
* You can deactivate warnings for specific exceptions (in particular the coding_exception, which is unlikely to be catched in your code) by going to Settings > PHP and add them to 'Unchecked Exceptions' under the 'Analysis' tab
Line 66: Line 66:
# Install Watchman - https://facebook.github.io/watchman/docs/install.html
# Install Watchman - https://facebook.github.io/watchman/docs/install.html
# From the main Moodle directory open terminal and run:  
# From the main Moodle directory open terminal and run:  
<code shell>
<syntaxhighlight lang="shell">
npm install -g grunt-cli
npm install -g grunt-cli
npm install
npm install
</code>
</syntaxhighlight>
# Open "Edit configuration"
# Open "Edit configuration"
# Add new Grunt Task
# Add new Grunt Task
Line 76: Line 76:
# Save the Grunt task
# Save the Grunt task
# Verify that in config.php the setting is not comment
# Verify that in config.php the setting is not comment
<code php>
<syntaxhighlight lang="php">
$CFG->cachejs = false;
$CFG->cachejs = false;
</code>
</syntaxhighlight>
# Click on run icon
# Click on run icon
# happy Javascript development
# happy Javascript development
Line 86: Line 86:
This is very helpful when developing locally and you need to go step by step on the execution path of something of your interest.
This is very helpful when developing locally and you need to go step by step on the execution path of something of your interest.


Assumptions: You're using moodle-docker or a custom docker container, with the web server container based on Debian.
If you're using [https://github.com/moodlehq/moodle-docker moodle-docker], please refer to its section about [https://github.com/moodlehq/moodle-docker#using-xdebug-for-live-debugging live debugging] before taking this section. If you are using a custom docker container, the web server container should be based on Debian-like to have the following instructions compatible.


These are the steps for configuring Xdebug to debug your code:
These are the steps for configuring Xdebug to live debugging your code:


# Be sure containers are stopped.
# Be sure containers are stopped.
# Create a file named `add-host.docker.internal-to-etc-hosts` with execution rights on the Moodle root:
# If you're using Docker on Mac or Windows, you can omit this step. So, only if you're using Docker on linux: Create a file named `add-host.docker.internal-to-etc-hosts` with execution rights on the Moodle root:
<code>
<syntaxhighlight lang="php">
#!/bin/bash
#!/bin/bash
apt update
apt update
Line 104: Line 104:
   echo -e "$HOST_IP\t$HOST_DOMAIN" >> /etc/hosts
   echo -e "$HOST_IP\t$HOST_DOMAIN" >> /etc/hosts
fi
fi
</code>
</syntaxhighlight>
# Edit the <code>base.yml</code> from the moodle-docker root (or equivalent from your custom docker container) to append these lines into the <code>webserver: environment:</code> section:
# Edit the <syntaxhighlight lang="php">base.yml</syntaxhighlight> from the moodle-docker root (or equivalent from your custom docker container) to append these lines into the <syntaxhighlight lang="php">webserver: environment:</syntaxhighlight> section:
<code>
<syntaxhighlight lang="php">
       XDEBUG_CONFIG:
       XDEBUG_CONFIG:
         idekey=phpstorm
         idekey=phpstorm
Line 116: Line 116:
       PHP_IDE_CONFIG:
       PHP_IDE_CONFIG:
         serverName=moodle-local
         serverName=moodle-local
</code>
</syntaxhighlight>
# The result for the <code>webserver</code> service should be like this:  
# The result for the <syntaxhighlight lang="php">webserver</syntaxhighlight> service should be like this (this example is from moodle-docker):  
<code>
<syntaxhighlight lang="php">
   webserver:
   webserver:
     image: "moodlehq/moodle-php-apache:${MOODLE_DOCKER_PHP_VERSION}"
     image: "moodlehq/moodle-php-apache:${MOODLE_DOCKER_PHP_VERSION}"
Line 142: Line 142:
       PHP_IDE_CONFIG:
       PHP_IDE_CONFIG:
         serverName=moodle-local
         serverName=moodle-local
</code>
</syntaxhighlight>
# Start the moodle-docker containers, or your custom ones.
# Start the moodle-docker containers, or your custom ones.
# From a PhpStorm terminal, run: <code>docker exec -it moodledocker_webserver_1 ./add-host.docker.internal-to-etc-hosts</code>. You have to see how packages are installed.
# Only if you're using Docker on linux: From a PhpStorm terminal, run: <syntaxhighlight lang="php">docker exec -it moodledocker_webserver_1 ./add-host.docker.internal-to-etc-hosts</syntaxhighlight>. You have to see how packages are installed.
# Check that /etc/hosts files was updated with the command <code>docker exec -it moodledocker_webserver_1 cat /etc/hosts</code>. The result should be something like this:
# In any type of host (Mac, Windows or linux): Check that <syntaxhighlight lang="php">/etc/hosts</syntaxhighlight> has a line with <syntaxhighlight lang="php">host.docker.internal</syntaxhighlight>. You can do that with the command <syntaxhighlight lang="php">docker exec -it moodledocker_webserver_1 cat /etc/hosts</syntaxhighlight> (if you have a custom container name, use the name for the webserver container). The result should be something like this:
<code>
<syntaxhighlight lang="php">
127.0.0.1      localhost
127.0.0.1      localhost
::1    localhost ip6-localhost ip6-loopback
::1    localhost ip6-localhost ip6-loopback
Line 155: Line 155:
172.20.0.6      17dff32616ac
172.20.0.6      17dff32616ac
172.20.0.1      host.docker.internal
172.20.0.1      host.docker.internal
</code>
</syntaxhighlight>
# Go to your PhpStorm and go to <code>Run -> Edit configurations</code> and select new <code>PHP Remove Debug</code>
# Go to your PhpStorm and go to <syntaxhighlight lang="php">Run -> Edit configurations</syntaxhighlight> and select new <syntaxhighlight lang="php">PHP Remove Debug</syntaxhighlight>
# Name: "xdebug localhost" (or what you want to)
# Name: "xdebug localhost" (or what you want to)
# Configuration: check "Filter debug connection by IDE key"
# Configuration: check "Filter debug connection by IDE key"
Line 163: Line 163:
# Name: must be "moodle-local"
# Name: must be "moodle-local"
# Host: localhost
# Host: localhost
# Port: type the port you're using for the web server.
# Port: must be the port you're using for the web server.
# Debugger: use the default (Xdebug)
# Debugger: use the default (Xdebug)
# Check "Use path mappings (...)"
# Check "Use path mappings (...)"
# Set for your "Project files" Moodle root the "Absolute path on the server" as "/var/www/html"
# Set for your "Project files" Moodle root the "Absolute path on the server" as "/var/www/html"
# Apply and OK
# Apply and OK on this screen. This screen will be closed.
# Apply and OK
# Apply and OK on the next screen. Settings screen will be closed.
# Test debug works:
# Now, test that live debugging works. To do so, please:
# Put a breakpoint on /index.php file.
# Put a breakpoint on /index.php file.
# Press telephone icon with a red symbol with title "Start listening for PHP Debug Connections": telephone should appear with some waves now.
# Press telephone icon with a red symbol with title "Start listening for PHP Debug Connections": telephone should appear with some waves now.
Line 175: Line 175:
# Happy debugging ;-)
# Happy debugging ;-)


Final note: Every time you start the webserver container, you have to run the script for adding the host.docker.internal.
Final note: Every time you start the webserver container, ONLY if you're using a linux host, you have to run the script for adding the host.docker.internal.
Final note 2: This method also works if your docker containers are in a different host from localhost: you just need to specify the proper server name and port.
Final note 2: This method also works if your docker containers are in a different host from localhost: you just need to specify the proper server name and port.
Final note 3: This configuration also allows you to debug CLI scripts.


==Useful plugins==
==Useful plugins==

Latest revision as of 15:54, 16 April 2022

PhpStorm is a commercial IDE, it is arguably the best IDE for PHP developers with features such as code completion, code inspection, phpunit support, Behat support, database editor, debugger, etc.

Installation

OS X

Do not install Java manually, download a PhpStorm package with bundled java instead.

General settings

  • Uncheck "Missing @throws tag(s)" setting in "Preferences / Editor / Inspections / PHP / PHPDoc"
  • Check "Strip trailing whitespace on Modified Lines" in "Preferences / Editor / General"
  • Check "Show line numbers" in "Preferences / Editor / Appearance"
  • Add Moodle database prefix by create file .phpstorm.meta.php in the project root directory, put the code below to enable PhpStorm recognized {table_name} as Database table:
<?php

namespace PHPSTORM_META {
    override(
    // Virtual function to indicate that all SQL
    // injections will have the following replacement rules.
        sql_injection_subst(),
        map([
            '{' => "mdl_", // all `{` in injected SQL strings will be replaced with a prefix
            '}' => '',        // all `}` will be replaced with an empty string
        ]));
}

Bug tracker integration

Code formatting

Tips & Tricks

  • Use
    /** @var admin_root $ADMIN */
    
    to autofill $ADMIN->...
  • Remove SQL syntax inspection errors for Moodle tables surrounded by curly brackets (like:
    SELECT * FROM {user}
    
    ) by adding
    \{(\w+)\}
    
    to Tools > Databases > user parameters

(more info: https://blog.jetbrains.com/phpstorm/2014/11/database-language-injection-configuration/ , and a "feature request" to improve it: https://youtrack.jetbrains.com/issue/WI-4123 )

  • You can deactivate warnings for specific exceptions (in particular the coding_exception, which is unlikely to be catched in your code) by going to Settings > PHP and add them to 'Unchecked Exceptions' under the 'Analysis' tab

Moodle code checker

Follow the instructions in the README

PHPUnit integration

  1. Install PHPUnit via Composer
  2. Tell PHPStorm where is composer - go to "Preferences / PHP / Composer", fill in "Path to PHP executable", "Path to composer.phar", "Path to composer.json" and make sure the option "Add packages as libraries" is enabled.
  3. Go to "Run / Edit configurations"
  4. Add PHPUnit configuration by clicking on "+"
  5. Click "Use alternative configuration file" and select your phpunit.xml file
  6. Go to "Run / Run ..." and select your new PHPUnit configuration to run

Database editor

  1. Click on the "Database" tab to see the database window
  2. Click "+" in the top left and add "Database source" for your database
  3. Note: click on the link to download the necessary drivers directly from IDE

Javascript Development

You can work on Javascript development by add Grunt configuration:

  1. Install Watchman - https://facebook.github.io/watchman/docs/install.html
  2. From the main Moodle directory open terminal and run:
npm install -g grunt-cli
npm install
  1. Open "Edit configuration"
  2. Add new Grunt Task
    1. Verify that the node version is set with proper version for the current Moodle version
    2. In Tasks select watch
  3. Save the Grunt task
  4. Verify that in config.php the setting is not comment
$CFG->cachejs = false;
  1. Click on run icon
  2. happy Javascript development

Debugging with Xdebug with docker containers

This is very helpful when developing locally and you need to go step by step on the execution path of something of your interest.

If you're using moodle-docker, please refer to its section about live debugging before taking this section. If you are using a custom docker container, the web server container should be based on Debian-like to have the following instructions compatible.

These are the steps for configuring Xdebug to live debugging your code:

  1. Be sure containers are stopped.
  2. If you're using Docker on Mac or Windows, you can omit this step. So, only if you're using Docker on linux: Create a file named `add-host.docker.internal-to-etc-hosts` with execution rights on the Moodle root:
#!/bin/bash
apt update
apt install -y iproute2
apt clean
apt auto-clean
HOST_DOMAIN="host.docker.internal"
ping -q -c1 $HOST_DOMAIN > /dev/null 2>&1
if [ $? -ne 0 ]; then
  HOST_IP=$(ip route | awk 'NR==1 {print $3}')
  echo -e "$HOST_IP\t$HOST_DOMAIN" >> /etc/hosts
fi
  1. Edit the
    base.yml
    
    from the moodle-docker root (or equivalent from your custom docker container) to append these lines into the
    webserver: environment:
    
    section:
      XDEBUG_CONFIG:
        idekey=phpstorm
        remote_enable=1
        remote_mode=req
        remote_port=9000
        remote_host=host.docker.internal
        remote_connect_back=0
      PHP_IDE_CONFIG:
        serverName=moodle-local
  1. The result for the
    webserver
    
    service should be like this (this example is from moodle-docker):
  webserver:
    image: "moodlehq/moodle-php-apache:${MOODLE_DOCKER_PHP_VERSION}"
    depends_on:
      - db
    volumes:
      - "${MOODLE_DOCKER_WWWROOT}:/var/www/html"
      - "${ASSETDIR}/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      MOODLE_DOCKER_BROWSER: firefox
      MOODLE_DOCKER_WEB_HOST: "${MOODLE_DOCKER_WEB_HOST}"
      XDEBUG_CONFIG:
        idekey=phpstorm
        remote_enable=1
        remote_mode=req
        remote_port=9000
        remote_host=host.docker.internal
        remote_connect_back=0
      PHP_IDE_CONFIG:
        serverName=moodle-local
  1. Start the moodle-docker containers, or your custom ones.
  2. Only if you're using Docker on linux: From a PhpStorm terminal, run:
    docker exec -it moodledocker_webserver_1 ./add-host.docker.internal-to-etc-hosts
    
    . You have to see how packages are installed.
  3. In any type of host (Mac, Windows or linux): Check that
    /etc/hosts
    
    has a line with
    host.docker.internal
    
    . You can do that with the command
    docker exec -it moodledocker_webserver_1 cat /etc/hosts
    
    (if you have a custom container name, use the name for the webserver container). The result should be something like this:
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.20.0.6      17dff32616ac
172.20.0.1      host.docker.internal
  1. Go to your PhpStorm and go to
    Run -> Edit configurations
    
    and select new
    PHP Remove Debug
    
  2. Name: "xdebug localhost" (or what you want to)
  3. Configuration: check "Filter debug connection by IDE key"
  4. IDE key(session id): "phpstorm"
  5. Define a new server:
  6. Name: must be "moodle-local"
  7. Host: localhost
  8. Port: must be the port you're using for the web server.
  9. Debugger: use the default (Xdebug)
  10. Check "Use path mappings (...)"
  11. Set for your "Project files" Moodle root the "Absolute path on the server" as "/var/www/html"
  12. Apply and OK on this screen. This screen will be closed.
  13. Apply and OK on the next screen. Settings screen will be closed.
  14. Now, test that live debugging works. To do so, please:
  15. Put a breakpoint on /index.php file.
  16. Press telephone icon with a red symbol with title "Start listening for PHP Debug Connections": telephone should appear with some waves now.
  17. Open your browser and open your localhost Moodle site.
  18. Happy debugging ;-)

Final note: Every time you start the webserver container, ONLY if you're using a linux host, you have to run the script for adding the host.docker.internal. Final note 2: This method also works if your docker containers are in a different host from localhost: you just need to specify the proper server name and port. Final note 3: This configuration also allows you to debug CLI scripts.

Useful plugins

  1. Php Inspections ​(EA Extended) - https://plugins.jetbrains.com/plugin/7622-php-inspections-ea-extended-/
  2. SonarLint - https://plugins.jetbrains.com/plugin/7973-sonarlint/
  3. Diff / Patch File Support - https://plugins.jetbrains.com/plugin/11957-diff--patch-file-support/
  4. Handlebars/Mustache - https://plugins.jetbrains.com/plugin/6884-handlebars-mustache/
  5. Markdown Navigator - https://plugins.jetbrains.com/plugin/7896-markdown-navigator/
  6. PHP composer.json support - https://plugins.jetbrains.com/plugin/7631-php-composer-json-support/
  7. PHP Advanced AutoComplete - https://plugins.jetbrains.com/plugin/7276-php-advanced-autocomplete/