### Install Magento Coding Standard via Git Clone Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Install the Magento Coding Standard for development by cloning the GitHub repository and running Composer install. ```bash git clone git@github.com:magento/magento-coding-standard.git cd magento-coding-standard composer install ``` -------------------------------- ### Install ESLint Dependencies Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Install all necessary Node.js packages for ESLint as described in the package.json file. ```bash npm install ``` -------------------------------- ### PHPCBF Auto-Fixing Summary Example Source: https://context7.com/magento/magento-coding-standard/llms.txt Example output summarizing the results of PHPCBF auto-fixing, showing the number of errors fixed and remaining for each file. ```text PHPCBF RESULT SUMMARY ---------------------------------------------------------------------- FILE FIXED REMAINING ---------------------------------------------------------------------- app/code/MyVendor/MyExtension/view/frontend/templates/mytemplate.phtml 3 0 ---------------------------------------------------------------------- A TOTAL OF 3 ERRORS WERE FIXED IN 1 FILE ---------------------------------------------------------------------- ``` -------------------------------- ### Verify Magento Coding Standard Installation Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Verify that the Magento Coding Standard is installed and recognized by PHP_CodeSniffer. ```bash vendor/bin/phpcs -i ``` -------------------------------- ### Example: Run Rector PHP for Magento CMS Model Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md An example of running Rector PHP to process the Magento CMS Model directory, including the autoload file. ```bash vendor/bin/rector process magento2ce/app/code/Magento/Cms/Model --dry-run --autoload-file magento2ce/vendor/autoload.php ``` -------------------------------- ### Install Magento Coding Standard with Composer Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Install the Magento Coding Standard as a development dependency in your Magento 2 project using Composer. ```bash composer require --dev magento/magento-coding-standard ``` -------------------------------- ### Install Node.js Dependencies for ESLint Source: https://context7.com/magento/magento-coding-standard/llms.txt Installs necessary Node.js dependencies for using ESLint with Magento coding standards. This is a prerequisite for running ESLint. ```bash # Install Node.js dependencies npm install ``` -------------------------------- ### PHPCS Violation Output Example Source: https://context7.com/magento/magento-coding-standard/llms.txt Example output format for violations detected by PHP_CodeSniffer using the Magento2 standard, indicating file, severity, and sniff type. ```text FILE: app/code/MyVendor/MyExtension/Model/MyModel.php -------------------------------------------------------------------------------- FOUND 2 ERRORS AND 1 WARNING AFFECTING 3 LINES -------------------------------------------------------------------------------- 10 | ERROR | [x] Possible raw SQL statement detected (Magento2.SQL.RawQuery) 25 | ERROR | [ ] Use of eval() is forbidden (Squiz.PHP.Eval) 30 | WARNING | [x] Use of $this in templates is deprecated (Magento2.Templates.ThisInTemplate) -------------------------------------------------------------------------------- ``` -------------------------------- ### Configure PHP_CodeSniffer for Magento Standard Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Add the Magento standard path to your project's composer.json to enable automatic configuration after installation or updates. ```json { "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/)" ] } } ``` -------------------------------- ### Detect Unescaped Output in PHTML Templates (XSS) Source: https://context7.com/magento/magento-coding-standard/llms.txt This PHP code demonstrates examples of unescaped output in PHTML templates that trigger the Magento2.Security.XssTemplate.FoundUnescaped sniff, and shows correctly escaped alternatives. ```php getData('user_input'); echo $variable; echo $block->getCustomValue(); // GOOD: Properly escaped output using Magento escape methods echo $block->escapeHtml($block->getData('user_input')); echo $block->escapeUrl($url); echo $block->escapeJs($javascriptValue); echo $block->escapeQuote($attributeValue); echo $block->escapeXssInUrl($untrustedUrl); echo $block->escapeCss($cssValue); // GOOD: Methods containing 'html' in name are considered safe echo $block->toHtml(); echo $block->getChildHtml('child.block'); echo $block->renderHtmlContent(); // GOOD: Using @noEscape annotation for intentionally unescaped output /** @noEscape */ echo $block->getTrustedHtmlContent(); ?> ``` -------------------------------- ### Create Standalone Magento Coding Standard Project Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Create a standalone project for the Magento Coding Standard using Composer create-project. ```bash composer create-project magento/magento-coding-standard --stability=dev magento-coding-standard ``` -------------------------------- ### Run Unit Tests for Coding Standard Rules Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Execute unit tests to verify the correctness of the coding standard rules using PHPUnit. ```bash vendor/bin/phpunit ``` -------------------------------- ### Execute ESLint for Code Analysis Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Run ESLint to analyze JavaScript code in a specified path. ```bash npm run eslint -- path/to/analyze ``` -------------------------------- ### Run PHPUnit Tests with Coverage Report Source: https://context7.com/magento/magento-coding-standard/llms.txt Execute PHPUnit tests and generate an HTML coverage report to analyze test coverage. ```bash vendor/bin/phpunit --coverage-html coverage/ ``` -------------------------------- ### Run ESLint on Specific Directory Source: https://context7.com/magento/magento-coding-standard/llms.txt Execute ESLint to check JavaScript code quality in a specified directory. ```bash npm run eslint -- pub/static/frontend/Magento/luma/en_US/js ``` -------------------------------- ### Magento ESLint Configuration Source: https://context7.com/magento/magento-coding-standard/llms.txt Configuration file for Magento ESLint, extending base configurations and including Magento-specific plugins. ```javascript // eslint.config.mjs - Magento ESLint configuration import { defineConfig } from "eslint/config"; import magentoCodingStandardEslintPlugin from "magento-coding-standard-eslint-plugin"; import path from "node:path"; import { fileURLToPath } from "node:url"; import js from "@eslint/js"; import { FlatCompat } from "@eslint/eslintrc"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const compat = new FlatCompat({ baseDirectory: __dirname, recommendedConfig: js.configs.recommended, allConfig: js.configs.all }); export default defineConfig([ { extends: compat.extends( "./.eslintrc-reset", // Reset all rules "./.eslintrc-magento", // Magento standards "./.eslintrc-jquery", // jQuery rules "./.eslintrc-misc", // Miscellaneous rules ), plugins: { "magento-coding-standard-eslint-plugin": magentoCodingStandardEslintPlugin, } }, { ignores: ['**/eslint/rules/*.js'], languageOptions: { sourceType: "script" }, rules: { strict: ["error", "function"] // Enforce "use strict" in functions } } ]); ``` -------------------------------- ### Preview PHPCBF Fixes with PHPCS Source: https://context7.com/magento/magento-coding-standard/llms.txt Perform a dry run using PHPCS with the --report=diff option to preview the changes PHPCBF would make without actually modifying files. ```bash vendor/bin/phpcs --standard=Magento2 app/code/MyVendor/MyExtension --report=diff ``` -------------------------------- ### Run ESLint on JavaScript Files Source: https://context7.com/magento/magento-coding-standard/llms.txt Executes ESLint to check JavaScript files against Magento coding standards. Specify the target directory for linting. ```bash # Run ESLint on JavaScript files npm run eslint -- app/code/MyVendor/MyModule/view/frontend/web/js ``` -------------------------------- ### Run PHP_CodeSniffer with Custom Ruleset Source: https://context7.com/magento/magento-coding-standard/llms.txt Execute PHP_CodeSniffer using a custom ruleset file to check code quality in a specified directory. ```bash vendor/bin/phpcs --standard=./ruleset.xml app/code/MyVendor ``` -------------------------------- ### Run Rector PHP for Specific Magento Project Path Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Process a specific Magento project path with Rector PHP, providing the project's autoload file. ```bash vendor/bin/rector process MAGENTO_PATH --dry-run --autoload-file MAGENTO_AUTOLOAD_FILE ``` -------------------------------- ### Run Rector for PHP Upgrades (Apply Changes) Source: https://context7.com/magento/magento-coding-standard/llms.txt Applies PHP code upgrades using Rector for compatibility with PHP 8.0/8.1. Ensure to remove the --dry-run flag to modify files. ```bash # Run Rector on Magento project code vendor/bin/rector process magento2/app/code/MyVendor/MyModule \ --dry-run \ --autoload-file magento2/vendor/autoload.php # Apply changes (remove --dry-run) vendor/bin/rector process magento2/app/code/MyVendor/MyModule \ --autoload-file magento2/vendor/autoload.php ``` -------------------------------- ### Analyze Code with Magento2 Standard Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Run PHP_CodeSniffer to analyze your Magento 2 extension code using the Magento2 standard. ```bash vendor/bin/phpcs --standard=Magento2 app/code/MyAwesomeExtension ``` -------------------------------- ### Run Rector for PHP Upgrades (Dry Run) Source: https://context7.com/magento/magento-coding-standard/llms.txt Performs a dry run of Rector to show potential PHP code changes for compatibility with PHP 8.0/8.1 without modifying files. Useful for reviewing changes before applying them. ```bash # Dry run - show what would be changed without modifying files vendor/bin/rector process Magento2 Magento2Framework PHP_CodeSniffer \ --dry-run \ --autoload-file vendor/squizlabs/php_codesniffer/autoload.php ``` -------------------------------- ### Run Specific PHPUnit Test Class Source: https://context7.com/magento/magento-coding-standard/llms.txt Execute a single PHPUnit test class to isolate and verify specific functionality. ```bash vendor/bin/phpunit Magento2/Tests/Security/XssTemplateUnitTest.php ``` -------------------------------- ### PHP Interface Naming Convention Source: https://context7.com/magento/magento-coding-standard/llms.txt Ensures interfaces follow Magento's naming convention by including the 'Interface' suffix. Use this to maintain consistency in API definitions. ```php getStore(); Mage::getStoreConfig('section/group/field'); $model = new Mage_Catalog_Model_Product(); $helper = new Mage_Core_Helper_Data(); $block = new Enterprise_Banner_Block_Widget_Banner(); // GOOD: Magento 2 patterns using dependency injection use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Helper\Data as CatalogHelper; use Magento\Customer\Model\Session; use Magento\Framework\App\Config\ScopeConfigInterface; class ProductService { public function __construct( private ProductRepositoryInterface $productRepository, private CatalogHelper $catalogHelper, private Session $customerSession, private ScopeConfigInterface $scopeConfig ) {} public function getProduct(string $sku): \Magento\Catalog\Api\Data\ProductInterface { return $this->productRepository->get($sku); } public function getConfigValue(string $path): mixed { return $this->scopeConfig->getValue($path); } } ``` -------------------------------- ### Detect Discouraged PHP Functions Source: https://context7.com/magento/magento-coding-standard/llms.txt Warns about native PHP functions that should be replaced with Magento framework equivalents for better security and consistency. For file operations, use \Magento\Framework\Filesystem\DriverInterface. For type checking, use language constructs. ```php driver->isExists($path)) { return $this->driver->fileGetContents($path); } return ''; } public function writeFile(string $path, string $content): void { $this->driver->filePutContents($path, $content); } public function getPathInfo(string $path): array { return $this->fileIo->getPathInfo($path); } } ``` -------------------------------- ### Analyze Magento 2 Code with PHPCS Source: https://context7.com/magento/magento-coding-standard/llms.txt Execute PHP_CodeSniffer to analyze your Magento 2 code against the Magento2 standard. Specify the path to your extension and optionally file extensions. ```bash vendor/bin/phpcs --standard=Magento2 app/code/MyVendor/MyExtension ``` ```bash vendor/bin/phpcs --standard=Magento2 app/code/MyVendor/MyExtension --extensions=php,phtml ``` -------------------------------- ### Verify Sniffer Code with Magento Standard Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Check if the sniffer code itself adheres to the Magento Coding Standard. ```bash vendor/bin/phpcs --standard=Magento2 Magento2/ --extensions=php ``` -------------------------------- ### PHP Class and Interface PHPDoc Formatting Source: https://context7.com/magento/magento-coding-standard/llms.txt Enforces proper PHPDoc formatting for classes and interfaces, including meaningful descriptions and correct usage of tags like @deprecated and @see. Avoids redundant or forbidden tags. ```php getViewModel(); ?> ``` ```php getData('viewModel'); ?> ``` -------------------------------- ### Generate Detailed PHPCS Report Source: https://context7.com/magento/magento-coding-standard/llms.txt Generate a comprehensive report from PHP_CodeSniffer analysis, including full details of violations found. ```bash vendor/bin/phpcs --standard=Magento2 app/code/MyVendor/MyExtension --report=full ``` -------------------------------- ### Rector Rules for PHP Upgrades Source: https://context7.com/magento/magento-coding-standard/llms.txt Demonstrates specific Rector rules applied within the Magento Coding Standard for PHP upgrades, such as fixing null parameters in string functions and removing redundant 'final' keywords from private methods. ```php serializer->serialize($data); } public function executeCommand(string $command): string { return $this->shell->execute($command); } } ``` -------------------------------- ### Detect Raw SQL Queries Source: https://context7.com/magento/magento-coding-standard/llms.txt Identifies raw SQL statements to prevent SQL injection vulnerabilities. Use Magento's database abstraction layer (ResourceConnection and Select) for safe database interactions. ```php query("SELECT * FROM customers"); $connection->query('DROP TABLE sensitive_data'); // Heredoc/Nowdoc also detected $sql = <<resourceConnection->getConnection(); $tableName = $this->resourceConnection->getTableName('sales_order'); $select = $connection->select() ->from($tableName) ->where('customer_id = ?', $customerId) ->order('created_at DESC'); return $connection->fetchAll($select); } public function updateOrderStatus(int $orderId, string $status): void { $connection = $this->resourceConnection->getConnection(); $tableName = $this->resourceConnection->getTableName('sales_order'); $connection->update( $tableName, ['status' => $status], ['entity_id = ?' => $orderId] ); } } ``` -------------------------------- ### Optimized Array Merging After Loop Source: https://github.com/magento/magento-coding-standard/blob/develop/Magento2/Sniffs/Performance/ForeachArrayMergeSniff.md To improve performance, collect all arrays within the loop and then merge them once after the loop completes. This approach significantly reduces the overhead associated with repeated merging. ```php $options = []; foreach ($configurationSources as $source) { // code here $options[] = $source->getOptions(); } $options = array_merge([], ...$options); ``` -------------------------------- ### Dry Run Rector PHP for Magento Coding Standard Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Execute Rector PHP with the Magento Coding Standard rules in dry-run mode to see potential changes without applying them. ```bash vendor/bin/rector process Magento2 Magento2Framework PHP_CodeSniffer --dry-run --autoload-file vendor/squizlabs/php_codesniffer/autoload.php ``` -------------------------------- ### Filter PHPCS Analysis Results Source: https://context7.com/magento/magento-coding-standard/llms.txt Run PHP_CodeSniffer to show only errors (severity 10) and suppress warnings (severity 0) for a focused analysis. ```bash vendor/bin/phpcs --standard=Magento2 app/code/MyVendor/MyExtension --error-severity=10 --warning-severity=0 ``` -------------------------------- ### Fix Code Issues Automatically with phpcbf Source: https://github.com/magento/magento-coding-standard/blob/develop/README.md Use the phpcbf tool to automatically fix code style violations identified by the Magento2 standard. ```bash vendor/bin/phpcbf --standard=Magento2 app/code/MyAwesomeExtension ``` -------------------------------- ### Avoid array_merge in Loops for Performance Source: https://context7.com/magento/magento-coding-standard/llms.txt This sniff detects the inefficient use of array_merge() inside loops, which can lead to performance issues. Prefer using the spread operator, direct array assignment, or array_reduce for better performance. ```php getData()); } for ($i = 0; $i < count($products); $i++) { $allAttributes = array_merge($allAttributes, $products[$i]->getAttributes()); } // GOOD: Use spread operator or array assignment $result = []; foreach ($items as $item) { $result[] = $item->getData(); // If you want nested arrays } $flattened = array_merge(...$result); // Merge once at the end // GOOD: Direct array assignment $result = []; foreach ($items as $item) { foreach ($item->getData() as $key => $value) { $result[$key] = $value; } } // GOOD: Use array_reduce for complex merging $result = array_reduce($items, function ($carry, $item) { return array_merge($carry, $item->getData()); }, []); // GOOD: Pre-allocate and assign $result = []; foreach ($items as $item) { $data = $item->getData(); foreach ($data as $key => $value) { $result[$key] = $value; } } ``` -------------------------------- ### Auto-fix Violations with PHPCBF Source: https://context7.com/magento/magento-coding-standard/llms.txt Use PHP Code Beautifier and Fixer (PHPCBF) to automatically correct fixable coding standard violations within your Magento 2 extension. ```bash vendor/bin/phpcbf --standard=Magento2 app/code/MyVendor/MyExtension ``` -------------------------------- ### Inefficient Array Merging in Loop Source: https://github.com/magento/magento-coding-standard/blob/develop/Magento2/Sniffs/Performance/ForeachArrayMergeSniff.md Avoid using `array_merge` inside a loop as it is a resource-intensive operation that can slow down execution and increase CPU usage. This pattern is common but should be refactored for better performance. ```php $options = []; foreach ($configurationSources as $source) { // code here $options = array_merge($options, $source->getOptions()); } ``` -------------------------------- ### Fix Specific Sniffs with PHPCBF Source: https://context7.com/magento/magento-coding-standard/llms.txt Apply PHPCBF to fix only violations related to specific sniffs, such as Magento2.Templates.ThisInTemplate, for targeted code correction. ```bash vendor/bin/phpcbf --standard=Magento2 app/code/MyVendor/MyExtension --sniffs=Magento2.Templates.ThisInTemplate ``` -------------------------------- ### Custom PHP_CodeSniffer Ruleset Source: https://context7.com/magento/magento-coding-standard/llms.txt Defines a custom ruleset for PHP_CodeSniffer, extending Magento2 standards and configuring specific rules and exclusions. ```xml Custom coding standard based on Magento2 */Setup/* */Test/* 9 error */vendor/* */generated/* * .min .js$ ``` -------------------------------- ### Update composer.json for Magento Coding Standard Source: https://github.com/magento/magento-coding-standard/wiki/Release Modify the composer.json file to include the Magento Coding Standard as a development dependency. This is typically done when testing local changes or preparing for a release. ```json { ... "require-dev": { ... "magento/magento-coding-standard": "dev-[branch]" ... } ... "minimum-stability": "dev", "repositories": [ { "type": "git", "url": "https://github.com/[fork]/magento-coding-standard" } ] } ``` -------------------------------- ### Replace $this with $block in PHTML Templates Source: https://context7.com/magento/magento-coding-standard/llms.txt This sniff enforces the use of $block instead of the deprecated $this in PHTML templates. It can be auto-fixed by phpcbf. Avoid using $this->helper() directly; prefer ViewModels. ```php

escapeHtml($this->getProduct()->getName()) ?>

escapeHtml($this->getProduct()->getDescription()) ?>

getChildHtml('product.info.price') ?>
helper('Magento\Catalog\Helper\Data'); ?>

escapeHtml($block->getProduct()->getName()) ?>

escapeHtml($block->getProduct()->getDescription()) ?>

getChildHtml('product.info.price') ?>
getViewModel(); ?>
escapeHtml($viewModel->getFormattedPrice()) ?>
``` -------------------------------- ### Avoid $this in Magento Templates Source: https://github.com/magento/magento-coding-standard/blob/develop/Magento2/Sniffs/Templates/ThisInTemplateSniff.md In PHTML templates, use `$block` instead of `$this` to access the current block. This is a deprecated practice that may be removed in future versions. ```php helper()->...; ?> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.