Magento Coding Standard

repository·develop·Indexed 18 days ago

https://github.com/magento/magento-coding-standard

A collection of PHP_CodeSniffer rules, ESLint configurations, and Rector rules designed to enforce Magento coding standards across PHP and JavaScript codebases. It includes tools for analyzing code with phpcs, automatically fixing violations with phpcbf, and performing automated refactoring via Rector to ensure compatibility with modern PHP versions and cloud storage environments.

Tokens
3.3K
Snippets
15
Records
21
Agent score
62%

What's inside magento-coding-standard

  1. Avoid using getimagesize() for file information

    develop
    The getimagesize() function is discouraged because it only works with local files or specific supported streams. In modern environments using advanced storage solutions like AWS S3 or Azure Blob Storage, getimagesize() may fail because the file is not directly accessible via the local filesystem. To ensure compatibility with cloud storage, use getimagesizefromstring() instead.
  2. Avoid importing from `Magento ests` namespaces

    develop

    To prevent build failures and missing test reports in the Magento 2 repository, do not import namespaces that start with Magento\Tests.

    This issue often occurs when an IDE automatically imports a namespace for a return data type (like string or float) from a test utility instead of using the native type or the correct production namespace. Importing from Magento\Tests can cause static tests to fail without providing clear error reasons and can lead to missing build reports for 'Database Compare', 'Functional Tests', and 'Sample Data Tests'.

  3. Avoid using `$this` in PHTML templates

    develop

    In PHTML templates, $this refers to the current block. Using $this is considered legacy (from Magento 1) and is discouraged to ensure templates and blocks remain decoupled.

    To comply with the coding standard, always use $block instead of $this. If you are currently accessing private or protected methods via $this, you must refactor those methods to be public so they can be accessed via $block.

  4. Install Magento Coding Standard in a Magento 2 project

    develop

    To use the Magento coding standards within an existing Magento 2 project, install the package as a development dependency using Composer.

    Note: For security reasons, the standard is not added to PHP_CodeSniffer's installed paths automatically. You must manually configure your composer.json to register the paths during installation or updates.

    composer require --dev magento/magento-coding-standard

    Add this to your composer.json to automate path registration:

    "scripts": {
        "post-install-cmd": [
          "([ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/phpcs --config-set installed_paths ../../magento/magento-coding-standard/)
        ],
        "post-update-cmd": [
          "([ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/phpcs --config-set installed_paths ../../magento/magento-coding-standard/)
        ]
    }
  5. Avoid using array_merge() inside loops

    develop

    The ForeachArrayMergeSniff rule identifies performance issues caused by calling array_merge() inside a foreach loop. Merging arrays repeatedly within a loop is resource-intensive, leading to high CPU usage and slow execution times because a new array is created and all elements are copied in every iteration.

    To fix this, collect the arrays into a temporary collection during the loop and perform a single array_merge() using the spread operator (...) after the loop has finished.

    // BAD: array_merge inside a loop
    $options = [];
    foreach ($configurationSources as $source) {
        // code here
        $options = array_merge($options, $source->getOptions());
    }
    
    // GOOD: Collect arrays and merge once after the loop
    $options = [];
    foreach ($configurationSources as $source) {
        // code here
        $options[] = $source->getOptions();
    }
    
    $options = array_merge([], ...$options);
  6. Run Rector PHP for automated refactoring

    develop

    Rector can be used to process code using Magento-specific rules.

    To run Rector within the magento-coding-standard project: Use the --dry-run flag to see errors without applying fixes. You must provide the path to the PHP_CodeSniffer autoload file.

    To run Rector on a Magento project: You must specify the path to your Magento project and its specific vendor/autoload.php file.

    Rules applied are configured in the rector.php file.

    # Running within the coding-standard repo
    vendor/bin/rector process Magento2 Magento2Framework PHP_CodeSniffer --dry-run --autoload-file vendor/squizlabs/php_codesniffer/autoload.php
    
    # Running on a specific Magento project
    vendor/bin/rector process MAGENTO_PATH --dry-run --autoload-file MAGENTO_AUTOLOAD_FILE
    
    # Example for a specific path
    vendor/bin/rector process magento2ce/app/code/Magento/Cms/Model --dry-run --autoload-file magento2ce/vendor/autoload.php
  7. Install Magento Coding Standard for development

    develop

    If you are developing the coding standard itself or want a standalone installation, you can use one of the following methods:

    Method 1: Clone the repository

    git clone git@github.com:magento/magento-coding-standard.git
    cd magento-coding-standard
    composer install

    Method 2: Create a standalone project via Composer

    composer create-project magento/magento-coding-standard --stability=dev magento-coding-standard
  8. Refactor helpers to ViewModels in templates

    develop

    To fix the use of helpers in a PHTML template, create a ViewModel and inject it into the block. You can then access the ViewModel in the template using $block->getViewModel() or $block->getData('viewModel').

    <!-- Before: Using a helper -->
    <?php $_incl = $this->helper(<helper_class>)->...; ?>
    
    <!-- After: Using a ViewModel -->
    <?php $viewModel = $block->getViewModel(); ?>
    <?php // or
    <?php $viewModel = $block->getData('viewModel'); ?>